id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9866113 | import FWCore.ParameterSet.Config as cms
## test for electronId
simpleEleId70cIso = cms.EDProducer(
"EleIdCutBasedExtProducer",
src = cms.InputTag("gedGsfElectrons"),
reducedBarrelRecHitCollection = cms.InputTag("reducedEcalRecHitsEB"),
reducedEndcapRecHitCollection = cms.InputTag("reducedEcalRecHitsEE... |
9866126 | from flask import g
from ..models import db
from .base import auth, login_blueprint, complete_auth_flow, secure_url_for, prepare_state, validate_state, get_state
facebook = auth.remote_app(
'facebook',
base_url='https://graph.facebook.com/',
request_token_url=None,
access_token_method='POST',
acce... |
9866153 | import numpy as np
import model.item
from model.item import Item
from pathlib import Path
class Collection(Item):
#
# CTOR
#
def __init__(self, metadata, parent):
super(Collection, self).__init__(metadata, parent)
self.state = model.item.STATE_SYNCED
pass
#
# Getter ... |
9866164 | from mani_skill_learn.utils.data import to_torch
from mani_skill_learn.utils.torch import ExtendedModule
from ..builder import POLICYNETWORKS, build_backbone, build_dense_head
from ..utils import replace_placeholder_with_args, get_kwargs_from_shape
@POLICYNETWORKS.register_module()
class VAEPolicy(ExtendedModule):
... |
9866230 | import os
import unittest
from paraguay import paraguay
_SOURCE_ID = "abc123"
_SOURCE_URL = "https://public.tableau.com/vizql/w/COVID19PY-Registros/v/Descargardatos/vudcsv/sessions/D8CB602652A24E009F367E19322820E5-0:0/views/7713620505763405234_2641841674343653269?showall=true&underlying_table_id=Migrated%20Data&underl... |
9866273 | import numpy as np
import argparse
import os
import time
from datetime import timedelta
from kgcnn.selection.models import ModelSelection
from kgcnn.selection.data import DatasetSelection
from kgcnn.selection.hyper import HyperSelection
from tensorflow_addons import optimizers
from kgcnn.utils import learning
from kgc... |
9866299 | from .create import *
from .rm import *
from .login import *
from .logout import *
from .ls import *
from .sync import *
|
9866317 | import FWCore.ParameterSet.Config as cms
# ALCARECOZeeMCEcalCalElectron_Output.cff ###################
from Calibration.EcalAlCaRecoProducers.ALCARECOEcalCalElectron_Output_cff import *
from Calibration.EcalAlCaRecoProducers.zeeMCInfo_EventContent_cff import *
from Calibration.EcalAlCaRecoProducers.zeeHLTInfo_EventCon... |
9866323 | from abc import ABCMeta, abstractmethod
from fluent import sender
import re
import os
import time
import configparser
import numpy as np
from .datadog_client import DatadogClient
from .changefinder.ar_1d import ModelSelection
from .changefinder.changefinder_1d import ChangeFinder
from logging import getLogger
logge... |
9866332 | import unittest
from biicode.common.model.brl.brl_block import BRLBlock
from biicode.common.model.symbolic.block_version import BlockVersion
from biicode.common.model.symbolic.block_version_table import BlockVersionTable
from biicode.common.exception import BiiException
# reusable in other tests
test_dep_table1 = """... |
9866337 | def extractWord(fullData):
return (fullData[0]*256 + fullData[1], fullData[2:])
def extractTwoBytes(fullData):
return (fullData[0], fullData[1], fullData[2:])
def extractCol(data, colLen):
ans = []
while len(ans) < colLen and len(data)>0:
b1, b2, data = extractTwoBytes(data)
if b1 == 0xFF:
w, data = ex... |
9866342 | import numpy as np
from numpy.random import multivariate_normal, shuffle
# Another way of generating data which I didn't use
#from sklearn.datasets import make_blobs
# A more compact way of generating sample points
# which i discovered not soon enough
# this is also not used
def generate_samples():
data1 = np.r... |
9866351 | from math import log
from termcolor import colored
from re import search, IGNORECASE
from Nemesis.lib.Globals import Color
from Nemesis.lib.Globals import base64char, hexchar, dom_sources_regex, dom_sinks_regex, extractor
from Nemesis.lib.Globals import subdomain_regex, path_regex, single_path_regex, experimental_path... |
9866364 | import numpy as np
from src.models import *
from src.utils import auxiliary_plots, metrics
from src.preprocessing import normalization, data_generation
TRAIN_FILE_NAME = 'data/hourly_20140102_20191101_train.csv'
TEST_FILE_NAME = 'data/hourly_20140102_20191101_test.csv'
RESULT_FILE_NAME = 'files/results/simple_demo_re... |
9866368 | import random
from paragen.samplers import register_sampler
from paragen.samplers.sequential_sampler import SequentialSampler
@register_sampler
class BatchShuffleSampler(SequentialSampler):
"""
BatchShuffleSampler pre-compute all the batch sequentially,
and shuffle the reading order of batches before an ... |
9866386 | import tweepy
import time
# NOTE: I put my keys in the keys.py to separate them
# from this main file.
# Please refer to keys_format.py to see the format.
from keys import *
# NOTE: flush=True is just for running this script
# with PythonAnywhere's always-on task.
# More info: https://help.pythonanywhere.com/pages/Alw... |
9866399 | import tensorflow as tf
from tensorflow.keras.layers import Conv1D, BatchNormalization, MaxPooling1D, \
Dense, ReLU, Flatten, Dropout, Input
class CNN_Model(tf.keras.Model):
def __init__(self, num_classes: int):
super().__init__()
# channels_last, (N, L, C)
# self.feature = tf.keras.Se... |
9866401 | from __future__ import division
import pandas as pd
import SimpleITK as sitk
import numpy as np
import os
import argparse
def resample_img(itk_image, out_spacing=[2.0, 2.0, 2.0], is_label=False):
# resample images to 2mm spacing with simple itk
original_spacing = itk_image.GetSpacing()
original_size = i... |
9866431 | from twisted.internet import reactor
from twisted.internet.protocol import ClientFactory
from iwant.core.messagebaker import bake, unbake
from iwant.cli.utils import update_config, print_log, CLIENT_LOG_INFO, WARNING_LOG, ERROR_LOG
from iwant.core.constants import SEARCH_REQ, SEARCH_RES, \
LEADER_NOT_READY, IWANT_P... |
9866438 | import csv
import logging
import time
from datetime import timedelta
from decimal import Decimal
from cryptocompy import price
from forex_python.converter import CurrencyRates, RatesNotAvailableError
from src.DateUtils import parse_date, date_to_string, get_start_of_year, get_start_of_year_after
from src.NumberUtils ... |
9866445 | import numpy as np
import scipy
from tqdm import tqdm
import pickle
from sklearn.metrics import confusion_matrix
from keras.preprocessing.image import img_to_array
def get_psf_airy(n, nr):
"""
Calculates Point Spread Function.
:param n:
:param nr:
:return: Numpy array of Point Spread Function
... |
9866454 | import argparse
import os
import re
from os import listdir
from os.path import isfile, join
from main import main
def snake_case(value):
"""
Convert camel case to snake case.
i.e.: CamelCase turns to camel_case
"""
return re.sub(r'(?<!^)(?=[A-Z])', '_', value).lower()
def get_models_files(path)... |
9866467 | import numpy as np
import trimesh
def parse_obj_file(filename):
faces = []
vertices = []
texture = []
normals = []
with open(filename, 'r') as stream:
for line in stream:
elements = line.replace(' ', ' ').strip().split(' ')
if elements[0] == 'f':
fa... |
9866502 | from common import load_minecraft_json, camel_case, generate_enum, generate_enum_property, output
# build item ID => item kind index
item_kinds_by_id = {}
for item in load_minecraft_json("items.json"):
item_kinds_by_id[item['id']] = camel_case(item['name'])
# Build material name => dig multipliers index
material... |
9866515 | import angr
import claripy
import archinfo
import copy
import logging
from .base_state_snapshot import BaseStateSnapshot
from .angr_utils import MAX_DEAD_VARS, NVIC_RET_START
l = logging.getLogger("LIVENESS")
class StackFrame:
def __init__(self, base_sp=None, tracked_addrs=None):
# We use a None base_sp a... |
9866537 | import logging
import tornado.web
from bot.models import SpotifyClient, User
from bot.utils import animation_id, bot, bot_description
from pony import orm
from telegram import ReplyKeyboardRemove
class MainHandler(tornado.web.RequestHandler):
def get(self):
self.write("Hello, world")
class SpotifyCallb... |
9866563 | from pypylon import genicam # CNodeMapRef, GenericException, IsReadable
def main():
try:
XMLFileName = "HelloWorld.xml"
Camera = genicam.CNodeMapRef()
Camera._LoadXMLFromFile(XMLFileName)
theNode = Camera.GetNode("TheNode")
print(type(theNode))
theInt = Camera.G... |
9866566 | import unittest
import checksieve
class TestEnvironment(unittest.TestCase):
def test_environment_name(self):
sieve = '''
require ["environment"];
if environment :is "name" "check-sieve" {
discard;
}
'''
self.assertFalse(checksieve.parse_string(sieve, Fa... |
9866573 | from typing import Optional
from app.schemas.common import (
IDeleteResponseBase,
IGetResponseBase,
IPostResponseBase,
)
from fastapi_pagination import Page, Params
from app.schemas.user import IUserCreate, IUserRead, IUserReadWithoutGroups, IUserStatus
from sqlmodel.ext.asyncio.session import AsyncSession
... |
9866585 | from __future__ import print_function
from .decoder import decode_lea, RDI
from .kaitai.mach_o import MachO
def find_idausr_offset(ida_path):
ida = MachO.from_file(ida_path)
string = None
segments = (cmd.body for cmd in ida.load_commands if cmd.type == cmd.type.segment_64)
sections = (section for se... |
9866586 | from sfaira.train.summaries import GridsearchContainer, SummarizeGridsearchEmbedding, SummarizeGridsearchCelltype
from sfaira.train.train_model import TrainModelEmbedding, TrainModelCelltype
|
9866676 | from itertools import chain
import math
import torch
import torch.nn as nn
from torch.nn.utils.rnn import pad_packed_sequence, pack_padded_sequence
from .gaussian_encoder import GaussianEncoderBase
from .encoder_vmf import VMFEncoderBase
from ..utils import log_sum_exp
from sympy import *
class VMFLSTMEncoder(VMFEnc... |
9866696 | import struct
from datetime import datetime
from typing import TYPE_CHECKING
from .base import Converter
if TYPE_CHECKING:
from ..device import XDevice
BLE_FINGERPRINT_ACTION = [
"Match successful", "Match failed", "Timeout", "Low quality",
"Insufficient area", "Skin is too dry", "Skin is too wet"
]
BLE_... |
9866697 | import math
from rlbot.agents.base_agent import BaseAgent, SimpleControllerState
from rlbot.utils.structures.game_data_struct import GameTickPacket
from rlbot.utils.structures.quick_chats import QuickChats
from util.orientation import Orientation
from util.vec import Vec3
import util.const
from rlutilities.linear_alg... |
9866702 | from dacbench.abstract_agent import AbstractDACBenchAgent
from gym import spaces
class RandomAgent(AbstractDACBenchAgent):
def __init__(self, env):
self.sample_action = env.action_space.sample
self.shortbox = isinstance(env.action_space, spaces.Box)
if self.shortbox:
self.short... |
9866708 | from typing import List, Tuple
from logging import getLogger
import pandas as pd
import numpy as np
from xfeat.types import XDataFrame, XSeries
logger = getLogger(__name__)
try:
import cudf # NOQA
import cupy as cp # NOQA
except ImportError:
cudf = None
cp = None
def analyze_columns(input_df: ... |
9866729 | import os
from absl import logging # noqa: F401
from icubam.db import store
from icubam.analytics import operational_dashboard
from icubam.www.handlers import base
class OperationalDashboardHandler(base.APIKeyProtectedHandler):
ROUTE = '/dashboard'
# Problably better not to be equal to admin.
BACKOFFICE_PRE... |
9866746 | import numpy
import pytest
from chainer_chemistry.dataset.parsers import SmilesParser
from chainer_chemistry.dataset.preprocessors import GGNNPreprocessor
def test_ggnn_preprocessor():
preprocessor = GGNNPreprocessor()
dataset = SmilesParser(preprocessor).parse(
['C#N', 'Cc1cnc(C=O)n1C', 'c1ccccc1']
... |
9866749 | from .onlinestats import OnlineStats
__red_end_user_data_statement__ = 'This cog does not store user data.'
def setup(bot):
bot.add_cog(OnlineStats(bot))
|
9866772 | from .state import EOF
from .tokens import TokenEof
from .tokens_base import TOKEN_COMMAND_COPY
from .tokens_base import TokenOfCommand
from .parser import parse_command_line
from Vintageous import ex
@ex.command('copy', 'co')
class TokenCopy(TokenOfCommand):
def __init__(self, params, *args, **kwargs):
s... |
9866773 | def test_base_box_has_git(box):
box.provision(roles=[], parameters={})
assert 'git version ' in box.execute('git --version')
|
9866789 | from typing import Tuple
from fhirclient.models.operationdefinition import OperationDefinition
from adaptor.outgoing.interchange_adaptor import InterchangeAdaptor
class OutgoingAdaptor(object):
def __init__(self, operation_dict):
self.operation_dict = operation_dict
def convert_to_edifact(... |
9866816 | from typing import Union
from discord import Embed, AllowedMentions, InvalidArgument
from discord.http import Route
from discord_components import Interaction as DCInteraction, Component, FlagsType, \
DiscordComponents as DCDiscordComponents, Select
class Interaction(DCInteraction):
@property
def id(self... |
9866828 | import unittest
from StringIO import StringIO
from warcrecords import WarcinfoRecord
from hanzo.warctools import WarcRecord
def record_to_string(record):
buffer = StringIO()
record.write_to(buffer)
return buffer.getvalue()
class TestWarcinfoRecord(unittest.TestCase):
def id_test(self, defaults):
... |
9866845 | from hazelcast.serialization.bits import *
from hazelcast.protocol.builtin import FixSizedTypesCodec
from hazelcast.protocol.client_message import OutboundMessage, REQUEST_HEADER_SIZE, create_initial_buffer, RESPONSE_HEADER_SIZE
# hex: 0x150200
_REQUEST_MESSAGE_TYPE = 1376768
# hex: 0x150201
_RESPONSE_MESSAGE_TYPE = 1... |
9866904 | import os, re, sys, copy, warnings
import tensorflow as tf
if tf.__version__.split('.')[0] == '2':
tf = tf.compat.v1
tf.disable_v2_behavior()
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
ROOT_DIR = os.path.dirname(BASE_DIR)
sys.path.insert(0, ROOT_DIR)
from collections import defaultdict
from config ... |
9866928 | import logging
from uuid import UUID
from flask_login import current_user
from auth.validateresult import AuthKind, ValidateResult
logger = logging.getLogger(__name__)
def validate_session_cookie(auth_header_unusued=None):
"""
Attempts to load a user from a session cookie.
"""
if current_user.is_an... |
9866964 | import pymel.core as pm
def getFCurveValues(fcv_node, division, factor=1):
"""Get X values evenly spaced on the FCurve.
Arguments:
fcv_node (pyNode or str): The FCurve to evaluate.
division (int): The number of division you want to evaluate on
the FCurve.
factor (float): M... |
9866970 | from setuptools import setup
exec (open('dash_callback_chain/version.py').read())
setup(
name='dash_callback_chain',
version=__version__,
author='nicolaskruchten',
packages=['dash_callback_chain'],
include_package_data=True,
license='MIT',
description='Dash component to visualize callback ... |
9866999 | import torch
import torch.nn.functional as F
from torch.nn import init
import numpy as np
from scipy.stats import truncnorm
def truncated_normal_initializer(shape, mean, stddev):
# compute threshold at 2 std devs
values = truncnorm.rvs(mean - 2 * stddev, mean + 2 * stddev, size=shape)
return torch.from_nu... |
9867029 | from qtpy import QtWidgets, QtCore
__all__ = ['CloseAllFilter']
class CloseAllFilter(QtCore.QObject):
"""Event filter for closing all windows if the widget is closed."""
def eventFilter(self, receiver, event):
results = super().eventFilter(receiver, event)
if event.type() == QtCore.QEvent.Cl... |
9867041 | import redistrib.command as comm
import six
from redistrib.connection import Connection
from redistrib.exceptions import RedisStatusError
from six.moves import range
import base
from rediscluster import StrictRedisCluster
from rediscluster.exceptions import RedisClusterException
class ApiTest(base.TestCase):
def... |
9867070 | import os
import sys
import wasmtime
try:
from importlib import resources as importlib_resources
importlib_resources.files # py3.9+ stdlib
except (ImportError, AttributeError):
import importlib_resources # py3.8- shim
wasm_cfg = wasmtime.Config()
wasm_cfg.cache = True
wasi_cfg = wasmtime.WasiConfig()
was... |
9867170 | from pathlib import Path
from string import ascii_lowercase
from typing import Any
import hypothesis.strategies as st
import pytest
from hypothesis import given, settings
from numpy.testing import assert_array_equal
from mygrad import Tensor, load, save
from tests.custom_strategies import everything_except, tensors
... |
9867186 | import json
from ..views import View
from ..controllers import Controller
from ..utils.structures import data_get
class HttpTestResponse:
def __init__(self, testcase, application, request, response, route):
self.testcase = testcase
self.application = application
self.request = request
... |
9867232 | from __future__ import print_function, division
import sys,os
quspin_path = os.path.join(os.getcwd(),"../")
sys.path.insert(0,quspin_path)
from quspin.basis import spin_basis_1d,photon_basis # Hilbert space bases
from quspin.operators import hamiltonian # Hamiltonian and observables
from quspin.tools.measurements imp... |
9867251 | class Speed:
def __init__(self, speed = 0):
self.speed = speed
def change_to_mile(self):
return (self.speed*0.6213," miles")
def get_speed(self):
return self._speed
def set_speed(self, km):
if km > 50:
raise ValueError("You are liable to speeding ticket"... |
9867283 | from __future__ import division
import re
import sys
from multiprocessing import cpu_count
from os import path, sep as os_sep
from canaryd_packages import six
from canaryd.subprocess import get_command_output
def get_ps_cpu_stats():
'''
Uses ps + awk to total CPU usage, then divide by # CPUs to get the fi... |
9867311 | import argparse
from copo.eval.get_policy_function import PolicyFunction
from metadrive.envs.marl_envs import MultiAgentBottleneckEnv, MultiAgentRoundaboutEnv, MultiAgentIntersectionEnv, \
MultiAgentParkingLotEnv, MultiAgentTollgateEnv
def get_env(env_name, use_native_render=False):
config = {"use_render": u... |
9867357 | import json
import openpyxl
import pandas
def output_sanitization(path_to_excel, path_to_out_json=None, path_to_log=None):
''' Find the Success percentage of each output report '''
path = path_to_excel
out_obj = []
excel_obj = []
# Output Sanitization
s = pandas.read_excel(path, engine='open... |
9867365 | import webapp2
import cloudstorage as gcs
def Speichern(prjname, bucket_name, subdir4bg, subdir4rss, rssname, result):
bucket = bucket_name
filename = '/' + bucket+ '/' + rssname + '.xml'
class FeedSaver(webapp2.RequestHandler):
def create_file(self, filename):
gcs_file = gcs.open(file... |
9867368 | from __future__ import absolute_import, division, print_function
from scitbx.array_family import flex
from libtbx.test_utils import approx_equal
import scitbx.simplex
from six.moves import range
from six.moves import zip
class test_function(object):
def __init__(self,n):
self.n = n
self.starting_simplex=[]
... |
9867386 | import unittest
import spydrnet as sdn
class TestComposers(unittest.TestCase):
def test_compose(self):
netlist = sdn.Netlist()
self.assertRaises(RuntimeError, sdn.compose, netlist, "fakefile.fakeext")
|
9867403 | import os
import gin
import tensorflow.compat.v1 as tf
from absl import app, flags
import reaver as rvr
flags.DEFINE_string('env', None, 'Either Gym env id or PySC2 map name to run agent in.')
flags.DEFINE_string('agent', 'a2c', 'Name of the agent. Must be one of (a2c, ppo).')
flags.DEFINE_bool('render', False, 'Whe... |
9867406 | import json
import os
import re
from pyBaiduPan.exceptions import *
from pyBaiduPan.login import baidu_pan_login
from pyBaiduPan.config import get_config, DEFAULT_CONFIG
import logging
from itertools import count
import pickle
import shutil
from hashlib import md5
from functools import partial
from base64 import b64enc... |
9867423 | import numpy as np
from eigen_ref import *
def test(mat):
printMatrix(mat)
fill(mat,1.)
printMatrix(mat)
assert np.array_equal(mat,np.full(mat.shape,1.))
A_ref = asRef(mat.shape[0],mat.shape[1])
A_ref.fill(1.)
A_ref2 = asRef(mat.shape[0],mat.shape[1])
assert np.array_equal(A_ref,A_ref2)
A_ref2.fi... |
9867425 | import logging
from copy import deepcopy
from typing import List, Dict, Union, Set
import csv
import requests
import json
import sys
from datetime import datetime, timezone
from pathlib import Path
import pyexcel_ods3
logging.basicConfig(format="%(asctime)s - %(name)s - %(levelname)s - %(message)s")
logger = logging.... |
9867427 | import pytest
from tartiflette.language.ast import DirectiveNode
def test_directivenode__init__():
directive_node = DirectiveNode(
name="directiveName",
arguments="directiveArguments",
location="directiveLocation",
)
assert directive_node.name == "directiveName"
assert directi... |
9867443 | import json
import django.test
import django.shortcuts
from django.core.signing import dumps, loads
from . import factories
from . import test_models
from .. import models
from .. import views
class TestChangeOtherAvatar(django.test.TestCase):
def setUp(self):
self.user = factories.UserFactory.create()
... |
9867447 | import torch.backends.cudnn as cudnn
import torch.multiprocessing as mp
import torch.distributed as dist
from torch.nn.parallel import DistributedDataParallel as DDP
import os
import re
import collections
from pathlib import Path
from packaging import version
import numpy as np
from tqdm import tqdm
import torch
impor... |
9867455 | import os
import random
from PIL import Image
import numpy as np
import torch
import torch.utils.data as data
class PolishDataset(data.IterableDataset):
def __init__(self, data_dir, train=True, aux=False, crop_size=192, samples=(128, 512),
extra_aug=False):
self.crop_size = crop_size
... |
9867497 | import re
import pyodbc
from compare_results import handle_exception_in_file, process_multiple_resultsets
from datetime import date, datetime, time
from decimal import Decimal
from uuid import UUID
from xml.dom.minidom import parseString
from utils.config import config_dict as cfg
from utils.base import handle_babel_ex... |
9867533 | from torch import Tensor, nn
from models.building_blocks.utils import get_activation, get_initialiser
def create_batch_norm_1d_layers(num_layers: int, dim_hidden: int):
batch_norm_layers = nn.ModuleList()
for i in range(num_layers - 1):
batch_norm_layers.append(nn.BatchNorm1d(num_features=dim_hidden)... |
9867542 | from ExportMLModel import main
from CommonServerPython import *
dummy_data = [i for i in range(10)]
def test_main(mocker):
mocker.patch.object(demisto, 'args', return_value={"modelName": 'model'})
def get_file_path(entry_id):
return {'path': './TestData/entry_file'}
def execute_command(command... |
9867561 | import sys
from . import config_validator, config
class InteractiveConfig(object):
def __init__(self):
self._config_types = config_validator.ConfigValidatorInteractive()
def ask_for_config_if_interactive_mode(self):
if self._is_interactive():
self._start_url()
self._ma... |
9867575 | from unittest.mock import call, patch
from botocore.session import Session
from awscli_login.configure import configure
from .base import CleanTestEnvironment
from .util import login_cli_args
# TODO Not very dry...
class TestNoProfile(CleanTestEnvironment):
""" Integration tests for no profile. """
profile ... |
9867587 | from typing import Union, Tuple
from hwt.interfaces.agents.handshaked import HandshakedAgent
from hwt.interfaces.std import Handshaked, HandshakeSync, VectSignal
from hwt.synthesizer.param import Param
from hwtLib.handshaked.intfBiDirectional import HandshakedBiDirectionalAgent
from ipCorePackager.constants import DIR... |
9867614 | import typer
app = typer.Typer()
@app.command("create")
def cli_create_user(username: str):
typer.echo(f"Creating user: {username}")
@app.command("delete")
def cli_delete_user(username: str):
typer.echo(f"Deleting user: {username}")
if __name__ == "__main__":
app()
|
9867730 | import argparse
import functools
from ppasr.trainer import PPASRTrainer
from ppasr.utils.utils import add_arguments, print_arguments
parser = argparse.ArgumentParser(description=__doc__)
add_arg = functools.partial(add_arguments, argparser=parser)
add_arg('batch_size', int, 32, '่ฎญ็ป็ๆน้ๅคงๅฐ... |
9867757 | import cv2
import os
import re
import tqdm
import matplotlib.pyplot as plt
exp_name = '0Dinit_VDupdate_DTE_batch24_LRG1e-5D1e-4_Range5e3_DecompClippedNoisedPatchD_VerifyingDonPrev_LossLR_debug'
FPS = 5
final_blinking_seconds = 40
images_folder = '../../experiments/'+exp_name+'/val_images'
video_name = os.path.join(im... |
9867768 | class Solution:
def judgeCircle(self, moves: str) -> bool:
vertical, horizontal = 0, 0
for move in moves:
if move == 'U': vertical += 1
elif move == 'D': vertical -= 1
elif move == 'R': horizontal += 1
elif move == 'L': horizontal -= 1
return v... |
9867779 | import os
import sys
sys.path.append('Helpers/')
import TradeGenerator
sys.path.append('../')
sys.path.append('../')
from ore_examples_helper import OreExample
oreex = OreExample(sys.argv[1] if len(sys.argv)>1 else False)
oreex.print_headline("Running in currency trades")
oreex.run("Input/ois_ore.xml")
oreex.print... |
9867797 | from .baseresource import BaseResource
class AccountFunds(BaseResource):
def __init__(self, **kwargs):
super(AccountFunds, self).__init__(**kwargs)
self.available_to_bet_balance = kwargs.get("availableToBetBalance")
self.discount_rate = kwargs.get("discountRate")
self.exposure = kw... |
9867802 | import logging; log = logging.getLogger(__name__)
import struct
import math
import sys
import os
import os.path
from common.BinaryFile import BinaryFile
from common.sfa.zlb import Zlb
from common.math import Vec2s, Vec3s, Vec3f, Quaternion, Mtx43, Mtx44
from ..ModelRenderer import ModelRenderer
class MapObject:
""... |
9867861 | from c4.board import WrongMoveError
from c4.engine.base import Engine
class HumanEngine(Engine):
def __init__(self, name):
self.name = name
def choose(self, board):
"""Ask the user to choose the move"""
print(board)
while True:
try:
move = int(inpu... |
9867864 | from django.test import TestCase
import os
import pymarc
from lxml import etree
import core
from core.models import Title
from core.title_loader import TitleLoader
def abs_filename(rel_filename):
abs_filename = os.path.join(
os.path.dirname(core.__file__),
rel_filename)
return abs_filename
... |
9867870 | import threading as threading
import sys, time, os, re
import pandas as pd
import xlsxwriter, glob
start_time = time.time()
from modules.main import ArgParse
from modules.logging import Logger
from modules.output import Output
from modules import process as k8s
from modules.load_kube_config import kubeConfig
kubeConfi... |
9867931 | from power import POWER
from gas import GAS
from hepmass import HEPMASS
from miniboone import MINIBOONE
from bsds300 import BSDS300
from mnist import MNIST
from cifar10 import CIFAR10
|
9867950 | import sublime
class UnitCollections:
@staticmethod
def load_default_collections():
execution_units = {}
collections = sublime.find_resources("*.terminality-collections")
for collection_file in collections:
collection = sublime.decode_value(
sublime.load_re... |
9868006 | import numpy as np
import os
import shapely
from shapely.geometry import Polygon,MultiPoint
def polygon_from_list(line):
"""
Create a shapely polygon object from gt or dt line.
"""
#polygon_points = [float(o) for o in line.split(',')[:8]]
#polygon_points = np.array(line).reshape(4, 2)
polygon =... |
9868074 | import os
import pathlib
import shutil
import pytest
from ansible_builder.utils import write_file, copy_file, run_command
def test_write_file(tmp_path):
path = tmp_path / 'foo.txt'
text = [
'foo # from some collection',
'bar',
'# a comment',
'',
'zoo',
'' # ... |
9868075 | class Storage:
"""
helper base class for the Storage object hierarchy
"""
def __init__(self, *args, **kw ):
pass
@property
def _name(self):
return self.__class__.__name__
def read(self, model_class):
raise NotImplementedError()
def write(self, model_class, ite... |
9868143 | from .features import RegexMatches
name = "korean"
# No useful dictionary. hunspell-ko is broken on Ubuntu 14.10
# No korean stopwords
# No stemmer
badword_regexes = [
r'ใ
ใ
',
r'ใ
ใ
',
r'ใ
ใ
',
r'ใ
ใน',
r'๊ฐ๋',
r'๊ฐ๋ณด',
r'๊ฐ(๊ธฐ[๋ค์ง]|๋
|๋ผ|์?๋ฆฌ|์์|์๋ผ|์์|์ข|์ฐจ๋ฐ)',
r'๊ฑธ๋ ๋
',
r'๊ณ์ง๋
',
r'๊ทธ์ง์๋ผ',
... |
9868155 | import datetime
from django.test import TestCase
from django.utils.timezone import now
from register.tests.factories import RegistrationFactory
from help_desk.models import Case
class CaseModelTest(TestCase):
def test_registration_unlocked(self):
reg = RegistrationFactory()
case = Case()
... |
9868166 | import unittest
import shutil
import os
from clockwork import samtools_qc
modules_dir = os.path.dirname(os.path.abspath(samtools_qc.__file__))
data_dir = os.path.join(modules_dir, "tests", "data", "samtools_qc")
# Made ref files like this:
# fastaq make_random_contigs --seed 42 1 2000 samtools_qc.ref.fa
# bwa index s... |
9868192 | from . import fast_ffts
import numpy as np
def fourier_interp1d(data, out_x, data_x=None, nthreads=1, use_numpy_fft=False,
return_real=True):
"""
Use the fourier scaling theorem to interpolate (or extrapolate, without
raising any exceptions) data.
Parameters
----------
dat... |
9868204 | from abc import ABC
from dataclasses import dataclass
from typing import Any, Iterator
from rxbp.acknowledgement.acksubject import AckSubject
class ControlledZipStates:
class ZipState(ABC):
pass
@dataclass
class WaitOnLeft(ZipState):
""" Zip observable actor has or will back-pressure the... |
9868209 | class Schema:
"""Data schema class.
Used provide uniform access to fields in the data set.
"""
stock_columns = [
"symbol", "date", "open", "close", "high", "low", "volume", "adjClose", "adjHigh", "adjLow", "adjOpen",
"adjVolume", "divCash", "splitFactor"
]
option_columns = [
... |
9868231 | import numpy as np;
m=5;
n=7;
c = np.array( [2, 1.5, 0, 0, 0, 0, 0] );
A = np.array( [ [12, 24, -1, 0, 0, 0, 0],
[16, 16, 0, -1, 0, 0, 0],
[30, 12, 0, 0, -1, 0, 0],
[1, 0, 0, 0, 0, 1, 0],
[0, 1, 0, 0, 0, 0, 1] ] );
b = np.array( [ 120, 120, 120, 15, 15] );
x = np.array( [14, 1, 72, 120, 312, 1, 14] ... |
9868244 | import re
COORDINATE_RX = re.compile(r'^[-+]?([1-8]?\d(\.\d+)?|90(\.0+)?),\s*[-+]?(180(\.0+)?|((1[0-7]\d)|([1-9]?\d))(\.\d+)?)$')
TIME_RX = re.compile(r'^([0-9]|0[0-9]|1[0-9]|2[0-3]):[0-5][0-9]$')
def is_address(address: str) -> bool:
return bool(re.search('[a-zA-Z]', address))
def is_valid_coordinate(coordina... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.