id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1769132 | from matplotlib import pyplot as plt
import numpy as np
class Plots():
def __init__(self, plotname):
self.plotname = plotname
self.att_fig, self.att_ax = plt.subplots(3,1, sharex=True)
self.att_ax[0].grid()
self.att_ax[1].grid()
self.att_ax[2].grid()
self.at... |
1769201 | from PhysicsTools.Heppy.analyzers.core.Analyzer import Analyzer
from PhysicsTools.Heppy.analyzers.core.AutoHandle import AutoHandle
from PhysicsTools.Heppy.physicsobjects.PhysicsObjects import Jet
from PhysicsTools.HeppyCore.utils.deltar import *
from PhysicsTools.HeppyCore.statistics.counter import Counter, Counters
... |
1769206 | from toolz import curry
from .any import any
from functools import partial
@curry
def contains_with(is_equal, x, xs):
"""Creates a new list out of the two supplied by applying the function to each
equally-positioned pair in the lists. The returned list is truncated to the
length of the shorter of the two ... |
1769220 | import random
import time
from itertools import product
import numpy as np
import gym
from gym import logger
env = gym.make('MountainCarContinuous-v0')
POPULATION_SIZE = 10
MAX_POPULATION_SIZE = 100
MUTATION_CHANCE = 0.5
BREEDING_CHANCE = 0.5
CURRENT_AGENTS_COUNT = 0
# Constants got from continuous_mountain_car.... |
1769233 | from cog import BasePredictor, Input, Path
from typing import Iterator
import torch
import yaml
import pathlib
import os
import yaml
from util import get_single_rgb
# https://stackoverflow.com/a/6587648/1010653
import tempfile, shutil
def create_temporary_copy(src_path):
_, tf_suffix = os.path.splitext(src_path)
... |
1769267 | import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
def generate_data_ajive_fig2(seed=None, all_components=False):
"""
Samples the data from AJIVE figure 2. Note here we use rows as observations
i.e. data matrices are n x d where n = # observations.
Parameter... |
1769268 | from collections import defaultdict
import pymysql
import os
from statsmodels.stats.inter_rater import fleiss_kappa
connection = pymysql.connect(host=os.getenv("DB_HOST", "localhost"),
user=os.getenv("DB_USER", "root"),
password=os.getenv("DB_PASS", ""),
... |
1769300 | import requests
import json
def get_header(token, accept=False, content=False):
header = {
"Authorization": "Bearer {}".format(token),
"Accept": "application/json",
"Content-Type": "application/json",
}
fields = (
["Authorization"]
+ (["Accept"] if accept else [])
... |
1769407 | import dash_core_components as dcc
import dash_html_components as html
import dash
import datetime
app = dash.Dash()
app.layout = html.Div([
dcc.Interval(id='my-interval'),
dcc.RadioItems(id='set-time',
value=1000,
options=[
{'label': 'Every second', 'value': 1000},
{'l... |
1769420 | import time
class Timer:
""" Use the Python with-statement to time your code
with this timer. """
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, *args):
self.end = time.time()
self.elapsed = round(self.end - self.start, 6)
# Logging
def info(message):
print(message)
de... |
1769429 | from .biothings_transformer import BioThingsTransformer
class SemmedTransformer(BioThingsTransformer):
def wrap(self, res):
result = {}
for pred, val in res.items():
tmp = []
if isinstance(val, list) and len(val) > 0:
for item in val:
if ... |
1769443 | from __future__ import division
import os
from os.path import abspath, expanduser, join, dirname, pardir
from yaml import load as load_yaml
from ngs_utils.config import load_yaml_config, fill_dict_from_defaults
from ngs_utils.file_utils import verify_file, verify_module, adjust_path
from ngs_utils.logger import info, ... |
1769448 | import os
from datetime import datetime
from pyhocon import ConfigFactory
import sys
import torch
import importlib
from datasets.scene_dataset import SceneDataset
from model.implicit_differentiable_renderer import IDRNetwork
from model.loss import IDRLoss
import utils.general as utils
import utils.plots as ... |
1769455 | import os
import sys
from django.conf import settings
location = lambda x: os.path.join(
os.path.dirname(os.path.realpath(__file__)), x
)
sandbox = lambda x: location("sandbox/%s" % x)
sys.path.insert(0, location('sandbox'))
from oscar import get_core_apps
from oscar import OSCAR_MAIN_TEMPLATE_DIR
from oscar.de... |
1769456 | import FWCore.ParameterSet.Config as cms
from CommonTools.ParticleFlow.Isolation.tools_cfi import *
#Now prepare the iso deposits
muPFIsoDepositChargedPFBRECO=isoDepositReplace('pfSelectedMuonsPFBRECO','pfAllChargedHadronsPFBRECO')
muPFIsoDepositChargedAllPFBRECO=isoDepositReplace('pfSelectedMuonsPFBRECO','pfAllChar... |
1769522 | import pytest
from autofit import database as db
@pytest.fixture(
name="fit"
)
def make_fit():
return db.Fit(
id="id",
info={
"key": "value"
}
)
def test_create(
fit
):
assert fit.info["key"] == "value"
@pytest.fixture(
autouse=True
)
def add_to_ses... |
1769526 | import os
import pygame
import math
import time
lines = 100
def setup(screen,etc):
pass
def draw(screen, etc):
etc.color_picker_bg(etc.knob5)
for i in range(0, lines) :
seg(screen, etc, i)
def seg(screen, etc, i) :
x0 = 0
x1 = 0 + (etc.audio_in[i] / 35)
y = ((i ... |
1769540 | from __future__ import division, unicode_literals
from builtins import object
import numpy as np
from sklearn.preprocessing import LabelEncoder, OneHotEncoder
class DataEncoder(object):
def __init__(self, class_column='class', feature_columns=None):
self.class_column = class_column
self.feature_... |
1769552 | from enum import IntEnum
from typing import Callable, Dict, List, Iterable
from spherov2.commands.animatronic import R2LegActions, Animatronic
from spherov2.commands.api_and_shell import ApiAndShell
from spherov2.commands.core import IntervalOptions, Core
from spherov2.commands.io import AudioPlaybackModes, IO
from sp... |
1769572 | import torch
import torch.nn as nn
import torch.nn.functional as F
class IFNet(nn.Module):
"""
Input: IFNet for feature extraction.
"""
def __init__(self, tex=False, **kwargs):
super(IFNet, self).__init__()
self.tex = tex
if tex:
self.conv_00 = nn.Conv3d(3, 32, 3,... |
1769637 | import os
import pytest
from clikit.formatter import AnsiFormatter
from clikit.io import BufferedIO
@pytest.fixture()
def io():
return BufferedIO()
@pytest.fixture()
def ansi_io():
return BufferedIO(formatter=AnsiFormatter(forced=True))
@pytest.fixture
def environ():
original_environ = dict(os.envir... |
1769651 | import string
from kivy.app import App
from task_widgets.task_base.intro_hint import IntroHint
from utils import import_kv
from .find_in_table_dynamic import FindInTableDynamic
import_kv(__file__)
class IntroHintFindLetterDynamic(IntroHint):
pass
class FindLetterDynamic(FindInTableDynamic):
SIZE = 5
T... |
1769670 | from http.server import BaseHTTPRequestHandler, HTTPServer
class DummyServer(BaseHTTPRequestHandler):
def _set_headers(self):
self.send_response(200)
self.send_header('Content-type', 'text/html')
self.end_headers()
def do_GET(self):
self._set_headers()
self.wfile.write(... |
1769673 | from models.dense_net import DenseNetConfig, DenseNet
from models.convnet import SimpleConvnetConfig, SimpleConvnet
import numpy as np
def get_model_config_by_name(name):
if name == 'DenseNet':
return DenseNetConfig
elif name == 'SimpleConvnet':
return SimpleConvnetConfig
else:
raise ValueError('Unknown mode... |
1769680 | from office365api.model.email_address import EmailAddress
from office365api.model.model import Model
class Recipient(Model):
"""
Represents information about a user in the sending or receiving end of an event or message.
"""
# noinspection PyShadowingNames
def __init__(self, EmailAddress=None):
... |
1769689 | from concurrent.futures import ThreadPoolExecutor
from email.mime.text import MIMEText
from functools import partial
import smtplib
from . import base
class SMTPConnection(base.BaseConnection):
def __init__(self, loop, conf, **kwargs):
super().__init__(**kwargs)
self._conn = None
self.loo... |
1769707 | import requests
import random
import string
from plugins.oob import verify_request, gen_oob_domain
# Vuln Base Info
def info():
return {
"author": "cckuailong",
"name": '''Apache APISIX apisix/batch-requests Remote Code Execution''',
"description": '''A default configuration of Apache API... |
1769763 | import tqdm as tqdm
from torch.multiprocessing import Pool
from torch.optim import Adam
from evostrat import compute_centered_ranks, NormalPopulation
from evostrat.examples.lunar_lander import LunarLander
if __name__ == '__main__':
"""
Lunar landers weights and biases are drawn from normal distributions with ... |
1769809 | import sys
from2to = []
for entry in sys.argv[1].split(","):
from2to.append([int(entry.split(":")[0]), int(entry.split(":")[1])])
f1 = open(sys.argv[2])
f2 = open(sys.argv[3])
for line1 in f1:
parts1 = line1.strip().split("\t")
line2 = f2.readline()
parts2 = line2.strip().split("\t")
if line1... |
1769851 | from mythic_payloadtype_container.MythicCommandBase import *
import json
class PwdArguments(TaskArguments):
def __init__(self, command_line):
super().__init__(command_line)
self.args = {}
async def parse_arguments(self):
pass
class PwdCommand(CommandBase):
cmd = "pwd"
needs_ad... |
1769862 | def manhattan(x1,y1,x2,y2):
return (abs(x1-x2)+abs(y1-y2))
t=int(input())
for _ in range(t):
n,m=[int(x) for x in input().strip().split()]
arr=[]
for eachrow in range(n):
row=list(str(input()))
arr.append(row)
ones=[]
for i in range(n):
for j in range(m):
if(arr[i][j]=='1'):
ones.... |
1769874 | import discord
async def createEmbed(title, desc = None, footer = None, thumbnail = None):
if desc is not None:
em = discord.Embed(title = title, description = desc)
else:
em = discord.Embed(title = title)
if footer is None:
em.set_footer(text = "Bot made by NightZan999#0194... |
1769883 | import numpy as np
from roadrunner import RoadRunner
from roadrunner.testing import TestModelFactory as tmf
from threading import Thread
from multiprocessing import Queue
import time
from platform import platform
import cpuinfo # pip install py-cpuinfo
import mpi4py # pip install mpi4py
NTHREADS = 16
NSIMS = 100000... |
1769945 | from .chapter_dto import ChapterDTO
from .metadata_dto import MetaDataDTO
from .novel_dto import NovelDTO
from .volume_dto import VolumeDTO
|
1769953 | import os, glob
from setuptools import setup
install_requires = [line.rstrip() for line in open(os.path.join(os.path.dirname(__file__), "requirements.txt"))]
setup(
name="s3mi",
version="0.10",
url='https://github.com/chanzuckerberg/s3mi',
license=open("LICENSE").readline().strip(),
author='S3MI c... |
1769961 | import rospy
from mavros_msgs.msg import GlobalPositionTarget, State
from mavros_msgs.srv import CommandBool, CommandTOL, SetMode
from geometry_msgs.msg import PoseStamped, Twist
from sensor_msgs.msg import Imu, NavSatFix
from std_msgs.msg import Float32, String
from pyquaternion import Quaternion
import time
import ma... |
1769970 | class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
j=0
tong=0
res=float('inf')
for i in range(len(nums)):
tong+=nums[i]
while tong>=s and j<len(nums):
res=min(res,i-j+1)
... |
1769983 | import os
import raven
import logging as _logging
logger = _logging.getLogger()
PDB_DEBUG = True if os.getenv("PDB_DEBUG") else False
if PDB_DEBUG:
DEBUG = True
ALLOWED_HOSTS = ["*"]
else:
ALLOWED_HOSTS = os.environ.get("PDB_ALLOWED_HOSTS", "*").split(";") \
if os.environ.get("PDB_A... |
1770001 | import os
import glob
import sys
import struct
import subprocess
from struct import pack, unpack
class UndervoltSystem(object):
def __init__(self):
pass
def applyUndervolt(self, mv, plane):
"""
Apply undervolt to system MSR for Intel-based systems
:return: int error: error cod... |
1770035 | from django.core.exceptions import ValidationError as DjangoValidationError
from django.urls import reverse
from django.utils.translation import gettext_lazy as _
from rest_framework import serializers
from rest_framework.exceptions import ValidationError
from rest_framework.settings import api_settings
from salesman.... |
1770043 | import sys
from unittest import TestCase
import unittest
import os
from importlib import reload
from mock import Mock, call
from mockextras import stub
sys.path = [os.path.abspath(os.path.join('..', os.pardir))] + sys.path
from digesters.confluence.confluence_notification_digester import ConfluenceNotificationDigeste... |
1770052 | import os
import os.path
import json
import logging
from piecrust.tasks.base import TaskRunner
logger = logging.getLogger(__name__)
class InvalidMentionTargetError(Exception):
pass
class SourceDoesntLinkToTargetError(Exception):
pass
class DuplicateMentionError(Exception):
pass
class MentionTaskRu... |
1770053 | import torch
from torch.autograd import Function
from torch.autograd import Variable
from torch.nn.modules.module import Module
import math
import sys
import os
import numpy as np
import _FullAtomModel
def convertStringList(stringList):
'''Converts list of strings to 0-terminated byte tensor'''
maxlen = 0
for stri... |
1770063 | import json
from enum import Enum
from stix_shifter_utils.modules.base.stix_transmission.base_status_connector import BaseStatusConnector
from stix_shifter_utils.modules.base.stix_transmission.base_status_connector import Status
from stix_shifter_utils.utils.error_response import ErrorResponder
from stix_shifter_utils... |
1770100 | import pydoc
from jirafs.plugin import CommandPlugin
class Command(CommandPlugin):
""" Print the log for this issue """
MIN_VERSION = "2.0.0"
MAX_VERSION = "3.0.0"
def main(self, folder, **kwargs):
results = folder.get_log()
pydoc.pager(results)
return results
|
1770106 | class ClientInterfaceController:
def __init__(self):
self.commandDict = {
'help': self.helpCommand
}
def commandInput(self):
command = str(input('FTS $ '))
output = self.commandDict[command]()
print(output)
def helpCommand(self):
output = "this i... |
1770143 | from tensorflow import keras
import tensorflow as tf
from tensorflow.keras.datasets import cifar10
import numpy as np
from attack import FGSM, PGD
import os
os.environ["CUDA_VISIBLE_DEVICES"]="-1"
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
# preprocess cifar dataset
x_train = x_train.astype('float32... |
1770199 | import gym
import numpy as np
import random
from MEC_env import mec_def
from MEC_env import mec_env
import tensorflow as tf
from tensorflow import keras
import tensorboard
import datetime
import MAAC_agent
from matplotlib import pyplot as plt
import json
print("TensorFlow version: ", tf.__version__)
# ... |
1770205 | import subprocess
def test_flake8_output() -> None:
result = subprocess.run(
["flake8", "--config", "integrate/setup.cfg", "integrate"],
capture_output=True,
text=True,
)
assert result.returncode != 0
assert result.stdout == (
"integrate/__init__.py:2:7: T100 fixme fou... |
1770237 | import networkx as nx
import numpy as np
import scipy.sparse as sp
from scipy import linalg
from scipy.special import iv
from sklearn import preprocessing
from sklearn.utils.extmath import randomized_svd
class ProNE(object):
def __init__(self, dimension, step=5, mu=0.2, theta=0.5, **kwargs):
self.dimensio... |
1770254 | from __future__ import division
import numpy as np
from openmdao.api import ExplicitComponent
class TrueAirspeedComp(ExplicitComponent):
'''
Computes true airspeed from equivalent airspeed and density
Inputs
------
fltcond|rho : float
Density (vector, kg/m3)
fltcond|Ueas : float
... |
1770312 | from simple_ddl_parser import DDLParser
def test_no_unexpected_logs(capsys):
ddl = """
CREATE EXTERNAL TABLE test (
test STRING NULL COMMENT 'xxxx',
)
PARTITIONED BY (snapshot STRING, cluster STRING)
"""
parser = DDLParser(ddl)
out, err = capsys.readouterr()
assert out == ""
... |
1770359 | import numpy as np
import pandas as pd
import pytest
import scipy.stats
from pyextremes.models import Emcee, get_model
@pytest.fixture(scope="function")
def extremes() -> pd.Series:
np.random.seed(0)
return pd.Series(
index=pd.date_range(start="2000-01-01", periods=1000, freq="1H"),
data=scip... |
1770387 | from . import utils
from . import labels_to_image_model
from .model_input_generator import build_model_input_generator
|
1770397 | import numpy as np
from scipy.stats.mstats import gmean
from dpn.storable import Storable
class SizeDistribution(Storable):
"""Class to store sizedistributions and determine their characterstics."""
def __init__(self, unit):
"""Create and initialize a SizeDistribution object.
:param unit: Ei... |
1770430 | from abc import ABC
from typing import Any, Optional
from textdatasetcleaner.exceptions import TDCNotImplemented
from textdatasetcleaner.helpers import ClassProperty
class BaseProcessor(ABC):
__processor_name__: str = ''
__processor_type__: str = ''
def __init__(self, *_args: Any, **_kwargs: Any) -> No... |
1770450 | import unittest
import tempfile
import os
from .ParsedArgs import ParsedArgs
from meraki_cli.__main__ import _args_from_file
class TestArgsFromFile(unittest.TestCase):
def setUp(self):
self.parsed_args = ParsedArgs()
def testArgsFromFileExplicitPathNoExist(self):
self.parsed_args.configFile ... |
1770484 | import setuptools
setuptools.setup(
name='neurite',
version='0.1',
license='MIT',
description='Neural Networks Toolbox for Medical Imaging',
url='https://github.com/adalca/neurite',
keywords=['imaging', 'cnn'],
packages=setuptools.find_packages(),
python_requires='>=3.6',
classifier... |
1770501 | from .branch_permissions import BranchPermissions
from .default_reviewers import DefaultReviewers
from .compat import update_doc
from .errors import ok_or_error, response_or_error
from .helpers import Nested, ResourceBase, IterableResource
from .permissions import ProjectPermissions
from .repos import Repos
from .setti... |
1770514 | from quickdraw import QuickDrawData
qd = QuickDrawData()
anvil = qd.get_drawing("anvil")
anvil.image.save("my_anvil.gif") |
1770566 | from __future__ import annotations
import datetime
from collections import OrderedDict
from dataclasses import dataclass
from dataclasses import field
from typing import List
from typing import Optional
from patent_client import session
from patent_client.util import Model
from patent_client.util import one_to_many
f... |
1770581 | a=float(input("Enter decimal number to be converted :"))
print(a)
arr=[]
while a>1 :
if a%2==0.0:
arr.append('0')
a=a/2
else :
arr.append('1')
a=a-1
a=a/2
arr.append('1')
arr=arr[::-1]
def listToString(arr):
str1 = ""
for ele in arr:
str1 += ele
return str1
int(str1)
... |
1770614 | from functools import cached_property
from warnings import warn
import esda
import geopandas as gpd
import scikitplot as skplt
from sklearn.metrics import silhouette_samples
from ..visualize.mapping import plot_timeseries
from .dynamics import predict_markov_labels as _predict_markov_labels
from .incs import lincs_fr... |
1770630 | from cointk.backtest import backtest
from cointk.strategies import NaiveStrategyReverse
import random
random.seed(1)
strategy = NaiveStrategyReverse(n_prices=1000, threshold=0.8)
backtest(strategy)
|
1770641 | from __future__ import annotations
import typing
from ctc import spec
from . import erc20_metadata
async def async_normalize_erc20_quantity(
quantity: typing.SupportsFloat,
token: typing.Optional[spec.ERC20Address] = None,
provider: spec.ProviderSpec = None,
decimals: typing.Optional[typing.Support... |
1770656 | import os
import tempfile
import threading
import unittest2 as unittest
from cactus.listener import PollingListener
from cactus.tests.compat import has_symlink
try:
from cactus.listener import FSEventsListener
except ImportError:
FSEventsListener = None
def sleep(s):
# time.sleep(s)
event = threadin... |
1770664 | from collections import OrderedDict
import torch
from apex.optimizers import FusedAdam
from apex.contrib.sparsity import ASP
def build_model(args):
od = OrderedDict()
for i in range(args.num_layers):
if i == 0:
od['linear_layer_%d' % (i+1)] = torch.nn.Linear(args.input_features, args.hidde... |
1770769 | from app.api.now_applications.models.activity_detail.activity_detail_base import ActivityDetailBase
class CutLinesPolarizationSurveyDetail(ActivityDetailBase):
__mapper_args__ = {'polymorphic_identity': 'cut_lines_polarization_survey'}
def __repr__(self):
return '<CutLinesPolarizationSurveyDetail %r>... |
1770774 | from twisted.internet import reactor
from pyscrabble.gui.chat import ChatFrame
from pyscrabble.gui.game import GameFrame
from pyscrabble.constants import *
from pyscrabble.gtkconstants import *
from pyscrabble.gui.options import OptionWindow
from pyscrabble import manager
from pyscrabble import gtkutil
from pys... |
1770795 | import numpy as np
import pickle
from project.utils import add_beat, padding
def generator(batch_size, subdivision, timesteps, step, dataset,
phase='train', percentage_train=0.8,
constraint=False
):
if("jazz" in dataset):
Y, X_metadatas = pickle.load(open(dataset... |
1770800 | import tensorflow as tf
import math
num_classes = 85742 # 10572
initializer = 'glorot_normal'
# initializer = tf.keras.initializers.TruncatedNormal(
# mean=0.0, stddev=0.05, seed=None)
# initializer = tf.keras.initializers.VarianceScaling(
# scale=0.05, mode='fan_avg', distribution='normal', seed=None)
clas... |
1770843 | from tensorflow.keras.callbacks import Callback
import tensorflow.keras.backend as K
import numpy as np
class CosineAnnealingScheduler(Callback):
def __init__(self, cycle_iterations, min_lr, t_mu=2, start_iteration=0):
self.iteration_id = 0
self.start_iteration = start_iteration
self.cycle... |
1770869 | from __future__ import print_function
import os
import textwrap
import xml.etree.ElementTree as ET
def join_all_element_text(el, sep=""):
bits = []
for txt in el.itertext():
bits.append(txt)
return sep.join(bits)
def remove_empty_header_or_footer_lines(lines):
while lines and not lines[0].str... |
1770882 | from flask import json
import pytest
@pytest.yield_fixture
def post_endpoint_paths():
cases = [
'/sms/notification',
'/job',
'/service'
]
yield cases
def test_should_reject_if_no_content_type(post_endpoint_paths, notify_api, notify_db, notify_db_session, notify_config): # noqa
... |
1770893 | import os
import numpy as np
from locs.utils.flags import build_flags
import locs.models.model_builder as model_builder
from locs.datasets.ind_data import IndData, ind_collate_fn
import locs.training.train_dynamicvars as train
import locs.training.train_utils as train_utils
import locs.training.evaluate as evaluate
i... |
1770905 | from .transaction import AssetTransaction
from .transaction import Transaction
class WrapCCC(Transaction, AssetTransaction):
pass
|
1770992 | import logging
import os
from logging import DEBUG, INFO, WARNING, ERROR, CRITICAL # NOQA
from typing import Optional
_logger_name = 'ppe'
_logger_format = '[%(name)s] %(asctime)s: (%(levelname)s) %(message)s'
_logger = None
def _configure_logging(
*,
filename: Optional[str] = None,
level: ... |
1771007 | from .StorageUnitLabel import StorageUnitLabel
from .VisibleRecord import VisibleRecord
from .common import file_size, myLogger
from .LogicalFile import LogicalFile
from .LogicalRecord import *
from .core import parse, dump, cli
__version__ = '0.1.0'
__author__ = 'Teradata'
__all__ = ['parse', 'dump'] |
1771071 | import pytest
import mock
from datetime import datetime
from app.lib.room_list import RoomList
class TestRoomList():
def test_it_takes_a_list_of_rooms_as_an_argument(self):
rooms = ['Big One', 'Little One', 'Cardboard One']
room_list = RoomList(rooms)
assert room_list.rooms == rooms
@... |
1771076 | import unittest
from base import testlabel
from cqparts.utils.test import CatalogueTest
from cqparts.catalogue import JSONCatalogue
catalogue = JSONCatalogue('test-files/thread_catalogue.json')
cls = testlabel('complex_thread')(CatalogueTest.create_from(catalogue))
# FIXME: when #1 is fixed, remove this so tests ar... |
1771095 | import sys
from pypy.translator.llvm.log import log
from pypy.translator.llvm.typedefnode import create_typedef_node
from pypy.translator.llvm.typedefnode import getindexhelper
from pypy.translator.llvm.funcnode import FuncImplNode
from pypy.translator.llvm.extfuncnode import ExternalFuncNode
from pypy.translator.l... |
1771096 | import asyncio
def compute_pi(digits):
# implementation
return 3.14
async def main(loop):
digits = await loop.run_in_executor(None, compute_pi, 20000)
print(("pi: %s" % digits))
loop = asyncio.get_event_loop()
loop.run_until_complete(main(loop))
loop.close()
|
1771128 | from typing import Iterable, Tuple
from bitarray import bitarray
from . import TimestampsEncoder
from . import ValuesEncoder
from .result import PairsGorillaContent
class PairsEncoder:
"""Gorilla Pairs (Timestamp-Value) Encoder.
Parameters
----------
float_format : {{'f64', 'f32', 'f16'}}, default '... |
1771165 | from django.contrib.auth import get_user_model
from django.utils.decorators import method_decorator
from drf_yasg import openapi
from drf_yasg.utils import swagger_auto_schema
from qfieldcloud.core import permissions_utils, utils
from qfieldcloud.core.models import Project, ProjectQueryset
from qfieldcloud.core.seriali... |
1771215 | import blst
import hashlib
from poly_utils import PrimeField
from time import time
import sys
import gmpy2
#
# Proof of concept implementation for Eth1 simple custody
#
# https://notes.ethereum.org/1Rn2MwsoSWuEUHTnaRgLcw
#
# BLS12_381 curve modulus
MODULUS = 0x73eda753299d7d483339d80809a1d80553bda402fffe5bfeffffffff... |
1771266 | left_motor = 47246689260697394641558
right_motor = 47251723202529841910772
intake = 47254408925743638880954
shooter = 47252346776555950902602
door = 47251015244498422263341
def autonomous_setup():
#Robot.set_value(right_motor, "duty_cycle", 1)
#Robot.set_value(left_motor, "duty_cycle", 1)
#Robot... |
1771278 | from accountancy.mixins import AuditMixin
from django.apps import AppConfig
class ContactsConfig(AuditMixin, AppConfig):
name = 'contacts'
|
1771286 | COMPLETE_A = """\
[build-system]
requires = [ "whey",]
build-backend = "whey"
[project]
name = "whey"
version = "2021.0.0"
description = "A simple Python wheel builder for simple projects."
keywords = [ "pep517", "pep621", "build", "sdist", "wheel", "packaging", "distribution",]
dynamic = [ "classifiers", "requires-py... |
1771287 | import os
import json
from discord.ext import commands
# from modules.database import *
blacklist = json.load(
open(
f"{os.path.split(os.getcwd())[0]}/{os.path.split(os.getcwd())[1]}/data/blacklist.json"
)
)["commandblacklist"]
def isAllowedCommand():
async def predicate(ctx):
return (
... |
1771426 | import tempfile
from unittest import TestCase
from kg_covid_19.transform_utils.scibite_cord import ScibiteCordTransform
class TestScibiteCord(TestCase):
@classmethod
def setUpClass(cls) -> None:
cls.input_dir = "tests/resources/scibite_cord"
cls.output_dir = "tests/resources/scibite_cord"
... |
1771484 | import torch
import matplotlib.pyplot as plt
import torchvision.transforms as T
import torch.nn.functional as F
import numpy as np
import os
import json
import tqdm
import shutil
from PIL import Image, ImageFont, ImageDraw
from models.build_model import PrepareModel
from config import get_classify_config
############... |
1771489 | load("//node:internal/node_utils.bzl", "execute")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
NODE_TOOLCHAIN_BUILD_FILE = """
package(default_visibility = [ "//visibility:public" ])
exports_files(["bin/node", "bin/npm", "bin/tsc", "bin/yarn", "bin/bower"])
"""
def _mirror_path(ctx, workspace_... |
1771531 | from ytmusicapi._version import __version__
from ytmusicapi.ytmusic import YTMusic
__copyright__ = 'Copyright 2020 sigma67'
__license__ = 'MIT'
__title__ = 'ytmusicapi'
|
1771533 | from pydantic import Field
from typing import Optional
from .base import SnakeModel
class ClassifierDTO(SnakeModel):
device: str = Field(example="EdgeTPU")
name: str = Field(example="OFMClassifier")
imageSize: str = Field(example="45,45,3")
modelPath: Optional[str] = Field(example="/repo/data/custom-... |
1771566 | import click
from isitfit.cli.click_descendents import IsitfitCommand, isitfit_group
@isitfit_group(help="Manage migrations for local files (useful for debugging)", invoke_without_command=False, hidden=True)
@click.pass_context
def migrations(ctx):
# FIXME click bug: `isitfit command subcommand --help` is calling th... |
1771589 | from z3.z3 import Distinct
from .esilclasses import *
import z3
import sys
import random
import time
import socket
import os
from struct import pack, unpack
import logging
logger = logging.getLogger("esilsolve")
def puts(state, addr):
addr = state.evaluate(addr).as_long()
length, last = state.mem_search(addr... |
1771590 | import tensorflow as tf
from models import CDAE
class CDAETesting(tf.test.TestCase):
def setUp(self):
self.CDAE_test = CDAE()
def test_variable_packing(self):
X = tf.constant()
with
def test_presision(self):
test_set_positive_indicies = np.array([55, 32, 89, 49])
mod... |
1771597 | import json
import requests
import sys
from pyspark import SparkContext, SparkConf
from pyspark.streaming import StreamingContext
from pyspark.streaming.kafka import KafkaUtils
from pyspark.sql.functions import window
import numpy as np
from kafka import KafkaProducer
PHASENET_API_URL = "http://localhost:8000"
if __... |
1771649 | import json
from spotinst_sdk2.client import Client
class McsClient(Client):
__base_kube_url = "https://api.spotinst.io/mcs/kubernetes/cluster"
def get_kubernetes_cluster_cost(self, custer_id, from_date, to_date):
"""
Get kubernetes cluster cost
# Arguments
custer... |
1771668 | import argparse
import numpy as np
import os
import pprint
import yaml
# HACK: Get logger to print to stdout
import sys
sys.ps1 = '>>> ' # Make it "interactive"
import tensorflow as tf
from multiprocessing import Queue
from lib.config import cfg_from_file, cfg_from_list, cfg
from lib.data_process import make_data_p... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.