code stringlengths 1 199k |
|---|
from haproxy_manager.haproxy import Haproxy
import unittest
FILE_CONTENTS = """frontend machine0001
maxconn 100
frontend machine0002
maxconn 100
frontend machine0003
maxconn 100
"""
class HaproxyTest(unittest.TestCase):
def setUp(self):
self.clazz = Haproxy('t... |
import pytest
from ..am_statements import *
from ..am_statements import inch, metric
def test_AMPrimitive_ctor():
for exposure in ("on", "off", "ON", "OFF"):
for code in (0, 1, 2, 4, 5, 6, 7, 20, 21, 22):
p = AMPrimitive(code, exposure)
assert p.code == code
assert p.expo... |
"""
Kubernetes
No description provided (generated by Swagger Codegen https://github.com/swagger-api/swagger-codegen)
OpenAPI spec version: v1.6.1
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from pprint import pformat
from six import iteritems
import re
class V2alpha1HorizontalPo... |
"""Generally useful utility functions."""
from __future__ import print_function
import codecs
import collections
import json
import math
import os
import sys
import time
import numpy as np
import tensorflow as tf
def check_tensorflow_version():
if tf.__version__ < "1.2.1":
raise EnvironmentError("Tensorflow versi... |
import os
from os.path import join, dirname, abspath
from topology_lib_files_management import __version__
extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.inheritance_diagram',
'sphinx.ext.intersphinx',
'sphinxcontrib.plantuml',
'sphinx.ext.graphviz',
'autoapi.sphi... |
from __future__ import absolute_import, unicode_literals, print_function
class AppInfo(object):
"""This class holds application informations for OAuth2 providers (web application workflow).
Also used in case of login/password authenticated users: in this case application name
can be set to 'login'
"""
... |
"""
Created on Sun Mar 6 23:11:02 2016
@author: stephan
ToDo: Merge with variable tests ...
"""
from os.path import join as join
import base64
import os
name_space={'sub':'http://enes.org/entities/ingest-workflow#',
'ing':'http://enes.org/entities/ingest-workflow#',
'qua':'http://enes.org/entit... |
import os
import io
import sys
import typing
import http.client
import urllib.request
path = os.path.join
def get_extras():
return {
'angle': {
'name': 'ANGLE - Almost Native Graphics Layer Engine',
'license': 'BSD License',
'url': 'https://github.com/google/angle',
... |
from __future__ import with_statement
from alembic import context
from sqlalchemy import engine_from_config, pool
from logging.config import fileConfig
import logging
config = context.config
fileConfig(config.config_file_name)
logger = logging.getLogger('alembic.env')
from flask import current_app
config.set_main_optio... |
import json
from mock import patch
from django.core.urlresolvers import reverse
from seahub.test_utils import BaseTestCase
from seahub.share.models import UploadLinkShare
from seahub.api2.endpoints.upload_links import UploadLinks, UploadLink
class UploadLinksTest(BaseTestCase):
def setUp(self):
self.repo_id... |
from twisted.internet import defer
from synapse.streams.config import PaginationConfig
from synapse.types import StreamToken, UserID
import synapse.util.async
import baserules
import logging
import simplejson as json
import re
import random
logger = logging.getLogger(__name__)
class Pusher(object):
INITIAL_BACKOFF ... |
"""
Installs and configures nova
"""
import os
import uuid
import logging
import platform
import socket
from packstack.installer import basedefs, processors, utils, validators
from packstack.installer.exceptions import ScriptRuntimeError
from packstack.modules.shortcuts import get_mq
from packstack.modules.ospluginutil... |
"Utilities for file I/O with SGS data"
from pydigree.sgs import SGSAnalysis, SGS, Segment
from pydigree.io import smartopen
def write_sgs(data, filename):
"""
GERMLINE files are text files with the format:
0) Family ID 1
1) Individual ID 1
2) Family ID 2
3) Individual ID 2
... |
from __future__ import absolute_import
import os
import sys
from happy.ReturnMsg import ReturnMsg
from happy.Utils import *
from happy.utils.IP import IP
from happy.HappyNetwork import HappyNetwork
from happy.HappyNode import HappyNode
from WeaveTest import WeaveTest
options = {"border_gateway": None,
"servi... |
"""timecast/modules/_predict_constant.py"""
from timecast.modules.core import Module
class PredictConstant(Module):
"""Predict constant value"""
def __init__(self, constant: int = 0.0):
"""init"""
self.constant = constant
def __call__(self, x):
"""call"""
return self.constant |
import scrapy
from scrapy import log
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors import LinkExtractor
from rcbi.items import Part
import os
import urlparse
import urllib
MANUFACTURERS = ["Cobra", "DTF-UHF", "EMAX", "FatShark", "Foxeer", "FrSky", "Gemfan", "ImmersionRC", "XHover"]
CORRECT = {... |
import abc
import six
@six.add_metaclass(abc.ABCMeta)
class IObjectSerializer(object):
"""
Raw Python object serialization and deserialization. Object serializers are
used by classes implementing WAMP serializers, that is instances of
:class:`autobahn.wamp.interfaces.ISerializer`.
"""
@abc.abstractpro... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import argparse
import collections
import json
import sys
BUILD_RULE_FINISHED_TOKEN = 'BuildRuleEvent.Finished'
BuildRule = collections.namedtuple(
'BuildRule', 'name ... |
import time
import mock
import datetime
import unittest
from nose.tools import * # noqa
import httplib as http
import jwe
import jwt
import furl
import itsdangerous
from modularodm import storage, Q
from framework.auth import cas
from framework.auth import signing
from framework.auth.core import Auth
from framework.ex... |
import numpy as np
from tensornetwork.block_sparse.utils import intersect, unique
from typing import (List, Optional, Type, Any, Union, Callable)
class BaseCharge:
"""
Base class for charges of BlockSparseTensor. All user defined charges
should be derived from this class.
Attributes:
* unique_charges: np.nd... |
from cloudshell.cp.vcenter.common.utilites.savers.linked_clone_artifact_saver import LinkedCloneArtifactHandler
class ArtifactHandler(object):
@staticmethod
def factory(saveDeploymentModel, pv_service, vcenter_data_model, si, logger, deployer, reservation_id,
resource_model_parser, snapshot_save... |
from django.conf import settings
from django.db import migrations, models
import django.db.models.deletion
class Migration(migrations.Migration):
initial = True
dependencies = [
('dcim', '0002_auto_20160622_1821'),
('auth', '0007_alter_validators_add_error_messages'),
migrations.swappabl... |
# This code is part of pyCMPL
#
# Copyright (C) 2013
# Mike Steglich - Technical University of Applied Sciences
# Wildau, Germany
#
# pyCMPL is a project of the Technical University of
# Applied Sciences Wildau and the Institute for Operations Research
# and Business Management at the Martin Luther Univ... |
"""Tests to check the integrity of json config files.
These tests assume that the json configs live in a top-level
folder named config."""
import glob
import json
import logging
import os
import subprocess
import unittest
class ReconcilePresubmitTest(unittest.TestCase):
# This function requires gcloud be installed ... |
import argparse
import json
import logging
import logging.config
import os
import pkg_resources
import sys
from poller import Poller
import settings
def setup_logging(cli_args):
""" Setup logging configuration
:param cli_args: Argparse object containing parameters from the command line
:return: Logger
"... |
import sys
sys.path.insert(1, "../../")
import h2o, tests
def hist_test():
kwargs = {}
kwargs['server'] = True
print "Import small prostate dataset"
hex = h2o.import_file(tests.locate("smalldata/logreg/prostate.csv"))
hex["AGE"].hist(**kwargs)
hex["VOL"].hist(**kwargs)
if __name__ == "__main__":... |
import logging
from cinderclient import exceptions as cinder_exceptions
from novaclient import exceptions as nova_exceptions
from cloudferry import discover
from cloudferry import model
from cloudferry.model import compute
from cloudferry.model import identity
from cloudferry.model import storage
from cloudferry.lib.os... |
from getpass import getuser
SMELLS_DEP_STM = "Deprecated Statements"
SMELLS_INC_TSK = "Incomplete tasks"
SMELLS_COM_EXP = "Complex Expression"
SMELLS_MIS_ELS = "Missing Else"
RULE1_1 = "case statement without a default case"
RULE2_1 = "class name containing a dash"
RULE2_2 = "variable contains a dash"
RULE3_1 = SMELLS_... |
"""Base Manager class.
Managers are responsible for a certain aspect of the system. It is a logical
grouping of code relating to a portion of the system. In general other
components should be using the manager to make changes to the components that
it is responsible for.
For example, other components that need to dea... |
"""Unit tests for survey logic."""
import unittest
from google.appengine.ext import ndb
from datetime import timedelta
from soc.models import survey as soc_survey_model
from soc.modules.seeder.logic.seeder import logic as seeder_logic
from summerofcode.logic import survey as survey_logic
from summerofcode.models import... |
import copy
import os
import xml.dom.minidom
import xml.etree.ElementTree as ET
import uuid
import typing as T
from pathlib import Path, PurePath
from . import backends
from .. import build
from .. import dependencies
from .. import mlog
from .. import compilers
from ..interpreter import Interpreter
from ..mesonlib imp... |
"""Helper methods for dealing with Cloud Datastore's Protobuf API."""
from datetime import datetime
import pytz
from gclouddatastore.key import Key
def get_protobuf_attribute_and_value(val):
"""Given a value, return the protobuf attribute name and proper value.
The Protobuf API uses different attribute names
base... |
import numpy as np
from .time_series import MarketDataSeries
from .func import (
SumSeries,
AbsSeries,
StdSeries,
SMASeries,
MovingAverageSeries,
WeightedMovingAverageSeries,
ExponentialMovingAverageSeries,
CrossOver,
minimum,
maximum,
every,
count,
hhv,
llv,
... |
import sys
import os
SYSFS_GPIO_DIR = "/sys/class/gpio"
def gpioUnexport (gpio):
try:
fo = open(SYSFS_GPIO_DIR + "/unexport","w")
fo.write(gpio)
fo.close()
return
except IOError:
return
def gpioExport (gpio):
try:
fo = open(SYSFS_GPIO_DIR + "/export","w")
fo.write(gpio)
fo.cl... |
import mock
from poppy.manager.base import notifications
from tests.unit import base
class TestProviderWrapper(base.TestCase):
def setUp(self):
super(TestProviderWrapper, self).setUp()
self.notifications_wrapper_obj = notifications.NotificationWrapper()
def test_create(self):
mock_obj = ... |
import sys
import nose
if __name__ == '__main__':
args = sys.argv
args.remove(__file__)
args = ['nosetests', '--with-coverage', '--cover-erase', '--cover-package=roundabout'] + args
sys.path.append('tests')
nose.run('tests', argv=args) |
import os
from flask import Flask, send_file, abort
webserver = Flask(__name__)
@webserver.route("/")
def acc_denied():
return "You cannot browse this subdomain."
@webserver.route("/<path:imageid>")
def i(imageid):
imageid = imageid.rstrip('/').split('.')[0]
x = False
for file in os.listdir("./i"):
... |
import contextlib
import copy
import itertools
import time
import mock
from oslo.config import cfg
import testtools
from neutron.agent.linux import ovs_lib
from neutron.extensions import securitygroup as ext_sg
from neutron.plugins.nec.agent import nec_neutron_agent
from neutron.tests import base
DAEMON_LOOP_COUNT = 10... |
"""
Painless environment setup for acceptance tests. Powered by behave.
Visit the docs at
https://behave.readthedocs.io/en/latest/tutorial.html#environmental-controls
"""
from contextlib import contextmanager
from os import chdir, getcwd, system
from os.path import dirname, join
from shutil import rmtree
from tempfile... |
from unittest import mock
from neutron.tests import base
from gbpservice.contrib.nfp.configurator.lib import demuxer as demuxer_lib
from gbpservice.contrib.nfp.configurator.modules import configurator as cfgr
from gbpservice.contrib.tests.unit.nfp.configurator.test_data import (
... |
import unittest
class TestSequenceFunctions(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_listcontroler_loads(self):
pass |
from setuptools import setup, find_packages
setup(
name='mathjax',
version='0.0.20131125',
packages=find_packages('src'),
package_dir={'': 'src'},
include_package_data=True,
author='Raphael Lullis',
description='A Django application that allows install mathjax as an app.',
license='Apach... |
import spatial
import general
import geometry
import filters
import servicedef
import find
__version__ = "2.0.100" |
from flask_sqlalchemy import SQLAlchemy
from sqlalchemy.inspection import inspect
db = SQLAlchemy()
#return {c: (serialize(c) if isinstance(c.__class__, DeclarativeMeta) else getattr(self,c)) for c in inspect(self).attrs.keys()}
#return {c: getattr(self,c) for c in inspect(self).attrs.keys()}
class Evento(db.Model... |
import mxnet as mx
import random
import sys
import copy
from mxnet.io import DataBatch, DataIter
import numpy as np
from mxnet.image import *
import bson
import struct
import pickle
import logging
def add_data_args(parser):
data = parser.add_argument_group('Data', 'the input images')
data.add_argument('--data-d... |
class FileToSocketAdapter(object):
def __init__(self, file):
self.file = file
def recv(self, nbytes):
return self.file.read(nbytes)
def send(self, buff):
self.file.write(buff) |
DESCRIPTION = "exits the program"
def autocomplete(shell, line, text, state):
return None
def help(shell):
pass
def execute(shell, cmd):
import sys
sys.exit(0) |
__authors__ = ['"Liu Fei" <fei.liu@cs2c.com.cn>']
__version__ = "V0.1"
'''
'''
import xmltodict
from BaseAPIs import BaseAPIs
from Configs.GlobalConfig import WebBaseApiUrl
from Utils.HttpClient import HttpClient
from Utils.PrintLog import LogPrint
from Utils.Util import wait_until
def smart_create_vm(vm_name, xml_vm_i... |
from bigdl.dllib.nn.layer import SpatialAveragePooling, SpatialBatchNormalization
from bigdl.dllib.nn.layer import SpatialConvolution, SpatialMaxPooling, JoinTable
from bigdl.dllib.nn.layer import ReLU, SoftMax, CAddTable, Unsqueeze
from bigdl.dllib.nn.onnx.layer import Constant, Gather, Gemm, Shape, Reshape
from .conv... |
"""This package provides tools for appending layers to docker images."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import json
from containerregistry.client import docker_name
from containerregistry.client.v2_2 import docker_digest
from containerregistr... |
"""Data model source model."""
import pathlib
from typing import cast, Optional
from pydantic import BaseModel, Field, HttpUrl, validator # pylint: disable=no-name-in-module
from .base import DescribedModel, NamedModel
from .entity import Entities
from .parameter import Parameters
class Configuration(NamedModel): # p... |
__author__ = 'tongxindao'
__date__ = '17-9-10 下午11:19'
from .models import Course, Lesson, Video, \
CourseResource, BannerCourse
from organization.models import CourseOrg
import xadmin
class LessonInline(object):
model = Lesson
extra = 0
class CourseResourceInline(object):
model = CourseResource
ext... |
"""
A Hyper-V Nova Compute driver.
"""
from nova.openstack.common.gettextutils import _
from nova.openstack.common import log as logging
from nova.virt import driver
from nova.virt.hyperv import hostops
from nova.virt.hyperv import livemigrationops
from nova.virt.hyperv import migrationops
from nova.virt.hyperv import ... |
from __future__ import print_function
import argparse
import os
import time
import torch.nn.parallel
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
import torchvision.transforms as transforms
from wresnet_models import *
from h5_dataloaders import *
import pandas as pd
parser = argparse... |
"""Generates Python proto modules and grpc stubs for Beam protos."""
from __future__ import absolute_import
from __future__ import print_function
import glob
import logging
import multiprocessing
import os
import platform
import shutil
import subprocess
import sys
import time
import warnings
import pkg_resources
GRPC_T... |
import numpy as np
import codecs
import json
import sys
dateMap = {}
mergedFile = sys.argv[1]
scoreList = []
with codecs.open(mergedFile, "r", "utf8") as inFile:
for line in inFile:
jsonInput = json.loads(line)
pairs = jsonInput["pairs"]
if ( len(pairs) == 0 ):
continue
scoreList.extend(pairs.values())
scor... |
from __future__ import print_function
from __future__ import division
from __future__ import absolute_import
from congress.api import api_utils
from congress.api import base
from congress.api import webservice
from congress import exception
class WebhookModel(base.APIModel):
"""Model for handling webhook notificati... |
"""
Protocol 17 introduces operations that allow asset issuers to maintain tighter control
over how their asset is distributed to the world. Specifically, it gives them power to
burn their asset from a trustline or claimable balance, effectively removing it from the
recipient’s balance sheet:
> The amount of the asset ... |
import sys
from mgr.metagrammar import grammar
from makelr import make_lr_table, generate_parser
def main(output_filename):
stuff = make_lr_table(grammar)
parser = generate_parser(grammar, *stuff)
if not output_filename.endswith('.py'): raise ValueError(output_filename)
with open(output_filename, 'w') a... |
import os, sys
from optparse import OptionParser
parser = OptionParser(
#用法说明
usage="USAGE: %prog [options] SOURCE_FOLDER",
#版本
version="0.10.0",
#描述
description="Run all the pyConcordion tests contained in SOURCE_FOL DER and sub folders."
)
parser.add_option("-o", "--output_folder",
help="generate report in ... |
"""
Command-line interface for the Ripcord APIs.
"""
import sys
from cliff import app
from cliff import commandmanager
from oslo.config import cfg
from ripcordclient import client
from ripcordclient.common import exception
from ripcordclient.common import utils
from ripcordclient.openstack.common import log as logging
... |
import os
import shutil
import stat
import sys
import tempfile
import salt.utils.files
import salt.utils.find
from tests.support.runtests import RUNTIME_VARS
from tests.support.unit import TestCase, skipIf
class TestFind(TestCase):
def test_parse_interval(self):
self.assertRaises(ValueError, salt.utils.find... |
import sys
import os
import numpy
from osgeo import gdal, gdal_array
TAIL_TRIM = 0.01
def get_band(filename, target_percent):
ds = gdal.Open(filename)
xsize = int(ds.RasterXSize * target_percent / 100.0)
ysize = int(ds.RasterYSize * target_percent / 100.0)
image = ds.GetRasterBand(1).ReadAsArray(resampl... |
from google.cloud.devtools import cloudbuild_v1
async def sample_retry_build():
# Create a client
client = cloudbuild_v1.CloudBuildAsyncClient()
# Initialize request argument(s)
request = cloudbuild_v1.RetryBuildRequest(
project_id="project_id_value",
id="id_value",
)
# Make the ... |
"""Tests for ceilometer agent manager"""
import shutil
from keystoneclient import exceptions as ks_exceptions
import mock
from novaclient import client as novaclient
from oslo_service import service as os_service
from oslo_utils import fileutils
from oslotest import base
from oslotest import mockpatch
import requests
i... |
import getpass
import os
import re
import shutil
import signal
import time
import pytest
from unit.applications.lang.php import TestApplicationPHP
from unit.option import option
class TestPHPApplication(TestApplicationPHP):
prerequisites = {'modules': {'php': 'all'}}
def before_disable_functions(self):
... |
__authors__ = [
'"Sverre Rabbelier" <sverre@rabbelier.nl>',
]
import unittest
from google.appengine.api import memcache
from soc.cache import base
class CacheDecoratorTest(unittest.TestCase):
"""Tests that the @cache decorator caches the result.
"""
def setUp(self):
self.called = 0
decorator = base.ge... |
from pyvcloud import _get_logger
from pyvcloud import Http
from pyvcloud.schema.vcd.v1_5.schemas.vcloud import tasksListType
from pyvcloud.schema.vcd.v1_5.schemas.vcloud import taskType
import requests
from urlparse import urlparse
class Task(object):
statuses = ['running',
'success',
... |
from __future__ import print_function
from tixi3 import tixi3wrapper
from tigl3 import tigl3wrapper
from tigl3.configuration import CCPACSConfigurationManager_get_instance
from tigl3.boolean_ops import CFuseShapes
from tigl3.import_export_helper import export_shapes
import os
def get_fused_shape(tigl_handle):
"""
... |
path = './OUTCAR'
path2 = 'mag-fang.out'
f = open(path)
linenumber = 0
for line in f:
linenumber = linenumber + 1
if 'magnetization (x)' in line:
#print(line)
linenumber_mag = linenumber
f.close()
f = open(path)
f2 = open(path2,'w')
linenumber = 0
for line in f:
linenumber = linenumber + 1
... |
from string import Template
def start_response(resp="text/html"):
return('Content-type: ' + resp + '\n\n')
def include_header(the_title):
with open('templates/header.html') as headf:
head_text = headf.read()
header = Template(head_text)
return(header.substitute(title=the_title))
def include_foot... |
import sys
import os
import shlex
from recommonmark.parser import CommonMarkParser
sys.path.append(os.path.abspath('.'))
extensions = [
'sphinx.ext.doctest',
'code-block-with-version-replacement'
]
source_parsers = {
'.md': CommonMarkParser,
}
templates_path = ['_templates']
source_suffix = ['.rst', '.md']
ma... |
from google.appengine.ext import ndb
import webapp2
import struct
import json
import base64
import datetime
def encode_id(numeric_id):
return base64.urlsafe_b64encode(struct.pack("!Q", numeric_id)).rstrip("=")
def decode_id(encoded_id):
padding = "=" * (len(encoded_id) % 3)
return struct.unpack("!Q", base64... |
import os
import re
import gtk
import pango
from application import application
from editor import Editor
from global_settings import global_settings
from shell_buffer import ShellBuffer
from shell_view import ShellView
from worksheet_print import WorksheetPrintOperation, export_to_pdf
_LETTER_OR_UNDERSCORE = re.compil... |
from .rudp_hid_client import foils_hid_device_descriptor
unicode_report_descriptor = bytes([
0x05, 0x01, # Usage Page (Desktop),
0x09, 0x06, # Usage (Keyboard),
0xA1, 0x01, # Collection (Application),
0x85, 0x01, # . Report ID (1),
0x05, 0x10, ... |
import pytest
import random
from uuid import UUID
from helusers.utils import uuid_to_username, username_to_uuid
def test_uuid_to_username():
assert uuid_to_username('00fbac99-0bab-5e66-8e84-2e567ea4d1f6') == 'u-ad52zgilvnpgnduefzlh5jgr6y'
def test_username_to_uuid():
assert username_to_uuid('u-ad52zgilvnpgnduef... |
import json
import urllib
from requestbuilder import Arg, MutuallyExclusiveArgList
from euca2ools.commands.argtypes import file_contents
from euca2ools.commands.iam import IAMRequest, AS_ACCOUNT
class CreateRole(IAMRequest):
DESCRIPTION = 'Create a new role'
ARGS = [Arg('-r', '--role-name', dest='RoleName', met... |
"""
@package mi.instrument.sunburst.sami2_pco2.pco2a.driver
@file marine-integrations/mi/instrument/sunburst/sami2_pco2/pco2a/driver.py
@author Christopher Wingard & Kevin Stiemke
@brief Driver for the Sunburst Sensors, SAMI2-PCO2 (PCO2W)
Release notes:
Sunburst Sensors SAMI2-PCO2 pCO2 underwater sensor.
Derive... |
from __future__ import print_function
from __future__ import with_statement
import struct
class GcodeSyntaxError(Exception):
pass
EncodeLineErrors = GcodeSyntaxError
def encode_line(line):
comment_index = line.find(';')
if comment_index >= 0:
line = line[:comment_index]
line = line.strip()
i... |
import re
import os.path
from zipfile import ZipFile
from zipfile import BadZipfile
from zipfile import LargeZipFile
def _xml_to_list(xml_str):
# Convert test generated XML strings into lists for comparison testing.
# Split the XML string at tag boundaries.
parser = re.compile(r'>\s*<')
elements = parse... |
import os
import sys
import inspect
import traceback
saved_path = sys.path[:]
sys.path.append(os.path.dirname(os.path.abspath(inspect.getsourcefile(lambda:0))))
from internal.memcached_connection import MemcachedBinaryConnection
from internal.memcached_connection import STATUS, COMMANDS
mc = MemcachedBinaryConnection("... |
import os
import sys
import tarfile
import urllib
from pysquidblacklists import PySquidBlacklistsConfig
print("Parsing configuration file ...")
config = PySquidBlacklistsConfig()
config.get_config()
def download(url, path):
bl_file = urllib.URLopener()
bl_file.retrieve(url, path)
def extract(base_dir, archive):... |
""" Create and manipulate C compatible data types in Python. """
FUNCFLAG_CDECL = 1
FUNCFLAG_PYTHONAPI = 4
FUNCFLAG_USE_ERRNO = 8
FUNCFLAG_USE_LASTERROR = 16
RTLD_GLOBAL = 256
RTLD_LOCAL = 0
_cast_addr = 3070067376L
_memmove_addr = 3075058560L
_memset_addr = 3075043696L
_string_at_addr = 3070066336L
_wstring_at_addr = ... |
"""
WSGI config for dev project.
It exposes the WSGI callable as a module-level variable named ``application``.
For more information on this file, see
https://docs.djangoproject.com/en/dev/howto/deployment/wsgi/
"""
import os
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "dev.settings")
from django.core.wsgi import g... |
from sys import stdin, stdout
while True:
line = stdin.readline().strip()
print 'Hello %s!' % line
stdout.flush() # Remember to flush |
def clamp(v, low, high):
v[v < low] = low
v[v > high] = high
return v |
from keygenerator import *
from .. import utils
from math import ceil
import copy
import random
import crossovers
class SubstitutionKeyGenerator(KeyGenerator):
def __init__(self, alphabet=utils.alphabet, rand_func=lambda x: x ** 6, weighted=None,
crossover=crossovers.Tournament(crossover_func=cross... |
"""
Radio driver for the AT86RF215, for the rPi 3.
Connections
| rPi pin | ATREB215-XPRO Extension Board pin |
|---------|-----------------------------------|
| 01- +3V | 20 - VCC |
| 11- | 09 - IRQ |
| 09- GND | 19 - GND |
| 19- | 16 -... |
import json
import requests
class Boards(object):
__module__ = 'trello'
def __init__(self, apikey, token=None):
self._apikey = apikey
self._token = token
def get(self, board_id, actions=None, action_fields=None, action_limit=None, cards=None, card_fields=None, lists=None, list_fields=None, m... |
from Tkinter import Tk, Text, BOTH, W, N, E, S
from ttk import Frame, Button, Label, Style
class Example(Frame):
def __init__(self, parent):
Frame.__init__(self, parent)
self.parent = parent
self.initUI()
def initUI(self):
self.parent.title("Windows")
self.pack(fill=BOTH,... |
from xscontainer import api_helper
from xscontainer import util
from xscontainer.util import tls_secret
from xscontainer.util import log
import constants
import errno
import select
import ssl
import socket
import sys
DOCKER_TLS_PORT = 2376
TLS_CIPHER = "ECDHE-RSA-AES256-GCM-SHA384"
ERROR_CAUSE_NETWORK = (
"Error: C... |
try:
import importlib
try:
SOURCE_SUFFIXES = importlib.machinery.SOURCE_SUFFIXES
except Exception:
raise ImportError()
except ImportError:
import imp
SOURCE_SUFFIXES = [s[0] for s in imp.get_suffixes()
if s[2] == imp.PY_SOURCE]
from pysmi.borrower.base import A... |
from django.core.management.base import NoArgsCommand, make_option
from funda.models import *
import nltk
import itertools
import math,re
from django.db import connection, transaction
import gc
class TermCache:
max_terms=500
def __init__(self):
self.terms={}
def get_term(self,term):
try:
t=Term.obje... |
__author__ = "Peter Shipley"
import os
from ISY.IsyEvent import ISYEvent, _print_event
def main():
server = ISYEvent(debug=0x0000)
# you can subscribe to multiple devices
# server.subscribe('10.1.1.25')
server.subscribe(
addr=os.getenv('ISY_ADDR', '10.1.1.36'),
userl=os.getenv('ISY_USER... |
from __future__ import unicode_literals
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('fieldsight', '0015_chatmessage'),
('eventlog', '0001_initial'),
]
operations = [
migrations.AddField(
model_name='fieldsightlog',
... |
"""ResourceAction index
Revision ID: cc8cfbcf8f1
Revises: f7f0f385f6b
Create Date: 2015-02-24 21:02:32.123830
"""
revision = 'cc8cfbcf8f1'
down_revision = 'f7f0f385f6b'
from alembic import op
def upgrade():
op.drop_index('resourceaction_resource_id_name_key', table_name='resourceaction')
op.create_unique_constr... |
from . import ExplorationTechnique
from ..sim_options import EFFICIENT_STATE_MERGING
class Veritesting(ExplorationTechnique):
"""
Enable veritesting. This technique, described in a paper[1] from CMU, attempts to address the problem of state
explosions in loops by performing smart merging.
[1] https://us... |
from django.views.generic.list import ListView
from rest_framework.decorators import list_route
from rest_framework.permissions import AllowAny
from mapentity import views as mapentity_views
from geotrek.feedback import models as feedback_models
from geotrek.feedback import serializers as feedback_serializers
class Rep... |
import socket
import struct
import time
import socks
import utils
from . import openssl_wrap
class ConnectCreator(object):
def __init__(self, logger, config, openssl_context, host_manager,
timeout=5, debug=False,
check_cert=None):
self.logger = logger
self.config = ... |
import math
from random import choice, triangular
from pyfrax.canvas import *
from pyfrax.model import *
from pyfrax.rendertools import *
from pyfrax.colors.rgb import *
FRAMES = 32
WIDTH = 500
HEIGHT = 500
STARS_PER_FRAME = 5
stars = []
for frame in xrange(FRAMES):
f = []
for star in xrange(STARS_PER_FRAME):
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.