id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1659438 | import hmac
import hashlib
import json
import time
API_KEY = "API_KEY"
SECRET_KEY = "SECRET_KEY"
req = {
"id": 11,
"method": "private/get-order-detail",
"api_key": API_KEY,
"params": {
"order_id": "337843775021233500",
},
"nonce": int(time.time() * 1000)
};
# First ensure the params... |
1659464 | import unittest
from tests.recipes.recipe_lib_test import BaseTestForCmakeRecipe
class TestLeveldbRecipe(BaseTestForCmakeRecipe, unittest.TestCase):
"""
An unittest for recipe :mod:`~pythonforandroid.recipes.leveldb`
"""
recipe_name = "leveldb"
|
1659483 | from graphene import AbstractType, Node
from graphene_django.filter import DjangoFilterConnectionField
from graphene_django.types import DjangoObjectType
from graphene import ID, Boolean, Float, Int, List, String
from graphene import AbstractType, Field, Node, ClientIDMutation, AbstractType
from graphql_relay.node.node... |
1659489 | import numpy as np
from deepneuro.models.dn_ops import DnConv, DnPixelNorm, DnUpsampling, DnMaxPooling, DnBatchNormalization, DnDropout, DnAveragePooling
from deepneuro.models.ops import leaky_relu, minibatch_state_concat
def generator(model, latent_var, depth=1, initial_size=(4, 4), max_size=None, reuse=False, tran... |
1659502 | impprt Propeller as prop
class ROVBase():
'''
This class will house the main Mate ROV file that can be inherited into different designs
The orientations of the propellors are set in standard Spherical coordinates.
https://en.wikipedia.org/wiki/Spherical_coordinate_system
The init will take the fol... |
1659505 | import cv2
import cv
import wx
import numpy as np
import time
class MyFrame(wx.Frame):
def __init__(self, parent, id, title, capture, fps=15):
# initialize screen capture
self.capture = capture
# determine window size and init wx.Frame
ret,frame = self.capture.read()
self.i... |
1659510 | import torch
import torch.nn as nn
from torchvision import transforms
from torch.utils.data import DataLoader
from torch.autograd import Variable
import numpy as np
import os
import sys
import argparse
from IL2A_tiny import dualAug
from ResNet import resnet18_cbam
from myNetwork_classaug import network
from data_manage... |
1659559 | from custom_components.hacs.repositories.base import RepositoryData
def test_guarded():
data = RepositoryData.create_from_dict({"full_name": "test"})
assert data.name == "test"
data.update_data({"name": "new"})
assert data.name != "new"
test = data.to_json()
test["name"] = "new"
assert ... |
1659654 | import torch
import tokenizers
from typing import Union, Optional, List
from lairgpt.utils.remote import load_asset
from lairgpt.utils.assets import Config, Snapshot, Tokenizer
from lairgpt.gpt_model import LairGPT
from lairgpt.text_generator import TextGenerator
class PAGnol(TextGenerator):
"""Factory class for... |
1659660 | from pathlib import Path
import ezdxf
from ezdxf.addons.dxf2code import entities_to_code
FILENAME = "A_000217"
CADKIT = Path(ezdxf.EZDXF_TEST_FILES) / "CADKitSamples"
OUTBOX = Path("~/Desktop/Outbox").expanduser()
DXF_FILE = CADKIT / f"{FILENAME}.dxf"
SOURCE_CODE_FILE = OUTBOX / f"{FILENAME}.py"
doc = ezdxf.readfile... |
1659668 | import os
from .bitcoin import Bitcoind
class Elementsd(Bitcoind):
datadir = os.path.abspath("./chain/elements")
rpcport = 18998
port = 18999
rpcuser = "liquid"
rpcpassword = "<PASSWORD>"
name = "Elements Core"
binary = "elementsd"
@property
def cmd(self):
return f"{self.bi... |
1659695 | import os
import numpy as np
import scipy
import tensorflow as tf
from scipy.misc import imread
from tensorpack import DataFlow
class DatasetMetadata(object):
"""Helper class which loads and stores dataset metadata."""
def __init__(self, filename):
import csv
"""Initializes instance of Datas... |
1659727 | import logging
import json
import codecs
import sys
import os
import re
import itertools
import warnings
from instagram_private_api.compat import compat_urllib_request
class TerminalColors:
HEADER = '\033[95m'
OKBLUE = '\033[94m'
OKGREEN = '\033[92m'
WARNING = '\033[93m'
FAIL = '\033[91m'
END... |
1659751 | import os
import numpy as np
import pandas as pd
import torch
from data_management import IPDataset
from operators import (
Fourier,
RadialMaskFunc,
TVAnalysisPeriodic,
noise_gaussian,
to_complex,
unprep_fft_channel,
)
from reconstruction_methods import admm_l1_rec_diag, grid_search
# ----- ... |
1659773 | import logging
import sys
from pandas import DataFrame
from obsei.analyzer.classification_analyzer import (
ClassificationAnalyzerConfig,
ZeroShotClassificationAnalyzer,
)
from obsei.misc.utils import obj_to_json
from obsei.sink.pandas_sink import PandasSink, PandasSinkConfig
from obsei.source.playstore_scrap... |
1659815 | from graphpipe import remote
url = "http://localhost:9000"
metadata = remote.metadata(url)
print(metadata.Outputs)
|
1659820 | class KingOfTheHill:
def __init__(self, bot, channel):
self.bot = bot
self.channel = channel
channel.set_beatmap_checker(True)
channel.maintain_password(True)
channel.maintain_size(True)
channel.set_custom_config("King Of The Hill:\n\nSee how good you really are! The ... |
1660011 | import docker
client = docker.from_env()
print(client.containers.run("ubuntu:16.04", "echo hello world"))
print(client.containers.list())
print(client.images.list())
|
1660028 | from pandas_datareader import data as web
import datetime
start1 = datetime.datetime(2016, 9, 21)
end1 = datetime.datetime(2016, 9, 21)
start2 = datetime.datetime(2016, 9, 22)
end2 = datetime.datetime(2016, 9, 22)
SPY1 = web.DataReader("SPY", 'yahoo', start1, end1)
VIX1 = web.DataReader("VIX",'yahoo', star... |
1660045 | import contextlib
from typing import (
Any,
Generator,
List,
)
from pybuses import CommandBus
class MakeSandwich:
def __init__(self, ingredients: List[str]) -> None:
self.ingredients = ingredients
def sandwich_maker(command: MakeSandwich) -> None:
print(f'Making sandwich with {command.i... |
1660048 | import pytest
import torch
import numpy as np
from cplxmodule import Cplx
from cplxmodule.nn import init
def cplx_allclose_numpy(input, other):
other = np.asarray(other)
return (
torch.allclose(input.real, torch.from_numpy(other.real))
and torch.allclose(input.imag, torch.from_numpy(other.im... |
1660057 | import argparse
import json
from repro.models.goyal2020 import DAE
def main(args):
data = json.load(open(args.input_file, "r"))
correct_inputs = []
incorrect_inputs = []
for instance in data:
correct_inputs.append(
{
"candidate": instance["correct_sent"],
... |
1660084 | from abc import ABCMeta
from collections import Counter
from typing import Optional, Union, List, Any, Tuple
from torchglyph.proc import Proc, Processors, compress, subs, Identity
from torchglyph.vocab import Vocab
__all__ = [
'Pipe', 'RawPipe',
]
class Pipe(object, metaclass=ABCMeta):
def __init__(self, pr... |
1660122 | from argparse import ArgumentError
import os
import re
import tweepy
import yaml
import sched
import time
import datetime
import argparse
from dotenv import load_dotenv
load_dotenv()
API_KEY = os.environ["API_KEY"]
API_KEY_SECRET = os.environ["API_KEY_SECRET"]
ACCESS_TOKEN = os.environ["ACCESS_TOKEN"]
ACCESS_TOKEN_... |
1660123 | import gzip
def get_event_text(eventfile):
if eventfile.split('.')[-1] == 'gz':
with gzip.open(eventfile, 'rt') as f:
filetext = f.read()
else:
with open(eventfile, 'r') as f:
filetext = f.read()
return filetext
def get_event_filename(name):
return(name.replace(... |
1660140 | import torch.nn as nn
import torch.nn.functional as F
from ..utils import ConvModule
class SSDNeck(nn.Module):
def __init__(self, in_channels = [1024,2048],out_channels = 256,out_map=None,start_level = 0,end_level = None):
super(SSDNeck,self).__init__()
self.in_channels = in_channels
if is... |
1660223 | from __future__ import division
from pyfmmlib import fmm_part
import numpy as np
import numpy.linalg as la
def test_fmm():
for dims in [2, 3]:
for kernel in [0, 5]:
sources = np.random.randn(4000, dims)
dipvec = np.random.randn(4000, dims)
fmm_part("pg", iprec=1, kerne... |
1660256 | import os.path as osp
import numpy as np
import torch
import torch.nn.functional as F
from model.trainer.base import Trainer
from model.trainer.SnaTCHer_helpers import (
get_dataloader, prepare_model,
)
from model.utils import (
count_acc,
)
from tqdm import tqdm
from sklearn.metrics import roc_curve, roc_auc... |
1660266 | from __future__ import print_function
import os
import argparse
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchvision
from torch.autograd import Variable
import torch.optim as optim
from torchvision import datasets, transforms
from models.wideresnet import *
from autoattack.autoattack im... |
1660361 | import textwrap
from prettytable import PrettyTable
from ..config import get_config, save_config_value, refresh_config_warnings
from .. import constants
from ..log import log_to_client
from ..payload import daemon_command
def _eligible_config_keys_for_setting():
config = get_config()
return [key for key in... |
1660413 | from node.blockchain.inner_models import Node, NodeDeclarationSignedChangeRequest
from node.blockchain.types import KeyPair
from ..signed_change_request_message.node_declaration import make_node_declaration_signed_change_request_message
def make_node_declaration_signed_change_request(
node: Node, node_key_pair: ... |
1660453 | import pytest
import numpy as np
from PythonLinearNonlinearControl.models.two_wheeled import TwoWheeledModel
from PythonLinearNonlinearControl.configs.two_wheeled \
import TwoWheeledConfigModule
class TestTwoWheeledModel():
"""
"""
def test_step(self):
config = TwoWheeledConfigModule()
... |
1660462 | import logging
import os
import tqdm
from citeomatic import file_util
from citeomatic.common import DatasetPaths, FieldNames, global_tokenizer
from citeomatic.config import App
from citeomatic.corpus import Corpus
from citeomatic.service import document_from_dict, dict_from_document
from citeomatic.traits import Enum... |
1660500 | from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from penguin_client.api.account_api import AccountApi
from penguin_client.api.formula_api import FormulaApi
from penguin_client.api.item_api import ItemApi
from penguin_client.api.notice_api import NoticeApi
from penguin_client.api.p... |
1660531 | from . import conf
from .build_server import BuildServer
from .manifest import ManifestReader
manifest_reader = ManifestReader()
build_server = BuildServer(conf.settings.BUILD_URL)
def webpack(config_file, context=None, settings=None, manifest=manifest_reader, compiler=build_server):
use_manifest = conf.settings... |
1660564 | import os
from io import BytesIO
from pathlib import PurePath
from typing import NoReturn, Union
from zipfile import ZipFile, ZIP_DEFLATED
class ZipUtils(object):
@classmethod
def get_compress_data(cls, src_paths: Union[str, list], basename=None) -> bytes:
"""
:param src_paths:
:para... |
1660569 | from pydantic import BaseModel
class ExampleModel(BaseModel):
example_int: int
example_str: str
|
1660576 | from .rigid_registration import RigidRegistration
from .affine_registration import AffineRegistration
from .deformable_registration import gaussian_kernel, DeformableRegistration
|
1660599 | from setuptools import setup, find_packages
setup(
name='battle-city-ai',
version='0.1',
description='whatever',
packages=find_packages(exclude=['tests', 'docs']),
install_requires=[
'pygame==1.9.4',
],
include_package_data=True,
extras_require={
'test': [
'p... |
1660659 | import snowboydecoder
def listen(event):
detector = snowboydecoder.HotwordDetector('resources/snowboy.umdl', sensitivity=0.5)
detector.start(detected_callback=event.set)
|
1660666 | import pathlib
import numpy as np
import cv2
try:
from apex.amp._amp_state import _amp_state
except ImportError:
pass
def amp_state_has_overflow():
for loss_scaler in _amp_state.loss_scalers:
if loss_scaler._has_overflow:
return True
return False
def read_im(impath: pathlib.Path,... |
1660733 | def write_csv(filename):
import csv
L = [['Date', 'Name', 'Notes'],
['2016/1/18', 'Martin Luther King Day', 'Federal Holiday'],
['2016/2/2','Groundhog Day', 'Observance'],
['2016/2/8','Chinese New Year', 'Observance'],
['2016/2/14','Valentine\'s Day', 'Obervance'],
... |
1660754 | from general.util.fid_official_tf import *
path = '/home/biomech/Documents/OsteoData/KneeXrayData/ClsKLData/kneeKL299_2/train'
inception_path = '/home/stefan/Desktop/Stefan/mastherthesiseval/general/inception_model'
save_path = '/home/stefan/Desktop/Stefan/mastherthesiseval/general/pre_calc_fid/mu_sigma_train.npz'
#ca... |
1660759 | import numpy as np
cube4 = np.full([4,4,4,3],-1,np.int32) # x, y, z, [x,y,z]
cube4[0,0,0] = [-1,-1,-1]
cube4[1,0,0] = [24,-1,-1]
cube4[2,0,0] = [24,-1,-1]
cube4[3,0,0] = [-1,-1,-1]
cube4[0,1,0] = [-1,25,-1]
cube4[1,1,0] = [27,28,-1]
cube4[2,1,0] = [29,30,-1]
cube4[3,1,0] = [-1,25,-1]
cube4[0,2,0] = [-1,25,-1]
cube4[... |
1660806 | import unittest
from webapp import create_app
from webapp.models import db, User, Role
from webapp.extensions import admin, rest_api
class TestURLs(unittest.TestCase):
def setUp(self):
# Bug workarounds
admin._views = []
rest_api.resources = []
app = create_app('webapp.config.Tes... |
1660822 | from __future__ import print_function, absolute_import
import datetime
import errno
import os
import six
import sys
import time
from requests.utils import quote as _quote
from requests.utils import unquote as _unquote
PY3 = sys.version_info[0] == 3
STREAM = sys.stderr
STRPTIME_FORMATS = ['%Y-%m-%d %H:%M', '%Y-%m-%d']
... |
1660828 | import numpy as np
from vg.compat import v2 as vg
__all__ = [
"rectangular_prism",
"cube",
"triangular_prism",
]
def _maybe_flatten(vertices, faces, ret_unique_vertices_and_faces):
if ret_unique_vertices_and_faces:
return vertices, faces
else:
return vertices[faces]
def rectangu... |
1660834 | from oem_format_minimize.main import MinimalFormat
from oem_format_msgpack.main import MessagePackFormat
class MessagePackMinimalFormat(MessagePackFormat, MinimalFormat):
__key__ = 'minimize+msgpack'
__extension__ = 'min.mpack'
|
1660839 | import math
import random
import numpy as np
from util.data_util import pad_seq, pad_char_seq, pad_video_seq
class TrainLoader:
def __init__(self, dataset, visual_features, configs):
super(TrainLoader, self).__init__()
self.dataset = dataset
self.visual_feats = visual_features
self... |
1660843 | import os
import os.path as osp
import sys
sys.path.append('../')
import numpy as np
import argparse
import cv2
import time
import configs
from preprocessing.dataset import preprocessing
from models import cpn as modellib
from pycocotools.coco import COCO
from pycocotools.cocoeval import COCOeval
from pycocotools impo... |
1660849 | import tensorflow as tf
import numpy as np
import sys
import random
class VanillaRNN(object):
def __init__(self, num_classes, state_size, seq_len, learning_rate=0.1, model_name='vanilla_rnn_model',
ckpt_path='./ckpt/vanilla/'):
self.num_classes = num_classes
self.state_size = stat... |
1660863 | import numpy as np
def get_features(conformer,S,bond_connectivity_list):
conformer=np.array(conformer)
nonbondcutoff = 6
bonds = generate_bondconnectivty_matrix(bond_connectivity_list)
#Calculate the atomic environment vector for each atom
atomic_envs = generate_atomic_env(bonds, S)
... |
1660880 | import io, os, sys, csv, random, logging
from jacks.infer import LOG, inferJACKS
from jacks.jacks_io import createPseudoNonessGenes, readControlGeneset, createGeneSpec, createSampleSpec, getJacksParser, collateTestControlSamples, writeJacksWResults
from jacks.preprocess import loadDataAndPreprocess
py_cmd = 'python'
... |
1660931 | class RoutingEngine:
def __init__(self, strategy):
self._strategy = strategy
def route(self, start, destination):
return self._strategy.route(start, destination)
|
1660949 | import docutils.nodes
from docutils.parsers.rst import Directive, directives
class IframeVideo(Directive):
DEFAULT_WIDTH = 700
DEFAULT_HEIGHT = 400
DEFAULT_ALIGN = 'left'
has_content = False
required_arguments = 1
optional_arguments = 0
option_spec = {
'height': directives.nonneg... |
1660959 | from collections import defaultdict
from .abstract_pop_splitter import AbstractPOPSplitter
from ...graph_utils import path_to_edge_list
from math import floor
class BaselineSplitter(AbstractPOPSplitter):
def __init__(self, num_subproblems):
super().__init__(num_subproblems)
def split(self, problem):
... |
1660973 | from astrodash.preprocessing import ReadSpectrumFile
from astrodash.helpers import temp_list
import pickle
import os
import gzip
class SaveTemplateSpectra(object):
def __init__(self, parameterFile):
with open(parameterFile, 'rb') as f:
pars = pickle.load(f)
self.w0, self.w1, self.n... |
1660992 | from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
import pickle
import sys, os, glob
import pdb
import json
import argparse
import numpy as np
import open3d as o3d
sys.path.append('/home/yzhang/workspaces/smpl-env-gen-3d-internal')
sys.path.append('/home/yzha... |
1660995 | import unittest
import torch
import os
from parapred.model import Parapred, clean_output
from parapred.preprocessing import encode_parapred, encode_batch
from parapred.cnn import generate_mask
FPATH = os.path.dirname(os.path.abspath(__file__))
WEIGHTS_PATH = os.path.join(FPATH, "../weights/parapred_pytorch.h5")
clas... |
1661048 | import logging
from typing import Callable, Dict, Mapping, Optional, Union
import numpy as np
from tqdm.auto import tqdm
from meerkat.provenance import capture_provenance
logger = logging.getLogger(__name__)
class MappableMixin:
def __init__(self, *args, **kwargs):
super(MappableMixin, self).__init__(*... |
1661149 | from functools import wraps
from twisted.web import http
from jsonschema import Draft4Validator
from junebug.utils import response
def validate(*validators):
def validator(fn):
@wraps(fn)
def wrapper(api, req, *a, **kw):
errors = []
for v in validators:
... |
1661186 | from soap.expression import (
is_variable, is_expression, External, InputVariableTuple,
OutputVariableTuple, SelectExpr, FixExpr, Subscript
)
from soap.program.graph import DependenceGraph
from soap.semantics import is_numeral, Label, MetaState
def sorted_args(expr):
if any((expr is None, is_variable(expr... |
1661197 | from flask import session, Blueprint
from lexos.helpers import constants as constants
from lexos.managers import session_manager as session_manager
from lexos.models.rolling_window_model import RollingWindowsModel
from lexos.views.base import render
rolling_window_blueprint = Blueprint("rolling_window", __name__)
@r... |
1661248 | import torchaudio
# https://github.com/dhpollack/audio, see VCTK branch
torchaudio.datasets.YESNO(".", download=True, dev_mode=True)
|
1661294 | import pytest
pytestmark = pytest.mark.django_db
from django.conf import settings
from seahub.utils import get_conf_text_ext
from seahub.test_utils import BaseTestCase
class GetConfTextExtTest(BaseTestCase):
def setUp(self):
self.clear_cache()
from constance import config
self.config = ... |
1661319 | import matplotlib.pyplot as plt
import numpy as np
from PIL import Image
import flowpy
flow = flowpy.flow_read("static/kitti_occ_000010_10.png")
first_image = np.asarray(Image.open("static/kitti_000010_10.png"))
second_image = np.asarray(Image.open("static/kitti_000010_11.png"))
flow[np.isnan(flow)] = 0
warped_seco... |
1661322 | import click
# from thampi.cli.init import commands
# from thampi.cli.deploy import commands as deploy_commands
# from thampi.cli.serve import commands as serve_commands
from thampi.cli.commands import init, serve, predict, info, clean
@click.group()
def main():
pass
# main.add_command(commands.init)
# main.ad... |
1661352 | from os_dbnetget.utils import binary_stdout
from os_dbnetget.commands.qdb import QDB
from os_dbnetget.commands.qdb.test.processor import Processor
class Test(QDB):
HELP = 'check if data exist in qdb'
def __init__(self, config=None):
super(Test, self).__init__(config)
self.config.cmd = 'test'
... |
1661360 | import os, sys, numpy, vcs, vcs.testing.regression as regression
x = regression.init()
data_values = [ 25, 45, 55.]
data_lon = [ 5., 10., 15.]
data_lat = [ 5., 10., 15.]
data_lon_vert = [
# Triangle (last one missing because traingle has only 3 vertices
[2.5,7.5,5.,1.e20],
# Square
[7.5,12.5,12.5,7.5... |
1661369 | from .global_configs import (ClusterConfig, Day2ClusterConfig, InfraEnvConfig,
TerraformConfig, global_variables)
__all__ = [
"ClusterConfig",
"InfraEnvConfig",
"InfraEnvConfig",
"TerraformConfig",
"Day2ClusterConfig",
"global_variables"
]
|
1661386 | import random
def strategy(history, memory):
a = 3
b = 8
if memory == None:
return 1, [0,0,0,0,0,0,0,False]
if not memory[7]:
memory[4] += 1
if history[1,-1] == 1:
memory[3] += 1
else:
memory[6] += 1
if history[1,-1] == 1:
memory[5] +... |
1661408 | import base64
import os
import argparse
import sys
def encode_file(file_path):
"""
Base64 encode a file.
:param file_path: File path.
:return: Base64 encoded file.
"""
with open(file_path, 'rb') as f:
s = base64.b64encode(f.read())
return s.decode('utf-8')
def get_output_path(file_path):
"""
... |
1661412 | from django.apps import AppConfig
class SafeDeleteConfig(AppConfig):
name = 'safedelete'
verbose_name = 'Safe Delete'
def ready(self):
pass
|
1661423 | import pytest
from kpm.manifest_jsonnet import ManifestJsonnet
@pytest.fixture()
def manifest(kubeui_package, package_dir):
return ManifestJsonnet(kubeui_package)
@pytest.fixture()
def empty_manifest(empty_package_dir):
return ManifestJsonnet(package=None)
@pytest.fixture()
def bad_manifest():
return Ma... |
1661444 | max_wav_value = 32768.0
sampling_rate = 22050
filter_length = 1024
hop_length = 256
win_length = 1024
n_mel_channels = 80
mel_fmin = 0.0
mel_fmax = 8000.0
|
1661448 | from datetime import datetime, timedelta
import time
import pandas as pd
from email.mime.text import MIMEText
from smtplib import SMTP
import pytz
from utility import run_function_till_success
pd.set_option('expand_frame_repr', False) # 当列太多时不换行
pd.set_option('display.max_rows', 1000)
tz = pytz.timezone('Asia/Shanghai... |
1661459 | from opentuner import MeasurementInterface
from opentuner import Result
class ProgramTunerWrapper(MeasurementInterface):
def get_qor(self):
f = open('qor.txt', 'r')
lut_count = 0.0
while True:
line = f.readline()
if not line: break
if 'nd' in line.split():
lut_count = line.spli... |
1661481 | import os
import importlib
import inspect
from pike.discovery import filesystem
def get_module_by_name(full_module_name):
"""Import module by full name
:param str full_module_name: Full module name e.g. (pike.discovery.py)
:return: Imported :class:`module`
"""
return importlib.import_module(full... |
1661526 | import os
import re
solution = {
'dir_name' : '',
'dir_url' : '',
'file_urls': {}
}
suffix = ["cpp", "java", "js", "py", "go", "kt"]
leetcode_loc = '.'
def main():
solution_list = []
for dir_url, _, files in os.walk(leetcode_loc):
dir_name = dir_url.split('\\')[-1]
if re.match(r'... |
1661543 | class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
c = collections.Counter(nums1)
ans = []
for n in nums2:
if c[n] > 0:
c[n]-=1
ans.append(n)
return ans
|
1661559 | import librosa
import soundfile as sf
import pandas as pd
import os
import math
def write_audio_for_df(data_csv_path, dir_in, dir_out, min_duration=0):
'''Extract wave files from dataframe df.
The sample rate at this stage of the processing is preserved. The written output writes to a single folder, dir
o... |
1661572 | from torchvision import models
import torch.nn as nn
class VGGNet(nn.Module):
def __init__(self):
super(VGGNet, self).__init__()
self.vgg = models.vgg19(pretrained=True)
def forward(self, x):
features = []
for name, layer in self.vgg.features.named_children():
# Th... |
1661581 | import random
MAX_INS = 0xffffffff
HALF_INS = 0xffff
def strategy_left_bits():
i = 0
while i <= MAX_INS:
yield int('{:032b}'.format(i)[::-1], 2)
i = i + 1
def strategy_right_bits():
i = 0
while i <= MAX_INS:
yield i
i = i + 1
def strategy_edge_bits():
# this is a ... |
1661619 | from bs4 import PageElement, Tag, NavigableString
def clone_element(el: PageElement) -> PageElement:
if isinstance(el, NavigableString):
return type(el)(el)
copy = Tag(None, el.builder, el.name, el.namespace, el.nsprefix)
# work around bug where there is no builder set
# https://bugs.launchpa... |
1661627 | from ._aesenc import ffi, lib
def encrypt_block(block, roundkeys):
""" Does the whole AES 11 rounds on one block, can probably be made faster if we pass a pointer to roundkeys instead
of the list itself.
"""
ptr = ffi.from_buffer(block)
lib.encrypt(ptr, ptr, roundkeys)
|
1661640 | import win32com.client
def removeDeletedTracks():
"""This function will remove every song that is not currently accessible from your iTunes library"""
#First, we create an instance of the iTunes Application
itunes= win32com.client.Dispatch("iTunes.Application")
#The ITTrackKindFile value will be use to chec... |
1661662 | import unittest2 as unittest
from datetime import datetime
import pytz
from .. import time
from ..error import TimeConstructionError
# IMPORTANT -- note to self -- you CANNOT use tzinfo on datetime-- ever! -- just pytz.timezone.localize everything to be safe
JAN_MICROS = 1325376000*1000**2
JAN_MILLIS = JAN_MICROS/100... |
1661756 | from .verbs import *
# preceed w/ underscore so it isn't exported by default
# we just want to register the singledispatch funcs
from .dply import vector as _vector
from .dply import string as _string
|
1661759 | import numpy as np
import torch
from baselines.common.vec_env import VecEnvWrapper
from gym import spaces, ActionWrapper
from envs.ImageObsVecEnvWrapper import get_image_obs_wrapper
from envs.ResidualVecEnvWrapper import get_residual_layers
from pose_estimator.utils import unnormalise_y
class PoseEstimatorVecEnvWrap... |
1661767 | import wx
import sys, platform, time, ast
from packages.rmnetwork import netutil
import packages.rmnetwork as network
from packages.rmnetwork.constants import *
from packages.lang.Localizer import *
from wx.lib.wordwrap import wordwrap
import wx.lib.scrolledpanel as scrolled
import wx.lib.masked as masked
if platform.... |
1661776 | from __future__ import annotations
import typing as t
from django.http import HttpRequest, HttpResponse
from django.urls.resolvers import URLPattern
URLPatternList = t.List[URLPattern]
DjangoHandler = t.Callable[[HttpRequest], HttpResponse]
|
1661834 | import sys
import argparse
import importlib
from types import SimpleNamespace
parser = argparse.ArgumentParser(description='')
parser.add_argument("-C", "--config", help="config filename")
parser_args, _ = parser.parse_known_args(sys.argv)
print("Using config file", parser_args.config)
args = importlib.import_modul... |
1661889 | from yawn.task.models import Template, Task, Execution # NOQA
from yawn.worker.models import Worker
from yawn.workflow.models import WorkflowName
def test_find_lost():
name = WorkflowName.objects.create(name='workflow1')
workflow = name.new_version(parameters={'parent': True, 'child': False})
task1 = Tem... |
1661986 | from unittest import TestCase
from py2swagger.introspector import BaseDocstringIntrospector
class Parent(object):
"""
Parent Class Docstring
---
parameters:
- name: parent_parameter
type: string
- name: overrided_parameter
type: string
responses:
200:
descri... |
1662003 | import unittest
from frds.measures import general
import numpy as np
class KyleLambdaCase(unittest.TestCase):
def test_lamdba(self):
volumes = np.array(
[
[100, 180, 900, 970, 430, 110],
[300, 250, 400, 590, 260, 600],
[200, 700, 220, 110, 290, 3... |
1662044 | from changes.testutils import TestCase
from changes.utils import phabricator_utils
class PhabUtilsTest(TestCase):
def test_is_iden(self):
candidates = {
"rREPOabcd": True,
"r": False,
"rREP": False,
"rrREPOabcd": False,
"rRePabcd": False,
... |
1662069 | import logging
import torch
import torch.cuda.amp as amp
import torch.distributed as dist
from torchkit.util.utils import AverageMeter, Timer
from torchkit.util.utils import adjust_learning_rate, warm_up_lr
from torchkit.util.utils import accuracy_dist
from torchkit.util.distributed_functions import AllGather
from tor... |
1662071 | from typing import (
Iterable,
Optional,
Tuple,
)
from trie.exceptions import (
PerfectVisibility,
)
from trie.fog import (
HexaryTrieFog,
TrieFrontierCache,
)
from trie.hexary import (
HexaryTrie,
)
from trie.typing import (
HexaryTrieNode,
Nibbles,
)
from trie.utils.nibbles import... |
1662125 | from .base import BaseLayer
import hetu as ht
class SumLayers(BaseLayer):
def __init__(self, layers):
self.layers = layers
def __call__(self, x):
if len(self.layers) == 1:
return self.layers[0](x)
else:
return ht.sum_op([layer(x) for layer in self.layers])
|
1662131 | from enum import Enum
import numpy as np
from qiskit.extensions import XGate, YGate, SGate, ZGate, HGate, TGate, RXGate, RYGate, RZGate, IdGate
from qiskit.circuit import Gate
from qiskit.circuit import QuantumRegister
def gen_predefined_payoffs(game_name: str, num_players: int, payoff_input: dict):
"""Generate... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.