code
stringlengths
1
199k
import zlib from . import register_test blacklisted_extensions = ("dll", "exe", "dylib", "so", "sh", "class") blacklisted_magic_numbers = ( (0x4d, 0x5a), # EXE/DLL (0x5a, 0x4d), # Alternative for EXE/DLL (0x7f, 0x45, 0x4c, 0x46), # UNIX elf (0x23, 0x21), # Shebang (shell script) ...
import os def limit(i): dr=i.get('list',[]) drx=[] for q in dr: if q.find('.libs')<0: drx.append(q) return {'return':0, 'list':drx} def version_cmd(i): ck=i['ck_kernel'] fp=i['full_path'] fn=os.path.basename(fp) rfp=os.path.realpath(fp) rfn=os.path.basename(rfp) ...
import os from django.apps import apps from django.db import connection from django.core import management from django.core.management import BaseCommand, CommandError, find_commands from django.core.management.utils import find_command, popen_wrapper from django.test import SimpleTestCase, ignore_warnings from django....
'''Quantizing a continuous distribution in 2d Author: josef-pktd ''' import numpy as np def prob_bv_rectangle(lower, upper, cdf): '''helper function for probability of a rectangle in a bivariate distribution Parameters ---------- lower : array_like tuple of lower integration bounds upper : a...
from os import path from gluon import * from gluon.storage import Storage from s3 import * class index(): """ Custom Home Page """ def __call__(self): request = current.request response = current.response response.title = current.deployment_settings.get_system_name() T = current....
from __future__ import print_function import time, sys, signal, atexit from upm import pyupm_hka5 as sensorObj def main(): # Instantiate a HKA5 sensor on uart 0. We don't use the set or # reset pins, so we pass -1 for them. sensor = sensorObj.HKA5(0, -1, -1) ## Exit handlers ## # This function stop...
__all__ = ['ExplorerTableElementWdg', 'ExplorerElementWdg'] from pyasm.common import TacticException, Common from pyasm.biz import Project from pyasm.web import Widget from pyasm.widget import IconWdg from tactic.ui.common import BaseTableElementWdg from tactic.ui.widget import IconButtonWdg class ExplorerElementWdg(Ba...
""" Course Goals Python API """ import models from six import text_type from opaque_keys.edx.keys import CourseKey from django.conf import settings from rest_framework.reverse import reverse from course_modes.models import CourseMode from openedx.features.course_experience import ENABLE_COURSE_GOALS def add_course_goal...
import sys import os path_to_db = os.environ.get( 'RADICAL_PILOT_DBURL', "mongodb://localhost:27017/rp") os.environ['RADICAL_PILOT_DBURL'] = path_to_db import time from adaptivemd import Project, ExecutionPlan from adaptivemd import AllegroCluster from adaptivemd import ExecutionPlan from adaptivemd import OpenMMEn...
import pilasengine import sys sys.path.insert(0, "..") pilas = pilasengine.iniciar() mono = pilas.actores.Mono() mono.aprender(pilas.habilidades.SeguirClicks) mono.aprender(pilas.habilidades.AumentarConRueda) pilas.avisar(u"El mono sigue los clicks, y cambia de tamaño si mueves la\nrueda del mouse.") pilas.ejecutar()
from oslotest import mockpatch from tempest.lib import exceptions as lib_exc from tempest.lib.services.compute import snapshots_client from tempest.tests.lib import fake_auth_provider from tempest.tests.lib.services.compute import base class TestSnapshotsClient(base.BaseComputeServiceTest): FAKE_SNAPSHOT = { ...
import re import sys import subprocess import os def generate(test): with open("tests/template.fmt") as file: template = file.read() lines = [] for line in re.split('(?<=[;{}])\n', test.read()): match = re.match('(?: *\n)*( *)(.*)=>(.*);', line, re.DOTALL | re.MULTILINE) if match: ...
m = 0 for line in open('/data/fuzzyjoin/pub/csx-id.txt'): l = len(line) if (l > m): m = l print m
from oslo.config import cfg from cinder import exception from cinder.i18n import _ from cinder.openstack.common import log as logging from cinder.volume.drivers.san.san import SanISCSIDriver LOG = logging.getLogger(__name__) solaris_opts = [ cfg.StrOpt('san_zfs_volume_base', default='rpool/', ...
'''main method for integration test topology''' import argparse import logging import sys from .basic_one_task import basic_one_task_builder from .all_grouping import all_grouping_buidler from .none_grouping import none_grouping_builder from .one_bolt_multi_tasks import one_bolt_multi_tasks_builder from .one_spout_bolt...
"""Self-test suite for Crypto.Random.new()""" import sys import unittest from Crypto.Util.py3compat import b class SimpleTest(unittest.TestCase): def runTest(self): """Crypto.Random.new()""" # Import the Random module and try to use it from Crypto import Random randobj = Random.new()...
import logging import sys logging.basicConfig(stream=sys.stderr, level=logging.INFO)
""" Copyright 2007, 2008, 2009 Free Software Foundation, Inc. This file is part of GNU Radio GNU Radio Companion is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option)...
"""Collector for MySQL.""" import errno import os import re import socket import sys import time try: import MySQLdb except ImportError: MySQLdb = None # This is handled gracefully in main() from collectors.etc import mysqlconf from collectors.lib import utils COLLECTION_INTERVAL = 15 # seconds CONNECT_TIMEOUT = ...
from odoo import models, fields class ResCompany(models.Model): _inherit = "res.company" def _localization_use_documents(self): """ Chilean localization use documents """ self.ensure_one() return self.account_fiscal_country_id.code == "CL" or super()._localization_use_documents()
from openerp import models, fields, api, _ from openerp.fields import DATE_LENGTH from openerp.exceptions import Warning class ProjectProject(models.Model): _inherit = 'project.project' calculation_type = fields.Selection( [('date_begin', 'Date begin'), ('date_end', 'Date end')], string...
""" Views related to the Custom Courses feature. """ import csv import datetime import functools import json import logging import pytz from copy import deepcopy from cStringIO import StringIO from django.conf import settings from django.core.urlresolvers import reverse from django.http import ( HttpResponse, H...
import re, os, sys from Tester import Tester from RunParallel import RunParallel # For TIMEOUT value class AnalyzeJacobian(Tester): @staticmethod def validParams(): params = Tester.validParams() params.addRequiredParam('input', "The input file to use for this test.") params.addParam('test_name', "...
'''OpenGL extension SGIX.interlace This module customises the behaviour of the OpenGL.raw.GL.SGIX.interlace to provide a more Python-friendly API Overview (from the spec) This extension provides a way to interlace rows of pixels when rasterizing pixel rectangles, and loading texture images. In this context, interla...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('osf', '0114_merge_20180621_1322'), ] operations = [ migrations.AlterField( model_name='providerassetfile', name='name', ...
import unittest, struct import os import sys from test import support import math from math import isinf, isnan, copysign, ldexp import operator import random, fractions INF = float("inf") NAN = float("nan") have_getformat = hasattr(float, "__getformat__") requires_getformat = unittest.skipUnless(have_getformat, ...
""" Test that 'stty -a' displays the same output before and after running the lldb command. """ from __future__ import print_function import lldb import six from lldbsuite.test.decorators import * from lldbsuite.test.lldbtest import * from lldbsuite.test import lldbutil class TestSTTYBeforeAndAfter(TestBase): mydir...
"""Classes that replace tkinter gui objects used by an object being tested. A gui object is anything with a master or parent paramenter, which is typically required in spite of what the doc strings say. """ class Event: '''Minimal mock with attributes for testing event handlers. This is not a gui object, but is...
import sys import matplotlib.pyplot as plt import numpy as np sys.path.append('../../') from util import readCSVToMatrix file_path = sys.argv[1] file = open(file_path) print file data = readCSVToMatrix(file, delimiter=',') print data fig, ax = plt.subplots(1) ax.fill_between(data[:,0], data[:,1]+data[:,2], data[:,1]-da...
import logging import os import tempfile import getpass import werkzeug.urls import werkzeug.exceptions from openid import oidutil from openid.store import filestore from openid.consumer import consumer from openid.cryptutil import randomString from openid.extensions import ax, sreg import openerp from openerp import S...
"""Support for Greenwave Reality (TCP Connected) lights.""" from datetime import timedelta import logging import os import greenwavereality as greenwave import voluptuous as vol from homeassistant.components.light import ( ATTR_BRIGHTNESS, PLATFORM_SCHEMA, SUPPORT_BRIGHTNESS, LightEntity, ) from homeass...
'''stream.py: module for defining Stream and Grouping for python topology''' import collections from heron.common.src.python.utils.misc import default_serializer from heron.proto import topology_pb2 class Stream(object): """Heron output stream It is compatible with StreamParse API. """ DEFAULT_STREAM_ID = "defa...
from oslo.config import cfg from oslo.db import exception as db_exc import sqlalchemy as sa from neutron.common import exceptions as exc from neutron.db import model_base from neutron.i18n import _LI, _LW from neutron.openstack.common import log from neutron.plugins.common import constants as p_const from neutron.plugi...
""" Copyright 2006 ThoughtWorks, Inc. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, softwar...
import pytest from thefuck.rules.git_not_command import match, get_new_command from tests.utils import Command @pytest.fixture def git_not_command(): return """git: 'brnch' is not a git command. See 'git --help'. Did you mean this? branch """ @pytest.fixture def git_not_command_one_of_this(): return """git: 'st...
'''tzinfo timezone information for US/Hawaii.''' from pytz.tzinfo import DstTzInfo from pytz.tzinfo import memorized_datetime as d from pytz.tzinfo import memorized_ttinfo as i class Hawaii(DstTzInfo): '''US/Hawaii timezone definition. See datetime.tzinfo for details''' zone = 'US/Hawaii' _utc_transition_ti...
""" *************************************************************************** lasthin.py --------------------- Date : September 2013 Copyright : (C) 2013 by Martin Isenburg Email : martin near rapidlasso point com ******************************************...
import traceback from ansible.module_utils.basic import AnsibleModule from ansible.module_utils.ovirt import ( check_sdk, create_connection, get_dict_of_struct, ovirt_full_argument_spec, ) ANSIBLE_METADATA = {'status': 'preview', 'supported_by': 'community', 'vers...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['stableinterface'], 'supported_by': 'certified'} DOCUMENTATION = r''' --- module: bigip_device_dns short_description: Manage BIG-IP devi...
test_names = [] test_sections = [] sample_types = [] descriptions = [] print_names = [] old_sort = [] uom = [] loinc_codes = [] sort_order = [] name_file = open('testName.txt','r') test_section_file = open("testSections.txt",'r') sample_type_file = open("sampleType.txt") uom_file = open("newUOM.txt", 'r') print_name_fi...
"""CSSImportRule implements DOM Level 2 CSS CSSImportRule plus the ``name`` property from http://www.w3.org/TR/css3-cascade/#cascading.""" __all__ = ['CSSImportRule'] __docformat__ = 'restructuredtext' __version__ = '$Id$' import cssrule import cssutils import os import urlparse import xml.dom class CSSImportRule(cssru...
from __future__ import division, print_function, unicode_literals from reportlab.lib.units import cm from reportlab.lib.pagesizes import A4, landscape from reportlab.lib.enums import TA_LEFT, TA_CENTER, TA_RIGHT from reportlab.lib.colors import HexColor from geraldo import ReportBand from geraldo import ObjectValue, La...
""" The sax module contains a collection of classes that provide a (D)ocument (O)bject (M)odel representation of an XML document. The goal is to provide an easy, intuitive interface for managing XML documents. Although, the term, DOM, is used above, this model is B{far} better. XML namespaces in suds are represented us...
import os import sys def _JoinPath(*path_parts): return os.path.abspath(os.path.join(*path_parts)) def _AddDirToPythonPath(*path_parts): path = _JoinPath(*path_parts) if os.path.isdir(path) and path not in sys.path: # Some call sites that use Telemetry assume that sys.path[0] is the # directory containing...
""" Custom version comparison filters for use in openshift-ansible """ from distutils.version import LooseVersion def legacy_gte_function_builder(name, versions): """ Build and return a version comparison function. Ex: name = 'oo_version_gte_3_1_or_1_1' versions = {'enterprise': '3.1', 'origin': '1....
"""Expose regular shell commands as services.""" from __future__ import annotations import asyncio from contextlib import suppress import logging import shlex import voluptuous as vol from homeassistant.core import HomeAssistant, ServiceCall from homeassistant.exceptions import TemplateError from homeassistant.helpers ...
from django.conf.urls import patterns # noqa from django.conf.urls import url # noqa from openstack_dashboard.dashboards.admin.images import views urlpatterns = patterns('openstack_dashboard.dashboards.admin.images.views', url(r'^images/$', views.IndexView.as_view(), name='index'), url(r'^create/$', views.Cre...
import locale def unicode_sorter(input): """ This function implements sort keys for the german language according to DIN 5007.""" # key1: compare words lowercase and replace umlauts according to DIN 5007 key1 = input.lower() key1 = key1.replace(u"ä", u"a") key1 = key1.replace(u"ö", u"o") key...
from __future__ import unicode_literals import frappe def before_install(): frappe.reload_doc("core", "doctype", "docfield") frappe.reload_doc("core", "doctype", "docperm") frappe.reload_doc("core", "doctype", "doctype") def after_install(): # reset installed apps for re-install frappe.db.set_global("installed_app...
from allmydata.util import mathutil # from the pyutil library """ Read and write chunks from files. Version 1.0.0. A file is divided into blocks, each of which has size L{BLOCK_SIZE} (except for the last block, which may be smaller). Blocks are encoded into chunks. One publishes the hash of the entire file. Clients ...
{ "name": "Product Variants", "version": "8.0.2.1.1", "depends": [ "product", ], "author": "OdooMRP team," "AvanzOSC," "Tecnativa", "contributors": [ "Oihane Crucelaegui <oihanecrucelaegi@avanzosc.es>", "Pedro M. Baeza <pedro.baeza@serviciosbae...
from __future__ import division, unicode_literals import os import re import sys import time import random from ..compat import compat_os_name from ..utils import ( decodeArgument, encodeFilename, error_to_compat_str, format_bytes, shell_quote, timeconvert, ) class FileDownloader(object): ""...
"""Support for monitoring the state of Digital Ocean droplets.""" import logging import voluptuous as vol from homeassistant.components.binary_sensor import ( DEVICE_CLASS_MOVING, PLATFORM_SCHEMA, BinarySensorEntity, ) from homeassistant.const import ATTR_ATTRIBUTION import homeassistant.helpers.config_vali...
import inspect from importlib import import_module from inspect import cleandoc from pathlib import Path from django.apps import apps from django.conf import settings from django.contrib import admin from django.contrib.admin.views.decorators import staff_member_required from django.contrib.admindocs import utils from ...
import numpy as np import time from operator import add import numpy as np import random from toolbox import * from models import * if __name__ == "__main__": hp = Parameters() with hp: batch_size = 256 test_batch_size = 256 load_model = False save_model = True debug = Fa...
import sys sys.path.insert(0, '.') from twisted.web.microdom import parseString from twisted.web.domhelpers import findNodesNamed from exe.engine.path import Path import json import re if __name__ == '__main__': files = {'lomVocab': Path('exe') / 'webui' / 'schemas' / 'scorm2004' / 'common' / 'vocabValues.xsd', ...
from django.conf import settings # noqa from django.forms import ValidationError # noqa from django import http from django.utils.translation import ugettext_lazy as _ # noqa from django.views.decorators.debug import sensitive_variables # noqa from horizon import exceptions from horizon import forms from horizon im...
'''Thread-safe version of Tkinter. Copyright (c) 2009, Allen B. Taylor This module is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This progra...
""" Tests for L{twisted.trial._dist.distreporter}. """ from twisted.python.compat import NativeStringIO as StringIO from twisted.trial._dist.distreporter import DistReporter from twisted.trial.unittest import TestCase from twisted.trial.reporter import TreeReporter class DistReporterTests(TestCase): """ Tests f...
def make_string(seq): str = '' for c in seq: # Screen out non-printing characters if 32 <= c and c < 256: str += chr(c) # If no printing chars if not str: return seq return str def make_string_uc(seq): code = seq[0:8] seq = seq[8:] # Of course, this is...
import distutils.sysconfig import sys import os import traceback from threading import Thread import time class reboot(Thread): def __init__ (self,api, target): Thread.__init__(self) self.api = api self.target = target def run(self): time.sleep(30) self.api.reboot(self.target) plib =...
import os import multiprocessing import random import signal import time from helpers import unittest, with_config import luigi.rpc import luigi.server from luigi.scheduler import CentralPlannerScheduler from tornado.testing import AsyncHTTPTestCase class ServerTestBase(AsyncHTTPTestCase): def get_app(self): ...
from ..data import BoletoData, custom_property class BoletoHsbc(BoletoData): ''' Gera Dados necessários para criação de boleto para o banco HSBC ''' numero_documento = custom_property('numero_documento', 13) def __init__(self): super(BoletoHsbc, self).__init__() self.codigo_banco...
import Gaffer import GafferScene Gaffer.Metadata.registerNode( GafferScene.Plane, "description", """ Produces scenes containing a plane. """, plugs = { "dimensions" : [ "description", """ The size of the plane in the X and Y directions. """, ], "divisions" : [ "description", """ The num...
import unittest from test import support import operator class Number: def __init__(self, x): self.x = x def __lt__(self, other): return self.x < other def __le__(self, other): return self.x <= other def __eq__(self, other): return self.x == other def __ne__(self, oth...
""" Test connections without the builtin ssl module Note: Import urllib3 inside the test functions to get the importblocker to work """ from ..test_no_ssl import TestWithoutSSL from dummyserver.testcase import ( HTTPDummyServerTestCase, HTTPSDummyServerTestCase) class TestHTTPWithoutSSL(HTTPDummyServerTestCase,...
""" Documents """ from __future__ import absolute_import from __future__ import print_function from __future__ import division from __future__ import unicode_literals from . import base class TargetProgrammerInfo(object): def __init__(self, root_dirs): self.target_programmer = None self.settings = b...
from __future__ import unicode_literals import re from .common import InfoExtractor from ..compat import compat_urllib_parse_unquote from ..utils import ( ExtractorError, int_or_none, parse_age_limit, parse_duration, ) class NRKBaseIE(InfoExtractor): _GEO_COUNTRIES = ['NO'] def _real_extract(sel...
"""Test configs for conv.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np import tensorflow.compat.v1 as tf from tensorflow.lite.testing.zip_test_utils import create_tensor_data from tensorflow.lite.testing.zip_test_utils import make_zip...
import urllib2 from cStringIO import StringIO import _response class GzipConsumer: def __init__(self, consumer): self.__consumer = consumer self.__decoder = None self.__data = "" def __getattr__(self, key): return getattr(self.__consumer, key) def feed(self, data): if...
import os from scrapy.command import ScrapyCommand from scrapy.utils.conf import arglist_to_dict from scrapy.exceptions import UsageError class Command(ScrapyCommand): requires_project = True def syntax(self): return "[options] <spider>" def short_desc(self): return "Run a spider" def ad...
from __future__ import print_function, division from sympy.core import Basic, Integer, Tuple, Dict, S, sympify from sympy.core.sympify import converter as sympify_converter from sympy.matrices.matrices import MatrixBase from sympy.matrices.dense import DenseMatrix from sympy.matrices.sparse import SparseMatrix, Mutable...
""" Django settings for {{ project_name }} project. For more information on this file, see https://docs.djangoproject.com/en/{{ docs_version }}/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/{{ docs_version }}/ref/settings/ """ import os BASE_DIR = os.path.dirname...
ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'network'} DOCUMENTATION = ''' --- module: nxos_vrrp extends_documentation_fragment: nxos version_added: "2.1" short_description: Manages VRRP configuration on NX-OS switches. description: -...
from . import purchase from . import sale
ENCODING = 'latin-1' STX = b'\x02' ETX = b'\x03' EOT = b'\x04' ENQ = b'\x05' ACK = b'\x06' NAK = b'\x15' ETB = b'\x17' LF = b'\x0A' CR = b'\x0D' CRLF = CR + LF RECORD_SEP = b'\x0D' # \r # FIELD_SEP = b'\x7C' # | # REPEAT_SEP = b'\x5C' # \ # COMPONENT_SEP = b'\x5E' # ^ # ESCAPE_SEP = b'\x26' # & #
from __future__ import absolute_import, division, print_function __metaclass__ = type import traceback from ansible.module_utils._text import to_native try: import ldap import ldap.sasl HAS_LDAP = True except ImportError: HAS_LDAP = False def gen_specs(**specs): specs.update({ 'bind_dn': dic...
from __future__ import absolute_import, division, print_function __metaclass__ = type ANSIBLE_METADATA = {'metadata_version': '1.1', 'status': ['preview'], 'supported_by': 'certified'} DOCUMENTATION = r''' --- module: bigiq_regkey_license_assignment short_description: Manage regk...
import fileinput import re import sys WARNING = '\033[93m' ENDC = '\033[0m' def myprint(*args): print(WARNING, filename + ":", ENDC,*args) def yield_line_and_islastline(f): global filename global linenumber try: prevline = next(f) filename = fileinput.filename() linenumber = file...
import binascii import os from django.conf import settings from django.db import models from django.utils.encoding import python_2_unicode_compatible from django.utils.translation import ugettext_lazy as _ @python_2_unicode_compatible class Token(models.Model): """ The default authorization token model. """...
__author__ = 'rochacbruno'
from pgi.clib.gir import GITypeTag, GIDirection, GITransfer, GIInfoType class CallbackArgument(object): TAG = None is_aux = False py_type = None def __init__(self, backend, info, type_, name): self.info = info self.name = name self.backend = backend self.type = type_ ...
""" Views for Instances and Volumes. """ from horizon import tabs from openstack_dashboard.dashboards.project.access_and_security \ import tabs as project_tabs class IndexView(tabs.TabbedTableView): tab_group_class = project_tabs.AccessAndSecurityTabs template_name = 'project/access_and_security/index.html'
from __future__ import division, print_function, absolute_import from numpy.testing import TestCase, run_module_suite, assert_equal, \ assert_array_almost_equal, assert_, assert_raises, assert_allclose import numpy as np from scipy.linalg import _flapack as flapack from scipy.linalg import inv try: from scipy.l...
"""Tests for tensorflow.ops.stack_ops.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import numpy as np from tensorflow.compiler.tests import xla_test from tensorflow.python.framework import dtypes from tensorflow.python.framework import ops from tensorf...
""" Strongly connected components. """ import networkx as nx __authors__ = "\n".join(['Eben Kenah', 'Aric Hagberg (hagberg@lanl.gov)' 'Christopher Ellison', 'Ben Edwards (bedwards@cs.unm.edu)']) __all__ = ['number_strongly_connected_components',...
def test(): print noname def foo(): try: test() except ValueError: raise RuntimeError("Accessing a undefined name should raise a NameError")
""" Split Test Block Transformer """ from openedx.core.lib.block_structure.transformer import BlockStructureTransformer, FilteringTransformerMixin class SplitTestTransformer(FilteringTransformerMixin, BlockStructureTransformer): """ A nested transformer of the UserPartitionTransformer that honors the block ...
from odoo import http from odoo.exceptions import AccessError from odoo.http import request class HrOrgChartController(http.Controller): _managers_level = 2 # FP request def _prepare_employee_data(self, employee): job = employee.sudo().job_id return dict( id=employee.id, ...
import os import optparse import sys import unittest USAGE = """%prog sdk_path test_path webtest_path Run unit tests for App Engine apps. sdk_path Path to the SDK installation. test_path Path to package containing test modules. webtest_path Path to the webtest library.""" def _WebTestIsInstalled(): try: im...
import mraa u = mraa.Uart(0) print u.getDevicePath()
"""Tests for cross entropy related functionality in tensorflow.ops.nn.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import math import numpy as np import tensorflow as tf exp = math.exp log = math.log class SigmoidCrossEntropyWithLogitsTest(tf.test.Test...
import subprocess, os, sys, re def shellCommand( command, cwd=None ): # The following line works with Python 2.7+ # return subprocess.check_output( command, shell=True, stderr=subprocess.STDOUT, cwd=cwd ) p = subprocess.Popen( command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, cwd=cwd ) p.wa...
class HelpHandler(object): def usage(self): return ''' This plugin will give info about Zulip to any user that types a message saying "help". This is example code; ideally, you would flesh this out for more useful help pertaining to your Zulip inst...
import sys, os curr_path = os.path.dirname(os.path.abspath(os.path.expanduser(__file__))) sys.path.append(os.path.join(curr_path, '../common/')) sys.path.insert(0, os.path.join(curr_path, '../../../python')) import models import get_data def assertRaises(expected_exception, func, *args, **kwargs): try: func...
import json import unittest import datetime from decimal import Decimal from twisted.internet import defer from scrapy.utils.serialize import ScrapyJSONEncoder from scrapy.http import Request, Response class JsonEncoderTestCase(unittest.TestCase): def setUp(self): self.encoder = ScrapyJSONEncoder() def ...
from .notifications import Notifications from .recordings import Recordings from twilio.rest.resources.call_feedback import ( CallFeedbackFactory, CallFeedbackSummary, ) from .util import normalize_dates, parse_date, transform_params from . import InstanceResource, ListResource class Call(InstanceResource): ...
import glob import os from cinder import exception from cinder.i18n import _ from cinder import test class ExceptionTestCase(test.TestCase): @staticmethod def _raise_exc(exc): raise exc() def test_exceptions_raise(self): # NOTE(dprince): disable format errors since we are not passing kwargs ...
from __future__ import unicode_literals import re from .common import InfoExtractor from ..utils import ( determine_ext, int_or_none, parse_iso8601, qualities, ) class NDRBaseIE(InfoExtractor): def _real_extract(self, url): mobj = re.match(self._VALID_URL, url) display_id = next(grou...
from neutron.api import extensions from neutron.api.v2 import attributes from neutron.api.v2 import base from neutron import manager RESOURCE_ATTRIBUTE_MAP = { 'network_profiles': { 'id': {'allow_post': False, 'allow_put': False, 'validate': {'type:regex': attributes.UUID_PATTERN}, ...