id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1662147 | import asyncio # noqa
import datetime
import logging
import typing # noqa
from ib_async.errors import UnsupportedFeature
from ib_async.event import Event
from ib_async.execution import Execution, CommissionReport
from ib_async.instrument import Instrument, SecurityType
from ib_async.messages import Outgoing
from ib_... |
1662166 | from math import *
f = factorial
def C(n,k):
return f(n)/(f(k)*f(n-k))
for i in xrange(1,20):
s = 0
for j in xrange(0,i+1):
s += C(i,j)
print s,
print
|
1662180 | value_decay = 0.95
tau_decay = 0.8
class Config(dict):
def __init__(self, **kwargs):
# mode 1: training mode, 2: AI vs Human, 3: Human vs Human, 0: Debug
self['mode'] = 1
# display mode
self['display'] = False
# screen size of renderer
self['screen_size'] = (72... |
1662202 | from .o3d import kdtree as o3d_kdtree
from concurrent.futures import ThreadPoolExecutor
from importlib import import_module
import numpy as np
FAISS_INSTALLED = False
try:
faiss = import_module('faiss')
FAISS_INSTALLED = True
except Exception as e:
print(e)
print('Cannot import faiss for GPU nearest ne... |
1662215 | import common as c
from config import os_name
import shutil
import os
c.print('>> Downloading charsetdetect for {}'.format(os_name))
src_dir = os.path.abspath(__file__ + '/../../../third-party/charsetdetect')
if not os.path.exists(src_dir):
c.run('git clone --depth 1 https://github.com/batterseapower/libcharsetde... |
1662222 | from holidays.models import Holiday
def create_holiday(date, name):
holiday = Holiday.objects.create(
date=date,
name=name
)
return holiday
|
1662229 | from recon.core.module import BaseModule
import os
import re
class Module(BaseModule):
meta = {
'name': 'Contacts to Domains Data Migrator',
'author': '<NAME> (@LaNMaSteR53)',
'description': 'Adds a new domain for all the hostnames associated with email addresses stored in the \'contacts\'... |
1662242 | import sys
import numpy as np
from abc import ABCMeta, abstractmethod
class OptimizationTestFunction:
__metaclass__ = ABCMeta
"""
General class for Test Functions used for optimization
"""
def __init__(self, mindim=1, maxdim=None, domain=np.array([-1, 1])):
self.mindim = mindim
se... |
1662249 | import glob
import pandas as pd
import numpy as np
import os
filenames = glob.glob("*.csv")
filenames = [filename for filename in filenames if os.path.getsize(filename) > 10000]
#filenames = ["CreditRequirement.csv"]
timestamp_col = "Complete Timestamp" # column that indicates completion timestamp
case_id_col = "Cas... |
1662251 | import pyarrow as pa
### When dtype -> arrow ambiguious, override
KNOWN_FIELDS = [
[0, 'contributors', pa.string()],
[1, 'coordinates', pa.string()],
[2, 'created_at', pa.string()],
#[3, 'display_text_range', pa.list_(pa.int64())],
[3, 'display_text_range', pa.string()],
[4, 'entities', pa.s... |
1662274 | import sys
import os
from multiprocessing import forking, process, freeze_support
from multiprocessing.util import _logger, _log_to_stderr
WINEXE = forking.WINEXE
def get_preparation_data(name):
'''
Return info about parent needed by child to unpickle process object.
Monkey-patch from
'''... |
1662292 | from pydantic import BaseModel
from typing import Optional
class ShopConfig(BaseModel):
shop_cpu: bool
shop_cpu_price: Optional[int] = None
shop_cpu_min: Optional[int] = None
shop_ram: bool
shop_ram_price: Optional[int] = None
shop_ram_min: Optional[int] = None
shop_hdd: bool
shop... |
1662298 | import re
from setuptools import setup, find_packages
install_requires = [
"boto3>=1.14.19,<1.15.0",
"click==7.0",
"pyaml==16.12.2",
"pytz",
]
tests_requires = [
"coverage[toml]==5.0.3",
"flake8==3.7.8",
"isort==5.0.6",
"moto==1.3.14",
"pytest==5.4.3",
"pytest-cov==2.10.0",
]... |
1662351 | import numpy as np
import tensorflow as tf
from external.bleu import *
from external.rouge import *
from external.squad import *
__all__ = ["evaluate_from_data", "evaluate_from_file"]
def _bleu(pred_data, ref_data):
"""BLEU score for translation task"""
max_order = 4
smooth = False
score, _, _, _, _,... |
1662399 | import numpy as np
from rdkit import Chem
from rdkit.Chem import AllChem
from rdkit.Chem import Lipinski
from rdkit.Chem import Descriptors
from rdkit.DataStructs import FingerprintSimilarity, ConvertToNumpyArray
def clean_mol(smiles):
"""
Construct a molecule from a SMILES string, removing stereochemistry and... |
1662400 | from typing import Any
from allauth.account.adapter import DefaultAccountAdapter
from allauth.socialaccount.adapter import DefaultSocialAccountAdapter
from django.conf import settings
from django.http import HttpRequest
class AccountAdapter(DefaultAccountAdapter):
def is_open_for_signup(self, request: HttpReque... |
1662434 | from __future__ import division
from __future__ import absolute_import
from __future__ import print_function
import tensorflow as tf
from dltk.core.modules.base import AbstractModule
class Linear(AbstractModule):
"""Linear layer module
This module builds a linear layer
"""
def __init__(self, out_u... |
1662459 | from ._base import BaseGaussianMixture
from ..weight_models import EqualWeighting
class EqualWeightedMixture(BaseGaussianMixture):
def __init__(self, *, n=1, rng=None, **kwargs):
weight_model = EqualWeighting(n=n, rng=rng)
self.n = n
super().__init__(weight_model=weight_model, rng=rng, **k... |
1662484 | from mock import call
from raptiformica.actions.modules import remove_keys
from tests.testcase import TestCase
class TestRemoveKeys(TestCase):
def setUp(self):
self.log = self.set_up_patch(
'raptiformica.actions.modules.log'
)
self.mapping = {
'some_key': 'some_val... |
1662565 | from dataset.datasets import MXFaceDataset, SyntheticDataset
from dataset.randaugment import RandAugment
from dataset.utils import *
|
1662569 | from .bound_general import BoundedModule, BoundDataParallel
from .bounded_tensor import BoundedTensor, BoundedParameter
from .perturbations import PerturbationLpNorm, PerturbationSynonym
from .wrapper import CrossEntropyWrapper, CrossEntropyWrapperMultiInput
__version__ = '0.2' |
1662585 | import pyctrl.bbb as pyctrl
class Controller(pyctrl.Controller):
def __init__(self, *vargs, **kwargs):
# Initialize controller
super().__init__(*vargs, **kwargs)
def __reset(self):
# call super
super().__reset()
# add source: encoder1
self.add_device('encode... |
1662600 | import re
import sqlite3
import time
#########################################################################
# Base class for generating a catebot response. This is intended to be a parent to classes that
# implement each type of response with overrides specific to them. The classes that are expected to be
# overrid... |
1662621 | import itertools as it
import brownie
import pytest
DAY = 86400
WEEK = DAY * 7
pytestmark = pytest.mark.usefixtures("lock_alice")
@pytest.mark.parametrize("use_operator,timedelta_bps", it.product([False, True], range(0, 110, 50)))
def test_receiver_can_cancel_at_anytime(
alice, bob, charlie, chain, alice_unlo... |
1662623 | from galaxy.jobs import JobDestination
import os
def dexseq_memory_mapper( job, tool ):
# Assign admin users' jobs to special admin_project.
# Allocate extra time
inp_data = dict( [ ( da.name, da.dataset ) for da in job.input_datasets ] )
inp_data.update( [ ( da.name, da.dataset ) for da in job.input_l... |
1662684 | import time
import io
def parse_timestamp(t):
"""Parses a string containing a timestamp.
Args:
t (str): A string containing a timestamp.
Returns:
time.struct_time: A timestamp.
"""
if t is None or t == '0000-00-00T00:00:00Z':
return time.struct_time((0, 0, 0, 0, 0, 0, 0, ... |
1662703 | from functools import partial
from collections import Callable
def call_or_pass(value, args, kwargs):
if isinstance(value, Callable):
return value(*args, **kwargs)
return value
class OptionProperty(object):
def __init__(self, name):
self.name = name
def __repr__(self):
retu... |
1662728 | import urllib.request, urllib.parse, urllib.error
import pyttsx
engine = pyttsx.init()
#engine.say('Greetings!')
#engine.say('How are you today?')
engine.runAndWait()
fhand = urllib.request.urlopen('http://data.pr4e.org/romeo.txt')
for line in fhand:
h=line.decode().strip()
print(h)
engine.say(h)
engine.runAndWait(... |
1662730 | import pyaudio
import socket
import select
FORMAT = pyaudio.paInt16
CHANNELS = 1
RATE = 44100
CHUNK = 4096
HOST = socket.gethostname()
PORT = 8082
audio = pyaudio.PyAudio()
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((HOST, PORT))
def callback(in_data, frame_count, time_info, status):
try:
... |
1662853 | import json
# execute a transaction/sendCoinsToAddress call
def sendCoinsToAddress(sidechainNode, address, amount, fee):
j = {
"outputs": [
{
"publicKey": str(address),
"value": amount
}
],
"fee": fee
}
request = json.dumps(j)... |
1662855 | import os, fnmatch
pattern = "// ignore-xcode-12"
def commentOut(n):
if pattern in n:
return "// %s" % (n)
return n
def find(directory, filePattern):
for path, dirs, files in os.walk(os.path.abspath(directory)):
for filename in fnmatch.filter(files, filePattern):
filepath = os.path.join(path, filename)
... |
1662861 | import json
import os
from pathlib import Path
import pytest
@pytest.fixture(scope="module")
def api_client():
from rest_framework.test import APIClient
return APIClient()
@pytest.fixture(autouse=True)
def force_authenticate(request, api_client):
"""Automatically authenticate generated requests.
... |
1662864 | import pytest
from pymonet.immutable_list import ImmutableList
def test_eq():
assert len(ImmutableList.empty()) == 0
assert len(ImmutableList.of(1)) == 1
assert len(ImmutableList.of(1).unshift(0)) == 2
def test_immutable():
lst = ImmutableList(1)
lst2 = lst.append(2)
assert lst is not lst2
... |
1662884 | from . import constants as CONSTANTS
from .producer_property import ProducerProperty
from common.telemetry import telemetry_py
from common.telemetry_events import TelemetryEvent
class Image:
"""
If ``string`` is used, it has to consist of digits 0-9 arranged into
lines, describing the image, for example::... |
1662897 | from .browser_viz import profile_viewer
from .visualizer import BaseProfileVisualizer, ProfileVisualizer
__ALL__ = [ProfileVisualizer, BaseProfileVisualizer, profile_viewer]
|
1662917 | from .bot import bot
from .server import run as run_server
from .healthcheck import run as run_healthcheck
if __name__ == '__main__':
run_server()
run_healthcheck()
bot.start_polling()
bot.idle()
|
1662935 | import numpy as np
import random
from q1_softmax import softmax
from q2_gradcheck import gradcheck_naive
from q2_sigmoid import sigmoid, sigmoid_grad
def normalizeRows(x):
""" Row normalization function """
l2norm = np.sqrt((x**2).sum(axis=1, keepdims=True))
x /= l2norm
return x
def test_normalize_ro... |
1662941 | import math
from functools import wraps
from theano import tensor as T
from theano.sandbox.rng_mrg import MRG_RandomStreams as RandomStreams
from lasagne import init
from lasagne.random import get_rng
__all__ = ['Accumulator', 'NormalApproximation', 'NormalApproximationScMix', 'bbpwrap']
c = - 0.5 * math.log(2 * ma... |
1662948 | import re
import random
import requests
import table
import user_agent_list
from bs4 import BeautifulSoup
class HtmlPage:
user_agent_number = 7345
def __init__(self, url):
self.url = url
def get_html(self, creds, proxy_pass):
have_a_try = 3
if not proxy_pass:
... |
1662978 | import functools
from pylearn2.models.mlp import MLP, CompositeLayer
from pylearn2.space import CompositeSpace, VectorSpace
import theano
from theano import tensor as T
from theano.compat import OrderedDict
from theano.sandbox.rng_mrg import MRG_RandomStreams
from adversarial import AdversaryPair, AdversaryCost2, Gen... |
1662994 | import ai_flow as af
from ai_flow_plugins.job_plugins.bash import BashProcessor
# Initialize the project and workflow environment.
af.init_ai_flow_context()
# Define 2 bash jobs with simple commands.
with af.job_config('job_1'):
af.user_define_operation(processor=BashProcessor("echo job_1"))
with af.job_config('j... |
1662995 | import json
import sys
def load_from_file():
try:
with open("plugin_options.sav") as fh:
str = fh.readline()
return json.loads(str)
except:
return []
def store_to_file(options):
with open("plugin_options.sav", "w") as fh:
fh.write(json.dumps(options))
def get_index_of_option_in_opti... |
1663008 | from floyd.model.experiment_config import ExperimentConfig
def mock_exp(exp_id):
class Experiment:
id = exp_id
state = 'success'
name = 'test_name'
task_instances = []
return Experiment()
def mock_exp(exp_id):
class Experiment:
id = exp_id
state = 'success... |
1663011 | import torch
from torch.autograd import Function
from . import _roi_pooling as roi_pooling
import pdb
class RoIPoolFunction(Function):
pooled_width = 0
pooled_height = 0
spatial_scale = 0
def __init__(ctx, pooled_height, pooled_width, spatial_scale):
RoIPoolFunction.static_init(pooled_height, pooled_widt... |
1663070 | import torch.nn as nn
import torchvision
import torch, os
from skimage import morphology as morph
import numpy as np
from src.modules.eprop import eprop
import torch.utils.model_zoo as model_zoo
from scripts.SEAM.network import resnet38_SEAM, resnet38_aff
#----------- LC-FCN8
class FCN8VGG16(nn.Module):
def __ini... |
1663109 | import pytest
from django.urls import reverse
@pytest.mark.django_db
def test_xliff_more_buttons(admin_client, page):
resp = admin_client.get(reverse("wagtailadmin_explore_root"))
# assert the last more button is download xliff
assert set(["Download XLIFF", "Upload XLIFF"]) <= set(
[button.label ... |
1663119 | import struct
import sys
import io
import wave
import flac
from pathlib import Path
from bitstring import Bits
MAGIC = Bits('0xbe0498c88')
def twos_complement(n, bits):
mask = 2 ** (bits - 1)
return -(n & mask) + (n & ~mask)
def iter_i24_as_i32(data):
for l, h in struct.iter_unpack('<BH', ... |
1663142 | import tensorflow as tf
import sys
import os
import tf_util
import multi_model as resnet_model
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
sys.path.append(BASE_DIR)
sys.path.append(os.path.join(BASE_DIR, '../utils'))
def placeholder_inputs(batch_size, num_point, resolution, views, devices):
pointcloud... |
1663187 | from pygears.lib import sdp, check, drv, delay
from pygears.typing import Uint, Tuple
wr_addr_data = drv(t=Tuple[Uint[2], Uint[3]],
seq=[(0, 0), (1, 2), (2, 4), (3, 6)])
rd_addr = drv(t=Uint[2], seq=[0, 1, 2, 3]) | delay(1)
rd_addr \
| sdp(wr_addr_data) \
| check(ref=[0, 2, 4, 6])
|
1663217 | from sklearn.ensemble import GradientBoostingRegressor
from sklearn.decomposition import PCA
from sklearn.pipeline import Pipeline
from sklearn.base import BaseEstimator
import numpy as np
class Regressor(BaseEstimator):
def __init__(self):
self.n_components = 10
self.n_estimators = 40
sel... |
1663218 | from pathlib import Path
import pandas as pd
from matplotlib import pyplot as plt
import seaborn as sns
import argparse
'''
How to run
python assemble_timer_output.py -b folder_before -a folder_after -d folder_output -o file_name_prefix
'''
plt.rcParams['figure.figsize'] = [10, 6]
plt.rcParams.update({'font.size': 18,... |
1663224 | from splitcli.ux import menu
from splitcli.accounts import user
from splitcli.split_apis import users_api
def sign_in():
email = menu.text_input("Enter your email")
menu.info_message("To find your Admin API Key, follow the directions here:")
menu.info_message("https://www.youtube.com/watch?v=80Bz2ZcZUrs")
... |
1663229 | notify_spec = {
'type': 'object',
'required': ['message'],
'properties': {
'message': {
'description': 'Message to send to administrators.',
'type': 'string',
},
'sendAsFile': {
'description': 'Whether to send message as a file. (0 or 1)',
... |
1663241 | from __future__ import absolute_import, division, print_function
import torch
from torch import nn
from utils.interpolation import interpolate2d, my_grid_sample, get_coordgrid
def post_processing(l_disp, r_disp):
b, _, h, w = l_disp.shape
m_disp = 0.5 * (l_disp + r_disp)
grid_l = torch.linspace(0.0,... |
1663243 | from __future__ import absolute_import, unicode_literals
import os
CWD = os.path.dirname(os.path.realpath(__file__))
|
1663263 | import pickle
import os
import numpy as np
import matplotlib.pyplot as plt
from tqdm import tqdm
def main():
directory_string = '~/Desktop/DEAP/data_preprocessed_python'
directory = os.path.expanduser(directory_string)
os.makedirs('data', exist_ok=True)
print("Importing data...")
for file... |
1663277 | import re
import os
import sys
import json
import scrapy
import argparse
from glob import glob
from datetime import datetime
from w3lib.url import is_url
from scrapy.crawler import CrawlerProcess
from scrapy.utils.project import inside_project, get_project_settings
from scrapy.utils.python import to_unicode
from scrap... |
1663298 | import abc
import threading
import six
@six.add_metaclass(abc.ABCMeta)
class ExecutionContext(object):
"""Base abstract execution context class."""
@abc.abstractmethod
def run(self, func, *args, **kwargs):
pass
class GeventExecutionContext(ExecutionContext):
"""Execution context that run b... |
1663321 | import logging
import os
from torch import Tensor
from torch.optim import SGD
from torch.utils.data import TensorDataset
from knodle.data.download import MinioConnector
from knodle.model.logistic_regression_model import (
LogisticRegressionModel,
)
from examples.ImdbDataset.utils import init_logger
from examples... |
1663332 | import json
import logging
import os
import re
import tempfile
import m3u8
from tqdm import tqdm
yuu_log = logging.getLogger('yuu.gyao')
class GYAODownloader:
def __init__(self, url, session):
self.url = url
self.session = session
self.merge = True
if os.name == "nt":
... |
1663354 | import falcon
from zappa.async import task
from mashape import fetch_quote
class RandomQuoteResource:
def on_get(self, req, resp):
"""Handles GET requests"""
try:
resp.media = fetch_quote()
except Exception as e:
raise falcon.HTTPError(falcon.HTTP_500, str(e))
@ta... |
1663402 | from spanet.network.jet_reconstruction import JetReconstructionModel
from spanet.dataset import JetReconstructionDataset
from spanet.options import Options
|
1663435 | from hpe3parclient import exceptions
import test.hpe_docker_unit_test as hpeunittest
from oslo_config import cfg
CONF = cfg.CONF
class EnablePluginUnitTest(hpeunittest.HpeDockerUnitTestExecutor):
def _get_plugin_api(self):
return 'plugin_activate'
def check_response(self, resp):
expected_resp... |
1663436 | import torch
import torchelie as tch
import torchelie.utils as tu
from torchelie.recipes.gan import GANRecipe
import torchvision.transforms as TF
import torchelie.loss.gan.standard as gan_loss
from torchelie.loss.gan.penalty import zero_gp, R1
from torchelie.datasets.pix2pix import UnlabeledImages
from torchelie.models... |
1663455 | from django.db import models
class TransformQuerySet(models.query.QuerySet):
def __init__(self, *args, **kwargs):
super(TransformQuerySet, self).__init__(*args, **kwargs)
self._transform_fns = []
def _clone(self, klass=None, setup=False, **kw):
c = super(TransformQuerySet, self)._clone... |
1663462 | import random
import re
from youtube_related import RateLimited
from youtube_related import preventDuplication as relatedClient
from .config import Config
from .connector import VoiceConnector
from .enums import PlayerState
from .errors import NotPlaying
from .player import Player
from .source import AudioData, Audio... |
1663486 | import time
from kombu import Connection, Queue, Exchange
from kombu.common import maybe_declare
from kombu.mixins import ConsumerProducerMixin
from kombu.pools import producers
from spylunking.log.setup_logging import build_colorized_logger
from celery_connectors.utils import SUCCESS
from celery_connectors.utils impor... |
1663510 | import torch
import torch.nn as nn
import torch.nn.functional as F
d1 = 64
d2 = 128
d3 = 256
d4 = 512
class AttnContentStrategy(nn.Module):
def __init__(self, n_labels):
super(AttnContentStrategy, self).__init__()
self.linearStrategy = nn.Linear(n_labels, d1)
self.linearStrategy2 = nn.Line... |
1663512 | import matplotlib.pyplot as plt
from sklearn import datasets
from sklearn import svm
digits = datasets.load_digits()
print(digits.data)
print(digits.target)
# digits.target is the actual label we've assigned to the digits data.
# Now that we've got the data ready, we're ready to do the machine learning.
# First, we ... |
1663513 | import tensorflow as tf
import numpy as np
import cv2
import matplotlib.pyplot as plt
from tensorflow_graphics.math.interpolation import bspline
def get_trajectories(dataset):
trajectories = []
avails = []
object_types = []
for i, batch in enumerate(dataset):
future_states = tf.squeeze(batch['gt_future_st... |
1663529 | load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
_DEFAULT_PY_BUILD_FILE = """
py_library(
name = "lib",
srcs = glob(["**/*.py"]),
visibility = ["//visibility:public"],
)
"""
_PANDOC_BUILD_FILE = """
filegroup(
name = "pandoc",
srcs = ["bin/pandoc"],
visibility = ["//visibil... |
1663569 | from geoalchemy2 import Geography, Geometry
from pytz import timezone
from shapely import wkb
from sqlalchemy import (
Column,
Integer, BigInteger,
String,
Boolean,
DateTime,
ForeignKey,
UniqueConstraint,
)
from sqlalchemy.dialects.postgresql import JSONB
from sqlalchemy.orm import deferred,... |
1663572 | import pybedtools as bt
from bcbio.utils import file_exists
from bcbio import utils
def decomment(bed_file, out_file):
"""
clean a BED file
"""
if file_exists(out_file):
return out_file
with utils.open_gzipsafe(bed_file) as in_handle, open(out_file, "w") as out_handle:
for line in ... |
1663604 | from fastapi import APIRouter
from . import ballot
from . import guardian
from . import tally_decrypt
router = APIRouter()
router.include_router(guardian.router, prefix="/guardian")
router.include_router(ballot.router, prefix="/ballot")
router.include_router(tally_decrypt.router, prefix="/tally")
|
1663607 | from SPARQLWrapper import SPARQLWrapper, JSON
import json
import requests
def setup_query(person_complete_name: str):
"""
Return the SPARQL query for obtaining gender, birthdate and nationality (if available) of the given person from
DBpedia
:param person_complete_name: person whose metadata are of in... |
1663623 | from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import *
from PyQt5.QtCore import *
from .util import number_color
from functools import partial
import glob
import math
from ui.util import number_object
from ui.mouse_event import ReferenceDialog, SnapshotDialog
import copy
Lb_width = 100
Lb_height = 40
Lb... |
1663628 | from graphics import *
import random
class TspPainter:
def __init__(self):
self.win = GraphWin('TSP', 500, 500)
self.win.setCoords(0, 0, 80, 80)
self.win.width = 100
self.coord_mat = None
self.nodes = []
self.lockers = []
self.paths = []
def reset(self):... |
1663723 | import click
@click.group()
def haproxy(**kwargs):
"""
Manage haproxy loadbalancer operations
"""
|
1663730 | from flask import Flask, render_template, request
from BOT import Bot
app = Flask(__name__)
@app.route('/', methods=['GET', 'POST'])
def home():
req = request.args
credentials_in = False
if 'username' in req.keys() and 'password' in req.keys() and 'dm' in req.keys() and 'message' in req... |
1663758 | import sys
sys.path.insert(0, "..")
import logging
from IPython import embed
from opcua import Client
if __name__ == "__main__":
logging.basicConfig(level=logging.WARN)
client = Client("opc.tcp://localhost:53530/OPCUA/SimulationServer/")
client.load_client_certificate("server_cert.pem")
client.load_... |
1663760 | import logging
import torch
import torch.utils.data
logger = logging.getLogger(__name__)
def _get_pytorch_version():
version = torch.__version__
major, minor = [int(x) for x in version.split(".")[:2]]
if major != 1:
raise RuntimeError(
"nonechucks only supports PyTorch major version... |
1663778 | from bxutils.logging.log_level import LogLevel
from bxcommon import constants
from bxcommon.messages.bloxroute.abstract_bloxroute_message import AbstractBloxrouteMessage
from bxgateway.messages.gateway.gateway_message_type import GatewayMessageType
class BlockPropagationRequestMessage(AbstractBloxrouteMessage):
... |
1663783 | from torch.utils.data.sampler import Sampler
## one by one
class CustomBatchSampler_Multi(Sampler):
def __init__(self, sampler):
for samp in sampler:
if not isinstance(samp, Sampler):
raise ValueError("sampler should be an instance of "
"torch.... |
1663804 | import os
import sys
import utils
import random
import datetime
import argparse
import matplotlib
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
from sklearn.metrics import roc_curve, roc_auc_score, precision_recall_curve
class Evaluation(object):
d... |
1663810 | import asyncio
import logging
from os.path import abspath,realpath,expanduser,expandvars
from importlib.util import spec_from_file_location, module_from_spec
try:
import asyncpg
has_pgsql = True
except:
has_pgsql = False
clogger = logging.getLogger("dnstap_receiver.console")
from dnstap_receiver.outputs... |
1663831 | import os, tempfile, re, json, six, sys
def format_dynamic_params(params):
behavior_params = {}
behavior_params["behavior"] = {str(params["first_year"]): {"_" + k:v for k, v in list(params.items()) if k.startswith("BE")}}
for key in ("growdiff_response", "consumption", "growdiff_baseline"):
behavi... |
1663842 | from unittest.mock import Mock, patch, call
import pytest
from faker import Faker
import spotipy as spt
from diversify.session import SpotifySession, _get_session, _fields
fake = Faker()
Faker.seed(0)
# I'm using this project as a way to learn how to test functions
# and isolate dependencies, so there might be a bunc... |
1663857 | from django.conf.urls import url
from app.views.api.users import views
urlpatterns = [
url(r'^$', views.api_index, name='api_users_index'),
url(r'^(?P<id_number>[0-9]+)$', views.api, name='api_users_id'),
]
|
1663899 | import pytest
from indy_common.authorize.auth_actions import ADD_PREFIX
from indy_common.authorize.auth_constraints import AuthConstraint
from indy_common.authorize import auth_map
from indy_common.constants import NYM, ROLE, ENDORSER
from indy_node.test.auth_rule.auth_framework.basic import roles_to_string, AuthTest
... |
1663906 | import qdarkstyle
import sys
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from Voicelab.VoicelabWizard.InputTab import InputTab
from Voicelab.VoicelabWizard.OutputTab import OutputTab
from Voicelab.VoicelabWizard.SettingsTab import SettingsTab
from Voicelab.VoicelabWizard.VoicelabC... |
1663907 | import PIL
import torch
from PIL import Image
import torch.nn as nn
from log_utils import get_logger
from feature_transforms import wct, wct_mask
from encoder_decoder_factory import Encoder, Decoder
import torchvision.transforms.functional as transforms
log = get_logger()
def stylize(level, content, style0, encoder... |
1663969 | from .client import HTTPClient
from .httperror import HTTPError
__all__ = (
"HTTPClient",
"HTTPError",
)
|
1663980 | import scipy.signal
import numpy as np
from .cltools import HAVE_PYOPENCL, OpenCL_Helper
if HAVE_PYOPENCL:
import pyopencl
mf = pyopencl.mem_flags
#~ from pyacq.dsp.overlapfiltfilt import SosFiltfilt_Scipy
from .tools import FifoBuffer, median_mad
def offline_signal_preprocessor(sigs, sample_rate, common_r... |
1664009 | def armsFront():
i01.moveHead(90,90)
i01.moveArm("left",13,115,100,50)
i01.moveArm("right",13,115,100,50)
i01.moveHand("left",50,24,54,50,82,0)
i01.moveHand("right",50,24,54,50,82,180)
i01.moveTorso(90,90,90)
|
1664010 | from pathlib import Path
from libdotfiles.packages import has_installed, try_install
from libdotfiles.util import (
HOME_DIR,
PKG_DIR,
create_symlink,
distro_name,
run,
)
FZF_DIR = HOME_DIR / ".fzf"
if distro_name() == "arch":
try_install("fzf") # super opener
try_install("ripgrep") # s... |
1664056 | from abc import ABC, abstractmethod
class ConfigStore(ABC):
data = {}
@abstractmethod
def read(self):
pass
@abstractmethod
def write(self, data: dict):
pass
|
1664117 | from schematics.types import StringType
from schematics.exceptions import ValidationError
from openprocurement.tender.core.models import BaseDocument, Model, get_tender
class Document(BaseDocument):
documentOf = StringType(
required=True,
choices=["tender", "item"],
default="tender"
)
... |
1664179 | import io
from typing import Any, Callable, Dict, List, Optional, Set
import determined as det
import determined.keras
train_begin = "on_train_begin"
train_workload_begin = "on_train_workload_begin"
train_batch_begin = "on_train_batch_begin"
train_batch_end = "on_train_batch_end"
train_workload_end = "on_train_worklo... |
1664200 | from __future__ import print_function
from sklearn.datasets import fetch_20newsgroups
from sklearn.feature_extraction.text import TfidfVectorizer
import cPickle as pickle
import argparse
import logging
from time import time
import numpy as np
class streamer(object):
def __init__(self, file_name):
self.fi... |
1664218 | from tempfile import NamedTemporaryFile
from typing import IO
from fastapi.middleware.cors import CORSMiddleware
from bson import ObjectId
from fastapi import FastAPI, UploadFile, File, HTTPException, Header, Depends, BackgroundTasks
from pybadges import badge
from pydantic import BaseModel, validator
from keras.models... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.