code
stringlengths
1
199k
''' Description: Created on 2016Äê5ÔÂ26ÈÕ @author: weihua @version: ''' from __future__ import division import pandas as pd import numpy as np import pandas.io.sql as sql from datetime import datetime from sklearn.linear_model import LogisticRegression from sklearn import cross_validation from sklearn import metrics fr...
import sys import os import cv2 from keras.models import load_model sys.path.append("/Users/alexpapiu/Documents/Conv/OpenCV_CNN") from webcam_cnn_pipeline import return_compiled_model_2, real_time_pred model_name = sys.argv[1] w = 1.5*144 h = 2*144 all_labels = {"model_hand":["A", "B", "C", "D", "No Hand"], ...
import json import operator import nova.scheduler from nova.scheduler.filters import abstract_filter class JsonFilter(abstract_filter.AbstractHostFilter): """Host Filter to allow simple JSON-based grammar for selecting hosts. """ def _op_compare(self, args, op): """Returns True if the specified ...
from os.path import join, dirname from setuptools import setup setup( name = 'xmppgcm', packages = ['xmppgcm'], # this must be the same as the name above version = '0.2.3', description = 'Client Library for Firebase Cloud Messaging using XMPP', long_description = open(join(dirname(__file__), 'README.txt')).re...
"""Base class for plugins.""" import os import sys import platform from os import access, F_OK from sys import stdout from time import sleep from subprocess import call from mbed_lstools.main import create from ..host_tests_logger import HtrunLogger class HostTestPluginBase: """Base class for all plugins used with ...
def italianhello(): i01.setHandSpeed("left", 0.60, 0.60, 1.0, 1.0, 1.0, 1.0) i01.setHandSpeed("right", 1.0, 1.0, 1.0, 1.0, 1.0, 1.0) i01.setArmSpeed("left", 1.0, 1.0, 1.0, 1.0) i01.setArmSpeed("right", 1.0, 1.0, 1.0, 1.0) i01.setHeadSpeed(0.65, 0.75) i01.moveHead(105,78) i01.moveArm("left",78,48,37,11) ...
""" The same MNIST ConvNet example, but with weights/activations visualization. """ import tensorflow as tf from tensorpack import * from tensorpack.dataflow import dataset IMAGE_SIZE = 28 def visualize_conv_weights(filters, name): """Visualize use weights in convolution filters. Args: filters: tensor c...
""" Misc stuff also needed for core imports and monkey patching """ import numpy as np from .core import (RVector3, R3Vector, RMatrix) def isScalar(v, val=None): """Check if v is scalar, i.e. int, float or complex. Optional compare with val. Examples -------- >>> import pygimli as pg >>> print(p...
import webob.exc from neutron.db import db_base_plugin_v2 from neutron.db import subnet_service_type_db_models from neutron.extensions import subnet_service_types from neutron.tests.unit.db import test_db_base_plugin_v2 class SubnetServiceTypesExtensionManager(object): def get_resources(self): return [] ...
""" Module with location helpers. detect_location_info and elevation are mocked by default during tests. """ import asyncio import collections import math from typing import Any, Dict, Optional, Tuple import aiohttp ELEVATION_URL = "https://api.open-elevation.com/api/v1/lookup" IP_API = "http://ip-api.com/json" IPAPI =...
import logging from google.appengine.ext import ndb from endpoints_proto_datastore.ndb.model import EndpointsModel, EndpointsAliasProperty class UserModel(EndpointsModel): email = ndb.StringProperty() name = ndb.StringProperty()
import telnetlib import subprocess import signal import time def signal_handler(signal, frame): pass # do nothing signal.signal(signal.SIGINT, signal.SIG_IGN) openocd = subprocess.Popen(["openocd"]) time.sleep(2) # Wait for this to start up signal.signal(signal.SIGINT, signal_handler) subprocess.call(["arm-none-eab...
""" Python Data Types used for the REST objects """ import json ETHERNET = ['ipv4', 'arp', 'rarp', 'snmp', 'ipv6', 'mpls_u', 'mpls_m', 'lldp', 'pbb', 'bddp'] VERSION = ['1.0.0', '1.1.0', '1.2.0', '1.3.0)'] ACTIONS = ['output', 'set_vlan_vid', 'set_vlan_pcp', 'strip_vlan', ...
import json from boxsdk.object.base_object import BaseObject from ..util.api_call_decorator import api_call class Comment(BaseObject): """An object that represents a comment on an item""" _item_type = 'comment' @staticmethod def construct_params_from_message(message: str) -> dict: message_type =...
import urllib from oslo_log import log as logging from oslo_serialization import jsonutils import requests import six LOG = logging.getLogger(__name__) class APIResponse(object): """Decoded API Response This provides a decoded version of the Requests response which include a json decoded body, far more conv...
"""Script to test TF-TRT INT8 conversion without calibration on Mnist model.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.compiler.tf2tensorrt.python.ops import trt_ops from tensorflow.core.protobuf import config_pb2 from tensorflow.pyth...
from ironicclient import exceptions from ironic_inspector import node_cache from ironic_inspector import utils def hook(introspection_data, **kwargs): ironic = utils.get_client() try: node = ironic.node.create(**{'driver': 'fake'}) except exceptions.HttpError as exc: raise utils.Error(_("Can...
"""Support for Aurora ABB PowerOne Solar Photvoltaic (PV) inverter.""" from __future__ import annotations from collections.abc import Mapping import logging from typing import Any from aurorapy.client import AuroraError, AuroraSerialClient from homeassistant.components.sensor import ( SensorDeviceClass, SensorE...
from tempest.api.object_storage import base from tempest.common import custom_matchers from tempest.common import utils from tempest.lib import decorators class CrossdomainTest(base.BaseObjectTest): @classmethod def resource_setup(cls): super(CrossdomainTest, cls).resource_setup() cls.xml_start ...
import base64 import copy import json import urllib import urlparse import uuid from keystone import config from keystone.common import dependency from keystone.contrib.oauth2 import core from keystone.tests import test_v3 CONF = config.CONF class OAuth2BaseTests(test_v3.RestfulTestCase): EXTENSION_NAME = 'oauth2' ...
import torch from ..builder import BBOX_ASSIGNERS from ..iou_calculators import build_iou_calculator from ..transforms import bbox_xyxy_to_cxcywh from .assign_result import AssignResult from .base_assigner import BaseAssigner @BBOX_ASSIGNERS.register_module() class UniformAssigner(BaseAssigner): """Uniform Matching...
np.random.seed(1234) fig, ax = plt.subplots(1) x = 30*np.random.randn(10000) mu = x.mean() median = np.median(x) sigma = x.std() textstr = '$\mu=%.2f$\n$\mathrm{median}=%.2f$\n$\sigma=%.2f$'%(mu, median, sigma) ax.hist(x, 50) props = dict(boxstyle='round', facecolor='wheat', alpha=0.5) ax.text(0.05, 0.95, textstr, tran...
from pants.backend.jvm.artifact import Artifact from pants.backend.jvm.ossrh_publication_metadata import ( Developer, License, OSSRHPublicationMetadata, Scm, ) from pants.backend.jvm.repository import Repository as repo from pants.backend.jvm.scala_artifact import ScalaArtifact from pants.backend.jvm.su...
"""The volumes snapshots api.""" import webob from webob import exc from cinder.api import common from cinder.api.openstack import wsgi from cinder.api.v1 import volumes from cinder.api import xmlutil from cinder import exception from cinder.openstack.common import log as logging from cinder.openstack.common import str...
import pytest import doctest from insights.parsers import docker_inspect, SkipException from insights.tests import context_wrap DOCKER_CONTAINER_INSPECT = """ [ { "Id": "97d7cd1a5d8fd7730e83bb61ecbc993742438e966ac5c11910776b5d53f4ae07", "Created": "2016-06-23T05:12:25.433469799Z", "Path": "/bin/bash", "...
import os import sys import mock import time import random import shutil import contextlib import tempfile import binascii import platform import select import datetime from io import BytesIO from subprocess import Popen, PIPE from dateutil.tz import tzlocal import unittest from nose.tools import assert_equal import bo...
""" Ex 1. Construct a script that retrieves NAPALM facts from two IOS routers, two Arista switches, and one Junos device. pynet-rtr1 (Cisco IOS) 184.105.247.70 pynet-rtr2 (Cisco IOS) 184.105.247.71 pynet-sw1 (Arista EOS) 184.105.247.72 pynet-sw2 (Arista EOS) 184.105.247.73 ​juniper-srx 184.105...
"""Utilities and helper functions.""" import contextlib import datetime import functools import hashlib import hmac import inspect import os import pyclbr import random import re import shutil import socket import struct import sys import tempfile from xml.sax import saxutils import eventlet import netaddr from oslo_co...
from __future__ import unicode_literals from caniusepython3 import command from caniusepython3.test import unittest, skip_pypi_timeouts from distutils import dist def make_command(requires): return command.Command(dist.Distribution(requires)) class RequiresTests(unittest.TestCase): def verify_cmd(self, requirem...
import fractions import math print('PI =', math.pi) f_pi = fractions.Fraction(str(math.pi)) print('No limit =', f_pi) for i in [1, 6, 11, 60, 70, 90, 100]: limited = f_pi.limit_denominator(i) print('{0:8} = {1}'.format(i, limited))
import sqlite3 conn = sqlite3.connect('accesslist.db') conn.execute('''CREATE TABLE USUARIO (CELLPHONE CHAR(11) PRIMARY KEY NOT NULL, PASSWD CHAR(138) NOT NULL);''') print "Table created successfully"; conn.close()
import random import requests import shutil import logging import os import traceback import ujson from typing import List, Dict, Any, Optional, Set, Callable, Iterable, Tuple, TypeVar from django.forms.models import model_to_dict from zerver.models import Realm, RealmEmoji, Subscription, Recipient, \ Attachment, S...
from unittest import mock import testtools from designate import context from designate import exceptions from designate import policy import designate.tests class TestDesignateContext(designate.tests.TestCase): def test_deepcopy(self): orig = context.DesignateContext( user_id='12345', project_i...
"""Contains convenience wrappers for typical Neural Network TensorFlow layers. Additionally it maintains a collection with update_ops that need to be updated after the ops have been computed, for exmaple to update moving means and moving variances of batch_norm. Ops that have different behavior during train...
__version__='0.2.1' import argparse import logging import os import os.path import sys import requests import getpass import ConfigParser def _persist( export, rcfile ): f = open( rcfile, 'w' ) logging.debug( "writing to {}".format( rcfile ) ) f.write( "\n".join( export ) ) f.close() os.chmod( rcfil...
"""ResNet model family.""" import functools import haiku as hk import jax import jax.numpy as jnp from nfnets import base class ResNet(hk.Module): """ResNetv2 Models.""" variant_dict = {'ResNet50': {'depth': [3, 4, 6, 3]}, 'ResNet101': {'depth': [3, 4, 23, 3]}, 'ResNet152': {'dep...
import os from kubernetes import client from kfserving import ( constants, KFServingClient, V1beta1InferenceService, V1beta1InferenceServiceSpec, V1beta1PredictorSpec, V1beta1TorchServeSpec, ) from kubernetes.client import V1ResourceRequirements from ..common.utils import predict from ..common.u...
import os basedir=os.path.abspath(os.path.dirname(__file__))#get basedir of the project WTF_CSRF_ENABLED = True SECRET_KEY = 'you-will-guess' SQLALCHEMY_DATABASE_URI = "mysql://username:password@server_ip:port/database_name" SQLALCHEMY_MIGRATE_REPO = os.path.join(basedir, 'db_repository') UPLOAD_FOLDER = basedir+'/uplo...
from tempest.api.object_storage import base from tempest import config from tempest.lib.common.utils import data_utils from tempest.lib import decorators from tempest.lib import exceptions as lib_exc CONF = config.CONF class ObjectACLsNegativeTest(base.BaseObjectTest): """Negative tests of object ACLs""" creden...
"""Test the data reference resolver.""" import base64 import responses from drydock_provisioner.statemgmt.design.resolver import ReferenceResolver class TestClass(object): def test_resolve_file_url(self, input_files): """Test that the resolver will resolve file URLs.""" input_file = input_files.join...
__author__ = 'ray' import wave import numpy as np wav_1_path = "origin.wav" wav_2_path = "clap.wav" wav_out_path = "mixed.wav" wav_1 = wave.open(wav_1_path, 'rb') wav_2 = wave.open(wav_2_path, 'rb') wav_out = wave.open(wav_out_path, 'wb') len_1 = wav_1.getnframes() len_2 = wav_2.getnframes() if len_1>len_2: wav_out...
"""Unit tests.""" import pytest from google.rpc import status_pb2 from google.cloud import videointelligence_v1beta2 from google.cloud.videointelligence_v1beta2.proto import video_intelligence_pb2 from google.longrunning import operations_pb2 class MultiCallableStub(object): """Stub for the grpc.UnaryUnaryMultiCall...
import asyncio from functools import partial class AsyncWrapper: def __init__(self, target_instance, executor=None): self._target_inst = target_instance self._loop = asyncio.get_event_loop() self._executor = executor def __getattribute__(self, name): try: return super...
"""Module containing methods needed to load skill data such as dialogs, intents and regular expressions. """ from os import walk from os.path import splitext, join import re from mycroft.messagebus.message import Message def load_vocab_from_file(path, vocab_type, bus): """Load Mycroft vocabulary from file The v...
import argparse import sys from a_sync import block from paasta_tools.mesos.exceptions import MasterNotAvailableException from paasta_tools.mesos_tools import get_mesos_master from paasta_tools.metrics.metastatus_lib import assert_frameworks_exist def parse_args(): parser = argparse.ArgumentParser() parser.add_...
""" @author waziz """ import logging import sys import traceback import os import argparse import numpy as np from functools import partial from multiprocessing import Pool from chisel.decoder import MBR, MAP, consensus from chisel.util.iotools import read_sampled_derivations, read_block, list_numbered_files from chise...
import unittest from google.appengine.api import files from google.appengine.ext import db from mapreduce import control from mapreduce import model from mapreduce import output_writers from mapreduce import test_support from testlib import testutil BLOBSTORE_WRITER_NAME = (output_writers.__name__ + "." + ...
import binascii import netaddr from oslo_log import log as logging from oslo_utils import excutils from neutron.agent.l3 import dvr_fip_ns from neutron.agent.l3 import router_info as router from neutron.agent.linux import ip_lib from neutron.common import constants as l3_constants from neutron.common import exceptions ...
class CGpm(object): """Interface for composable generative population models. Composable generative population models provide a computational abstraction for multivariate probability densities and stochastic samplers. """ def __init__(self, outputs, inputs, schema, rng): """Initialize the CG...
import unittest import os import tempfile from yotta.lib.fsutils import mkDirP, rmRf from yotta.lib.detect import systemDefaultTarget from yotta.lib import component from .cli import cli Test_Files = { '.yotta_ignore': ''' /moo b/c/d b/c/*.txt /a/b/test.txt b/*.c /source/a/b/test.txt /test/foo sometest/a someothert...
"""Gauge watcher configuration.""" from copy import deepcopy from faucet.conf import Conf class WatcherConf(Conf): """Gauge watcher configuration.""" db = None # pylint: disable=invalid-name dp = None # pylint: disable=invalid-name prom_client = None defaults = { 'name': None, 'type'...
from __future__ import unicode_literals from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('person', '0049_patient_photo'), ] operations = [ migrations.RenameField( model_name='patient', old_name='photo', new_name='pi...
"""Tests for grr.lib.flows.general.services.""" from grr.lib import aff4 from grr.lib import rdfvalue from grr.lib import test_lib class ServicesTest(test_lib.FlowTestsBaseclass): def testEnumerateRunningServices(self): class ClientMock(object): def EnumerateRunningServices(self, _): service = rdfva...
"""Converting BAM to BEDPE and normalized BigWig files.""" import os from resolwe.process import ( Cmd, DataField, FileField, FloatField, Process, SchedulingClass, StringField, ) class BamToBedpe(Process): """Takes in a BAM file and calculates a normalization factor in BEDPE format. ...
from enum import Enum from math import * __version__ = "0.3.0" LIBCELLML_VERSION = "0.2.0" STATE_COUNT = 1 VARIABLE_COUNT = 2 class VariableType(Enum): VARIABLE_OF_INTEGRATION = 1 STATE = 2 CONSTANT = 3 COMPUTED_CONSTANT = 4 ALGEBRAIC = 5 VOI_INFO = {"name": "time", "units": "second", "component": "...
import rospy import math from std_msgs.msg import String from geometry_msgs.msg import Twist key_mapping = { 'w': [ 0, 1], 'x': [ 0, -1], 'a': [ 1, 0], 'd': [-1, 0], 's': [ 0, 0] } g_twist_pub = None g_target_twist = None g_last_twist = None g_last_send_time = None g_vel_scales = [0.1, ...
from tm import TuringMachine class TuringMachineBuilder: """ Creates a turing machine step by step by retrieving all the necessary information. By default (can be specified) sets the halt state to 'HALT and the blank symbol to '#' """ def __init__(self): """ Initialize a new ...
import mock import six import yaml from oslo_config import fixture as fixture_config from oslo_utils import fileutils from oslotest import mockpatch from ceilometer import declarative from ceilometer.hardware.inspector import base as inspector_base from ceilometer.hardware.pollsters import generic from ceilometer impor...
from django.contrib import admin from django.core.urlresolvers import NoReverseMatch from . import models class WPSiteAdmin(admin.ModelAdmin): list_display = ('name', 'url', 'hook') readonly_fields = ('name', 'description') def save_model(self, request, obj, form, change): # TODO do this sync async ...
from __future__ import division from __future__ import print_function from transformer_layers import TransformerBlock import tensorflow as tf def mean_pool(x, m): m = tf.cast(m, tf.float32) x = tf.multiply(x, tf.expand_dims(m, 2)) x = tf.reduce_sum(x, 1) / tf.reduce_sum(m, 1, keepdims=True) return x class RNN(o...
""" pygments.styles.sas ~~~~~~~~~~~~~~~~~~~ Style inspired by SAS' enhanced program editor. Note This is not meant to be a complete style. It's merely meant to mimic SAS' program editor syntax highlighting. :copyright: Copyright 2006-2021 by the Pygments team, see AUTHORS. :license: BSD, see...
from JumpScale9 import j redisFound = False try: from .Redis import Redis from .RedisQueue import RedisQueue from redis._compat import nativestr # import itertools import socket redisFound = True except: pass import os import time from JumpScale9 import tcpPortConnectionTest from JumpScale9....
""" Enum implementation. """ __all__ = ["Enum", "EnumType", "EnumValueGenerator", "Flags", "IntEnum"] import inspect import sys from . import helpers from . import inspection _no_default = helpers.MarkerObject("no_default @ enums") class EnumType(type): """Metaclass for all enum types.""" def __init__(cls, what...
""" Provider info for Azure """ from perfkitbenchmarker import provider_info from perfkitbenchmarker import benchmark_spec class AzureProviderInfo(provider_info.BaseProviderInfo): UNSUPPORTED_BENCHMARKS = ['mysql_service'] CLOUD = benchmark_spec.AZURE
import sys import io import re import urllib import urllib2 import urlparse import lxml.etree def get_outlinks(url): ''' url: the url to the page to crawl ''' result = [] if url is None: return result html = None resp = None try: url = url.strip() resp = urllib2.urlopen(url) if resp.code...
import logging from datetime import timedelta from core import Feed import pandas as pd from core.observables import Ip, Observable from core.errors import ObservableValidationError class ThreatFox(Feed): default_values = { "frequency": timedelta(hours=1), "name": "ThreatFox", "source": "htt...
"""Module to train sequence model. Vectorizes training and validation texts into sequences and uses that for training a sequence model - a sepCNN model. We use sequence model for text classification when the ratio of number of samples to number of words per sample for the given dataset is very large (>~15K). """ from _...
try: from setuptools import setup except ImportError: from ez_setup import use_setuptools use_setuptools() from setuptools import setup import sys test_suite = "tests" tests_require = ["mongo-orchestration >= 0.2, < 0.4", "requests >= 2.5.1"] if sys.version_info[:2] == (2, 6): # Need unittest2 to ru...
import sys import os import pkg_resources extensions = [ 'sphinx.ext.autodoc', 'sphinx.ext.viewcode', ] templates_path = ['_templates'] source_suffix = '.rst' master_doc = 'index' project = u'Scan PDF' copyright = u'2014, Virantha N. Ekanayake' version = '' try: release = pkg_resources.get_distribution('sca...
"""A base class for all codecs using encode-to-file.""" import encoder import filecmp import json import os import re import subprocess class FileCodec(encoder.Codec): """Base class for file-using codecs. Subclasses MUST define: - EncodeCommandLine - DecodeCommandLine - ResultData """ def __init__(self, n...
import pytest import logging from dtest import Tester from tools.data import rows_to_list since = pytest.mark.since logger = logging.getLogger(__name__) @since('3.0') class TestStressSparsenessRatio(Tester): """ @jira_ticket CASSANDRA-9522 Tests for the `row-population-ratio` parameter to `cassandra-stress`...
import os import sys import sqlite3 import re import itertools import collections import json import abc import re import numpy as np import gemini_utils as util from gemini_constants import * from gemini_utils import OrderedSet, OrderedDict, itersubclasses, partition import compression from sql_utils import ensure_col...
""" Glance Image Cache Pre-fetcher This is meant to be run from the command line after queueing images to be pretched. """ import os import sys possible_topdir = os.path.normpath(os.path.join(os.path.abspath(sys.argv[0]), os.pardir, os.pardir)) if os...
from utils.header import MagicField, Field from load_command import LoadCommandHeader, LoadCommandCommand class PrebindCksumCommand(LoadCommandHeader): ENDIAN = None FIELDS = ( MagicField('cmd', 'I', {LoadCommandCommand.COMMANDS['LC_DYSYMTAB']: 'LC_DYSYMTAB'}), Field('cmdsize', 'I'), Fie...
import pyquil.forest as qvm_endpoint from pyquil.quil import Program from pyquil.quilbase import DirectQubit from pyquil.gates import I, X, Y, Z, H, T, S, RX, RY, RZ, CNOT, CCNOT, PHASE, CPHASE00, CPHASE01, \ CPHASE10, CPHASE, SWAP, CSWAP, ISWAP, PSWAP, MEASURE, HALT, WAIT, NOP, RESET, \ TRUE, FALSE, NOT, AND, ...
"""Function call retry utility.""" import time from typing import Any, Callable, Mapping, Optional, Sequence, Type, TypeVar from gazoo_device import errors def _default_is_successful(_: Any) -> bool: return True def not_func(val: Any) -> bool: """Returns True if bool(val) evaluates to False.""" return not bool(va...
from collections import namedtuple import tvm from tvm import relay from tvm.relay import quantize as qtz import mxnet as mx from mxnet import gluon import logging import os logging.basicConfig(level=logging.INFO) Config = namedtuple('Config', ['model', 'nbit_input', 'dtype_input', 'nbit_output', 'dtype_output', 'glob...
import pymongo from pymongo import MongoClient from pymongo import errors import re class Database(object): '''Database creation''' def __init__(self, database_name): self.client = MongoClient('mongodb://localhost,localhost:27017') self.db_name = database_name self.db = self.client[self.db_name] #self.jobs = ...
DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS import os if 'SERVER_SOFTWARE' in os.environ: from sae.const import ( MYSQL_HOST, MYSQL_PORT, MYSQL_USER, MYSQL_PASS, MYSQL_DB ) else: # Make `python manage.py syncdb` works happy! M...
import os import subprocess import sys deltext="" if sys.platform.startswith("linux") : deltext="rm" copytext="cp" if sys.platform.startswith("darwin") : deltext="rm" copytext="cp" if sys.platform.startswith("win") : deltext="del" copytext="copy" def run_in_shell(cmd): subprocess.check_call(cmd, shell=True)...
ghost = Runtime.start("ghost", "WebGui") ear = Runtime.start("ear", "WebkitSpeechRecognition") ghostchat = Runtime.start("ghostchat", "ProgramAB") htmlfilter = Runtime.start("htmlfilter", "HtmlFilter") mouth = Runtime.start("mouth", "NaturalReaderSpeech") ear.addTextListener(ghostchat) ghostchat.addTextListener(htmlfil...
from __future__ import unicode_literals import json import unittest from mopidy.models import ( Album, Artist, ModelJSONEncoder, Playlist, Ref, SearchResult, TlTrack, Track, model_json_decoder) class GenericCopyTest(unittest.TestCase): def compare(self, orig, other): self.assertEqual(orig, other) ...
from oauth2client.service_account import ServiceAccountCredentials from googleapiclient.discovery import build from google.oauth2 import service_account from common.methods import set_progress from infrastructure.models import CustomField, Environment from pathlib import Path import json, tempfile import os import zipf...
""" Created on Thu Apr 27 13:35:59 2017 @author: mkammoun.lct """ import numpy as np import matplotlib.pyplot as pl from bisect import bisect import math n=200 n2=10000 def per(theta,n): perm=[] for i in range(1,n+1): if np.random.binomial(1,theta/(float(theta)+i-1))==1: perm.append(i) ...
""" This code was Ported from CPython's sha512module.c """ import _struct as struct SHA_BLOCKSIZE = 128 SHA_DIGESTSIZE = 64 def new_shaobject(): return { 'digest': [0]*8, 'count_lo': 0, 'count_hi': 0, 'data': [0]* SHA_BLOCKSIZE, 'local': 0, 'digestsize': 0 } ROR64...
""" .. module: security_monkey.watchers.keypair :platform: Unix .. version:: $$VERSION$$ .. moduleauthor:: Mike Grima <mgrima@netflix.com> """ import json from security_monkey.decorators import record_exception from security_monkey.decorators import iter_account_region from security_monkey.watcher import Watcher, C...
""" Client side of the scheduler manager RPC API. """ from oslo.config import cfg from nova.openstack.common import jsonutils import nova.openstack.common.rpc.proxy rpcapi_opts = [ cfg.StrOpt('scheduler_topic', default='scheduler', help='the topic scheduler nodes listen on'), ] CONF = ...
""" Django settings for login project. """ from django.core.urlresolvers import reverse_lazy DEBUG = True TESTING = False SESSION_COOKIE_SECURE = False CSRF_COOKIE_SECURE = False SITE_NAME = 'app_login' ADMINS = ( ('admin', 'code@pkimber.net'), ) MANAGERS = ADMINS TIME_ZONE = 'Europe/London' LANGUAGE_CODE = 'en-gb'...
from unittest import TestCase from unittest.mock import patch, MagicMock import sqlalchemy as sa from sqlalchemy.orm import Session from sqlalchemy.ext.declarative import declarative_base from crate.client.cursor import Cursor fake_cursor = MagicMock(name='fake_cursor') FakeCursor = MagicMock(name='FakeCursor', spec=Cu...
from __future__ import unicode_literals import boto import copy import itertools import re import six from collections import defaultdict from datetime import datetime from boto.ec2.instance import Instance as BotoInstance, Reservation from boto.ec2.blockdevicemapping import BlockDeviceMapping, BlockDeviceType from bot...
import weakref from oslo.config import cfg from neutron.agent.common import config from neutron.agent import rpc as agent_rpc from neutron.common import constants from neutron import context from neutron.openstack.common import importutils from neutron.openstack.common import log as logging from neutron.openstack.commo...
from base import TestPscan import errno import mock from StringIO import StringIO import sys class TestScan(TestPscan): @mock.patch('socket.socket.connect') def test_tcp_port_open(self, mock_connect): hosts = "127.0.0.1" ports = "22" mock_connect.return_value = None scanner = sel...
import urllib2 import sys import simplejson as json import ConfigParser import signal import time CONF_FILE = '/etc/check_api.conf' plugin_name = "check-api-contrail-9081" plugin_instance = "lma-contrail-extension" plugin_interval = 90 plugin_type = 'gauge' plugin_request = 'active' url = "http://127.0.0.1:9081" class ...
from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('transactions', '0001_initial'), ] operations = [ migrations.AddField( model_name='transaction', name='response', fiel...
"""Errors for the Python logging handlers.""" class RecoverableError(Exception): """A special error case we'll ignore.""" pass
from scipy.integrate import cumtrapz from scipy.interpolate import griddata from scipy.stats import lognorm from scipy.optimize import curve_fit import numpy as np def fitLogNormParticleDistribution(D10, D50, D90): ''' Fitting function to get the mu and sigma -parameters of the Log-normal distribution from ...
""" Data access functions to read from and write to the SQLite backend. """ import sqlite3 import codecs import os import re def setup_db(): dbpath = os.path.dirname(os.path.realpath(__file__)) + os.sep +".."+os.sep+"gitdox.db" conn = sqlite3.connect(dbpath) cur = conn.cursor() # Drop tables if they exist cur.exec...
import collections from pyramid.view import view_defaults, view_config from kubb_match.data.models import Round @view_defaults(request_method='GET', accept='text/html') class HtmlView(object): def __init__(self, request): self.request = request self.data_manager = request.data_managers['data_manager...
from requests import HTTPError from database import Database import simplejson as json db = Database.getDatabaseConnection()["cras"] from log_session import LogSession import datetime class DB: def __init__(self): pass @staticmethod def add_user(user_id, user_name, mail,picture,fcm_token): p...
import ConfigParser as configparser import os import sys from pyspark import SparkContext, SparkConf, SparkFiles from pyspark.sql import SQLContext, Row from datetime import datetime from os_utils import make_directory, preparing_path, time_execution_log, check_file_exists from subprocess import Popen, PIPE from vina_u...