code stringlengths 1 199k |
|---|
import random
from parser_xml import doxml
__author__ = 'Administrator'
import pygame
def item_to_int(array=[]):
arr = []
for a in array:
arr.append(int(a))
return arr
pygame.init()
keys = [False, False, False, False]
screen = pygame.display.set_mode((450, 650), 0, 32)
pygame.display.set_caption(u'飞... |
from common.methods import set_progress
from utilities.models import ConnectionInfo
from servicecatalog.models import ServiceBlueprint
from infrastructure.models import CustomField
import json
from ast import literal_eval
import requests
API_CLIENT_CI = "Citrix API"
def create_custom_fields_as_needed():
CustomField... |
import csv
import datetime
import logging
import os
from celery.task import task
from django.conf import settings
from django.contrib.auth import get_user_model
from django.utils.timezone import now
from libya_elections.constants import REMINDER_CHECKIN, REMINDER_REPORT, \
REMINDER_LAST_REPORT, REMINDER_CLOSE
from ... |
import sys
import itk
itk.auto_progress(2)
if len(sys.argv) < 3:
print("Usage: " + sys.argv[0] + " <InputFileName> <OutputFileName> [Extension]")
sys.exit(1)
inputFileName = sys.argv[1]
outputFileName = sys.argv[2]
if len(sys.argv) > 3:
extension = sys.argv[3]
else:
extension = ".png"
fileNameFormat = o... |
import unittest
from datetime import datetime
from unittest.mock import call
from uuid import uuid4, UUID
from mock import patch, MagicMock
from alamo_worker.alerter.backend.cassandra import (
CassandraDriver, SELECT_QUERY, INSERT_QUERY, INSERT_SERVICE_QUERY,
AsyncCassandraDriver
)
from alamo_worker.alerter.uti... |
import numpy as np
import tvm
import topi
import topi.testing
from topi.util import get_const_tuple
from tvm.contrib.pickle_memoize import memoize
def generate_quantized_np(shape, bits, out_dtype):
min_val = 0
max_val = 1 << bits
return np.random.randint(min_val, max_val, size=shape).astype(out_dtype)
def v... |
from flask import Flask, redirect, abort, url_for
app = Flask(__name__)
app.debug = True
@app.route('/')
def index():
return redirect(url_for('login'))
@app.route('/login')
def login():
abort(401)
this_is_never_executed()
if __name__ == '__main__':
app.run() |
'''
OpTestPCI: PCI checks
-------------------------------
Perform various PCI validations and checks
--run-suite BasicPCI (includes skiroot_suite and host_suite)
--run-suite pci-regression
Sample naming conventions below, see each test method for
the applicable options per method.
--run testcases.OpTestPCI.PCISkiroot.p... |
from decimal import Decimal
from voluptuous import MultipleInvalid
from minfraud.validation import validate_transaction, validate_report
import unittest
class ValidationBase:
def setup_transaction(self, transaction):
if "device" not in transaction:
transaction["device"] = {}
if "ip_addre... |
"""Support for Subaru sensors."""
import subarulink.const as sc
from homeassistant.components.sensor import DEVICE_CLASSES
from homeassistant.const import (
DEVICE_CLASS_BATTERY,
DEVICE_CLASS_TEMPERATURE,
DEVICE_CLASS_VOLTAGE,
LENGTH_KILOMETERS,
LENGTH_MILES,
PERCENTAGE,
PRESSURE_HPA,
TE... |
from google.cloud import bigquery_storage_v1beta2
def sample_append_rows():
# Create a client
client = bigquery_storage_v1beta2.BigQueryWriteClient()
# Initialize request argument(s)
request = bigquery_storage_v1beta2.AppendRowsRequest(
write_stream="write_stream_value",
)
# This method ... |
from os import makedirs
from os.path import join, dirname, exists
from string import Template
from galaxy.util.bunch import Bunch
from galaxy.objectstore import build_object_store_from_config
from .test_utils import TempDirectoryTestCase
from .test_objectstore import MockDataset
class PulsarObjectStoreTest(TempDirector... |
from tornado.process import cpu_count, _reseed_random
from tornado import ioloop
import logging
import os
import signal
import sys
from tornado.util import errno_from_exception
import errno
logger = logging.getLogger(__name__)
_task_id = None
exiting = False
def fork_processes(num_processes, max_restarts=100):
"""S... |
from __future__ import absolute_import
import binascii
import glob
import gzip
import io
import logging
import os
import pickle
import random
import re
import sys
import unittest
import zlib
from builtins import range
import crcmod
import future.tests.base # pylint: disable=unused-import
import apache_beam as beam
fro... |
from designate.objects.base import BaseObject
class TsigKey(BaseObject):
FIELDS = ['name', 'algorithm', 'secret'] |
"""Tests for saving and loading using tf's saved_model APIs with DS."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from tensorflow.python.distribute import combinations
from tensorflow.python.distribute import saved_model_test_base as test_base
from tens... |
from keystoneclient import base
from keystoneclient import exceptions
from keystoneclient.v3.contrib.user_registration.utils import REGISTRATION_PATH
class Activation(base.Resource):
pass
class ActivationManager(base.CrudManager):
"""Manager class for activating user in the USER REGISTRATION extension for Keyst... |
import tornado.ioloop
import tornado.web
import tornado.websocket
import os
UPLOAD_FILE_PATH = "./tempfiles/"
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.render("./templates/main.html", title = "Main Page");
class EchoWebSocket(tornado.websocket.WebSocketHandler):
all_client = set... |
import glob
import os
import synapseclient
import uuid
from synapseclient import Project, File, Folder, Evaluation
from challenge import *
import challenge
from collections import OrderedDict
syn = synapseclient.Synapse()
syn.login()
CLEANUP = True
project = None
evaluation = None
ad_challenge = challenge.ad_challenge_... |
class Node:
def __init__(self, val):
self.val = val
self.next = None
class LinkList:
def __init__(self):
self.head = None
def push(self, val):
node = Node(val)
if self.head:
node.next = self.head
self.head = node
else:
self.... |
"""Unittest for instance_setup.py module."""
import subprocess
from google_compute_engine.instance_setup import instance_setup
from google_compute_engine.test_compat import mock
from google_compute_engine.test_compat import unittest
class InstanceSetupTest(unittest.TestCase):
def setUp(self):
self.mock_instance_c... |
from setuptools import setup
setup(
name = "smbios_validation_tool",
author = "Xu Han",
author_email = "",
license = "Apache",
url = "https://github.com/google/smbios-validation-tool",
packages=['smbios_validation_tool', 'dmiparse'],
scripts=['smbios_validation'],
) |
"""Unit tests for DB API."""
import mock
from oslo_config import cfg
from oslo_utils import importutils
from oslo_db import api
from oslo_db import exception
from oslo_db.tests import utils as test_utils
sqla = importutils.try_import('sqlalchemy')
if not sqla:
raise ImportError("Unable to import module 'sqlalchemy'... |
import pytest
from etcdb import OperationalError
from etcdb.lock import WriteLock
def test_insert(cursor):
cursor.execute('CREATE TABLE t1(id INT NOT NULL PRIMARY KEY AUTO_INCREMENT, name VARCHAR(255))')
cursor.execute("INSERT INTO t1(id, name) VALUES (1, 'aaa')")
cursor.execute("INSERT INTO t1(id, name) VA... |
import uuid
from oslo_config import cfg
from vitrage.common.constants import DatasourceOpts as DSOpts
from vitrage.common.constants import DatasourceProperties as DSProps
from vitrage.common.constants import UpdateMethod
from vitrage.common.constants import VertexProperties as VProps
from vitrage.datasources.nova.host ... |
import unittest
import sys
import inspect
from robot.running.handlers import _PythonHandler, _JavaHandler, DynamicHandler
from robot import utils
from robot.utils.asserts import *
from robot.running.testlibraries import TestLibrary
from robot.running.dynamicmethods import (
GetKeywordArguments, GetKeywordDocumentat... |
"""Property classes for building wrapper classes for Pikov nodes.
We want to wrap our semantic graph with Python classes. This allows us to
interact with Python objects to modify the guid_map.
These classes encode the core types used in the semantic graph. When classes
use these properties, the guid_map is updated with... |
import os
from ruamel import yaml
import great_expectations as ge
from great_expectations.core.batch import BatchRequest, RuntimeBatchRequest
redshift_username = os.environ.get("REDSHIFT_USERNAME")
redshift_password = os.environ.get("REDSHIFT_PASSWORD")
redshift_host = os.environ.get("REDSHIFT_HOST")
redshift_port = os... |
"""Data preprocessing and augmentations."""
import functools
from typing import Any, Mapping, Text
import dm_pix as pix
import jax
import jax.numpy as jnp
JaxBatch = Mapping[Text, jnp.ndarray]
ConfigDict = Mapping[Text, Any]
augment_config = dict(
view1=dict(
random_flip=False, # Random left/right flip
... |
"""
gene.py realize the methods that are related to system recommendation.
@author: Bowen
"""
from system.models import gene, reaction, compound, reaction_compound, compound_gene, pathway, pathway_compound, organism
from system.fasta_reader import parse_fasta_str
from elasticsearch import Elasticsearch
import traceback... |
from collections import OrderedDict
import os
import re
from typing import Dict, Optional, Sequence, Tuple, Type, Union
import pkg_resources
from google.api_core import client_options as client_options_lib
from google.api_core import exceptions as core_exceptions
from google.api_core import gapic_v1
from google.api_cor... |
from json import dumps
import requests
d = {'yolar': 535, 'galaxy': 536, 'solar': 551, 'swordkeeper': 552, 'civilization': 553, 'CurvatureDrive': 554,
'singer': 555, 'hdfragments': 556, 'evans': 557, 'dagon': 558, 'di-foil': 559, 'dimension': 560, 'farmer': 562,
'hibernation': 564, 'huformation': 565, 'mental... |
from models.contact import Contacts
from data.data_for_contacts import constant as testdata
import pytest
def test_NewContact(app, db, json_contacts):
contact = json_contacts
old_contacts = db.get_contact_list()
app.contacts.create_contact(contact)
new_contacts = db.get_contact_list()
old_contacts.a... |
import sys
import pytest
sys.path.append('..')
from batchflow import Config
@pytest.fixture
def config():
_config = dict(key1='val1', key2=dict())
_config['key2']['subkey1'] = 'val21'
return Config(_config)
class TestConfig:
def test_getitem_key(self, config):
assert config['key1'] == config.con... |
import json
import time
import pytest
from anchore_engine.auth.common import (
get_creds_by_registry,
get_docker_registry_userpw,
registry_record_matches,
)
_test_username = "tonystark"
_test_password = "potts"
_test_registry_meta = {
"authorizationToken": "{}:{}".format(_test_username, _test_password)
... |
"""Tests for trainer_utils.py."""
from absl.testing import parameterized
import tensorflow as tf
import tensorflow_federated as tff
from generalization.utils import eval_metric_distribution
from generalization.utils import trainer_utils
def keras_model_builder_with_zeros():
# Create a simple linear regression model, ... |
"""High level pandas structure for the Sonata prometheus data"""
import datetime
import typing # noqa pylint: disable=unused-import
from typing import Dict
import pandas # type: ignore
from son_analyze.core.prometheus import PrometheusData
def convert_timestamp_to_posix(timestamp: str) -> datetime.datetime:
"""Co... |
import sys
import os
import unittest
import datetime
import time
from copy import deepcopy
src_dir = os.path.dirname(os.path.realpath(__file__))
sys.path.append(os.path.join(src_dir, '..'))
from pyspark.sql.types import Row, StructType, StructField, IntegerType, StringType, BinaryType, BooleanType, DateType, TimestampT... |
import logging
from cliff import command
logger = logging.getLogger(__name__)
class FreeboxCommand(command.Command):
"""Default Freebox command."""
pass
class FreeboxApiVersion(FreeboxCommand):
"""Retrieve the Freebox OS api version."""
def take_action(self, parsed_args):
logger.info("[FreeboxOS... |
import sys, re
def remove_absolute_paths(line):
"""
Removes libraries from the line that are found under /usr
"""
if sys.platform == 'win32':
return line
elif sys.platform == 'darwin':
return re.sub('/Applications/[-_a-zA-Z0-9/.]+.framework[;]?', '', line)
else:
return re... |
"""
Parse PER vs. SINR data from trace files.
Revision Info
=============
* $LastChangedBy: mandke $
* $LastChangedDate: 2011-10-19 17:04:02 -0500 (Wed, 19 Oct 2011) $
* $LastChangedRevision: 5220 $
:author: Ketan Mandke <kmandke@mail.utexas.edu>
:copyright:
Copyright 2009-2011 The University of Texas at Austin
... |
import ctypes
class JLinkException(Exception): pass
class JLink(object):
"Jlink api"
revser = 0
def __init__(self, dllpath):
self.jlink = ctypes.cdll.LoadLibrary(dllpath)
self.tif_select(1)
self.set_speed(1000)
self.reset()
def check_err(fn):
def checked_transacti... |
"""Tests for the XLSX output module."""
import os
import unittest
import zipfile
from xml.etree import ElementTree
from plaso.containers import events
from plaso.formatters import interface as formatters_interface
from plaso.formatters import manager as formatters_manager
from plaso.lib import eventdata
from plaso.lib ... |
import curses
import npyscreen
from vent.helpers.paths import PathDirs
from vent.menu import VentApp
from vent.menus.main import MainForm
npyscreen.TEST_SETTINGS['CONTINUE_AFTER_TEST_INPUT'] = False
def run_menu(test_input):
""" Actually run the menu and process any input """
# initialize tutorial
paths = P... |
import sys
import os
from twython import Twython
import twitter_api_creds
CONSUMER_KEY = os.getenv("CONSUMER_KEY")
CONSUMER_SECRET = os.getenv("CONSUMER_SECRET")
ACCESS_KEY = os.getenv("ACCESS_KEY")
ACCESS_SECRET = os.getenv("ACCESS_SECRET")
api = Twython(CONSUMER_KEY, CONSUMER_SECRET, ACCESS_KEY, ACCESS_SECRET)
api.up... |
from direct.actor.Actor import Actor
from direct.task.Task import Task
from panda3d.core import *
from panda3d.direct import *
from otp.otpbase.OTPBase import OTPBase
from toontown.toonbase import ToontownGlobals
from toontown.toonbase import TTLocalizer
from toontown.parties.DistributedPartyActivity import Distributed... |
import pickle
import redis
from pod_manager.settings import REDIS_HOST, REDIS_PORT, REDIS_DB
__all__ = [
'get_client',
'cache_object',
'get_object'
]
def get_client():
client = redis.Redis(host=REDIS_HOST, port=REDIS_PORT, db=REDIS_DB)
return client
def cache_object(client, key, obj, ttl=60):
pi... |
"""`BaseModule` defines an API for modules."""
import time
import logging
import warnings
from .. import metric
from .. import ndarray
from ..context import cpu
from ..model import BatchEndParam
from ..initializer import Uniform
from ..io import DataDesc
from ..base import _as_list
def _check_input_names(symbol, names,... |
from collections import OrderedDict
from pecan import abort
from pecan import expose
from repoxplorer import version
from repoxplorer.index.projects import Projects
rx_version = version.get_version()
class ProjectsController(object):
@expose('json')
def projects(self, pid=None):
projects_index = Project... |
"""Load plugin assets from disk."""
import os.path
from tensorboard.compat import tf
_PLUGINS_DIR = "plugins"
def _IsDirectory(parent, item):
"""Helper that returns if parent/item is a directory."""
return tf.io.gfile.isdir(os.path.join(parent, item))
def PluginDirectory(logdir, plugin_name):
"""Returns the... |
"""
Test management of KeyboardInterrupt in stratisd.
"""
import stratis_cli
from .._misc import SimTestCase
class KeyboardInterruptTestCase(SimTestCase):
"""
Test behavior of stratis on KeyboardInterrupt.
"""
def test_catch_keyboard_exception(self):
"""
Verify that the KeyboardInterrupt... |
def generate_data_section(dataName, memLocs, strideType):
assert(memLocs <= 0x10000)
#dataArray = []
#for i in range(memLocs):
# data = [i & 0xFF, (i >> 8) & 0xFF, 0xFF, 0xFF]
# dataArray += data
## Data contents will be initialized in test manager, so just create a placeholder
if (str... |
from django.core import urlresolvers
from django.utils.translation import ugettext_lazy as _
from django.template.defaultfilters import timesince, floatformat
from horizon import tables
from horizon.templatetags.sizeformat import mbformat
class CSVSummary(tables.LinkAction):
name = "csv_summary"
verbose_name = ... |
import subprocess
import jsonschema
import mock
from rally import consts
from rally.plugins.common.hook import sys_call
from rally.task import hook
from tests.unit import fakes
from tests.unit import test
class SysCallHookTestCase(test.TestCase):
def test_validate(self):
hook.Hook.validate(
{
... |
from __future__ import absolute_import, division, print_function, unicode_literals
from pants.contrib.python.checks.tasks.checkstyle.plugin_subsystem_base import PluginSubsystemBase
class IndentationSubsystem(PluginSubsystemBase):
options_scope = 'pycheck-indentation'
def get_plugin_type(self):
from pants.contr... |
from caldavclientlibrary.protocol.http.util import parsequoted
from caldavclientlibrary.protocol.http.util import parsetoken
from caldavclientlibrary.protocol.http.util import parseStatusLine
import unittest
class TestParseQuoted(unittest.TestCase):
def testParseQuotedOK(self):
data = {
"\"\"" ... |
from transitfeed import TYPE_ERROR, TYPE_WARNING, TYPE_NOTICE
from oba_rvtd_monitor.feedvalidator import LimitPerTypeProblemAccumulator
class MonitoringProblemAccumulator(LimitPerTypeProblemAccumulator):
pass |
"""
This component provides basic support for Amcrest IP cameras.
For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/camera.amcrest/
"""
import logging
from homeassistant.components.amcrest import (
DATA_AMCREST, STREAM_SOURCE_LIST, TIMEOUT)
from homeassi... |
from gafferpy import gaffer as g
from gafferpy import gaffer_connector
def run(host, verbose=False):
return run_with_connector(create_connector(host, verbose))
def run_with_connector(gc):
print()
print('Running operations')
print('--------------------------')
print()
get_schema(gc)
get_filte... |
usage = '''
Write buildbot spec to outfile based on the bot name:
$ python buildbot_spec.py outfile Test-Ubuntu-GCC-GCE-CPU-AVX2-x86-Debug
Or run self-tests:
$ python buildbot_spec.py test
'''
import inspect
import json
import os
import sys
import builder_name_schema
import dm_flags
import nanobench_flags
CONFIG_CO... |
import base64
import errno
import random
import ssl
import threading
import time
import copy
import websocket
import xmltodict
import config
import debug
from utils import exitutils
import hubs.isy.isycodes as isycodes
import logsupport
from controlevents import CEvent, PostEvent, ConsoleEvent, PostIfInterested
from hu... |
from .array_ import array # noqa: F401
from .base import ( # noqa: F401
ExtensionArray,
ExtensionOpsMixin,
ExtensionScalarOpsMixin,
)
from .categorical import Categorical # noqa: F401
from .datetimes import DatetimeArray # noqa: F401
from .integer import IntegerArray, integer_array # noqa: F401
from .i... |
"""Pipeline utility functions."""
import json
import os
import sys
from absl import logging
import tensorflow.compat.v1 as tf
import tf_slim
from poem.core import common
from poem.core import keypoint_utils
from poem.core import tfe_input_layer
def read_batch_from_dataset_tables(input_table_patterns,
... |
import time
from helpers import unittest
import luigi.notifications
from luigi.scheduler import DISABLED, DONE, FAILED, CentralPlannerScheduler
luigi.notifications.DEBUG = True
WORKER = 'myworker'
class CentralPlannerTest(unittest.TestCase):
def setUp(self):
super(CentralPlannerTest, self).setUp()
c... |
import unittest
import datetime
import iso8601
from brkt_cli import CLIConfig
from brkt_cli import version
class TestVersionCheck(unittest.TestCase):
def test_is_version_supported(self):
supported = [
'0.9.8', '0.9.9', '0.9.9.1', '0.9.10', '0.9.11', '0.9.12'
]
self.assertFalse(
... |
"""Single and multi-threaded executors."""
import datetime
import functools
import logging
import math
import os
import threading
from abc import ABCMeta, abstractmethod
from threading import Lock
from typing import (
Dict,
Iterable,
List,
MutableSequence,
Optional,
Set,
Tuple,
Union,
... |
from mistral.lang import types
from mistral.lang.v2 import base
from mistral_lib import utils
class ActionSpec(base.BaseSpec):
# See http://json-schema.org
_schema = {
"type": "object",
"properties": {
"base": types.NONEMPTY_STRING,
"base-input": types.NONEMPTY_DICT,
... |
from model.group_address import Address_data
import random
import string
import os.path
import jsonpickle
import getopt
import sys
try:
opts, args = getopt.getopt(sys.argv[1:], "n:f:", ["number of groups", "file"])
except getopt.GetoptError as err:
getopt.usage()
sys.exit(2)
n = 5
f = "data/contacts.json"
f... |
from collections import defaultdict, namedtuple
import csv
import datetime
import dateutil.parser
import pytz
import logging
import os
import sys
import tensorflow as tf
import yaml
import numpy as np
import hashlib
import six
from .feature_generation.file_iterator import GCSFile
""" The main column for vessel classifi... |
import logging
from django.shortcuts import redirect
from horizon import exceptions
from horizon import tables
from openstack_dashboard import api
from openstack_dashboard import fiware_api
from openstack_dashboard.dashboards.idm import utils as idm_utils
from openstack_dashboard.dashboards.idm.home import tables as ho... |
""" Creating ensembles predictions
"""
from .world import world, setup_module, teardown_module
from . import create_source_steps as source_create
from . import create_dataset_steps as dataset_create
from . import create_ensemble_steps as ensemble_create
from . import create_prediction_steps as prediction_create
class T... |
def f(a):
global a |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import codecs
import os
import re
from pkg_resources import resource_string
from pygments.formatters.html import HtmlFormatter
from pygments.styles import get_all_style... |
import mock
from jacket.compute import test
from jacket.compute.virt.disk.mount import api
from jacket.compute.virt.disk.mount import block
from jacket.compute.virt.disk.mount import loop
from jacket.compute.virt.disk.mount import nbd
from jacket.compute.virt.image import model as imgmodel
PARTITION = 77
ORIG_DEVICE = ... |
"""This code example updates a creative set by adding a companion creative.
To determine which creative sets exist, run get_all_creative_sets.py.
The LoadFromStorage method is pulling credentials and properties from a
"googleads.yaml" file. By default, it looks for this file in your home
directory. For more information... |
"""Defines interface for DB access.
The underlying driver is loaded as a :class:`LazyPluggable`.
Functions in this module are imported into the nova.db namespace. Call these
functions from nova.db namespace, not the nova.db.api namespace.
All functions in this module return objects that implement a dictionary-like
inte... |
import sys, os
sys.path.append(os.path.abspath("../utils/"))
from utils_io_list import *
from test_utils_io_folder import *
def test_generate_pairs_for_each_folder():
images_folder_path= "folder/path/example"
num_of_frames = 2
pairs = generate_pairs_for_each_folder(images_folder_path, num_of_frames)
exp... |
from __future__ import unicode_literals
from django.db import migrations, models
import datetime
import caching.base
class Migration(migrations.Migration):
dependencies = [
('opendebates', '0018_flag_note'),
]
operations = [
migrations.CreateModel(
name='SiteMode',
fi... |
from proxy import Proxy, proxied_attr
from proxy import proxied_attr_get as pag, proxied_attr_set as pas, proxied_attr_getset as pags
from arc_utils import arcmethod, uniq
from singleton import v as store_singleton
import errors
from errors import not_implemented, fail
from constants import PARTITION_GROUP, LABEL_SENTI... |
"""Layers for a progressive GAN model.
This module contains basic building blocks to build a progressive GAN model.
See https://arxiv.org/abs/1710.10196 for details about the model.
See https://github.com/tkarras/progressive_growing_of_gans for the original
theano implementation.
"""
import numpy as np
import tensorflo... |
import copy
import uuid
import mock
import yaml
from mistralclient.api.v2 import action_executions
from mistralclient.api.v2 import executions
from mistralclient.api.v2 import workflows
from oslo_config import cfg
import st2tests.config as tests_config
tests_config.parse_args()
from mistral_v2 import MistralRunner
impo... |
class Solution(object):
def count_bits(self, n):
c = (n - ((n >> 1) & 0o33333333333) - ((n >> 2) & 0o11111111111))
return ((c + (c >> 3)) & 0o30707070707) % 63
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
"""
return map(self.count_bits, x... |
""" Nodes for try/except/finally handling.
This is the unified low level solution to trying a block, and executing code
when it returns, break, continues, or raises an exception. See Developer
Manual for how this maps to try/finally and try/except as in Python.
"""
from nuitka.Errors import NuitkaOptimizationError
from... |
"""node_status version"""
__version__ = '0.1.0' |
import sys
from distutils.core import setup, Distribution
from aws.cfn import bridge
name = 'aws-cfn-resource-bridge'
if sys.version_info[0] == 2 and sys.version_info[1] < 6:
print >> sys.stderr, "Python 2.6+ is required"
sys.exit(1)
rpm_requires = ['python >= 2.6', 'python-daemon', 'python-botocore >= ... |
__version__ = "1.3.15" |
from __future__ import absolute_import, print_function
import logging
from datetime import datetime
from changes.config import db
from changes.models import Repository, RepositoryStatus
from changes.queue.task import tracked_task
logger = logging.getLogger('repo.sync')
@tracked_task(max_retries=None)
def import_repo(re... |
from django.contrib.auth.forms import PasswordResetForm, SetPasswordForm
from django.contrib.auth.tokens import default_token_generator
from django.contrib.auth.views import password_reset_confirm
from django.template.response import TemplateResponse
from django.utils.translation import ugettext as _
from xadmin.sites ... |
import atexit
import datetime
import json
import os
import threading
import time
import logging
from functools import wraps
import elasticsearch as es7
import elasticsearch6 as es6
import pytz
from elasticsearch import helpers as helpers7
from elasticsearch6 import helpers as helpers6
from .common import Config, INDEX_... |
from neural_compressor.conf.config import Quantization_Conf
from neural_compressor.experimental import Quantization, common
from neural_compressor.experimental.common import Metric
from .metric import METRICS
class QuantizationINC(Quantization):
def __init__(self,
framework: str,
c... |
"""An HTTP proxy that supports IPv6 as well as the HTTP CONNECT method, among
other things."""
import socket
import thread
import select
__version__ = '0.1.0 Draft 1'
BUFFER_LENGTH = 8192
VERSION = 'Python Proxy/{}'.format(__version__)
HTTP_VERSION = 'HTTP/1.1'
class ConnectionHandler(object):
"""Handles connection... |
from __future__ import print_function
import argparse
import sys
import os
import multiprocessing as mp
import subprocess as sp
import tempfile
import shlex
import shutil
"""
Compress all netcdf files under a directories.
compress_nc.py ~/exps/access/cm_1440x1080-1/archive/ ./'
This will recursively search under that d... |
from posixpath import join as pjoin
import pytest
from pandas.util.testing import assert_frame_equal
import pandas as pd
from ibis.compat import unittest
from ibis.impala.compat import ImpylaError
from ibis.impala.tests.common import ImpalaE2E
from ibis.tests.util import assert_equal
import ibis
import ibis.util as uti... |
import sys, csv, string
def generate_R_input(report_path, output_path):
confidence_values = []
report_file = open(report_path, 'r')
first_line = True
for line in report_file:
if first_line:
first_line = False
continue
line = line.strip().split(',')
if line[5] == 'Yes':... |
from kubeflow.kubeflow.crud_backend import api, status
def pvc_status(pvc):
"""
Set the status of the pvc
"""
if pvc.metadata.deletion_timestamp is not None:
return status.create_status(status.STATUS_PHASE.TERMINATING,
"Deleting Volume...")
if pvc.status.p... |
from __future__ import absolute_import, print_function
import os
import pickle
import time
from collections import namedtuple
from math import sqrt
from tempfile import mkstemp
import inspyred
import numpy
import pytest
from inspyred.ec import Bounder
from inspyred.ec.emo import Pareto
from ordered_set import OrderedSe... |
"""
Kubernetes
No description provided (generated by Openapi Generator https://github.com/openapitools/openapi-generator) # noqa: E501
The version of the OpenAPI document: release-1.23
Generated by: https://openapi-generator.tech
"""
import pprint
import re # noqa: F401
import six
from kubernetes.clie... |
r"""Script to generate api_docs for MLMD.
The script needs to be run under Python3.
The doc generator can be installed with:
```
$> pip3 install git+https://github.com/tensorflow/docs
```
To run from it on the mlmd pip package:
```
python3 ml_metadata/tools/documentation/build_docs.py --output_dir=/tmp/mlmd
```
"""
fro... |
import os
import pydoc
import sys
class DocTree:
def __init__(self, src, dest):
self.basepath = os.getcwd()
sys.path.append(os.path.join(self.basepath, src))
self.src = src
self.dest = dest
self._make_dest(dest)
self._make_docs(src)
self._move_docs(dest)
d... |
import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.coils import CoilHeatingDxVariableSpeed
log = logging.getLogger(__name__)
class TestCoilHeatingDxVariableSpeed(unittest.TestCase):
def setUp(self):
self.fd, self.path ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.