id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3390169 | import numpy as np
from matplotlib.patches import Ellipse
def generate_bounding_box_from_mask(mask):
"""
Function for generating a bounding box around a mask.
Bounding box covers the extremes of the mask inclusively such that the far left box aligns
with the far left of the mask.
:param mask: 2D ma... |
3390189 | import logging
import random
from tornado import gen
from zoonado import exc
log = logging.getLogger(__name__)
def arguments(parser):
parser.add_argument(
"--path", "-b", type=str, default="/example-counter",
help="ZNode path to use for the barrier."
)
parser.add_argument(
"--wo... |
3390206 | import random
import string
from os import makedirs
def __generate_random_string(length=20):
return "".join([random.choice(string.ascii_lowercase) for _ in range(length)])
def __write_to_file(file_path, items):
makedirs(file_path.parent, exist_ok=True)
with open(file_path, 'w') as f:
for item in... |
3390212 | from datetime import datetime
from django.shortcuts import render
from django.http import HttpResponseRedirect
from server import logger
from server.forms import PrescriptionForm
from server.models import Account, Prescription, Action
from server import views
def create_view(request):
# Authentication Check
... |
3390225 | from __future__ import annotations
from traceback import StackSummary
from types import TracebackType
from typing import Any, Callable
from django.conf import settings
from django_perf_rec.utils import sorted_names
class Operation:
def __init__(
self, alias: str, query: str | list[str], traceback: Stac... |
3390238 | import datetime
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from tabledef import *
# create a Session
Session = sessionmaker(bind=engine)
session = Session()
user = User("<EMAIL>","password")
session.add(user)
user = User("<EMAIL>", "<PASSWORD>")
session.add(user)
user = User("... |
3390247 | from xlsxwriter import Workbook
from series_tiempo_ar_api.apps.dump.generator.xlsx.worksheet import DumpWorksheet, SingleWorksheet
class DumpWorkbook:
frequency_col_name = 'indice_tiempo_frecuencia'
@property
def worksheets_objs(self):
return self.workbook.worksheets_objs
def __init__(self,... |
3390258 | from numpy import ndarray
from pandas import DataFrame, Series
from typing import Union
ArrayLike = Union[ndarray, DataFrame, Series] |
3390281 | from .character_model import CharacterModel
##### Hide lines below until Lab 2
from .line_model import LineModel
##### Hide lines above until Lab 2
##### Hide lines below until Lab 3
from .line_model_ctc import LineModelCtc
##### Hide lines above until Lab 3
|
3390283 | from collections import Counter, defaultdict
from aoc import *
def parse_input(data):
guards = defaultdict(Counter)
for line in data:
last_digit = extract_numbers(line)[-1]
if line[-2] == 'f': # ...shiFt
current_guard = last_digit
elif line[-2] == 'e': # ...asleEp
... |
3390341 | import pytest
@pytest.fixture
def procfs_timeline():
"""
Timeline of procfs report for the tests
"""
return [
{
"timestamp": "2021-09-14T12:37:37.168817",
"sensor": "formula_group",
"target": ["firefox_cgroup", "emacs_cgroup",
"zsh_cg... |
3390369 | import torch
import torch.nn as nn
import torch.nn.functional as func
from torchsupport.modules.separable import DepthWiseSeparableConv2d
class WNet(nn.Module):
def __init__(self, down_block=None, up_block=None, n_classes=2,
in_channels=1, depth=5, first_filters=6, up_mode='upconv'):
"""
Templ... |
3390384 | import random
class QLearn:
def __init__(self, actions, maxStates, epsilon=0.1, alpha=0.2, gamma=0.9):
self.q = {} # emulate the Q-Value matrix as a dictionary
self.epsilon = epsilon
self.alpha = alpha
self.gamma = gamma
self.actions = actions
self.maxStates = max... |
3390387 | from flask import Flask, request
from flask_cors import CORS
from fate_manager.controller.user_controller import check_token
from fate_manager.service import user_service
from fate_manager.utils import detect_utils
from fate_manager.utils.api_utils import server_error_response, get_json_result
manager = Flask(__name_... |
3390389 | from a10sdk.common.A10BaseClass import A10BaseClass
class SamplingEnable(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param counters1: {"enum": ["all", "tcp-total-ports-allocated", "udp-total-ports-allocated", "icmp-total-ports-allocated"], "type": "string", "descrip... |
3390400 | import logging
import requests
import json
def setup_loggers(name, log_file, level=logging.INFO):
formatter = logging.Formatter('%(asctime)s — %(message)s')
handler = logging.FileHandler(log_file)
handler.setFormatter(formatter)
logger = logging.getLogger(name)
logg... |
3390428 | def load_data(cursor):
cursor.execute("""MATCH (n)
DETACH DELETE n;""")
cursor.fetchall()
cursor.execute("""CREATE INDEX ON :User(id);""")
cursor.fetchall()
cursor.execute("""CREATE INDEX ON :User(name);""")
cursor.fetchall()
cursor.execute("""CREATE CONSTRAINT ON (use... |
3390437 | import sys
import os
import numpy as np
a3m1 = sys.argv[1]
a3m2 = sys.argv[2]
def read_a3m(fn):
'''parse an a3m files as a dictionary {label->sequence}'''
seq = []
lab = []
is_first = True
for line in open(fn, "r"):
if line[0] == '>':
label = line.strip()[1:]
is_inc... |
3390446 | import seaborn as sns
import matplotlib.pyplot as plt
sns.set()
plt.style.use("dark_background")
def plot_metrics(train_metric, test_metric):
(train_losses, train_acc) = train_metric
(test_losses, test_acc) = test_metric
fig, axs = plt.subplots(2, 2, figsize=(14, 10))
fig.suptitle('Metrics')
axs[... |
3390463 | import os
import os.path as osp
import torch
from torch.utils.tensorboard import SummaryWriter
from skimage import io
from core.trainer import Trainer
from ..builders.sched_builders import build_schedulers
class CDTrainer(Trainer):
def __init__(self, model, dataset, criterion, optimizer, settings):
supe... |
3390487 | import pytest
import responses
from sparkpost import SparkPost
from sparkpost.exceptions import SparkPostAPIException
@responses.activate
def test_success_list():
responses.add(
responses.GET,
'https://api.sparkpost.com/api/v1/suppression-list',
status=200,
content_type='applicati... |
3390497 | from pandas import DataFrame
from trane.ops.aggregation_ops import * # noqa
from trane.utils.table_meta import TableMeta as TM
df = DataFrame({'col': [1, 2, 3, 4, 5]})
meta = TM({
"tables": [
{"fields": [{'name': 'col', 'type': TM.SUPERTYPE[
TM.TYPE_FLOAT], 'subtype': TM.TYPE_FLOAT}]}
]})... |
3390514 | import sys
import pdb
import psycopg2
from sqlalchemy import create_engine
from sqlalchemy.pool import NullPool
from datetime import datetime, date, timedelta
from datetime import time as dttime
from collections import deque, defaultdict
from dateutil.parser import parse as dateparse
from browser.auth import *
from s... |
3390517 | from .lib.context import ContextStack, Proxy
_build_proxy = ContextStack()
current_build = Proxy(_build_proxy)
|
3390538 | from .colors.default_colors import DefaultBodyColors as bc
class Banner():
"""
Display the SkipTracer banner
using the BodyColors lib
to set text color.
"""
def banner(self):
"""
Print the banner
out to the screen
"""
print("")
print("\t\t.▄▄ · ... |
3390597 | class Solution:
def distributeCandies(self, candies: int, num_people: int) -> List[int]:
result = [0] * num_people
curr = 1
while candies > 0:
for i in range(num_people):
if candies >= curr + i:
result[i] += curr + i
candies... |
3390606 | from calm.dsl.decompile.render import render_template
from calm.dsl.builtins import RefType
from calm.dsl.log import get_logging_handle
from calm.dsl.decompile.ref_dependency import (
get_service_name,
get_profile_name,
get_substrate_name,
)
from calm.dsl.decompile.ref_dependency import get_package_name, ge... |
3390612 | import random
import numpy as np
import torch
def set_seed(seed: int):
""" Set random seed for python, numpy and pytorch RNGs """
random.seed(seed)
np.random.seed(seed)
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
def get_random_state():
return {
'python': random.getstate(... |
3390640 | from __future__ import absolute_import, division, print_function
from telnyx.api_resources.abstract import ListableAPIResource
class AvailablePhoneNumber(ListableAPIResource):
OBJECT_NAME = "available_phone_number"
|
3390656 | from flask import current_app, g, abort
from flask_restful import Resource
from app.apiv2.decorators import permission_sudo
from app.caches import ShiftsCache, SchedulesCache, Schedules2Cache, \
Shifts2Cache, IncidentCache, SessionCache
from app.constants import API_ENVELOPE
KEY_TO_CACHES = {
"shifts": [Shift... |
3390694 | import sys
try: # Qt4 vs Qt5
from python_qt_binding.QtGui import QSortFilterProxyModel
except ImportError:
from python_qt_binding.QtCore import QSortFilterProxyModel
from python_qt_binding.QtCore import QRegExp
if sys.version_info[0] is 2 or (sys.version_info[0] is 3 and sys.version_info[1] < 2):
from lr... |
3390720 | from collections import defaultdict
import itertools
from geosolver.ontology.ontology_definitions import issubtype
from geosolver.text.semantic_tree import SemanticTreeNode
__author__ = 'minjoon'
class SemanticForestNode(object):
def __init__(self, tag_rule, unary_rules, binary_rules):
self.tag_rule = ta... |
3390750 | import functools
from .exceptions import UnknownOperator
def only_ops(ops):
def decorator(func):
@functools.wraps(func)
def new_func(self, op, value):
if op.op not in ops:
raise UnknownOperator(op.op)
return func(self, op, value)
return new_func
... |
3390759 | from src.objs import *
#: Main reply keyboard
def mainReplyKeyboard(userId, userLanguage):
keyboard = telebot.types.ReplyKeyboardMarkup(resize_keyboard=True)
button1 = telebot.types.KeyboardButton(text=language['fileManagerBtn'][userLanguage])
button2 = telebot.types.KeyboardButton(text=language['acti... |
3390816 | class Solution:
def findPeakElement(self, nums: List[int]) -> int:
return self.search(nums, 0, len(nums) - 1)
def search(self, nums: List[int], l: int, r: int) -> int:
if l == r: return l
m = l + (r - l) // 2
if nums[m] > nums[m + 1]: return self.search(nums, l, m)
retur... |
3390859 | from jmeter_api.basics.thread_group.elements import BasicThreadGroup, ThreadGroupAction
from jmeter_api.basics.utils import Renderable, IncludesElements, tree_to_str
class SteppingThreadGroup(BasicThreadGroup, Renderable):
root_element_name = 'kg.apc.jmeter.threads.SteppingThreadGroup'
def __init__(self, *,... |
3390880 | from functools import partial
from collections import OrderedDict, namedtuple
from os import name
from typing import Optional, Union, Dict, NamedTuple
import torch
from torch import nn
try:
from typing_extensions import Final
except:
from torch.jit import Final
from comvex.utils import EfficientNetBase, MBCon... |
3390884 | from __future__ import division
import re
from math import sqrt, sin, cos, log, tan, acos, asin, atan, e, pi
from operator import truediv as div
from operator import add, sub, mul, pow
from .numbers import NumberService
class MathService(object):
__constants__ = {
'e': e,
'E': e,
'EE': e,... |
3390939 | import matplotlib.pyplot as plt
from scipy.optimize import minimize
class PolicyOptimizer:
"""
Fit a suppression policy to minimize total death count.
Note that it is apparent that many suppression polices (especially piecewise
are either not convex and hence converge with significant differences run... |
3390966 | import tushare as ts
import matplotlib.pyplot as plt
from datetime import datetime
import pandas as pd
import matplotlib.dates as mdates
data = ts.get_hist_data('600848', ktype='60')
data = data.head(5)
print(data.index)
xs = [mdates.strpdate2num('%Y-%m-%d %H:%M:%S')(d ) for d in data.index ]
fig1 = plt.figure(figsi... |
3390974 | import numpy
from .AssemblyFlaw import AssemblyFlaw
class Assembly:
"""Base class to represent assemblies. See GibsonAssembly, BASICAssembly,
etc. for usage classes
Parameters
----------
parts
List of part names corresponding to part records in a repository
name
Name of the a... |
3390981 | import _init_paths
import time
import argparse
import os.path as osp
import cv2
from pose_estimation import get_pose_estimator
from tracker import get_tracker
from classifier import get_classifier
from utils.config import Config
from utils.video import Video
from utils.drawer import Drawer
from utils import utils
de... |
3390992 | def divisible_evenly(number, max_range):
for x in range(max_range - 1, 1, -1):
if number % x != 0:
return False
return True
def find_smallest_multiple():
smallest = 20
while True:
if smallest % 20 == 0 and divisible_evenly(smallest, 20):
return smallest
... |
3390995 | try:
import testtools as unittest
except ImportError:
import unittest
import io
import json
import falcon
import falcon.testing as testing
from meniscus.validation import SchemaLoader
from meniscus.validation.jsonv import JsonSchemaValidatorFactory
from meniscus.validation.integration.falcon_hooks import vali... |
3391012 | import sys
import numpy as np
import SUMatch as TMT
from puffDataClass import puffData
from undulator import undulator
##### FOR NEW OUTER DRIVER:
def MTdriver(fnamein):
puffVars = puffData()
# Initialize CLARA base parameters
puffVars.aw = 0.8745*np.sqrt(2.) # The PEAK!!!
puffVars.gamma0 = 469.0
... |
3391028 | import warnings
from sys import stderr
import numpy as np
from sklearn.base import BaseEstimator, TransformerMixin, RegressorMixin, ClassifierMixin
from sklearn.cross_decomposition import PLSRegression
from sklearn.metrics import accuracy_score, roc_auc_score, roc_curve, r2_score
from sklearn.model_selection import KF... |
3391034 | import bpy
from .BlenderObjects import *
from .BlenderShapes import *
from .BlenderLamps import BlenderPoint
from ..RandomLib import random_render as rnd
class BlenderRoom(object):
def __init__(self, radius):
self.walls = []
self.walls.append(
BlenderPlane(location=(-radius, 0, 0), sc... |
3391039 | import json
import os.path
import posixpath
import platform
import sys
from subprocess import Popen, PIPE, STDOUT
if __name__ == '__main__':
print "Running " + str(__file__) + "..."
#Run the XFoil simulation ------------------------------------------------------------------------------------------
print ... |
3391110 | import plotly.offline as po
import plotly.graph_objs as go
import numpy as np
# plotly.offline.init_notebook_mode(connected=True)
# 格子状に座標を生成
grid = np.mgrid[0:10, 0:20]
grid_x = grid[0].flatten()
grid_y = grid[1].flatten()
grid_z = grid_x + grid_y
points = np.array(list(zip(grid_x, grid_y, grid_z)))
# プロットのためにxyzごと... |
3391116 | from jnpr.junos import Device
from lxml import etree
dev = Device(host='xxxx', user='demo', password='<PASSWORD>', gather_facts=False)
dev.open()
# Below rpc call will return xm object
op = dev.rpc.get_interface_information()
# To print to content of object returned, use below function (etree.tostring)
print (etree.t... |
3391129 | created = [
"assembled",
"brewed",
"built",
"created",
"composed",
"constructed",
"designed",
"devised",
"done",
"forged",
"formed",
"initiated",
"invented",
"made",
"organized",
"planned",
"prepared",
"set up",
"thrown together"
]
creating = ... |
3391140 | import asyncio
__all__ = ['graceful_shutdown', 'graceful_execute']
# Refer: https://stackoverflow.com/questions/30765606/whats-the-correct-way-to-clean-up-after-an-interrupted-event-loop
def graceful_shutdown(loop: asyncio.AbstractEventLoop = None):
tasks = asyncio.gather(*asyncio.Task.all_tasks(loop=loop), loop... |
3391146 | from IPython.core.getipython import get_ipython
class BaseModelRegression(object):
def fit(self, X, y):
return NotImplementedError
def predict(self, X):
return NotImplementedError
def __visual_training__(self):
return NotImplementedError
def score(self, real, predicted):
return NotImplementedError
d... |
3391156 | from typing import List
from hrmachine import Letter, Value
def string_to_values(string: str, zero_terminated=False) -> List[Value]:
output = []
for word in string.split():
for char in word:
if char.isalpha():
output.append(Letter.from_string(char))
elif char.is... |
3391157 | from abc import ABC, abstractmethod
from typing import Dict, Sequence, Generic, TypeVar
from .eval_stats.eval_stats_clustering import ClusteringUnsupervisedEvalStats, \
ClusteringSupervisedEvalStats, ClusterLabelsEvalStats
from .evaluator import MetricsDictProvider
from ..clustering import EuclideanClusterer
from ... |
3391169 | import tensorflow as tf
from tensorflow.keras import losses, applications, Model
def generator_loss(y):
return -tf.reduce_mean(y)
def kl_divergence_loss(mean, variance):
return -0.5 * tf.reduce_sum(1 + variance - tf.square(mean) - tf.exp(variance))
class FeatureMatchingLoss(losses.Loss):
def __init__(... |
3391183 | import subprocess
import shutil
def query(key):
if shutil.which("xgetres"):
return subprocess.run(["xgetres", key],
capture_output=True).stdout.decode("utf-8").strip()
else:
raise Exception("xgetres must be installed for this theme")
|
3391186 | import unittest
from liquer import Q
class TestLiquer(unittest.TestCase):
def testQ(self):
a = {'foo': {'bar': 'Hello World!', 'baz': 1}}
self.assertTrue(Q(foo__bar='Hello World!')(a))
self.assertFalse(Q(foo__bar='hello world!')(a))
self.assertTrue(Q(foo__bar__iexact='hello world!... |
3391216 | from collections.abc import Mapping
from pychemia.utils.periodic import *
madelung_exceptions = {'Cr': ['Ar', '4s1', '3d5'],
'Cu': ['Ar', '4s1', '3d10'],
'Nb': ['Kr', '5s1', '4d4'],
'Mo': ['Kr', '5s1', '4d5'],
'Ru': ['Kr', '5s1... |
3391227 | import torch.nn as nn
import torch.nn.init as init
from rcnn.modeling import registry
from rcnn.core.config import cfg
# ---------------------------------------------------------------------------- #
# R-CNN bbox branch outputs
# ---------------------------------------------------------------------------- #
@registr... |
3391238 | import demistomock as demisto
import pytest
EMAIL_HTML = """
<html><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8"></head><body><div dir="ltr">image 1:
<div><div><img src="cid:ii_kgjzy6yh0" alt="image_1.png" width="275" height="184"><br></div></div><div>image 2:
</div><div><div><img src="cid:i... |
3391275 | from __future__ import annotations
import pytest
from steam.ext.commands.utils import MissingClosingQuotation, Shlex
test_strings = [
("foo bar baz", ["foo", "bar", "baz"]),
('foo "bar baz"', ["foo", "bar baz"]),
('foo \\"bar baz', ["foo", '"bar', "baz"]),
('foo bar baz\\"', ["foo", "bar", 'baz"']),
... |
3391282 | import os, requests, zipfile
def get_year_quarter_tuples(years):
for year in years:
for quarter in [1,2,3,4]:
if year == 2010 and quarter < 4: continue # First: 2010 Q4
if year == 2016 and quarter > 1: continue # Last: 2016 Q1
yield (year, quarter)
def get_bikeshare_... |
3391292 | import unittest
from typing import List
import numpy as np
from nuplan.common.actor_state.agent import Agent
from nuplan.common.actor_state.ego_state import EgoState
from nuplan.common.actor_state.scene_object import SceneObject, SceneObjectMetadata
from nuplan.common.actor_state.state_representation import StateSE2,... |
3391304 | import math
import numpy as np
import torch
NEG_INF = torch.finfo(torch.float32).min
PI = math.pi
SOUND_SPEED = 343 # m/s
EPSILON = np.finfo(np.float32).eps
MAX_INT16 = np.iinfo(np.int16).max
|
3391306 | import copy
from misc import *
from path import *
from draw import *
from mode import Mode
from knob import DraggableKnob
from nanogui import *
class SpecularManifoldSamplingMode(Mode):
def __init__(self, viewer):
super().__init__(viewer)
self.seed_path = None
self.solution_path = None
... |
3391334 | import json
import elasticsearch
from elasticsearch.exceptions import RequestError, ElasticsearchException
from daybed import logger
class SearchError(Exception):
"""Exception raised on request error to indexer.
"""
def __init__(self, *args):
self.status_code, self.error, self.info = args[:3]
... |
3391335 | from flask import current_app
from scaner.utils import add_metadata
import json
# PRUEBA EXTRACION USUARIOS
# @add_metadata()
# def get(userId, fields=None, *args, **kwargs):
# #get_task = current_app.tasks.get_users_from_twitter.delay()
# get_task = current_app.tasks.execute_metrics.delay()
# return {'res... |
3391340 | import siliconcompiler
def main():
chip = siliconcompiler.Chip('mkFibOne')
chip.set('input', 'bsv', 'FibOne.bsv')
chip.set('option', 'frontend', 'bluespec')
# default Bluespec clock pin is 'CLK'
chip.clock(pin='CLK', period=5)
chip.load_target('freepdk45_demo')
chip.run()
chip.summary()... |
3391353 | import asyncio
import unittest
from mediatr import __behaviors__, __handlers__, Mediator
from tests.example_handlers import get_array_handler, get_array_handler_sync, get_array_query_behavior, \
get_array_query_behavior_3, get_array_query_behavior_6
from tests.example_queries import GetArrayQuery
class MainMedia... |
3391399 | from cython.cimports.cpython.version import PY_VERSION_HEX
# Python version >= 3.2 final ?
print(PY_VERSION_HEX >= 0x030200F0)
|
3391438 | from __future__ import absolute_import
import codecs
import os
import re
from setuptools import setup
def get_version(filename):
with codecs.open(filename, 'r', 'utf-8') as fp:
contents = fp.read()
return re.search(r"__version__ = ['\"]([^'\"]+)['\"]", contents).group(1)
version = get_version(os.p... |
3391452 | import re
from . import info as _info
from .parser._regexes import SIMPLE_TYPE
_KIND = _info.KIND
def match_storage(decl, expected):
default = _info.get_default_storage(decl)
#assert default
if expected is None:
expected = {default}
elif isinstance(expected, str):
expected = {expect... |
3391475 | import spacy
import json
import random
import numpy as np
from tqdm import tqdm
nlp_sent = spacy.load("en_core_web_sm")
doc = nlp_sent('European authorities fined Google a record $5.1 billion on Wednesday for abusing its power in the mobile phone market and ordered the company to alter its practices')
print([(X.text, ... |
3391524 | from typing import Optional
from functools import partial
from collections import OrderedDict
import torch
from torch import nn
from einops import repeat
from comvex.vit import ViTBase
from comvex.utils import LayerScale, ClassMultiheadAttention, TalkingHeadAttention, MLP, TokenDropout, ProjectionHead
from comvex.uti... |
3391536 | from .astf_general_test import CASTFGeneral_Test, CTRexScenario
import os, sys
from trex.astf.api import *
import time
import pprint
from nose.tools import assert_raises, nottest
from scapy.all import *
from trex.astf.topo import *
import tempfile
import copy
class ASTFTopology_Test(CASTFGeneral_Test):
''' Checks... |
3391556 | import re
import os
import sys
import json
import yaml
import base64
import hashlib
import subprocess
wd = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
package_path = os.path.join(wd, "package.json")
releases_yml_path = os.path.join(wd, "releases.yml")
releases_json_path = os.path.join(wd, "releases.jso... |
3391580 | import sys, os
import copy
import Config
from core.attributes import UNARY, BINARY
from core.expression import Symbol, Matrix, Vector, Scalar, \
Equal, Plus, Minus, Times, \
Transpose, Inverse, Predicate, \
PatternDot, Operator
from co... |
3391588 | from __future__ import annotations
import copy
import datetime
from itertools import chain
from typing import (
NewType,
Tuple,
Union,
List,
Dict,
Any,
Set
)
from bson import ObjectId
from networkx import DiGraph
from matchengine.internals.utilities.object_comparison import nested_object_... |
3391607 | import arcade
class Base:
display: arcade.Window
spritelist: arcade.SpriteList
spritedict: dict
sceneTime: float = 0
def sprite_setup(self) -> None:
pass
def update(self, delta_time: float) -> None:
self.sceneTime += delta_time
def draw(self) -> None:
pass
... |
3391644 | import json
from unittest import mock
from tornado import testing
from tests import utils
class TestRevisionHandler(utils.HandlerTestCase):
HOOK_PATH = 'waterbutler.server.api.v0.revisions.RevisionHandler._send_hook'
@testing.gen_test
def test_get_coro(self):
expected = [
utils.Moc... |
3391709 | from functools import partial
import gzip
import lzma
from pathlib import Path
from typing import Iterator
import warnings
__all__ = ['EXTENDED_IUPAC_PROTEIN_ALPHABET',
'SeqIO',
'parse',
]
# Bio.Alphabet.ExtendendIUPACProtein (deprecated in 2020)
EXTENDED_IUPAC_PROTEIN_ALPHABET = 'ACD... |
3391716 | import os
import unittest
import json
import jc.parsers.wc
THIS_DIR = os.path.dirname(os.path.abspath(__file__))
class MyTests(unittest.TestCase):
def setUp(self):
# input
with open(os.path.join(THIS_DIR, os.pardir, 'tests/fixtures/centos-7.7/wc.out'), 'r', encoding='utf-8') as f:
se... |
3391770 | from collections import namedtuple
# ======================================
# Some global configs for the experiments.
BUDGET = 400 # Maximum number of networks evaluated.
PLOT_EVERY = 25 # Frequency at which incumbents are chosen (and plotting is done).
MAX_M = 30 # Largest ensemble size used.
model_seeds = namedt... |
3391774 | import random, time, sys, subprocess, threading, pycurl, os, requests
from colorama import Fore
class Proxy_Checker():
def __init__(self):
subprocess.call('clear', shell=True)
sys.setrecursionlimit(10**6)
print(f"""{Fore.BLUE}
██▓███ ██▀███ ▒█████ ▒██ ██▓██ ██▓ ▄▄▄█████▓▒█████ ▒... |
3391775 | import time
from flask import Flask, send_file
from selenium import webdriver
import chromedriver_binary # Adds chromedriver binary to path
from PIL import Image
from io import BytesIO
from google.cloud import storage
app = Flask(__name__)
chrome_options = webdriver.ChromeOptions()
chrome_options.add_argument("--hea... |
3391812 | from decimal import Decimal
from functools import partial
from typing import Any
from cryptofeed.connection import AsyncConnection, WSAsyncConn
from cryptofeed.defines import TRADES
from cryptofeed.exchanges import Bybit
from ..exchange import Exchange
class BybitExchange(Exchange, Bybit):
def connect(self) -> ... |
3391815 | import logging
from dbnd import pipeline, task
logger = logging.getLogger(__name__)
@task
def calculate_alpha(base: int):
calculated_alpha = base + 1
logging.info("Alpha=%s", calculated_alpha)
return calculated_alpha
@task
def calculate_ratio(base: int):
calculated_ratio = base + 1
logging.in... |
3391824 | import datetime
from django.conf import settings
from django.contrib.auth.models import User
from django.core.exceptions import ObjectDoesNotExist
from rest_framework.views import APIView
from rest_framework.response import Response
from simple_salesforce import Salesforce
from django_countries import countries
fro... |
3391875 | from __future__ import annotations
from unittest import TestCase
from tests.classes.cb_product import CBProduct
from tests.classes.cbm_product import CBMProduct
from tests.classes.cbo_product import CBOProduct
class TestDecoratedOnDelete(TestCase):
def test_callback_are_called_for_existing_objects_on_delete(self... |
3391915 | from .fc import ZeroTorquePolicy, CancelGravityPolicy
from .mpfc import PlanningAndForceControlPolicy
|
3391939 | def minimum(z):
temp_min = 0
ind = (len(z)-1)//2
for x in z:
temp_min += abs(z[ind]-x)
return temp_min
def solve(i):
temp = 0
N = int(input())
x = []
y = []
for _ in range(N):
a,b = [int(j) for j in input().split(" ")]
x.append(a)
y.append(b)
y.so... |
3391972 | import torch
import numpy as np
from torch import nn
from scipy.sparse import coo_matrix
from torch_scatter import scatter_add
from sklearn.feature_extraction import FeatureHasher
class FlexiHashEmbedding(nn.Module):
cache = {}
def __init__(self, n_features=1048576, dim=128, embedding=nn.Embedding,
... |
3392040 | import torch
import torch.nn as nn
from torch import Tensor
from deep_table.nn.encoders.embedding.layer.base import BaseEmbeddingLayer
class AppendCLSToken(BaseEmbeddingLayer):
def __init__(self, d_token: int, initialization: str = "uniform") -> None:
super().__init__()
self.weight = nn.Parameter... |
3392052 | from flavio.physics.bdecays.formfactors.b_v import bsz, sse, cln, clnexp
from flavio.classes import AuxiliaryQuantity, Implementation
from flavio.config import config
processes_H2L = ['B->K*', 'B->rho', 'B->omega', 'Bs->phi', 'Bs->K*'] # heavy to light
processes_H2H = ['B->D*', ] # heavy to heavy
def ff_function(f... |
3392077 | from base import Publisher
import msgpack
import socket
class UDPPublisher(Publisher):
def __init__(self, host, port):
self.host = host
self.port = port
self.socket = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
def publish(self, request):
x = self.socket.sendto(msgpack.du... |
3392091 | import jwt
import gzip
from functools import wraps
from flask import request, after_this_request, current_app, jsonify
from flask_jwt_extended import get_jwt_identity
from io import BytesIO as IO
from server.models import User
def check_confirmed(func):
@wraps(func)
def decorated_function(*args, **kwargs):
... |
3392099 | import sys
import os
from datetime import datetime, timedelta
input_file = sys.argv[1]
rate = int(sys.argv[2])
input_fd = open(input_file, 'r')
vals = [0] * 1000
count = 0
for line in input_fd:
strs = line.split(',')
for i in range(len(strs)):
vals[i] = vals[i] + float(strs[i])
count = count + 1
if count ... |
3392116 | from picamera2.encoders.v4l2_encoder import V4L2Encoder
from v4l2 import *
class H264Encoder(V4L2Encoder):
def __init__(self, bitrate, repeat=False, iperiod=None):
super().__init__(bitrate, V4L2_PIX_FMT_H264)
if iperiod is not None:
self._controls += [(V4L2_CID_MPEG_VIDEO_H264_I_PERIOD... |
3392172 | from __future__ import print_function
import numpy as np
from ..PatchPipette import PatchPipette
from acq4.util.mies import MIES
from .patch_clamp import MIESPatchClamp
from .pressure_control import MIESPressureControl
from .testpulse import MIESTestPulseThread
from .states import MIESPatchPipetteStateManager
class M... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.