code stringlengths 1 199k |
|---|
import json
import os
import shutil
import tempfile
from unittest import TestCase
from transformers import BartTokenizer, BartTokenizerFast, DPRQuestionEncoderTokenizer, DPRQuestionEncoderTokenizerFast
from transformers.file_utils import is_datasets_available, is_faiss_available, is_torch_available
from transformers.mo... |
import copy
import unittest
import numpy as np
from transformers.file_utils import is_torch_available
from transformers.testing_utils import require_torch
if is_torch_available():
import torch
from torch import nn
from torch.utils.data import IterableDataset
from transformers.modeling_outputs import Seq... |
from models.RepPoints.builder import RepPoints as Detector
from models.dcn.builder import DCNResNetFPN as Backbone
from models.RepPoints.builder import RepPointsNeck as Neck
from models.RepPoints.builder import RepPointsHead as Head
from mxnext.complicate import normalizer_factory
def get_config(is_train):
class Ge... |
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.template import RequestContext
from django.shortcuts import redirect
from main.models import Link
from main.models import Tag
def index(request):
context = RequestContext(request)
links = Link.objects.all()
retur... |
import os
import time
import uuid
import concurrent.futures
from oslo_config import cfg
import six.moves
from testtools import matchers
import oslo_messaging
from oslo_messaging.tests.functional import utils
class CallTestCase(utils.SkipIfNoTransportURL):
def setUp(self):
super(CallTestCase, self).setUp(con... |
from __future__ import annotations
from typing import *
from edb.edgeql import ast as qlast
from edb.edgeql import qltypes
from edb import errors
from . import abc as s_abc
from . import constraints
from . import delta as sd
from . import indexes
from . import inheriting
from . import properties
from . import name as s... |
import bisect
import string
from abc import ABC, abstractmethod
from typing import Optional
from django.conf import settings
class AbstractGrid(ABC):
enabled = False
@abstractmethod
def get_square_for_point(self, x, y) -> Optional[str]:
pass
@abstractmethod
def get_squares_for_bounds(self, b... |
from model.contact import Contact
from random import randrange
def test_edit_contact(app, db, check_ui):
if len(db.get_contact_list()) == 0:
app.contact.create(Contact(first_name ="Sabina", last_name="test", company="Pewex",
address="osiedle", phone_home="123456789", e_mai... |
import os
import socket
from unittest import mock
from oslotest import base as test_base
from oslo_service import systemd
class SystemdTestCase(test_base.BaseTestCase):
"""Test case for Systemd service readiness."""
def test__abstractify(self):
sock_name = '@fake_socket'
res = systemd._abstracti... |
class Solution:
def dailyTemperatures(self, T):
ans = []
m = [None]*101
for i in range(len(T)-1, -1, -1):
x = T[i]
m[x] = i
ans.append(min([x for x in m[x+1:] if x is not None], default=i)-i)
ans.reverse()
return ans
print(Solution().dailyT... |
"""
Print the number of bases in a nib file.
usage: %prog nib_file
"""
from bx.seq import nib as seq_nib
import sys
nib = seq_nib.NibFile( file( sys.argv[1] ) )
print nib.length |
'''
Created on Feb 3, 2013
@author: bpurgaso
'''
from twisted.words.protocols import irc
from twisted.internet import protocol
from twisted.internet import reactor
from twisted.internet import threads
from ConfigManager import ConfigManager
from Authenticator import Authenticator
from subprocess import PIPE, STDOUT, Po... |
"""Support for Tibber."""
import asyncio
import logging
import aiohttp
import tibber
from homeassistant.const import (
CONF_ACCESS_TOKEN,
CONF_NAME,
EVENT_HOMEASSISTANT_STOP,
Platform,
)
from homeassistant.exceptions import ConfigEntryNotReady
from homeassistant.helpers import discovery
from homeassista... |
import pytest
from collections import OrderedDict
from insights.parsers import (calc_offset, keyword_search, optlist_to_dict, parse_delimited_table, parse_fixed_table,
split_kv_pairs, unsplit_lines, ParseException, SkipException)
SPLIT_TEST_1 = """
keyword1 = value1 # Inline comments
... |
"""
@date 2014-11-16
@author Hong-She Liang <starofrainnight@gmail.com>
"""
from selenium.common.exceptions import * |
"""
Runs either `.fit()` or `.test()` on a single node across multiple gpus.
"""
import os
from argparse import ArgumentParser
import torch
from pytorch_lightning import seed_everything, Trainer
from tests.helpers.datamodules import ClassifDataModule
from tests.helpers.simple_models import ClassificationModel
def main(... |
import csv
import os
import color
def _GetDataDirPath():
return os.path.join(os.path.dirname(__file__), 'data')
def _GetCsvPath():
return os.path.join(_GetDataDirPath(), 'dmccolors.csv')
def _GetCsvString():
with open(_GetCsvPath()) as f:
return f.read().strip()
def _CreateDmcColorFromRow(row):
number = int... |
"""A simple memcache-like server.
The basic data structure maintained is a single in-memory dictionary
mapping string keys to string values, with operations get, set and
delete. (Both keys and values may contain Unicode.)
This is a TCP server listening on port 54321. There is no
authentication.
Requests provide an op... |
import operator
from pyspark import since, keyword_only
from pyspark.ml import Estimator, Model
from pyspark.ml.param.shared import *
from pyspark.ml.regression import DecisionTreeModel, DecisionTreeRegressionModel, \
RandomForestParams, TreeEnsembleModel, TreeEnsembleParams
from pyspark.ml.util import *
from pyspa... |
"""
Test lldb breakpoint command add/list/delete.
"""
from __future__ import print_function
import lldb
from lldbsuite.test.decorators import *
from lldbsuite.test.lldbtest import *
from lldbsuite.test import lldbutil
import side_effect
class BreakpointCommandTestCase(TestBase):
NO_DEBUG_INFO_TESTCASE = True
my... |
"""Functional tests for Stack and ParallelStack Ops."""
import numpy as np
from tensorflow.python import tf2
from tensorflow.python.eager import context
from tensorflow.python.eager import def_function
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes
from tensorflow.pyt... |
from flask import abort
from flask import Blueprint
from flask import jsonify
from flask import request
from keystoneauth1 import exceptions as exc
from keystoneauth1 import session as ks_session
from keystoneclient.auth.identity import v3
from keystoneclient.v3 import client as ks_client
import logging
import os
from ... |
import experiment
from ..util import dirs
from ..util import file_handling as fh
from optparse import OptionParser
import sys
def main():
usage = "%prog project logfile "
parser = OptionParser(usage=usage)
parser.add_option('-n', dest='new_name', default=None,
help='New name for experi... |
from __future__ import with_statement
import functools
import errno
import os
import resource
import signal
import time
import subprocess
import re
from swift.common.utils import search_tree, remove_file, write_file
SWIFT_DIR = '/etc/swift'
RUN_DIR = '/var/run/swift'
ALL_SERVERS = ['account-auditor', 'account-server', ... |
"""App name"""
from django.apps import AppConfig
class CertificateEngineConfig(AppConfig):
name = "certificate_engine" |
"""Base classes and functions for dynamic decoding."""
import abc
import tensorflow as tf
from tensorflow_addons.utils.types import TensorLike
from typeguard import typechecked
from typing import Any, Optional, Tuple, Union
from tensorflow.python.ops import control_flow_util
class Decoder(metaclass=abc.ABCMeta):
""... |
from collections import OrderedDict
import functools
import re
from typing import (
Dict,
Optional,
AsyncIterable,
Awaitable,
AsyncIterator,
Sequence,
Tuple,
Type,
Union,
)
import pkg_resources
from google.api_core.client_options import ClientOptions
from google.api_core import excep... |
"""Testing.
See the [Testing](https://tensorflow.org/api_docs/python/tf/test) guide.
Note: `tf.compat.v1.test.mock` is an alias to the python `mock` or
`unittest.mock` depending on the python version.
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from t... |
import click
from copy import copy
from netCDF4 import Dataset
import numpy as np
import numpy.ma as ma
import os
import rasterio
import rasterio.warp as rwarp
import time
import osr
from .. import geotools
from .. import utils
def earth_radius():
srs = osr.SpatialReference()
srs.ImportFromEPSG(4326)
return srs.G... |
import itertools
import json
import logging
import os
import time
from collections import deque
from six import iteritems, itervalues
from six.moves import queue as Queue
from pyspider.libs import counter, utils
from pyspider.libs.base_handler import BaseHandler
from .task_queue import TaskQueue
logger = logging.getLog... |
"""
Wavefront REST API Documentation
<p>The Wavefront REST API enables you to interact with Wavefront servers using standard REST API tools. You can use the REST API to automate commonly executed operations such as automatically tagging sources.</p><p>When you make REST API calls outside the Wavefront REST API ... |
"""
- 1. This model has 1,068,298 paramters and quantization compression strategy(weight:8 bits, active: 8 bits here, you can change the setting),
after 705 epoches' training with GPU, test accurcy of 84.0% was found.
- 2. For simplified CNN layers see "Convolutional layer (Simplified)"
in read the docs website.
- 3. D... |
__author__ = 'thorsteinn'
def get_all_ship_fields(db):
ships = db.keys()
fields = []
for ship in ships:
shipDB = db[ship]
shipKeys = shipDB.keys()
for oneKey in shipKeys:
if oneKey not in fields:
fields.append(oneKey)
return fields |
print(2 + 2) # 4
print(50 - 5*6) # 20
print((50 - 5*6) / 4) # 5.0
print(8/5) # 1.6
print(17 / 3) # 5.666666666666667 float
print(17 // 3) # 5 取整
print(17 % 3) # 2 取模
print(5*3+2) # 17 先乘除,后加减
print(2+5*3) # 17 先乘除,后加减
print(5**2) ... |
"""
Server API
Reference for Server API (REST/Json)
OpenAPI spec version: 2.0.6
Generated by: https://github.com/swagger-api/swagger-codegen.git
"""
from __future__ import absolute_import
import sys
import os
import re
from six import iteritems
from ..configuration import Configuration
from ..api_client... |
"""
.. module:: shellscribe
Shell-Scribe run.py
@author: Keith E. Miller <keithmiller@umass.edu>
Expected issues:
- cd command is shell-scribe specific so commands that use cd in a non-trivial
way might break the cd command
"""
import cmd
import os
import sys
import argparse as ap
import datetime
import json
from twili... |
import os
import sys
import etcd
import subprocess
import signal
import time
if len(sys.argv) < 2:
print("Please provide a server argument")
sys.exit(1)
def siginthandler(signum, stackframe):
sys.exit(-1)
signal.signal(signal.SIGINT, siginthandler)
logpath="/log"
if len(sys.argv) > 2:
logpath=sys.argv[2]
while True... |
from mido import MidiFile
from time import sleep
import pibrella
""" fade test
pibrella.light.red.fade(0,100,10)
sleep(11)
pibrella.light.red.fade(100,0,10)
sleep(11)
"""
""" start
pibrella.buzzer.note(-9)
sleep(.9)
pibrella.buzzer.off()
sleep(0.1)
pibrella.buzzer.note(-9)
sleep(0.9)
pibrella.buzzer.off()
sleep(0.1)
pi... |
from model.contact import Contact
import random
def test_delete_some_contact(app, db, check_ui):
if len(db.get_contact_list()) == 0:
app.contact.add(Contact(firstname="test"))
old_contacts = db.get_contact_list()
contact = random.choice(old_contacts)
app.contact.delete_contact_by_id(contact.id)
... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import paddle.fluid as fluid
from utility import get_gpu_num
class NpairsLoss():
def __init__(self,
train_batch_size = 160,
samples_each_class=2,
reg_lambda... |
"""Support for INSTEON Modems (PLM and Hub)."""
import asyncio
from contextlib import suppress
import logging
from pyinsteon import async_close, async_connect, devices
from homeassistant.config_entries import SOURCE_IMPORT
from homeassistant.const import CONF_PLATFORM, EVENT_HOMEASSISTANT_STOP
from homeassistant.except... |
"""Config flow for ReCollect Waste integration."""
from __future__ import annotations
from typing import Any
from aiorecollect.client import Client
from aiorecollect.errors import RecollectError
import voluptuous as vol
from homeassistant import config_entries
from homeassistant.const import CONF_FRIENDLY_NAME
from hom... |
import robot_util
def sendSettings(ser, args):
if args.right_wheel_forward_speed is not None:
robot_util.sendSerialCommand(ser, "rwfs " + str(args.right_wheel_forward_speed))
if args.right_wheel_backward_speed is not None:
robot_util.sendSerialCommand(ser, "rwbs " + str(args.right_wheel_backward... |
""" Cisco_IOS_XR_infra_objmgr_cfg
This module contains a collection of YANG definitions
for Cisco IOS\-XR infra\-objmgr package configuration.
This module contains definitions
for the following management objects\:
object\-group\: Object\-group configuration
Copyright (c) 2013\-2016 by Cisco Systems, Inc.
All rights ... |
from django.contrib.contenttypes.fields import GenericForeignKey
from django.contrib.contenttypes.models import ContentType
from django.db import models
from model_utils import Choices
from model_utils.models import TimeStampedModel
class History(TimeStampedModel):
RESOLUTIONS = Choices('second', 'minute', 'hour', ... |
pass |
import sys
import re
"""Baby Names exercise
Define the extract_names() function below and change main()
to call it.
For writing regex, it's nice to include a copy of the target
text for inspiration.
Here's what the html looks like in the baby.html files:
...
<h3 align="center">Popularity in 1990</h3>
....
<tr align="ri... |
from selenium import webdriver
from selenium.common.exceptions import NoSuchElementException, TimeoutException
from bs4 import BeautifulSoup
from datetime import datetime
from decimal import *
import sys
phantonPath = "../phantomjs/phantomjs"
contratacionPage = "https://contrataciondelestado.es/wps/portal/!ut/p/b1/lZD... |
from python_kemptech_api import *
loadmaster_ip = ""
username = ""
password = ""
vs_ip_1 = ""
vs_ip_2 = ""
rs_ip_1 = ""
rs_ip_2 = ""
vs_port = ""
rs_port = ""
class RealServerPool(object):
healthcheck_parameters = [
"checktype",
"checkport",
"checkurl",
"checkheaders",
"check... |
import mock
from neutron_lib import constants as common_constants
from neutron_lib import context
from neutron_lib.db import constants as db_consts
from neutron_lib.services.qos import constants as qos_consts
from oslo_utils import uuidutils
from neutron.agent.l2.extensions import qos
from neutron.agent.l2.extensions i... |
"""Python DB-API (PEP 249) interface to SQL Service.
http://www.python.org/dev/peps/pep-0249/
"""
import collections
import datetime
import exceptions
import os
import time
import types
from google.storage.speckle.proto import client_error_code_pb2
from google.storage.speckle.proto import client_pb2
from google.storage... |
"""
[START gae_block_comment_tag]
[END gae_block_comment_tag]
""" |
from future import standard_library
standard_library.install_aliases()
import logging
import sys
from thrift.transport.TTransport import *
from desktop.lib.rest.http_client import HttpClient
from desktop.lib.rest.resource import Resource
if sys.version_info[0] > 2:
from io import BytesIO as buffer_writer
else:
from... |
"""Python wrapper for gcd.sh."""
__author__ = 'eddavisson@google.com (Ed Davisson)'
import logging
import os
import shutil
import socket
import subprocess
import tempfile
import time
import urllib
import zipfile
import httplib2
import portpicker
from googledatastore import connection
_DEFAULT_GCD_OPTIONS = ['--allow_re... |
from __future__ import (absolute_import, division, generators, nested_scopes, print_function,
unicode_literals, with_statement)
import logging
from pants.engine.fs import EMPTY_SNAPSHOT
from pants.engine.rules import RootRule, rule
from pants.engine.selectors import Select
from pants.util.object... |
import sys
sys.path.insert(0, './getresults')
import datetime
from flightsearch import flightsearch, flightresult
import os
import uuid
import time
from pprint import pprint
def main():
flyfrom = 'YYZ' #input("Enter departure city or airport code, e.g. Toronto or YYZ:\n")
datefrom = '2017-04-26' #input("Enter d... |
import pytest
import torch
from torch.autograd import Variable
from allennlp.common import Params
from allennlp.common.checks import ConfigurationError
from allennlp.data import Vocabulary
from allennlp.modules.text_field_embedders import BasicTextFieldEmbedder
from allennlp.common.testing import AllenNlpTestCase
class... |
import inventory.inventory_class as inv
import weapons.weapon_class as wp
class people:
"""This is the people class with attributes:"""
def name():
n = ''
return n
def health():
hp = 0
return hp
def descript():
d = 'Description of the person or creature'
r... |
az.plot_dist(b, rug=True, quantiles=[.25, .5, .75], cumulative=True) |
"""Tests for parser and parser plugin presets."""
from __future__ import unicode_literals
import unittest
from plaso.containers import artifacts
from plaso.parsers import presets
from tests import test_lib as shared_test_lib
class ParserPresetTest(shared_test_lib.BaseTestCase):
"""Tests for the parser and parser plug... |
import csv
import numpy
import matplotlib.pyplot as plt
price, size = numpy.loadtxt('house.csv', delimiter='|', usecols=(1, 2), unpack=True)
print price
print size
plt.figure()
plt.subplot(211)
plt.title("/ 10000RMB")
plt.hist(price, bins=20)
plt.subplot(212)
plt.xlabel("/ m**2")
plt.hist(size, bins=20)
plt.figure(2)
p... |
import requests
import yaml
import time
import enum
import sys
import re
import logging
import ssl
from requests.auth import HTTPDigestAuth
from requests.auth import HTTPBasicAuth
from lxml import etree as ET
from requests.packages.urllib3.exceptions import InsecureRequestWarning
from requests.adapters import HTTPAdapt... |
import os
import subprocess
import sys
import pytest
sys.path.append("tests/python")
import testing as tm
import test_demos as td # noqa
@pytest.mark.skipif(**tm.no_cupy())
def test_data_iterator():
script = os.path.join(td.PYTHON_DEMO_DIR, 'quantile_data_iterator.py')
cmd = ['python', script]
subpr... |
"""
Tests for zipline.pipeline.loaders.frame.DataFrameLoader.
"""
from unittest import TestCase
from mock import patch
from numpy import arange, ones
from numpy.testing import assert_array_equal
from pandas import (
DataFrame,
DatetimeIndex,
Int64Index,
)
from zipline.lib.adjustment import (
Float64Add,... |
'''
Implements the RTS ALUA Target Port Group class.
This file is part of RTSLib.
Copyright (c) 2016 by Red Hat, Inc.
Licensed under the Apache License, Version 2.0 (the "License"); you may
not use this file except in compliance with the License. You may obtain
a copy of the License at
http://www.apache.org/license... |
from . import submission
from .submission.run_context import RunContext
from .submission.submit import SubmitTarget
from .submission.submit import PathType
from .submission.submit import SubmitConfig
from .submission.submit import submit_run
from .submission.submit import get_path_from_template
from .submission.submit ... |
"""A soccer ball that keeps track of ball-player contacts."""
import os
from dm_control import mjcf
from dm_control.entities import props
import numpy as np
from dm_control.utils import io as resources
_ASSETS_PATH = os.path.join(os.path.dirname(__file__), 'assets', 'soccer_ball')
_REGULATION_RADIUS = 0.117 # Meters.
... |
"""
Track Control User Modes component originally designed for use with the APC40.
Copyright (C) 2010 Hanz Petrov <hanz.petrov@gmail.com>
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... |
"""Tests for the Jaco arm class."""
import itertools
import unittest
from absl.testing import absltest
from absl.testing import parameterized
from dm_control import composer
from dm_control import mjcf
from dm_control.entities.manipulators import kinova
from dm_control.entities.manipulators.kinova import jaco_arm
from ... |
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import unittest
from ddp.messages.client import MethodMessage
from ddp.messages.client import MethodMessageParser
class MethodMessageParserTestCase(unittest.TestCase):
def setUp(self):
self.parser = ... |
"""The tests for the Tasmota binary sensor platform."""
import copy
from datetime import timedelta
import json
from unittest.mock import patch
from hatasmota.utils import (
get_topic_stat_result,
get_topic_stat_status,
get_topic_tele_sensor,
get_topic_tele_will,
)
from homeassistant.components import bi... |
"""Code that creates simple startup projects."""
from pathlib import Path
from enum import Enum
import subprocess
import shutil
import sys
import os
import re
from glob import glob
from mesonbuild import mesonlib
from mesonbuild.environment import detect_ninja
from mesonbuild.templates.samplefactory import sameple_gene... |
From SimpleCV import Camera
cam = Camera()
while True:
# Get Image from camera
img = cam.getImage()
# Make image black and white
img = img.binarize()
# Draw the text "Hello World" on image
img.drawText("Hello World!")
# Show the image
img.show() |
class RelationHistory(In.entity.Entity):
'''RelationHistory Entity class.
'''
def __init__(self, data = None, items = None, **args):
# default
self.relation_id = 0
self.action = ''
self.actor_entity_type = ''
self.actor_entity_id = 0
self.message = ''
super().__init__(data, items, **args)
@IN.register(... |
from south.utils import datetime_utils as datetime
from south.db import db
from south.v2 import SchemaMigration
from django.db import models
class Migration(SchemaMigration):
def forwards(self, orm):
# Deleting field 'ToIndexStore.basemodel_ptr'
db.delete_column(u'catalog_toindexstore', u'basemodel_... |
import copy
import mock
from oslo_serialization import jsonutils
import webob
from nova.api.openstack.compute import image_metadata as image_metadata_v21
from nova import exception
from nova import test
from nova.tests.unit.api.openstack import fakes
from nova.tests.unit import image_fixtures
IMAGE_FIXTURES = image_fix... |
"""File system module."""
import posixpath
from functools import wraps as implements
import ibis.common.exceptions as com
from ibis.config import options
class HDFSError(com.IbisError):
"""HDFS Error class."""
pass
class HDFS:
"""Interface class to HDFS.
Interface class to HDFS for ibis that abstracts a... |
import common
import ports
import os
import subprocess
import time
await_seconds = 1 # Async invocations must be verfied (or used) after a delay.
def setup_container_port(docker_pid=None, port_name=None, port_ip_addr=None):
"""
Push the vport to the container namespace.
"""
# Push the KNI port ... |
from __future__ import print_function
from optparse import OptionParser
import json
import os
import pdb
import pickle
import sys
import h5py
import numpy as np
import pandas as pd
import pysam
import pyBigWig
import tensorflow as tf
if tf.__version__[0] == '1':
tf.compat.v1.enable_eager_execution()
from basenji impo... |
import signal
import boto.sqs
import ujson
from mobile_push.config import setting
from mobile_push.logger import logger
from mobile_push.message_router import MessageRouter
keep_running = True
def sigterm_handler(signum, _):
global keep_running
logger.warn('Receive SIGTERM')
keep_running = False
def get_que... |
import os
import subprocess
from ruamel import yaml
import great_expectations as ge
context = ge.get_context()
gcp_project = os.environ.get("GE_TEST_GCP_PROJECT")
if not gcp_project:
raise ValueError(
"Environment Variable GE_TEST_GCP_PROJECT is required to run BigQuery integration tests"
)
great_expect... |
"""Support for KNX/IP climate devices."""
import voluptuous as vol
from homeassistant.components.climate import PLATFORM_SCHEMA, ClimateDevice
from homeassistant.components.climate.const import (
STATE_DRY, STATE_ECO, STATE_FAN_ONLY, STATE_HEAT, STATE_IDLE, STATE_MANUAL,
SUPPORT_ON_OFF, SUPPORT_OPERATION_MODE, ... |
import argparse
import logging
import os
import stat
import subprocess
import sys
import time
import yaml
class ConfigurationError(Exception):
pass
def configure_waf_haproxy_cp(logger, run_dir, mgmt_ip, haproxy_cp_ip):
sh_file = "{}/waf_set_haproxy_config-{}.sh".format(run_dir, time.strftime("%Y%m%d%H%M%S"))
... |
import sys
import time
try:
from unittest import mock
except ImportError:
import mock
import testtools
import threading
import six
from six.moves.queue import Queue, Empty
from swiftclient import multithreading as mt
from swiftclient.exceptions import ClientException
class ThreadTestCase(testtools.TestCase):
... |
import concurrent
from concurrent.futures._base import Future
import json
from threading import Barrier
import time
import unittest
import requests_mock
from rpcclient.client import RpcClient
from rpcclient.deserialize import DictDeserializer
from rpcclient.exceptions import RemoteFailedError
from rpcclient.handlers im... |
"""
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this ... |
"""Functional tests for binary coefficient-wise operations."""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import numpy as np
from tensorflow.python.framework import constant_op
from tensorflow.python.framework import dtypes as dtypes_lib
from tensorflow.... |
import argparse, sys
from confluent_kafka import avro, KafkaError
from confluent_kafka.admin import AdminClient, NewTopic
from uuid import uuid4
name_schema = """
{
"namespace": "io.confluent.examples.clients.cloud",
"name": "Name",
"type": "record",
"fields": [
{"name": ... |
from django.shortcuts import redirect
from django.shortcuts import render
from django.views.decorators.cache import never_cache
from django.contrib.auth.decorators import permission_required
from django.contrib.auth.decorators import login_required
from registration.backends import get_backend
def register(request, bac... |
import happybase
from StringIO import StringIO
from PIL import Image
def decode_image_PIL(binary_data):
""" Returns PIL image from binary buffer.
"""
f = StringIO(binary_data)
img = Image.open(f)
return img
if __name__=="__main__":
tab_image = 'image_cache'
col_image = dict()
col_image['... |
import os
import json
import tempfile
import urllib, urllib2
import requests
from indra.java_vm import autoclass, JavaException
import indra.databases.pmc_client as pmc_client
from processor import ReachProcessor
def process_pmc(pmc_id):
xml_str = pmc_client.get_xml(pmc_id)
with tempfile.NamedTemporaryFile() as... |
import copy
import re
import sys
import tempfile
import unittest
from mock.tests.support import ALWAYS_EQ
from mock.tests.support import is_instance
from mock import (
call, DEFAULT, patch, sentinel,
MagicMock, Mock, NonCallableMock,
NonCallableMagicMock, AsyncMock,
create_autospec, mock
)
from mock.moc... |
import logging
from redash.query_runner import *
from redash.utils import json_dumps
logger = logging.getLogger(__name__)
try:
from influxdb import InfluxDBClusterClient
enabled = True
except ImportError:
enabled = False
def _transform_result(results):
result_columns = []
result_rows = []
for re... |
import unittest
from pyramid import testing
class ViewTests(unittest.TestCase):
def setUp(self):
self.config = testing.setUp()
def tearDown(self):
testing.tearDown()
def test_my_view(self):
from formhelpers2.views import comment
request = testing.DummyRequest()
info =... |
"""
Python module presenting an API to an ELM327 serial interface
(C) 2015 Jamie Fraser <fwaggle@fwaggle.org>
http://github.com/fwaggle/pyELM327
Please see License.txt and Readme.md.
"""
__pids ={
0x01: {
# TODO: ignoring fuel system #2 atm
0x03: {
'Name': 'Fuel system status',
'Units': '',
'Pattern... |
import ibm_circuit_object as ico
class IBMInputWire(ico.IBMCircuitObject):
"""
This class represents a single IBM input wire.
"""
def __init__(self, displayname, circuit):
"""Initializes the wire with the display name and circuit specified."""
ico.IBMCircuitObject.__init__(self, displayn... |
from __future__ import print_function
import time
import numpy as np
from numba import jit, stencil
@stencil
def jacobi_kernel(A):
return 0.25 * (A[0,1] + A[0,-1] + A[-1,0] + A[1,0])
@jit(parallel=True)
def jacobi_relax_core(A, Anew):
error = 0.0
n = A.shape[0]
m = A.shape[1]
Anew = jacobi_kernel(A)... |
"""
Custom module logger
"""
import logging
module_name = 'moflow'
logger = logging.getLogger(module_name)
logger.addHandler(logging.NullHandler()) # best practice to not show anything
def use_basic_config(level=logging.INFO, format=logging.BASIC_FORMAT):
"""Add basic configuration and formatting to the logger
... |
from airy.core.conf import settings
from mongoengine import *
connect(getattr(settings, 'database_name', 'airy')) |
from .sizedist import *
from .WD01 import make_WD01_DustSpectrum |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.