id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9842693 | from unittest import TestCase
from similarityPy.algorithms.find_nearest import FindNearest
from similarityPy.measure.numerical_data.canberra_distance import CanberraDistance
from tests import test_logger
__author__ = 'cenk'
class FindNearestTest(TestCase):
def setUp(self):
pass
def test_canberra_d... |
9842714 | from io import StringIO
from celery import shared_task
from django.utils import timezone
from django.utils.module_loading import import_string
from .models import ImportTask
@shared_task(track_started=True)
def csv_import(task_id): # pragma: no cover
task_obj = ImportTask.objects.get(pk=task_id)
log = Str... |
9842809 | from msrest.serialization import Model
class RouteSectionNaptanEntrySequence(Model):
"""RouteSectionNaptanEntrySequence.
:param ordinal:
:type ordinal: int
:param stop_point:
:type stop_point: :class:`StopPoint <models.StopPoint>`
"""
_attribute_map = {
'ordinal': {'key': 'ordinal... |
9842830 | from unittest import TestCase
from chia.types.blockchain_format.program import Program, INFINITE_COST
from chia.util.byte_types import hexstr_to_bytes
from chia.wallet.puzzles.load_clvm import load_clvm
DESERIALIZE_MOD = load_clvm("chialisp_deserialisation.clvm", package_or_requirement="chia.wallet.puzzles")
def se... |
9842853 | from contextlib import contextmanager
from unittest import skipIf, skipUnless
import os
import io
import socket
import sys
from sphinx.application import Sphinx
from sphinx.errors import SphinxWarning
try:
import enchant
except ImportError:
enchant = None
import cms
from cms.test_utils.testcases import CMST... |
9842855 | import random
import numpy as np
from nose import with_setup
from pypair.contingency import BinaryTable, CategoricalTable, ConfusionMatrix
def setup():
"""
Setup.
:return: None.
"""
np.random.seed(37)
random.seed(37)
def teardown():
"""
Teardown.
:return: None.
"""
pass... |
9842861 | import numpy as np
import tensorflow.compat.v1 as tf
from typing import Any, Dict, List, Optional
from dnnv.verifiers.common.base import Parameter, Verifier
from dnnv.verifiers.common.executors import VerifierExecutor
from dnnv.verifiers.common.results import SAT, UNSAT, UNKNOWN
from dnnv.verifiers.common.utils impor... |
9842867 | from abc import ABC, abstractmethod
from typing import List, Optional
import torch.distributed as dist
from colossalai.zero.sharded_param.sharded_tensor import ShardedTensor
class BaseShardStrategy(ABC):
def __init__(self) -> None:
"""Abstract Shard Strategy. Use to shard a tensors on multiple GPUs.
... |
9842901 | import os
from yolo.detect import prepare_detector
from pix2pix.utils.model import Pix2Pix
from utils import read_image, prepare_image_yolo, cut_result, create_new_image, prepare_frame_p2p, frame_to_int
import matplotlib.pyplot as plt
import argparse
import cv2
import time
if __name__ == '__main__':
parser = argp... |
9842904 | import requests
import json
def select_cryptocurrencies(cryptocurrency=None,
base_url="https://raw.githubusercontent.com/JerBouma/FinanceDatabase/master/"
"Database/Cryptocurrencies",
use_local_location=False, all_cryp... |
9842929 | from celery.result import EagerResult
from django.test import TestCase
from open.users.factories import UserFactory
from open.users.models import User
from open.users.tasks import get_users_count
class TestUserCeleryTasks(TestCase):
def test_user_count(self):
User.objects.all().delete()
"""A bas... |
9842956 | from dataclasses import dataclass, field
import os
import time
from threading import Lock
from typing import Dict, Iterable, Iterator, Optional, Tuple
from ouster.client import (LidarPacket, ImuPacket, Packet, PacketSource,
SensorInfo)
from ouster.pcap import _pcap
# TODO: Look into at pos... |
9842971 | import sympy
from ..core.enzyme import Enzyme
from ..utils.parsing import parse_gpr
def infer_enzyme_from_gpr(reaction, default_kcat, default_kdeg):
new_enzymes = list()
compositions = compositions_from_gpr(reaction)
for e,composition in enumerate(compositions):
new_enzyme = Enzyme(id = r... |
9842976 | from setuptools import setup
with open("README.md", "r", encoding="utf-8") as f:
LONG_DESCRIPTION = f.read()
setup(
name='stl-to-voxel',
version='0.9.1',
description='Turn STL files into voxels, images, and videos',
long_description=LONG_DESCRIPTION,
long_description_content_type='text/markdow... |
9843002 | from envs.env import *
from utils.helper import *
from agents.BaseAgent import *
from components.replay import *
from components.network import *
from components.normalizer import *
import components.exploration
class VanillaDQN(BaseAgent):
'''
Implementation of Vanilla DQN with only replay buffer (no target netw... |
9843041 | import esphome.codegen as cg
import esphome.config_validation as cv
from esphome import automation
from esphome.components import miot
from esphome.const import (
CONF_TRIGGER_ID,
)
CONF_BUTTON = "button"
CONF_ON_TWIST = "on_twist"
CODEOWNERS = ["@dentra"]
AUTO_LOAD = ["miot", "sensor"]
miot_xmmfo1jqd_ns = cg.es... |
9843047 | class Matriz(str):
def __init__(self, string):
#Separaramos nuestro string por los saltos de linea y cada salto de linea lo separamos por espacios vacios para asi obtener una lista
self.matriz = [[x for x in h.split()] for h in string.splitlines()]
def row(self, index):
#Regresa la pa... |
9843072 | import json
import sys
import random, math
def safe_encode(str):
str1 = str.replace('\\', "\\\\")
return ('"' + str1.replace('"', '\\"').replace("\n"," ").strip().decode('utf-8', 'ignore') + '"')
def collection_to_str(items, start_sep, end_sep):
if len(items) == 0:
return ""
tmp = start_sep
... |
9843076 | import configparser
import os
ROOT = os.path.dirname(os.path.abspath(__file__))
CONFIG_PATH = os.path.join(ROOT, 'app_config.ini')
SQLALCHEMY = 'SQLALCHEMY'
FLASK = 'FLASK'
APP = 'APP'
PARAMS = 'DEFAULT_PARAMS'
PATHS = 'PATHS'
def str2bool(v):
return v.lower() in ("yes", "true", "t", "1")
class ConfigApp(obje... |
9843092 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
from torch.autograd import Variable
import math
import copy
from load_data import EXTRA_CHARS
class OneHotEmbedding(nn.Module):
def __init__(self, alphabet_size):
super().__init__()
self.alphabet_size = alphabet_... |
9843103 | import matplotlib.pyplot as plt
import numpy as np
from sklearn.model_selection import train_test_split
from sklearn.datasets import load_breast_cancer
from sklearn.svm import SVC
from sklearn.linear_model import LogisticRegression
from sklearn.tree import DecisionTreeClassifier
# Load the data
cancer = load_breast_... |
9843109 | import time
import os
import subprocess
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.common import utils
chrome_options = Options()
chrome_options.add_argument("nwapp=" + os.path.dirname(os.path.abspath(__file__)))
testdir = os.path.dirname(os.path.absp... |
9843110 | from typing import Tuple
import torch
class AdaptiveConcatPool2d(torch.nn.Module):
def __init__(self, sz: Tuple[int, int] = (1, 1)):
super().__init__()
self.average_pool = torch.nn.AdaptiveAvgPool2d(sz)
self.max_pool = torch.nn.AdaptiveMaxPool2d(sz)
def forward(self, x):
retu... |
9843121 | size(200, 200)
path = BezierPath()
path.rect(25, 25, 100, 100)
path.rect(75, 75, 100, 100)
drawPath(path)
|
9843161 | import csv
from datetime import datetime
from matplotlib import pyplot as plt
filename = 'data/death_valley_2018_simple.csv'
with open(filename) as f:
reader = csv.reader(f)
header_row = next(reader)
# Get dates, and high and low temperatures from this file.
dates, highs, lows = [], [], []
for ro... |
9843193 | import unittest
from sqlalchemy.orm import sessionmaker
from nesta.core.orms.nomis_orm import Base
from nesta.core.orms.orm_utils import get_mysql_engine
class TestNomis(unittest.TestCase):
'''Check that the WiktionaryNgram ORM works as expected'''
engine = get_mysql_engine("MYSQLDBCONF", "mysqldb")
Sessi... |
9843231 | import theano
import theano.tensor as T
import numpy as np
from emolga.utils.theano_utils import sharedX, shared_zeros, shared_ones
def get_fans(shape):
if isinstance(shape, int):
shape = (1, shape)
fan_in = shape[0] if len(shape) == 2 else np.prod(shape[1:])
fan_out = shape[1] if len(shape) == 2... |
9843232 | from .dropout import LockedDropout, WordDropout
from .model import Model, Classifier, DefaultClassifier
|
9843236 | from pycqed.measurement import measurement_control as mc
import adaptive
from pycqed.instrument_drivers.meta_instrument.LutMans import flux_lutman as flm
from pycqed.instrument_drivers.virtual_instruments import noise_parameters_CZ_new as npCZ
from pycqed.simulations import cz_superoperator_simulation_new_functions a... |
9843248 | import cv2
from bar4py.shortfuncs import opjoin, filename2basename, bgr2gray
from glob import glob
class Dictionary:
'''
Dictionary Class, 2016/12/10 Edit
Inputs:
dictionaryObj is Dictionary object
ids is marker_id list
frames is marker frame list
en_pool is contrl of set pool
pool_si... |
9843276 | from .lir_basis import largest_interior_rectangle as lir_basis
from .lir_within_contour import largest_interior_rectangle \
as lir_within_contour
def lir(grid, contour=None):
"""
Returns the Largest Interior Rectangle of a binary grid.
:param grid: 2D ndarray containing data with `bool` type.
:par... |
9843331 | from ganslate.engines.trainer import Trainer
from ganslate.engines.validator_tester import Tester
from ganslate.engines.inferer import Inferer
from ganslate.utils import communication, environment
from ganslate.utils.builders import build_conf
ENGINES = {
'train': Trainer,
'test': Tester,
'infer': Inferer... |
9843365 | import utils
import argparser
from torch.utils.data.distributed import DistributedSampler
from torch.utils import data
from shutil import copy
import time
import torch
torch.backends.cudnn.benchmark = True
from utils.run_utils import *
from metrics import StreamSegMetrics
from segmentation_module import make_model,... |
9843377 | import pytest
import torch
from mmcv.ops import DeformConv2dPack
from torch.nn.modules import AvgPool2d, GroupNorm
from torch.nn.modules.batchnorm import _BatchNorm
from mmdet.models.backbones import RegNet, Res2Net, ResNet, ResNetV1d, ResNeXt
from mmdet.models.backbones.hourglass import HourglassNet
from mmdet.models... |
9843380 | import velocity_obstacle.velocity_obstacle as velocity_obstacle
import nmpc.nmpc as nmpc
import argparse
if __name__ == "__main__":
parser = argparse.ArgumentParser()
parser.add_argument(
"-m", "--mode", help="mode of obstacle avoidance; options: velocity_obstacle, or nmpc")
parser.add_argument(
... |
9843383 | import sys
from rebus.agent import Agent
@Agent.register
class ProcessedStats(Agent):
_name_ = "processed_stats"
_desc_ = "Display current processing stats for the given domain then exit"
_operationmodes_ = ('automatic', )
@classmethod
def add_arguments(cls, subparser):
subparser.add_argu... |
9843422 | import jax.numpy as np
from .dotrow import dotrow
def normrow(X):
"""
NORMROW computes the l2-norm of each row in a np array
Input:
X: (n,m) numpy array
Output:
nX: (n,) numpy array of l2 norm of each row in X
"""
return np.sqrt(dotrow(X,X)) |
9843443 | from django.utils.translation import gettext_lazy as _
# Create your tests here.
from rest_framework.exceptions import ValidationError
from openbook_common.utils.model_loaders import get_hashtag_model |
9843451 | from __future__ import absolute_import
from __future__ import print_function
import sys
import os
# the next line can be removed after installation
sys.path.insert(0, os.path.dirname(os.path.dirname(
os.path.dirname(os.path.abspath(__file__)))))
from veriloggen import *
import veriloggen.thread as vthread
def m... |
9843482 | import umi_tools.network as network
from itertools import product
input_data = {"ACGT": 456,
"AAAT": 90,
"ACAT": 72,
"TCGT": 2,
"CCGT": 2,
"ACAG": 1}
output_data = {"unique": [['ACAG'], ['ACGT'], ['ACAT'], ['CCGT'], ['TCGT'], ['AAAT']],
... |
9843491 | from torchlars.__version__ import __version__ # noqa
from torchlars.lars import LARS
__all__ = ['LARS']
|
9843502 | r"""
Tests for the optional ``p_group_cohomology`` package.
AUTHOR:
- <NAME>
TESTS::
sage: from pGroupCohomology import CohomologyRing # optional - p_group_cohomology
Computation of a modular cohomology ring of a prime power group in
characteristic 2, and comparison with stored result in a database::
sa... |
9843515 | from __future__ import print_function
import gunpowder as gp
import json
def predict(iteration):
##################
# DECLARE ARRAYS #
##################
# raw intensities
raw = gp.ArrayKey('RAW')
# the predicted affinities
pred_affs = gp.ArrayKey('PRED_AFFS')
####################
... |
9843606 | import unittest
from .. import pwgenerator
class Test(unittest.TestCase):
def test_load_dictionary(self):
dictionary = pwgenerator.load_dictionary()
self.assertIsInstance(dictionary, tuple)
def test_get_random_word(self):
dictionary = pwgenerator.load_dictionary()
self.ass... |
9843614 | from lib import action
class Action(action.BaseAction):
def run(self, board_id, api_key=None, token=None):
if api_key:
self._set_creds(api_key=api_key, token=token)
lists = {}
board = self._client().get_board(board_id)
for lst in board.all_lists():
lists[ls... |
9843639 | from django.apps import AppConfig
class SpectatorReadingAppConfig(AppConfig):
label = "spectator_reading"
name = "spectator.reading"
verbose_name = "Spectator Reading"
# Maintain pre Django 3.2 default behaviour:
default_auto_field = 'django.db.models.AutoField'
|
9843645 | import datetime
import subprocess
import os
import argparse
import threading
DeploymentFlag="==> v1beta1/Deployment\n"
# DeploymentColume=['NAME','DESIRED','CURRENT','UP-TO-DATE','AVAILABLE','AGE']
# SecretFlag="==> v1/Secret\n"
# SecretColume=[]
# IngressFlag="==> v1beta1/Ingress\n"
# IngressColume=[]
# ServiceFlag="... |
9843688 | import pandas as pd
import numpy as np
import scipy.stats
# AUC comparison adapted from
# https://github.com/Netflix/vmaf/
def compute_midrank(x):
"""Computes midranks.
Args:
x - a 1D numpy array
Returns:
array of midranks
"""
J = np.argsort(x)
Z = x[J]
N = len(x)
T = np.z... |
9843710 | from pandac.PandaModules import *
from direct.interval.IntervalGlobal import *
from direct.particles import ParticleEffect
from direct.particles import Particles
from EffectController import EffectController
import random
class RainMist(EffectController, NodePath):
cardScale = 64.0
def __init__(self, referenc... |
9843749 | from backend.models import *
from django.views.generic import TemplateView
from django.shortcuts import render, redirect
from frontend.util import *
from pathlib import Path
import frontend.experiment as experiment
import os
import signal
class DashboardView(TemplateView):
def is_rt_node_running(self):
sr... |
9843794 | description = 'setup for the poller'
group = 'special'
sysconfig = dict(cache = 'tofhw.toftof.frm2')
devices = dict(
Poller = device('nicos.services.poller.Poller',
autosetup = True,
poll = [],
neverpoll = ['detector', 'measurement', 'notifiers'],
alwayspoll = ['reactor'],
... |
9843795 | import argparse
import yaml
from plantseg.pipeline.raw2seg import raw2seg
from plantseg.gui.plantsegapp import PlantSegApp
def parser():
parser = argparse.ArgumentParser(description='Plant cell instance segmentation script')
parser.add_argument('--config', type=str, help='Path to the YAML config file', requir... |
9843838 | from conftest import *
from models.appendix import Department
from models.segment import Segment
def dep_getall():
dep = Department()
dep.id = 1
dep.idHospital = 1
dep.name = 'dep'
return [dep, dep]
@patch('models.main.User.find', side_effect=user_find)
@patch('models.appendix.Department.getAll', side_effect=dep... |
9843841 | import tarfile
import tempfile
import json
import shutil
import numpy as np
import torch
import torch.nn as nn
from ..utils import binary_to_array
class BaseNet(nn.Module):
def __init__(self):
super(BaseNet, self).__init__()
@property
def device(self):
try:
out = next(self.p... |
9843852 | import os
import json
import difflib
import hashlib
import tempfile
import subprocess
import shutil
from contextlib import contextmanager
from pygments import highlight
from pygments.lexers import CssLexer, DiffLexer
from pygments.formatters import HtmlFormatter
from jsonview.decorators import json_view
from django i... |
9843856 | from .base import * # noqa
# Disable debug mode
DEBUG = False
# Facebook JSSDB app id
FB_APP_ID = "323944607389"
try:
from .local import * # noqa
except ImportError:
pass
|
9843897 | import pytest
from signalwire.relay.consumer import Consumer
from signalwire.tests import MockedConnection
class InvalidConsumer(Consumer):
def setup(self):
self.Connection = MockedConnection
self.project = 'project'
self.token = 'token'
def test_invalid_consumer():
with pytest.raises(Exception):
... |
9843901 | import wx
import os
import time
import urllib
import tempfile
import util
from settings import settings
class CancelException(Exception):
pass
class DownloadDialog(wx.Dialog):
def __init__(self, parent):
super(DownloadDialog, self).__init__(parent, -1, 'Feed Notifier Update')
... |
9843906 | from datetime import timedelta
from io import BytesIO
from requests import (
Request,
Response,
Session,
)
from requests.structures import CaseInsensitiveDict
from prettyprinter import (
install_extras,
pformat,
)
install_extras(['requests'])
def test_session():
sess = Session()
sess.aut... |
9843923 | from flask_restx import Api
api = Api(version='0.1', title='LOST API', description='REST and LOST specific services.')
@api.errorhandler
def std_handler(e):
return {'message': 'An unexpected error has occured.'}, 500 |
9843925 | from notification import AlertController
from notification import BaseMessagesController
from notification import BaseNotificationView
from notification import LayoutController
from notification import ListController
from notification import NotificationLayoutView
from notification import NotificationListView
from noti... |
9843940 | import gzip
import logging
import os
import shutil
from io import BytesIO
from tempfile import NamedTemporaryFile
from typing import Optional, Tuple, Any, IO
from urllib import request
from urllib.parse import urlparse
from urllib.error import URLError
import requests
from irrd.conf import get_setting, RPKI_IRR_PSEUD... |
9843974 | import torch
class GloVe():
def __init__(self, file_path):
self.dimension = None
self.embedding = dict()
with open(file_path, 'r') as f:
for line in f.readlines():
strs = line.rstrip().split(' ')
word = strs[0].lower()
vector = t... |
9843982 | import pytest
import numpy as np
from mead.tasks import Task
def test_get_min_f_loader_backoff():
name = 'a'
gold_val = np.random.randint(5, 10)
fake = np.random.randint(10, 100)
c = {
'features': [{'name': name}],
'loader': {
'min_f': gold_val
},
'preproc':... |
9844002 | import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import random
import math
def MultiChannelSoftBinaryCrossEntropy(input, target, reduction='mean'):
'''
input: N x 38 x H x W --> 19N x 2 x H x W
target: N x 19 x H x W --> 19N x 1 x H x... |
9844006 | from multiprocessing import cpu_count
import paddle.v2 as paddle
class MyReader:
def __init__(self, imageSize):
self.imageSize = imageSize
def train_reader(self, train_list, buffered_size=1024):
def reader():
with open(train_list, 'r') as f:
lines = [line.strip() f... |
9844023 | from machina.pds.base import BasePd
from machina.pds.gaussian_pd import GaussianPd
from machina.pds.deterministic_pd import DeterministicPd
from machina.pds.mixture_gaussian_pd import MixtureGaussianPd
from machina.pds.categorical_pd import CategoricalPd
|
9844047 | from howtrader.event import EventEngine
from howtrader.trader.engine import MainEngine
from howtrader.trader.ui import QtWidgets
from ..engine import APP_NAME
class RiskManager(QtWidgets.QDialog):
""""""
def __init__(self, main_engine: MainEngine, event_engine: EventEngine):
""""""
super().__... |
9844075 | expected_output = {
"total_entries_displayed": 2,
"index": {
1: {
"device_id": "router1",
"duplex_mode": "full",
"vtp_management_domain": "",
"native_vlan": "1",
"management_addresses": {},
"entry_addresses": {"10.0.0.7": {}},
... |
9844079 | import sys
for line in open(sys.argv[1], "r").readlines():
if line.strip() == "":
continue
if line[0] != "@":
sys.stdout.write(line)
|
9844109 | from __future__ import absolute_import
import numpy as np
from .Node import Op
from .._base import DNNL_LIB
from ..cpu_links import softmax_crossentropy
from .Softmax import softmax_func
from ..gpu_links import CuDNN_softmax_cross_entropy
from ..gpu_links import softmax_cross_entropy
from ..gpu_links import CuDNN_softm... |
9844111 | from functools import wraps
try:
from io import BytesIO
except ImportError: # pragma: no cover
from cStringIO import StringIO as BytesIO
from flask import Blueprint, abort, g, request
from werkzeug.exceptions import InternalServerError
from celery import states
from . import celery
from .utils import url_fo... |
9844123 | def complete(completion_context):
"""
:param CompletionContext completion_context:
"""
import itertools
from robocorp_ls_core.lsp import (
TextEdit,
Range,
Position,
CompletionItem,
CompletionItemKind,
)
section_name = completion_context.get_current_s... |
9844124 | import unittest
import iarm.cpu
class TestCpu(unittest.TestCase):
pass
class TestRandomValueDict(unittest.TestCase):
def setUp(self):
self.register = iarm.cpu.RandomValueDict(8, False)
def test_link(self):
self.register['a'] = 0
self.register['b'] = 1
self.assertNotEqua... |
9844125 | from unittest.mock import patch
import pytest
import requests
from cryptography.fernet import Fernet
from flask import current_app
from python_freeipa.exceptions import BadRequest, FreeIPAError
from noggin.app import ipa_admin
from noggin.security.ipa import (
Client,
maybe_ipa_login,
maybe_ipa_session,
... |
9844131 | import os
import re
import ast
import shutil
from itertools import product
from setuptools import setup, find_packages
def get_version(file_name, version_name="__version__"):
with open(file_name) as f:
tree = ast.parse(f.read())
for node in ast.walk(tree):
if isinstance(node, ast.Assig... |
9844138 | import mock
from fastapi_mvc.utils import global_except_hook
@mock.patch("fastapi_mvc.utils.excepthook.hint", return_value=mock.Mock)
@mock.patch("fastapi_mvc.utils.excepthook.template", return_value=mock.Mock)
@mock.patch("fastapi_mvc.utils.excepthook.log", return_value=mock.Mock)
def test_excepthook_debug(log_mock,... |
9844218 | from SelfCalibration import SelfCalibration
import cv2
import numpy as np
import os
import sys
DatasetPath = ''
ParaPath = ''
# SavePath = r'D:\F_Estimation_private\RealWorldPred\ManualData\RANSAC'
# SavePath = r'D:\F_Estimation_private\RealWorldPred\ManualData'
SavePath = r'D:\F_Estimation_private\RealWorldPred\Man... |
9844262 | from __future__ import absolute_import
from django.contrib.auth.forms import ReadOnlyPasswordHashWidget
from django.contrib.admin.widgets import (AdminDateWidget, AdminTimeWidget,
AdminSplitDateTime, RelatedFieldWidgetWrapper)
from django.forms import (FileInput, CheckboxInput... |
9844297 | import os
import os.path
import sys
import shutil
import subprocess
import biothings
import config
biothings.config_for_app(config)
from config import DATA_ARCHIVE_ROOT, logger as logging
from biothings.hub.dataload.dumper import FTPDumper
class ClinvarDumper(FTPDumper):
SRC_NAME = "clinvar"
SRC_ROOT_FOLDE... |
9844368 | import time
import os
import string
import queue
import encoder
from tqdm import tqdm
import sys
import json
import gzip
import struct
from tensorflow.core.example import example_pb2
import pyrouge
import logging
import codecs
import csv
# bpe vocab
field_empty = 28920
eos = 50256
def clean_space(sent_in):
'''
... |
9844401 | import casadi.casadi as cs
from .set_y_calculator import SetYCalculator
from ..constraints.no_constraints import NoConstraints
class Problem:
"""Definition of an optimization problem
Provides the cost function, constraints and additional
ALM/penalty-type constraints.
"""
def __init__(self, u, p,... |
9844428 | from __future__ import absolute_import
import py
from rpython.tool.udir import udir
try:
from lib_pypy import gdbm
except ImportError, e:
py.test.skip(e)
def test_len():
path = str(udir.join('test_gdbm_extra'))
g = gdbm.open(path, 'c')
g['abc'] = 'def'
assert len(g) == 1
g['bcd'] = 'efg'
... |
9844464 | print "Running test without NIDAQmx installed"
import DAQmxConfigTest
from PyDAQmx import *
print DAQmxGetPersistedTaskAttribute(1,2,3,5,4)
|
9844486 | from plotly.basedatatypes import BaseTraceHierarchyType
import copy
class Lighting(BaseTraceHierarchyType):
# ambient
# -------
@property
def ambient(self):
"""
Ambient light increases overall color visibility but can wash
out the image.
The 'ambient' property is ... |
9844557 | import unittest
import base
class Test1(base.BaseScriptTest, unittest.TestCase):
command_line = "./scripts/maf_build_index.py ${maf} ${maf_index}"
input_maf = base.TestFile(filename="./test_data/maf_tests/mm8_chr7_tiny.maf")
output_maf_index = base.TestFile(filename="./test_data/maf_tests/mm8_chr7_tiny.m... |
9844670 | from jivago.inject.annotation import Component
from jivago.lang.registry import Registry
registry = Registry.INSTANCE
registrations = registry.get_annotated_in_package(Component, "")
for registration in registrations:
registered_class = registration.registered # Registered class or function
annotation_param... |
9844671 | import textwrap
import mock
import pytest
from detect_secrets.core.constants import VerifiedResult
from detect_secrets.core.potential_secret import PotentialSecret
from detect_secrets.plugins.aws import AWSKeyDetector
from detect_secrets.plugins.aws import get_secret_access_keys
from detect_secrets.plugins.aws import... |
9844733 | from QUANTAXIS.QASetting import QALocalize
from unittest.mock import MagicMock
import unittest
class TestQALocalize(unittest.TestCase):
def test_generate_path(self):
#use mock object to test the data
#QALocalize.generate_path();
pass
def setUp(self):
pass
def tearDow... |
9844759 | import requests, json, logging
from collections import Counter
from metagov.core.plugin_manager import Registry, Parameters, VotingStandard
from metagov.core.models import Plugin, GovernanceProcess, ProcessStatus, AuthType
from metagov.core.errors import PluginErrorInternal
import metagov.plugins.github.schemas as Sch... |
9844845 | from functools import cached_property
from naff.client import const
from naff.client.utils import define, field
__all__ = ("LocalisedField", "LocalizedField")
@define(slots=False)
class LocalisedField:
"""
An object that enables support for localising fields.
Supported locales: https://discord.com/deve... |
9844872 | import os
import shutil
import tarfile
import wget
import torch
import numpy as np
from transformers import BertForMaskedLM, BertTokenizer
from scipy.spatial import distance
class ContextWordEmbeddings:
'''
Utility class to calculate the contextual word embedding distance
between two texts, an approach ... |
9844881 | from django.db import transaction
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from rest_framework.response import Response
from rest_framework.views import APIView
from django.utils.translation import ugettext_lazy as _
from openbook_common.responses import ApiMessageRespon... |
9844890 | import logging
import os
import subprocess
import threading
import unittest
from compactor.context import Context
from compactor.pid import PID
from compactor.process import Process
import pytest
logging.basicConfig()
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)
class TestVagrantIntegration(unittes... |
9844902 | from datetime import datetime
from unittest.mock import MagicMock, patch
import pytest
from speid.helpers.callback_helper import (
auth_header,
send_transaction,
set_status_transaction,
)
from speid.models import Transaction
def test_auth_header():
user = 'TESTING'
password = 'PASSWORD'
auth... |
9844910 | import numpy as np
# Some physical constants at sea level
R0 = 6371.0008 # volumetric radius of the Earth, [km]
g0 = 9.80665 # standard gravity acceleration, [m/s^2]
M0 = 28.9644 # mean molecular weight, [kg/kmol]
R_air = 8314.32/M0 # gas constant for dry air, [J/kg/K]
gamma = 1.4 # specific heat ratio, namely the rat... |
9844925 | import click
from flask.cli import with_appcontext
from app.lib.database.seed import SeedDatabase
@click.command('snitchdb', help='SnitchDNS Database Setup')
@with_appcontext
def main():
seed = SeedDatabase()
seed.run()
return True
|
9844939 | from hknweb.academics.serializers.course_surveys import (
QuestionSerializer,
RatingSerializer,
SurveySerializer,
)
from hknweb.academics.serializers.logistics import (
CourseSerializer,
DepartmentSerializer,
InstructorSerializer,
SemesterSerializer,
)
from hknweb.academics.serializers.icsr ... |
9844952 | import socket
import platform
def getip():
try:
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(('www.baidu.com', 0))
ip = s.getsockname()[0]
except:
ip = "x.x.x.x"
finally:
s.close()
return ip
if __name__ == "__main__":
ip_address = "0.0.0.0"
sysstr = platform.system()
... |
9844973 | import sys
import os
UTILS_DIR = os.path.join(os.path.abspath(os.path.dirname(__file__)), '..', 'utils')
sys.path.insert(1, UTILS_DIR)
from training import train, test
if __name__ == '__main__':
print("\n\n\nIMPORTANT!!!!\nThis is UNNORMALIZED DCG\n\n\n")
BREAK_EARLY = False
BATCH_SIZE = 500
N_EPOCH... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.