id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3317067 | from functools import partial
#import numpy as np
import hyperopt
#from hyperopt import pyll
from hyperopt.fmin import fmin_pass_expr_memo_ctrl
from hpnnet.nips2011 import nnet1_preproc_space
#from hpnnet.skdata_learning_algo import PyllLearningAlgo
from hpnnet.skdata_learning_algo import eval_fn
from skdata.larochel... |
3317077 | import unittest
from libsaas import http
from libsaas.executors import test_executor
from libsaas.services import mixrank
class MixRankTestCase(unittest.TestCase):
def setUp(self):
self.executor = test_executor.use()
self.executor.set_response(b'{}', 200, {})
self.service = mixrank.MixRa... |
3317081 | from .Additive_mixing_layers_extraction import *
from .Convexhull_simplification import *
from .trimesh import *
from .GteDistPointTriangle import * |
3317113 | from __future__ import print_function
from __future__ import division
import findcaffe
import caffe
import os, argparse
import os.path as osp
import numpy as np
import scipy.ndimage as nd
import pylab, png, pickle
from shutil import copyfile
from ipdb import set_trace
import matplotlib.pyplot as plt
plt.switch_backe... |
3317114 | def test_cli_option_default(testdir):
testdir.makepyfile(
"""
def test_snail(request):
assert request.config.option.snail == 5.0
"""
)
result = testdir.runpytest("-v")
result.stdout.fnmatch_lines(["*::test_snail*PASSED*"])
assert result.ret == 0
def test_cli_opt... |
3317118 | from rest_framework import routers
from . import views
app_name = 'log_data'
router = routers.SimpleRouter()
router.register(r'data_logs', views.LogData, basename='log-upload')
urlpatterns = router.urls
|
3317123 | import logging
import os
from dateutil import parser
from .ProjectHolder import ProjectHolder
log = logging.getLogger(__name__)
class GitLabRepoSession(ProjectHolder):
DEFAULT_HOSTNAME = 'gitlab.com'
def __init__(self, repo, hostname):
super(GitLabRepoSession, self).__init__()
self.pa_toke... |
3317141 | from rest_framework import status
from mayan.apps.rest_api.tests.base import BaseAPITestCase
from ..events import event_tag_created, event_tag_edited
from ..models import Tag
from ..permissions import (
permission_tag_create, permission_tag_delete, permission_tag_edit,
permission_tag_view
)
from .mixins impo... |
3317150 | import requests
import sys
import traceback
XREFS_DS_DATA = None
XREFS_DS_URL = 'http://wwwdev.ebi.ac.uk/chembl/api/data/xref_source.json?limit=100'
# noinspection PyBroadException
def get_x_ref_url(x_ref_ds_name, x_ref_id):
global XREFS_DS_DATA
if x_ref_ds_name in XREFS_DS_DATA:
try:
ret... |
3317162 | import functools
from typing import Callable, Optional, Any, Tuple
from timeit import default_timer as timer
from mpi4py import MPI
def time(function_name: Optional[str] = None) -> Callable:
"""
Times the execution of the wrapped function, prints the execution time
using the provided function name, and r... |
3317176 | from __future__ import print_function
import Pyro4
print("Showing the different instancing modes.")
print("The number printed, is the id of the instance that handled the call.")
print("\n-----PERCALL (different number every time) -----")
with Pyro4.Proxy("PYRONAME:instance.percall") as p:
print(p.msg("hello1"))
... |
3317230 | import datetime
from django.views.generic import TemplateView
# TODO BR: move this dependency to website or openkamer layer
from document.models import CommissieDocument
from document.views import CommissieDocumentItem
from parliament.models import Commissie
from parliament.models import PartyMember
from parliament.... |
3317239 | from frictionless import describe_schema
# General
def test_describe_schema():
schema = describe_schema("data/leading-zeros.csv")
assert schema == {"fields": [{"name": "value", "type": "integer"}]}
|
3317247 | lang_short = {"german": "de", "english": "en", "turkish": "tr", "finnish": "fi", "russian": "ru", "spanish": "es",
'arabic': "ar", 'bulgarian': "bg", 'french': 'fr', 'hindi': 'hi', 'urdu': 'ur', 'vietnamese': 'vi',
'chinese': 'zh'}
def convert_long_to_short(lang):
return lang_short[lan... |
3317307 | import numpy as np
def threshold_matrix(mask_array:np.ndarray, pet_array:np.ndarray, threshold:float) -> np.ndarray:
"""function to threshold a ndarray mask
Args:
mask_array (np.ndarray): [(z,x,y,c)]
pet_array (np.ndarray): [(z,x,y)]
threshold (float): [0.41, 2.5, 4.0 or other]
Re... |
3317320 | from flask_restful import reqparse
from werkzeug.datastructures import FileStorage
class FileUploadMixin(object):
req_parser = reqparse.RequestParser()
req_parser.add_argument('file', location='files', type=FileStorage, required=True) |
3317352 | import unittest
from textblob import TextBlob
def translate(text, from_l, to_l):
en_blob = TextBlob(text)
return en_blob.translate(from_lang=from_l, to=to_l)
translate(text='muy bien', from_l='es', to_l='en')
print(translate('Hello', 'en', 'es'))
class TestMethods(unittest.TestCase):
def test_get_le... |
3317365 | from keras.preprocessing.image import load_img, img_to_array
import numpy as np
from keras.applications import vgg19
from keras import backend as K
from scipy.optimize import fmin_l_bfgs_b
from scipy.misc import imsave
import time
target_image_path = 'data/transfer-target.png' # 想要变化的图像路径
style_reference_image_path = ... |
3317380 | import re
from django.utils.translation import gettext_lazy as _
from rest_framework.exceptions import ValidationError, NotFound
from openbook_common.utils.model_loaders import get_community_model
def community_name_characters_validator(community_name):
if not re.match('^[a-zA-Z0-9_]*$', community_name):
... |
3317399 | import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import numpy as np
import cv2
import numpy as np
from IPython import embed
EPSILON = 1e-6
def lg10(x):
return torch.div(torch.log(x), math.log(10))
def maxOfTwo(x, y):
z = x.clone()
maskYLarger = torch.lt(x, y)
z[maskYLarg... |
3317401 | from TokenType import TokenType
from Environment import Environment
from Errors import *
from Kobe import Kobe
from Structures import *
from Functions import *
kobes = []
glob_env = Environment()
glob_env.loadFunction("randi", RandInt())
glob_env.loadFunction("randf", RandFloat())
cur_env = glob_env
d... |
3317449 | from deprecated import deprecated
from .grouped_predictor import GroupedPredictor
@deprecated(
version="0.5.2",
reason="Please use `sklego.meta.GroupedPredictor` instead. "
"This object will be removed from the meta submodule in version 0.7.0.",
)
def GroupedEstimator(*args, **kwargs):
return GroupedP... |
3317490 | from keras.models import Model
from keras.preprocessing import image
from keras.optimizers import SGD
from keras.applications.vgg16 import VGG16
import keras.applications as apps
model=apps.vgg16.VGG16()
from quiver_engine.server import launch
launch(model,input_folder=".")
|
3317515 | from .output import CVOutputDevice, get_cv_output_devices
__all__ = ["CVOutputDevice", "get_cv_output_devices"]
|
3317553 | import requests
import pandas as pd
url = "http://comp.fnguide.com/XML/Market/CompanyList.txt"
resp = requests.get(url)
resp.encoding = "utf-8-sig"
data = resp.json()
comp = data['Co']
df = pd.DataFrame(data=comp)
cond = df['gb'] == '701'
df2 = df[cond].copy()
df2.to_excel("comp_code.xlsx") |
3317570 | import os
import unittest
from scripts import train
cuda_on = 1
class TestsOmniglot(unittest.TestCase):
def test_1_shot_1_way(self):
config = {
"data.dataset": "omniglot",
"data.split": "vinyals",
"data.train_way": 1,
"data.train_support": 1,
"... |
3317645 | from expression import *
import multiprocessing
ok1=1;ok2=1
changeDegree([3,5,6,4],[20,40,140,140])
def Right():
changeDegree([3,2],[20,0])
#time.sleep(0.5)
changeDegree([2,4],[130,50],0.01)
#time.sleep(0.5)
def Left():
changeDegree([4,1],[140,180])
#time.sleep(0.5)
changeDegree([1,3],[50,1... |
3317661 | from mediator.event.aggregate import (
ConfigEventAggregateError,
EventAggregate,
EventAggregateError,
)
from mediator.event.base import EventPublish, EventPublisher, EventSubscriber
from mediator.event.local import LocalEventBus
from mediator.event.registry import EventHandlerRegistry
__all__ = [
"Con... |
3317715 | s = set([1,2,3])
copy_s = s.copy()
new_s = set(s)
copy_s.add(42)
new_s.add(13)
print s
print copy_s
print new_s
|
3317770 | from __future__ import print_function
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators.coxph import H2OCoxProportionalHazardsEstimator
def coxph_smoke_strata():
heart = h2o.import_file(pyunit_utils.locate("smalldata/coxph_test/heart.csv"))
heart['transpla... |
3317903 | from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.urls import include, path
urlpatterns = staticfiles_urlpatterns() + [
path("pattern-library/", include("pattern_library.urls")),
path("", include("demo.storybook.urls")),
]
|
3317938 | import asyncio
import datetime
import os
import sys
import websockets
DEBUG = 'WSDEBUG' in os.environ and os.environ['WSDEBUG'] == '1'
# Taken from qwarc.utils
PAGESIZE = os.sysconf('SC_PAGE_SIZE')
def get_rss():
with open('/proc/self/statm', 'r') as fp:
return int(fp.readline().split()[1]) * PAGESIZE
async de... |
3317942 | import os
import json
import torch
import threading
import numpy as np
from functools import partial
from PyQt5 import QtWidgets
import matplotlib.pyplot as plt
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as Navigat... |
3317947 | from ..flags import *
if BACKEND_FLAGS.HAS_PROTO:
from . import ChainProto
def get_protobuf_numbering_scheme(numbering_scheme):
"""
Returns ChainProto field value of a given numbering scheme
Args:
numbering_scheme:
Returns:
"""
if numbering_scheme == NUMBERING_FLAGS.KABAT:
... |
3317993 | import xmltodict
import pytest
from jmeter_api.controllers.throughput_controller.elements import ThroughputController, ThroughputMode
from jmeter_api.basics.utils import tag_wrapper
class TestThroughputController:
class TestThroughput:
def test_total1(self):
with pytest.raises(TypeError):
... |
3318046 | import os
import random
import string
from bitcoin_acks.database.session import get_url
def generate_secret():
alphanumeric = string.ascii_uppercase + string.ascii_lowercase + string.digits
x = ''.join(random.choice(alphanumeric) for _ in range(32))
return x
class Config(object):
DEBUG = False
... |
3318060 | import io
from freezegun import freeze_time
import pytest
import json
from CommonServerPython import DemistoException, EntryType, EntryFormat
from datetime import datetime
from SaasSecurity import Client
import demistomock as demisto
def util_load_json(path):
with io.open(path, mode='r', encoding='utf-8') as f:
... |
3318129 | import numpy as np
import matplotlib.pyplot as plt
import nyles as nyles_module
import parameters
nh = 3
nxglo = 32
nyglo = 32
nzglo = 32
npx = 2
npy = 2
npz = 1
nx = nxglo//npx
ny = nyglo//npy
nz = nzglo//npz
Lx = 1.
Ly = 1.
Lz = 1.
# Get the default parameters, then modify them as needed
param = parameters.U... |
3318145 | from threading import Thread, Semaphore
from aicm.landing_track import LandingPriority
from time import sleep
from aicm.airport_generator import AirportGenerator
from aicm.general import planes
g = AirportGenerator()
""" Class that represents the implementation of an Airplane. """
class Airplane(Thread):
"""__init__... |
3318167 | from django.shortcuts import render
from .tasks import add
def calc(req):
if req.method == "POST":
add.send(float(req.POST["a"]), float(req.POST["b"]))
return render(req, "calc.html")
|
3318202 | from typing import List
import numpy as np
import torch
from config.autoresponder_config import * # TODO: move elsewhere?
from ml.sampling_params import SamplingParams, DEFAULT_SAMPLING_CONFIG
from transformers import LogitsProcessorList
from ml.sample_torch import BreakrunsLogitsProcessor
from util.util import co... |
3318210 | from datetime import datetime
from django.db import models
from courses.models import CourseInfo
from users.models import UserProfile
# Create your models here.
class UserLove(models.Model):
"""
UserLove 用户收藏表
"""
love_man = models.ForeignKey(UserProfile, on_delete=models.CASCADE, verbose_name="收藏人"... |
3318240 | from beziers.path.representations.Segment import SegmentRepresentation
from beziers.path.representations.Nodelist import NodelistRepresentation, Node
from beziers.point import Point
from beziers.boundingbox import BoundingBox
from beziers.utils.samplemixin import SampleMixin
from beziers.utils.booleanoperationsmixin im... |
3318243 | import torch
import numpy as np
import torch.nn as nn
from torch.nn.parameter import Parameter
class MeshNet(nn.Module):
def __init__(self, n_class, mask_ratio=0.95, dropout=0.5):
super(MeshNet, self).__init__()
self.spatial_descriptor = SpatialDescriptor()
self.structural_descriptor = S... |
3318248 | from electionsproject.settings_general import S3_ACCESS_KEY, S3_SECRET_KEY, S3_BUCKET
import tinys3
## set up and call the s3 connection using tinyS3
def s3_connection():
connection = tinys3.Connection(
S3_ACCESS_KEY,
S3_SECRET_KEY,
default_bucket=S3_BUCKET',
tls=True
)... |
3318251 | import google.protobuf.json_format as pbjson
import os
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D
import cv2
import LabeledImage_pb2
import argparse
import deepracing.imutils as imutils
import torchvision
import torchvision.utils as tvutils
import torchvision.transforms.f... |
3318266 | from flask_wtf import FlaskForm
from wtforms import (
Form,
validators,
StringField,
)
from wtforms.validators import DataRequired, Length
'''
Tag Form
'''
class TagForm(FlaskForm):
name = StringField(u'Titolo tag', validators=[Length(min=-1, max=255, message='Massimo 255 caratteri')])
|
3318273 | import tensorflow as tf
validation_dir="fooval/val" #"/datasets/ImageNet/ILSVRC/Data/CLS-LOC/val" #"val"
BATCH_SIZE = 32
IMG_SIZE = (224,224)
#model = tf.keras.applications.mobilenet
#pretrained = tf.keras.applications.MobileNet
model = tf.keras.applications.mobilenet_v2
pretrained = tf.keras.applications.MobileNetV2... |
3318302 | from _hydra import MMapBitField
import tempfile
def test_ro_segfault():
tf = tempfile.NamedTemporaryFile(delete=True)
rw_field = MMapBitField(tf.name, 80, 0)
rw_field[0] = 1
ro_field = MMapBitField(tf.name, 80, 1)
try:
ro_field[0] = 1
except ValueError:
pass
def test_setitem(... |
3318343 | import os
import math
import tempfile
import shutil
import unittest
import numpy as num
from numpy.testing import assert_allclose
from matplotlib import image
import gmtpy
from gmtpy import cm, inch, golden_ratio
noshow = False
@unittest.skipUnless(
gmtpy.have_gmt(), 'GMT not available')
@unittest.skipUnless(
... |
3318374 | import os
import sys
from nose.exc import SkipTest
try:
from pkg_resources import EntryPoint
except ImportError:
raise SkipTest("No setuptools available; skipping")
here = os.path.dirname(__file__)
support = os.path.join(here, 'support')
ep = os.path.join(support, 'ep')
def test_plugin_entrypoint_is_loadabl... |
3318376 | from matplotlib.pyplot import rcParams
from IPython.display import set_matplotlib_formats
rcParams['font.size'] = 14
rcParams['lines.linewidth'] = 2
rcParams['figure.figsize'] = (7.5, 5)
rcParams['axes.titlepad'] = 14
rcParams['savefig.pad_inches'] = 0.12
|
3318400 | import os
import errno
import os.path as osp
from configparser import ConfigParser
def get_parent_dir_path(path):
"""Returns the path to the parent directory in path. """
if osp.isfile(path):
return osp.dirname(path)
return osp.dirname(osp.abspath(path))
# Default file names
CONFIG_FILE_NAME = "... |
3318405 | import json
def update_packages(base_dir, dependencies={}, devDependencies={}, scripts={}):
packages_path = base_dir / "package.json"
packages_file = open(f"{packages_path}",)
packages = json.load(packages_file)
packages["devDependencies"] = {
**packages["devDependencies"], **devDependencies}... |
3318406 | import logging
logger = logging.getLogger(__name__)
import tarfile, os, fnmatch
from tarfile import TarError
import django_rq
from django.db import transaction
from thresher.models import UserProfile
from data.load_data import load_article_atomic, parse_batch_name
def import_archive(orig_filename, filename, owner_p... |
3318439 | from sqlalchemy import not_
from sqlalchemy.orm import Query
from reporter.database.model import Headline, HumanEvaluation
def construct_constraint_query(field: str, relation: str, condition: str) -> Query:
table = Headline if field in ['article_id', 't', 'phase', 'headline'] else HumanEvaluation
if relati... |
3318449 | import contextlib
import copy
import datetime
import logging
import requests
import time
_LOG = logging.getLogger('somecomfort')
FAN_MODES = ['auto', 'on', 'circulate', 'follow schedule']
SYSTEM_MODES = ['emheat', 'heat', 'off', 'cool', 'auto', 'auto']
HOLD_TYPES = ['schedule', 'temporary', 'permanent']
EQUIPMENT_OUT... |
3318501 | import os, sys
sys.path.insert(0, os.path.abspath(os.path.join(__file__, '../../scripts')))
import ctypes
import numpy as np
import rys_wheeler
import rys_roots
import rys_tabulate
cint = ctypes.CDLL('../build/libcint.so')
def cint_call(fname, nroots, x, low=None):
r = np.zeros(nroots)
w = np.zeros(nroots)
... |
3318505 | from django.db import models
from django.contrib.auth.models import User
from django.core.validators import MaxValueValidator, MinValueValidator
from core.models.market import Trade
from django.utils.translation import gettext as _
class Review(models.Model):
"""A review given to a particular trade by the user""... |
3318525 | from typing import List, Set
from ibis.expr.types import AnyColumn
# from sql_to_ibis.sql.sql_value_objects import TableOrJoinbase
def rename_duplicates(
table, # TODO Come back here and fix the type
duplicates: Set[str],
table_name: str,
table_columns: List[AnyColumn],
):
for i, column in enum... |
3318561 | from __future__ import print_function, division
#
import sys,os
quspin_path = os.path.join(os.getcwd(),"../../")
sys.path.insert(0,quspin_path)
#
from quspin.operators import hamiltonian # Hamiltonians and operators
from quspin.basis import boson_basis_1d # Hilbert space spin basis
from quspin.tools.evolution import ev... |
3318596 | import numpy as np
import os, logging
os.environ["TF_CPP_MIN_LOG_LEVEL"] = "3"
logging.getLogger("tensorflow").setLevel(logging.CRITICAL)
logging.getLogger("tensorflow_hub").setLevel(logging.CRITICAL)
import keras as K
import tensorflow as tf
import copy
import warnings
class batchless_VanillaLSTM_keras(object):
"... |
3318660 | import datetime as dt
from django.db import connections
from django.utils.translation import gettext_lazy as _
from workbench.accounts.models import User
from workbench.tools.formats import Z1, days, hours
def classify_logging_delay(delay):
explanation = _("Average logging time is %s after noon.") % hours(delay... |
3318681 | from unittest import TestCase
from robustnessgym import lookup
from robustnessgym.ops import SpacyOp
from tests.testbeds import MockTestBedv0
class TestSpacy(TestCase):
def setUp(self):
self.testbed = MockTestBedv0()
def test_apply(self):
# Create the Spacy cached operation
spacy = S... |
3318729 | from os.path import join
import types
from django.conf import settings
from django.template.base import TemplateDoesNotExist
from django.template.loader import find_template
def patched_find_template(name, dirs=None):
request = getattr(settings, 'request_handler', None)
if request:
for prefix in reque... |
3318741 | from sanic import Blueprint
from sanic.views import HTTPMethodView
from sanic.response import json
import uuid
import os
import ipfshttpclient
from .errors import bad_request
import configparser
import requests
config = configparser.ConfigParser()
config.read('config.ini')
ipfs = Blueprint('ipfs_v1', url_prefix='/ipf... |
3318750 | import sys
events = []
def can(f: float):
global events
cur_d, cur_n, leak_rate, dt = 0, 0, 0, 0
original_f = f
for i in range(len(events)):
dt = events[i][0] - cur_d
f -= dt / 100 * cur_n
f -= dt * leak_rate
if f < 0:
return False
if events[i][1] <= 0:
cur_n = -events[i][1]
... |
3318751 | import shutil
from .base_compiler import BaseCompiler
from ..typehint import TPyFilesToCompile
class EffectlessCompiler(BaseCompiler):
""" No compiling process, just do copy files.
This is made for debug mode. (See `pyportable_installer.main.debug_build`.)
"""
# noinspection PyMissingConstr... |
3318753 | import asyncio
import logging
from datetime import datetime
from decimal import Decimal
from elasticsearch import Elasticsearch
from model.f1_2020_struct import *
class F1UdpReceiver(asyncio.DatagramProtocol):
def __init__(self):
super().__init__()
self.es = Elasticsearch("http://es01:9200")
... |
3318787 | import os
import numpy as np
from audiomate import containers
import pytest
from tests import resources
@pytest.fixture()
def sample_container():
container_path = resources.get_resource_path(
['sample_files', 'audio_container']
)
sample_container = containers.AudioContainer(container_path)
s... |
3318861 | from http import HTTPStatus
from unittest.mock import patch
import requests
import requests_mock
from django.test import TestCase
from django.conf import settings
from readthedocs.forms import SignupFormWithNewsletter
class TestNewsletterSignup(TestCase):
form_data = {
"email": "<EMAIL>",
"user... |
3318876 | import tempfile
from mock.mock import call, patch
from pytest import mark
import insights.client.schedule as sched
from insights.client.config import InsightsConfig
def test_get_schedule_cron():
target = tempfile.mktemp()
config = InsightsConfig()
with tempfile.NamedTemporaryFile() as source:
sc... |
3318963 | import csv
import math
import numpy as np
def sigmoid(x):
if x >= 0:
return math.exp(-np.logaddexp(0, -x))
else:
return math.exp(x - np.logaddexp(x, 0))
def load_data_from_dir(dirname):
fname_user_idxseq = dirname + '/' + 'idxseq.txt'
fname_user_list = dirname + '/' + 'user_idx_list... |
3319027 | from datetime import datetime
import offchain
from offchain import FundPullPreApprovalStatus
from flask import Response
from flask.testing import Client
from tests.wallet_tests.resources.seeds.one_funds_pull_pre_approval import TIMESTAMP
from wallet.services.offchain import (
offchain as offchain_service,
fund... |
3319103 | import unittest
import responses
from tests.api.base import MediaFireApiTestCase
from mediafire.api import MediaFireApiError
class TestErrorResponse(MediaFireApiTestCase):
def __init__(self, *args, **kwargs):
super(MediaFireApiTestCase, self).__init__(*args, **kwargs)
self.url = self.build_url(... |
3319169 | from datasets import load_dataset, load_from_disk
from transformers import AutoTokenizer
from typing import Dict, List
def download_dataset(config: Dict, logger):
"""
:param config: "dataset" sub-config of a jsonnet config
"""
assert all(x in config for x in ['name', 'split', 'root_dir'])
if 'subs... |
3319182 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
class LeNet(nn.Module):
def __init__(self):
super(LeNet, self).__init__()
self.conv1 = nn.Conv2d(1, 6, 5)
self.conv2 = nn.Conv2d(6, 16, 5)
self.fc1 = nn.Linear(256, 120)
self.fc2 = nn.Linea... |
3319249 | from collections import defaultdict
import datetime
from datetime import date
import csv
InputData = './train.csv'
POIdata = 'PoliceCoords.csv'
trips = defaultdict(lambda: defaultdict(list))
###########################
def PolylineToGrid(polyline):
#print(polyline)
vals = []
polyline = ... |
3319252 | import logging
from typing import List, Optional
from hummingbot.connector.exchange.k2.k2_api_user_stream_data_source import \
K2APIUserStreamDataSource
from hummingbot.connector.exchange.k2.k2_auth import K2Auth
from hummingbot.connector.exchange.k2.k2_constants import EXCHANGE_NAME
from hummingbot.core.data_type... |
3319268 | import unittest
from formation import AppBuilder
from formation.tests.support import get_resource
class VariablesTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.builder = AppBuilder(path=get_resource("variables.xml"))
def test_string_var(self):
var = self.buil... |
3319275 | inp = int(input("Enter N: "))
m = []
for i in range(0 , inp):
n = int(input("Enter numbers: "))
m.append(n)
m.sort()
mis = 0
rep = 0
flg = 0
for i in range(1 , inp + 1):
flg = 0
for j in range(0 , len(m)):
if i == m[j]:
flg = 1
break
if flg == 0:
mis = i
... |
3319299 | from django.db import models
import uuid
class Musician(models.Model):
first_name = models.CharField(max_length = 50)
last_name = models.CharField(max_length = 50)
instrument = models.CharField(max_length = 100)
class Album(models.Model):
id = models.UUIDField(primary_key = True, default = uuid.uuid... |
3319300 | import datetime
import logging
import os
import boto3
CW = boto3.client("cloudwatch")
logging.getLogger().setLevel(os.environ.get("LOGLEVEL", logging.INFO))
def handler(_event, _context):
logging.debug("environment variables:\n %s", os.environ)
timestamp = datetime.datetime.now(datetime.timezone.utc)
t... |
3319395 | import os
from .las_handler import LASHandler as las
from .ply_handler import PLYHandler as ply
io_handlers = {
'.ply': ply,
'.las': las,
'.laz': las,
}
def get_io_handler(path, mode, format=None, overwrite=False):
"""
Return instance of format-specific IOHandler, already initialized to read or ... |
3319405 | import praw
from neo4j import BoltDriver
from typing import List, Union
from itertools import chain
from reddit_detective.relationships import Submissions, Comments, CommentsReplies
from reddit_detective.karma import (_remove_karma, _set_karma_subreddits, _set_karma_submissions,
_se... |
3319440 | from itertools import islice
import math
import time
from typing import Iterator, List, Optional, Set
import multiprocessing as mp
from sympy import isprime
import logging
from primify import console
logger = logging.getLogger(__file__)
class NextPrimeFinder:
def __init__(self, value: int, n_workers: int = 1):
... |
3319448 | import glob
import json
import os
import subprocess
import winreg
RELENG_DIR = os.path.abspath(os.path.dirname(__file__))
ROOT_DIR = os.path.dirname(RELENG_DIR)
DEFAULT_TOOLCHAIN_DIR = os.path.join(ROOT_DIR, "build", "toolchain-windows")
BOOTSTRAP_TOOLCHAIN_DIR = os.path.join(ROOT_DIR, "build", "fts-toolcha... |
3319453 | import tensorflow as tf
import numpy as np
hparams = tf.contrib.training.HParams(
#####################################
# Audio config
#####################################
sample_rate=22050,
silence_threshold=2,
num_mels=80,
fmin=125,
fmax=7600,
fft_size=1024,
win_length=1024,
... |
3319474 | from toee import *
import char_editor
def CheckPrereq(attachee, classLevelled, abilityScoreRaised):
# BAB enforced via prefeq properties
#if attachee.get_base_attack_bonus() < 4:
# return 0
#Paladin Smite Evil Check
if char_editor.has_feat(feat_smite_evil):
return 1
#Destruction Domain Check
domain_1 = at... |
3319512 | input = """
a | b | c | d.
a :- b.
b :- a.
c :- d.
d :- c.
:- not a.
:- not c.
"""
output = """
"""
|
3319535 | from operator import delitem
import sys
import os
import re
import json
import argparse
import cv2
import csv
import ffmpeg
from pathlib import Path
from pathvalidate.argparse import validate_filepath_arg
# IMPORTANT: Only add to the end of these lists. Doing otherwise could break the annotations.
weather_types = ['Dr... |
3319603 | import data_pre.transform_pool as bio_transform
import SimpleITK as sitk
import numpy as np
class Transform(object):
def __init__(self,option, dim=3):
self.transform_seq = []
self.dim = dim
self.option = option
self.patch_size =option[('patch_size',[128, 128, 32], 'patch size')]
... |
3319616 | import itertools
import os
from collections import OrderedDict
import numpy as np
import six
import tensorflow as tf
import tensorflow.contrib.graph_editor as ge
from tensorflow.core.framework import node_def_pb2
from tensorflow.python.framework import device as pydev
from tensorflow.python.training import device_sett... |
3319621 | from PyQt5 import QtCore, QtGui, QtWidgets
from morphine.globals import __enviroments__, __intended_audience__, __programming_lang__, __license__, find_packages
import os
from yapf.yapflib.yapf_api import FormatCode
from morphine.template import __minimal_deps__ as template
class Ui_minimal_deps(object):
def __in... |
3319622 | from typing import Tuple, List, Optional
def swap_sum(arr_a: List[int], arr_b: List[int]) -> Optional[Tuple]:
sum_a = sum(arr_a)
sum_b = sum(arr_b)
# sum_a - a + b = sum_b - b + a
# a - b = (sum_a - sum_b) / 2
diff = sum_a - sum_b
if diff % 2 != 0:
return None
target = int(diff / ... |
3319658 | from ._version import version_info, __version__
from .cyjs import *
def _jupyter_nbextension_paths():
return [{
'section': 'notebook',
'src': 'static',
'dest': 'cyjs',
'require': 'cyjs/extension'
}]
|
3319703 | from sqlalchemy.sql import text
import pkg_resources
from sqlalchemy import create_engine
from tabulate import tabulate
import os
class PGExtras:
def query(query_name, output="ascii", database_url=None):
database_url_val = database_url or os.environ['DATABASE_URL']
resource_path = '/'.join(('queries', qu... |
3319745 | import scipy as sp
from scipy.sparse.linalg import spsolve
from matplotlib import pyplot as plt
def Problem2Real():
beta = 0.95
N = 1000
u = lambda c: sp.sqrt(c)
psi_ind = sp.arange(0,N)
W = sp.linspace(0,1,N)
X, Y = sp.meshgrid(W,W)
Wdiff = Y-X
index = Wdiff <0
Wdiff[index] = 0
... |
3319790 | import logging
from django.test import TestCase
from django.urls import reverse
from rest_framework import status
from rest_framework.response import Response
from django_drf_filepond.utils import _get_file_id
# Python 2/3 support
try:
from unittest.mock import patch
except ImportError:
from mock import patc... |
3319846 | N = 100
l = [0] * N
for i in xrange(2, N):
t = [l[i-1]]
for j in xrange(2, i):
if i % j == 0:
t.append(l[i/j])
j = 0
while j in t:
j += 1
l[i] = j
for i in xrange(1, N):
print i, l[i]
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.