code
stringlengths
1
199k
"""Test custom node separator.""" import six from nose.tools import eq_ import anytree as at from helper import assert_raises class MyNode(at.Node): separator = "|" def test_render(): """Render string cast.""" root = MyNode("root") s0 = MyNode("sub0", parent=root) MyNode("sub0B", parent=s0) MyNo...
"""Support for Zigbee Home Automation devices.""" import asyncio import logging import voluptuous as vol from zhaquirks import setup as setup_quirks from zigpy.config import CONF_DEVICE, CONF_DEVICE_PATH from homeassistant import config_entries, const as ha_const from homeassistant.core import HomeAssistant import home...
"""Resolwe data serializer.""" from django.contrib.auth.models import AnonymousUser from rest_framework import serializers from resolwe.flow.models import Data, Process from resolwe.permissions.shortcuts import get_objects_for_user from resolwe.rest.fields import ProjectableJSONField from .base import ResolweBaseSerial...
""" Test the salt mine system """ import pprint import time import pytest import salt.utils.platform from tests.support.case import ModuleCase, ShellCase from tests.support.runtests import RUNTIME_VARS @pytest.mark.windows_whitelisted @pytest.mark.usefixtures("salt_sub_minion") class MineTest(ModuleCase, ShellCase): ...
import sys import pytest import tvm from tvm import tir from tvm.script import tir as T from tvm.tir.schedule.state import CachedFlags from tvm.tir.stmt_functor import post_order_visit @T.prim_func def elementwise(a: T.handle, c: T.handle) -> None: A = T.match_buffer(a, (128, 128), "float32") C = T.match_buffer...
import pylab as plt from autograd import numpy as np from autograd import grad import time import numpy as numpy import pylab as plt import seaborn as snb import pandas as pd import os from sklearn.preprocessing import StandardScaler def plot_summary(x, s, interval=95, num_samples=100, sample_color='k', sample_alpha=0....
from zstacklib.utils import jsonobject from zstacklib.utils import log from zstacklib.utils import shell from zstacklib.utils import http logger = log.get_logger(__name__) class AgentResponse(object): def __init__(self, success=True, error=None): self.success = success self.error = error if error el...
"""Defines neural_structured_learning version information.""" _MAJOR_VERSION = '1' _MINOR_VERSION = '3' _PATCH_VERSION = '1' _VERSION_SUFFIX = '' __version__ = '.'.join([_MAJOR_VERSION, _MINOR_VERSION, _PATCH_VERSION]) if _VERSION_SUFFIX: __version__ = '{}-{}'.format(__version__, _VERSION_SUFFIX)
import zstackwoodpecker.test_state as ts_header import os TestAction = ts_header.TestAction def path(): return dict(initial_formation="template5", checking_point=8, path_list=[ [TestAction.create_vm, 'vm1', ], [TestAction.create_volume, 'volume1', 'flag=scsi'], [TestAction.attach_volume, 'vm1', 'volume1'], ...
import json from django.shortcuts import redirect from django.conf import settings from django import http from editor.models import Resource def upload_resource(request, **kwargs): if request.method != 'POST': return http.HttpResponseNotAllowed(['POST']) file = request.FILES['files[]'] r = Resource...
''' JSON related utilities. This module provides a few things: 1) A handy function for getting an object down to something that can be JSON serialized. See to_primitive(). 2) Wrappers around loads() and dumps(). The dumps() wrapper will automatically use to_primitive() for you if needed. 3) This s...
"""URL encode / decode provided string. Examples: $ python urlencode.py "http://example.com/data/mydata?row=24" http://example.com/data/mydata?row%3D24 $ python urlencode.py -d "http://example.com/data/mydata?row%3D24" http://example.com/data/mydata?row=24 $ python urlencode.py -p "http://example.com/data/myd...
""" Trust Region Policy Optimization (TRPO) --------------------------------------- PG method with a large step can collapse the policy performance, even with a small step can lead a large differences in policy. TRPO constraint the step in policy space using KL divergence (rather than in parameter space), which can mon...
import subprocess, os, sys curlybrace1="{" curlybrace2="}" def add_forwd_record(): host_name_to_be_added= sys.argv[1] ip_addr_to_be_added= sys.argv[2] forwd_zone_file_path="/etc/bind/zones/db.cfy.org" forwd_zone_content = open(forwd_zone_file_path, 'a') forwd_zone_content.write("\n%s. \tIN \t A \t %s" % (host_name...
import os import pwd import uuid from oslo_config import cfg from eventlet.green import subprocess from st2common import log as logging from st2actions.runners import ActionRunner from st2actions.runners import ShellRunnerMixin from st2common.models.system.action import ShellCommandAction from st2common.models.system.a...
""" Downloads the example datasets for running the examples. """ import os import sys import hashlib import zipfile try: import requests except ImportError: print(( "The requests module is required to download data --\n" "please install it with pip install requests." )) sys.exit(1) DATAS...
"""Configuration and hyperparameter sweeps.""" from lra_benchmarks.image.configs.cifar10 import base_cifar10_config def get_config(): """Get the hyperparameter configuration.""" config = base_cifar10_config.get_config() config.model_type = "transformer" config.model.num_layers = 1 config.model.classifier_pool...
''' Created on Jun 18, 2012 Testing views. Each of these views is referenced in urls.py @author: Sjoerd ''' import pdb import mimetypes import logging from itertools import chain from os import path from django import forms from django.db import models from django.conf import settings from django.contrib.admin.options ...
import copy import re from oslo_config import cfg from six.moves import urllib versions_opts = [ cfg.StrOpt('public_endpoint', help="Public url to use for versions endpoint. The default " "is None, which will use the request's host_url " "attribute to populate ...
from django.conf.urls.defaults import patterns, url from feed import BookmarkFeed urlpatterns = patterns('', url(r'^/my/import/$', 'bookmark.views.import_bookmark', name='import_bookmark'), url(r'^/my/deleteall/$', 'bookmark.views.delete_all_bookmarks', name='delete_all_bookmarks'), url(r'^/my/export/$', 'b...
import signal from indicator import Indicator import unittest def run(): signal.signal(signal.SIGINT, signal.SIG_DFL) Indicator().run_forever() if __name__ == "__main__": run()
from oslo_log import log as logging from heat.common import exception from heat.common.i18n import _ from heat.common.i18n import _LI from heat.common.i18n import _LW from heat.engine import attributes from heat.engine import constraints from heat.engine import properties from heat.engine import resource from heat.engi...
import robocup import constants import main import evaluation.passing import evaluation.chipping def generate_default_rectangle(kick_point): offset_from_edge = 0.25 offset_from_ball = 0.4 # offset_from_ball = 0.7 if kick_point.x > 0: # Ball is on right side of field toReturn = robocup.Re...
import os import sys if 'USE_SETUPTOOLS' in os.environ or 'setuptools' in sys.modules: from setuptools import setup else: from distutils.core import setup NAME = 'dflow' DESC = ('flow programmign concepts') _locals = {} with open('dflow/version.py') as fp: exec(fp.read(), None, _locals) VERSION = _locals['_...
import logging from colorama import Fore, Style class BaseStatsLogger(object): """Base class for logging realtime events""" def __init__(self, prefix="superset"): self.prefix = prefix def key(self, key): if self.prefix: return self.prefix + key return key def incr(sel...
"""The main OpenHTF entry point.""" import argparse import collections import copy import functools import inspect import itertools import json import logging import pkg_resources import signal import socket import sys import textwrap import threading from types import LambdaType import uuid import weakref from openhtf...
from __future__ import absolute_import from builtins import object from . import offline from .views import offline_view try: # Django 1.10 from django.utils.deprecation import MiddlewareMixin except ImportError: # Django <1.10 class MiddlewareMixin(object): def __init__(self, get_response=None)...
import operator from pattern_position import * def log(args): if type(args) == list: print() print(*args, sep='\n') print() else: print(args) debug_enabled = False def debug(args): if debug_enabled: log(args) info_enabled = False def info(args): if info_enabled: log(args)...
"""Operations for automatic batching and unbatching.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function from tensorflow.python.eager import function from tensorflow.python.framework import ops from tensorflow.python.framework import tensor_spec from tensorflo...
"""Faster R-CNN meta-architecture definition. General tensorflow implementation of Faster R-CNN detection models. See Faster R-CNN: Ren, Shaoqing, et al. "Faster R-CNN: Towards real-time object detection with region proposal networks." Advances in neural information processing systems. 2015. We allow for two modes: fir...
import yaml from collections import OrderedDict def order_rep(dumper, data): """ YAML Dumper to represent OrderedDict """ return dumper.represent_mapping(u'tag:yaml.org,2002:map', data.items(), flow_style=False) yaml.add_representer(OrderedDict, order_rep) def pretty_yaml(val...
from InsertNewAB import InsertNewAB if __name__ == '__main__': xml_path = u'D:\InsertNewAB\paths.xml' inab = InsertNewAB(xml_path=xml_path) inab.remove_files() inab.copy_files() inab.generate_script()
from __future__ import (absolute_import, division, generators, nested_scopes, print_function, unicode_literals, with_statement) import os from pants.backend.jvm.tasks.classpath_products import ClasspathProducts from pants.util.dirutil import safe_file_dump, safe_mkdir, safe_mkdtemp from pants_te...
from django.utils.translation import ugettext_lazy as _ import horizon class BasePanels(horizon.PanelGroup): slug = "compute" name = _("Manage Compute") panels = ('overview', 'instances', 'images_and_snapshots', 'access_and_security') class ObjectStorePanels(horizon...
""" Kerberos authentication module. This implements two authentication modes: 1. An alternative to password based BASIC authentication in which the BASIC credentials are verified against Kerberos. 2. The NEGOTIATE mechanism (as defined in http://www.ietf.org/rfc/rfc4559.txt) that implements full...
input = """ c(1) | c(2) | c(3). d(1) | d(2) | d(3). e(1) | e(2) | e(3). a(X) :- c(X). b(Y) :- d(Y). okay :- 0<#count{V :a(V)} <3. okay1 :- 0<#count{V :a(V)} <2. okay2 :-0<#count{V :b(V)} <3. okay3 :-0<#count{V :e(V)} <3. """ output = """ c(1) | c(2) | c(3). d(1) | d(2) | d(3). e(1) | e(2) | e(3). a(X) :- c(X). b(Y) :- ...
from __future__ import absolute_import from .factory import toolkit_factory myTabularEditor = toolkit_factory('tabular_editor', 'myTabularEditor')
""" Building emails to send asynchronously, via cron job or scheduler """ from portality import app_email from portality.core import app from portality.tasks import async_workflow_notifications import time def send_emails(emails_dict): for (email, (to_name, paragraphs)) in emails_dict.items(): time.sleep(0....
""" A class that describes the location of an image in Glance. In Glance, an image can either be **stored** in Glance, or it can be **registered** in Glance but actually be stored somewhere else. We needed a class that could support the various ways that Glance describes where exactly an image is stored. An image in Gl...
from __future__ import absolute_import from pychron.loggable import Loggable class BaseImportMapper(Loggable): """ base class for mapping between two data sources use this to fix/change run info on import fix typos e.g change Mina Bluff > Minna Bluff """ class MinnaBluffMapper(Ba...
from impala.error import Error as ImpylaError # noqa from impala.error import HiveServer2Error as HS2Error # noqa from impala._thrift_api import TGetOperationStatusReq, TOperationState import impala.dbapi as impyla # noqa
from ichnaea.api.locate.geoip import GeoIPPositionSource, GeoIPRegionSource from ichnaea.api.locate.tests.base import BaseSourceTest class SourceTest(object): def test_no_fallback(self, london_model, geoip_db, http_session, session, source): query = self.make_query( geoip_db, http_session, sessi...
"""Implementation of an image service that uses Glance as the backend.""" from __future__ import absolute_import import copy import inspect import itertools import os import random import sys import time import cryptography from cursive import exception as cursive_exception from cursive import signature_utils import gl...
"""This code example gets all labels. To create labels, run create_labels.py. This feature is only available to DFP premium solution networks.""" __author__ = ('Nicholas Chen', 'Joseph DiLallo') from googleads import dfp def main(client): # Initialize appropriate service. label_service = client.GetSer...
import os ARCH='arm' CPU='cortex-m4' CROSS_TOOL='gcc' BSP_LIBRARY_TYPE = None if os.getenv('RTT_CC'): CROSS_TOOL = os.getenv('RTT_CC') if os.getenv('RTT_ROOT'): RTT_ROOT = os.getenv('RTT_ROOT') if CROSS_TOOL == 'gcc': PLATFORM = 'gcc' EXEC_PATH = r'C:\Users\XXYYZZ' elif CROSS_TOOL == 'keil': P...
""" docker_registry.core.driver ~~~~~~~~~~~~~~~~~~~~~~~~~~ This file defines: * a generic interface that describes a uniform "driver" * methods to register / get these "connections" Pretty much, the purpose of this is just to abstract the underlying storage implementation, for a given scheme. """ __all__ = ["fetch", ...
input = """ a(a). b(1). b(2). cap(1). all(X,Y) | nall(X,Y) :- a(X), b(Y). :- #count{Y:all(a,Y)} > C, cap(C). :- #count{Y:all(a,Y)} < C, cap(C). """ output = """ a(a). b(1). b(2). cap(1). all(X,Y) | nall(X,Y) :- a(X), b(Y). :- #count{Y:all(a,Y)} > C, cap(C). :- #count{Y:all(a,Y)} < C, cap(C). """
import argparse import os import sys import traceback import lief from lief import OAT EXIT_STATUS = 0 terminal_rows, terminal_columns = 100, 100 try: terminal_rows, terminal_columns = os.popen('stty size', 'r').read().split() except ValueError: pass class exceptions_handler(object): func = None def __i...
""" Handles command line parsing """ from __future__ import absolute_import, division, print_function, unicode_literals import sys import six import os from six.moves import builtins import itertools import argparse from utool import util_inject from utool import util_type from utool._internal import meta_util_six, met...
from django.core.exceptions import ValidationError from django.db import models from django.utils import timezone from coberturas_medicas.managers import CoberturaManager from dj_utils.models import BaseModel class Cobertura(BaseModel): """ Representa una obra social o mutual. """ nombre = models.CharFi...
import features as f import numpy as np from sklearn import pipeline from sklearn.base import BaseEstimator from sklearn.ensemble import RandomForestRegressor, GradientBoostingRegressor, GradientBoostingClassifier from estimator_base import * rfr_params_cc = { 'n_estimators': 30, 'max_features': "auto", 'bo...
import glob import json import os import re from random import shuffle, seed import wget def download_dstc2_data(): if not os.path.isfile('./tmp/dstc2_traindev.tar.gz'): wget.download('http://camdial.org/~mh521/dstc/downloads/dstc2_traindev.tar.gz', './tmp') wget.download('http://camdial.org/~mh521/...
import unittest from mock import patch from malcolm.core.loggable import Loggable class TestLoggable(unittest.TestCase): @patch("malcolm.core.loggable.logging") def test_init(self, mock_logging): loggable = Loggable() loggable.set_logger(foo="foo", bar="bat") mock_logging.getLogger.asser...
from django.apps import AppConfig class cookie_app_Config(AppConfig):##change the verbose name of cookie_app name = 'cookie_app' verbose_name = "Business Database"
import pytest @pytest.fixture def app_context(): """ A fixture for running the test inside an app context. """ from superset.app import create_app app = create_app() with app.app_context(): yield
''' Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. Count the number of nodes connected to a node network Created on Aug 15, 2014 @author: dfleck ''' from twisted.internet import defer,reactor, task from gmu.chord.CopyEnvelope import CopyEnvelope import datet...
""" Implements the Gaussian process functionality needed for the probabilistic line search algorithm. """ import numpy as np from scipy import linalg from utils import erf class ProbLSGaussianProcess(object): """Gaussian process implementation for probabilistic line searches [1]. Implements 1D GP regression with ob...
"""Generic Node base class for all workers that run on hosts.""" import os import random import sys from oslo_concurrency import processutils from oslo_config import cfg from oslo_log import log as logging import oslo_messaging as messaging from oslo_service import service from oslo_utils import importutils from nova i...
import os, sys, subprocess, shutil, time, signal, string, platform, re, glob, hashlib, imp, inspect import run, avd, prereq, zipfile, tempfile, fnmatch, codecs, traceback from os.path import splitext from compiler import Compiler from os.path import join, splitext, split, exists from shutil import copyfile from xml.dom...
import os import numpy as np from tqdm import tqdm import jsonlines DOC_STRIDE = 2048 MAX_LENGTH = 4096 SEED = 42 PROCESS_TRAIN = os.environ.pop("PROCESS_TRAIN", "false") CATEGORY_MAPPING = {"null": 0, "short": 1, "long": 2, "yes": 3, "no": 4} def _get_single_answer(example): def choose_first(answer, is_long_answer...
''' fantastic Add-on Copyright (C) 2016 fantastic This program 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 3 of the License, or (at your option) any later version. Th...
from pygeosearch.geosearch import GeoSearch __all__ = [ 'GeoSearch' ]
import argparse from moviepy.editor import VideoFileClip from _ctypes import resize if __name__ == "__main__": parser = argparse.ArgumentParser(description='Convert video to animated gif') parser.add_argument('video') parser.add_argument('gif') args = parser.parse_args() (VideoFileClip(args.video) ...
from prometheus_client import CollectorRegistry, Counter, Gauge, generate_latest from luigi.metrics import MetricsCollector class PrometheusMetricsCollector(MetricsCollector): def __init__(self): super(PrometheusMetricsCollector, self).__init__() self.registry = CollectorRegistry() self.task...
from tweepy import Stream from tweepy import OAuthHandler from tweepy.streaming import StreamListener import json ckey = "ckey" csecret = "csecret" atoken = "atoken" asecret = "asecret" class listener(StreamListener): def on_data(self, data): # tweet = data.split(',"text":"')[1].split('","source')[0] ...
from __future__ import unicode_literals from cloudify import ctx from cloudify.decorators import operation from .. import utils from ..gcp import check_response from ..pubsub import PubSubBase class SubscriptionPolicy(PubSubBase): def __init__(self, config, logger, ...
import time from prettytable import PrettyTable x = PrettyTable() c = PrettyTable() def Wait(x): # Wait x amount of time before next line is executed! time.sleep(x) class Student(): # Class Student def __init__(self, Fullname, age, born, classes, grades): #Arguments self.Fullname = Fullname # Define...
import re from pystorm.bolt import BasicBolt class AdderBolt(BasicBolt): def process(self, tup): request_id, args = tup.values args = re.sub(r' {2,}', ' ', args) args = [int(x) for x in args.split(' ')] total = args[0] for arg in args[1:]: total += arg Bas...
import snowflake.connector from airflow.hooks.dbapi_hook import DbApiHook class SnowflakeHook(DbApiHook): """ Interact with Snowflake. get_sqlalchemy_engine() depends on snowflake-sqlalchemy """ conn_name_attr = 'snowflake_conn_id' default_conn_name = 'snowflake_default' supports_autocommit ...
import unittest from libbgp.bgp.update.attribute.med import MED from libbgp.exception import BGPNotification class TestMED(unittest.TestCase): def test_unpack(self): data_hex = b'\x00\x00\x00\xa0' self.assertEqual(160, MED.unpack(data=data_hex, capability={}).value) def test_bad_message_len(self...
import argparse import re import sys from pathlib import Path import matplotlib.pyplot as plt import numpy as np USAGE = """ This script parses reports generated with the sweep.tcl DC synthesis script and creates an AT-plot with that data. usage: ./at-plot.py ./REPORTS/<dut1_basename> ./REPORTS/<dut2_basename> ... In o...
__author__ = "Simone Campagna" __all__ = [ 'RubikTestInputOutput', ] import numpy as np from rubik.cubes import api as cb from rubik.shape import Shape from ...rubik_test_case import RubikTestCase, testmethod class RubikTestDiff(RubikTestCase): METHOD_NAMES = [] def create_random_cubes(self...
from api.decorators import api_view, request_data_defaultdc, setting_required from api.permissions import IsSuperAdmin from api.mon.node.api_views import NodeSLAView, NodeHistoryView __all__ = ('mon_node_sla', 'mon_node_history') @api_view(('GET',)) @request_data_defaultdc(permissions=(IsSuperAdmin,)) @setting_required...
''' @author: sheng @contact: sinotradition@gmail.com @copyright: License according to the project license. ''' NAME='renyin22' SPELL='rényín' CN='壬寅' SEQ='39' if __name__=='__main__': pass
from __future__ import absolute_import from django import http from django.conf import settings from mox import IsA from openstack import compute as OSCompute from openstackx import admin as OSAdmin from openstackx import auth as OSAuth from openstackx import extras as OSExtras from horizon.tests.api_tests.utils import...
import csv from django.db import transaction import xlwt from ibms.models import ( IBMData, GLPivDownload, CorporateStrategy, NCStrategicPlan, NCServicePriority, ERServicePriority, GeneralServicePriority, PVSServicePriority, SFMServicePriority, ServicePriorityMappings) CSV_FILE_LIMIT = 100000000 def export_...
from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion import django.utils.timezone class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Station', f...
import terasaur.db.mongodb_db as mongodb_db import pymongo """ Customized interface for Seedbank CRUD functions """ SEEDBANK_COLLECTION = 'seedbank' def get(id): item = mongodb_db.get(SEEDBANK_COLLECTION, {'seedbank_id': id}) return item def save(seedbank_data): if not seedbank_data['seedbank_id']: ...
""" Why our own memcache client? By Michael Barton python-memcached doesn't use consistent hashing, so adding or removing a memcache server from the pool invalidates a huge percentage of cached items. If you keep a pool of python-memcached client objects, each client object has its own connection to every memcached ser...
import unittest from python_digits import DigitWord from python_digits import DigitWordAnalysis class TestDigitWord_2_0(unittest.TestCase): def test_dw20_instantiate_dec(self): dw = DigitWord(1, 2, 3, 4, wordtype=DigitWord.DIGIT) self.assertEqual(dw.word, [1, 2, 3, 4]) def test_dw20_instantiate_...
from __future__ import print_function, division import os,unittest,numpy as np from pyscf.nao import mf as mf_c from pyscf import gto, scf, tddft from pyscf.data.nist import HARTREE2EV class KnowValues(unittest.TestCase): def test_0069_vnucele_coulomb_water_ae(self): """ This """ mol = gto.M(verbose=1,atom='...
bootstrap_url="http://agent-resources.cloudkick.com/" s3_bucket="s3://agent-resources.cloudkick.com" pubkey="etc/agent-linux.public.key" branding_name="cloudkick-agent"
import osgtest.library.core as core import osgtest.library.osgunittest as osgunittest class TestGridProxyDestroy(osgunittest.OSGTestCase): def test_01_check_proxy(self): core.skip_ok_unless_installed('globus-proxy-utils') self.skip_ok_unless(core.state['proxy.created'], "didn't create proxy") ...
import argparse import logging import numpy as np import os import paddle import paddle.fluid as fluid import reader logging.basicConfig(format='%(asctime)s - %(levelname)s - %(message)s') logger = logging.getLogger("fluid") logger.setLevel(logging.INFO) def parse_args(): parser = argparse.ArgumentParser(descriptio...
from qgl2.qgl2 import concur, seq from qgl2.qgl2 import qgl2decl, qgl2main from qgl2.qgl2 import classical, pulse, qreg from qgl2.qgl1 import QubitFactory, X, X90, Y, Y90 @qgl2decl def t3(x: qreg, y: qreg): t2(y, x) @qgl2decl def t2(x: qreg, y: qreg): t1(x, y) @qgl2decl def t1(q_a: qreg, q_b: qreg): with co...
"""PILdriver, an image-processing calculator using PIL. An instance of class PILDriver is essentially a software stack machine (Polish-notation interpreter) for sequencing PIL image transformations. The state of the instance is the interpreter stack. The only method one will normally invoke after initialization is the...
import numpy as np import scipy.sparse as sp from sklearn.metrics import roc_auc_score from lightfm import LightFM, evaluation def _generate_data(num_users, num_items, density=0.1, test_fraction=0.2): # Generate a dataset where every user has interactions # in both the train and the test set. train = sp.lil...
import lxml.etree from eutils.exceptions import * import eutils.xmlfacades.base class GBSet(eutils.xmlfacades.base.Base): # TODO: GBSet is misnamed; it should be GBSeq and get the GBSeq XML node as root (see client.py) def __unicode__(self): return "GBSet({self.acv})".format(self=self) @property ...
n = int(input()) people = [] for i in range(n): people.append(list(map(int, input().split()))) def isPerfectCandidate(x, people, n): for i in people: if i[x] == 0: return False if people[x][x] == 0: return False people[x].remove(x) for i in range(n - 1): if people...
from django.core.management.base import BaseCommand from peering.models import BGPGroup, InternetExchange class Command(BaseCommand): help = "Poll peering sessions for BGP groups and Internet Exchanges." def add_arguments(self, parser): parser.add_argument( "-a", "--all", action="store_true"...
"""Writes the register header file based on a YAML configuration file.""" import os import sys import textwrap import gflags import makani from makani.lib.python import string_util import yaml gflags.DEFINE_string('definition_file', None, 'Full path to YAML registers definition file.') gflags.DEFIN...
from django.apps import AppConfig class ProjecthandlerConfig(AppConfig): name = 'projecthandler'
from __future__ import absolute_import, division, unicode_literals from changes.api.base import APIView, error from changes.config import db from changes.models.build import Build from changes.models.job import Job from changes.models.phabricatordiff import PhabricatorDiff from changes.utils.phabricator_utils import Ph...
from .statistical import ( RollingLinearRegressionOfReturns, RollingPearsonOfReturns, RollingSpearmanOfReturns, ) from .technical import ( AnnualizedVolatility, Aroon, AverageDollarVolume, BollingerBands, EWMA, EWMSTD, ExponentialWeightedMovingAverage, ExponentialWeightedMovi...
from scattertext import SampleCorpora, RankDifference, dense_rank, PyTextRankPhrases, AssociationCompactor, \ produce_scattertext_explorer from scattertext import CorpusFromParsedDocuments import spacy import numpy as np import pytextrank nlp = spacy.load('en_core_web_sm') nlp.add_pipe("textrank", last=True) conven...
""" @version: 0.1 @author: wenzhiquan @contact: wenzhiquanr@163.com @site: http://github.wenzhiquan.com @software: PyCharm @file: config.py @time: 16/1/5 17:48 @description: null """ from os import path from sys import argv from ConfigParser import ConfigParser conf = ConfigParser() conf.read('config/config.ini') separ...
""" Copyright 2015 INFN (Italy) 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, sof...
import yaml, json, pprint with open("week1.yaml") as f: y = yaml.load(f) with open("week1.json") as f: j = json.load(f) print '#'.center(37, '#') + ' YAML ' + '#'.center(37, '#') pprint.pprint(y) print print '#'.center(37, '#') + ' JSON ' + '#'.center(37, '#') pprint.pprint(j)
from pycopia.aid import Enum import pycopia.SMI.Basetypes Range = pycopia.SMI.Basetypes.Range Ranges = pycopia.SMI.Basetypes.Ranges from pycopia.SMI.Objects import ColumnObject, MacroObject, NotificationObject, RowObject, ScalarObject, NodeObject, ModuleObject, GroupObject from SNMPv2_SMI import MODULE_IDENTITY, OBJECT...
import pymysql.cursors import logging import logging.config logging.config.fileConfig('./conf/log.ini') db_logger = logging.getLogger() config = { 'host':'172.17.0.2', 'port':3306, 'user':'root', 'password':'123456', 'db':'test', 'charset':'utf8', } connection = pymysql.connect(**config) def get_token(appid, card...