id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
1766741 | import asyncio
import logging
import os
import time
import unittest
from integration_tests.env_variable_names import (
SLACK_SDK_TEST_GRID_ORG_ADMIN_USER_TOKEN,
SLACK_SDK_TEST_GRID_IDP_USERGROUP_ID,
SLACK_SDK_TEST_GRID_TEAM_ID,
SLACK_SDK_TEST_GRID_USER_ID,
)
from integration_tests.helpers import async_... |
1766744 | import pandas as pd
from sklearn.cross_validation import train_test_split
import numpy as np
from sklearn.metrics import mean_squared_error
import os
class collaborativeFiltering():
def __init__(self):
pass
def readSongData(self, top):
"""
Read song data from targeted url
"""
... |
1766764 | from .resnet20 import rf_resnet20
from ..genotypes import *
from ..spaces import *
from ..operations import *
from lib.models.autorf import genotypes
MODEL_LIST = {
'resnet20': rf_resnet20,
}
def build_auto_network(model_name='resnet20',num_classes=10, genotype=None):
return MODEL_LIST[model_name](num_c... |
1766848 | from visadore import base
import pyvisa
from ._tek_series_mso import get_event_queue
class TekSeriesDefaultFeat(base.FeatureBase):
def feature(self):
"""Performs a default setup and waits for the operation to finish"""
with self.resource_manager.open_resource(self.resource_name) as inst:
... |
1766863 | from django.contrib import admin
from django.contrib.contenttypes.admin import GenericTabularInline
from derrida.common.admin import NamedNotableAdmin
from .models import SourceType, Bibliography, Footnote
class FootnoteAdmin(admin.ModelAdmin):
CONTENT_LOOKUP_HELP = '''Select the kind of record you want to attach... |
1766876 | from __future__ import absolute_import
from django.core import serializers
from ajax.exceptions import AlreadyRegistered, NotRegistered
from django.db.models.fields import FieldDoesNotExist
from django.db import models
from django.conf import settings
from django.utils.html import escape
from django.db.models.query imp... |
1766886 | from gazette.spiders.base.instar import BaseInstarSpider
class MsMaracajuSpider(BaseInstarSpider):
TERRITORY_ID = "5005400"
name = "ms_maracaju"
allowed_domains = ["maracaju.ms.gov.br"]
start_urls = ["https://www.maracaju.ms.gov.br/portal/diario-oficial"]
|
1766938 | import os
import sys
if sys.version_info[0] < 3:
from cPickle \
import \
load, dump, dumps
else:
from pickle \
import \
load, dump, dumps
from yaku._config \
import \
DEFAULT_ENV, BUILD_CONFIG, BUILD_CACHE, CONFIG_CACHE, HOOK_DUMP, \
_OUTPUT
from yak... |
1766953 | from functools import partial
from mission.framework.helpers import call_if_function, within_deadband
from mission.framework.task import Task
from shm import kalman
from shm import navigation_desires as desires
from shm.navigation_settings import position_controls
class PositionalControlNeedy(Task):
def on_first_... |
1766954 | from tir import Webapp
import unittest
class GTPA060(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup("SIGAGTP", "07/10/2020", "T1", "D MG 01 ")
inst.oHelper.Program('GTPA060')
def test_GTPA060_CT001(self):
self.oHelper.SetButton('Incluir')
... |
1767008 | from typing import Optional
from fastapi.openapi.models import OpenIdConnect as OpenIdConnectModel
from fastapi.security.base import SecurityBase
from starlette.exceptions import HTTPException
from starlette.requests import Request
from starlette.status import HTTP_403_FORBIDDEN
class OpenIdConnect(SecurityBase):
... |
1767013 | import spira.all as spira
class Resistor(spira.PCell):
width = spira.NumberParameter(default=spira.RDD.R1.MIN_WIDTH, doc='Width of the shunt resistance.')
length = spira.NumberParameter(default=spira.RDD.R1.MIN_LENGTH, doc='Length of the shunt resistance.')
def validate_parameters(self):
if self... |
1767026 | import numpy as np
import math as mt
import sys
from sklearn.cluster import KMeans
from sklearn import datasets
from sklearn import metrics
class XMeans:
def loglikelihood(self, r, rn, var, m, k):
l1 = - rn / 2.0 * mt.log(2 * mt.pi)
l2 = - rn * m / 2.0 * mt.log(var)
l3 = - (rn - k) / 2.0
... |
1767056 | from figcli.test.cli.actions.delete import DeleteAction
from figcli.test.cli.actions.put import PutAction
from figcli.test.cli.config import *
from figcli.test.cli.figgy import FiggyTest
from figcli.test.cli.test_utils import TestUtils
from figcli.utils.utils import *
class DevPromote(FiggyTest):
def __init__(s... |
1767087 | import numpy as np
import chainer
import torch
from torch.nn.functional import cross_entropy
from pytorch_bcnn.functions.loss import softmax_cross_entropy
def test():
b, c, w, h = 5, 10, 20, 30
x = np.random.rand(b, c, w, h).astype(np.float32)
t = np.random.randint(0, c, (b, w, h)).astype(np.int32)
... |
1767104 | from tir import Webapp
import unittest
class MATA730(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup('SIGAPCP','29/04/2019','T1','D MG 01 ','10')
inst.oHelper.Program('MATA730')
def test_MATA730_001(self):
self.oHelper.SetValue('Periodo Inicial ?',... |
1767107 | from typing import Any
import json
class OrderService:
def get_dimensions(self, **kwargs) -> Any:
"""7.1.1. Request for the trading venue and order options for a particular instrument.
Kwargs: Filter Parameter
instrument_id: Instrument id (UUID), unique identification of an instrument... |
1767119 | import unittest
class SomeClass(unittest.TestCase):
def test_something(self):
x = 5
print("print")
print("print")
print("print")
def do_something(self):
print("print")
def test_something_else(self):
x = 6
print("print")
class OtherClass(unittest... |
1767120 | import torch
import triton
import pytest
import subprocess
import triton.language as tl
import numpy as np
def get_p2p_matrix():
try:
stdout = subprocess.check_output(["nvidia-smi", "topo", "-p2p", "n"]).decode("ascii")
except subprocess.CalledProcessError:
return pytest.skip("No m... |
1767124 | class Solution(object):
# def subsetsWithDup(self, nums):
# """
# :type nums: List[int]
# :rtype: List[List[int]]
# """
# nums.sort()
# res = []
# for i in range(1 << len(nums)):
# res.append(self.get_subsets(nums, i))
# # remove duplicate
... |
1767125 | import requests
from update_v3 import get_table
from bs4 import BeautifulSoup
import pathlib
import json
URL="https://www.health.ny.gov/diseases/communicable/coronavirus/"
CAL_URL="http://web.archive.org/__wb/calendarcaptures/2"
ARCH_URL="http://web.archive.org/web"
year = 2020
res = requests.get(CAL_URL, params={
... |
1767141 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="cvae",
version="0.0.3",
author="<NAME>",
author_email="<EMAIL>",
description="CompressionVAE: General purpose dimensionality reduction and manifold learning tool based on "
... |
1767155 | class Solution:
def strStr(self, haystack: str, needle: str) -> int:
for i in range(len(haystack)):
if needle==haystack[i:i+len(needle)]:
return i
else:
if len(needle)==0:
return 0
else:
return -1
|
1767176 | import pytest
import torch
from metrics import accuracy_linear_assignment, accuracy_max
from maskedtensor import from_list
N_VERTICES_RANGE = range(40, 50)
@pytest.fixture
def correct_batch():
tensor_lst = [torch.eye(n_vertices) for n_vertices in N_VERTICES_RANGE]
return from_list(tensor_lst, dims=(0, 1))
TE... |
1767200 | from multiprocessing import Pool
import itertools
def chunks(l, n):
count = 0
for i in range(0, len(l), n):
yield l[i: i + n], count
count += 1
def multiprocessing(strings, function, cores=16):
df_split = chunks(strings, len(strings) // cores)
pool = Pool(cores)
pooled = pool.map... |
1767206 | from . import account_profile, bidict, drive_config, path_filter, pretty_api, webhook_notification
__all__ = ['account_profile', 'bidict', 'drive_config', 'path_filter', 'pretty_api', 'webhook_notification']
|
1767286 | from sklearn.linear_model import LogisticRegression
from sklearn.grid_search import GridSearchCV
from mock import Mock
import numpy as np
def test_grid_search():
from ..grid_search import grid_search
dataset = Mock()
dataset.data = np.array([[1, 2, 3], [3, 3, 3]] * 20)
dataset.target = np.array([0, 1... |
1767294 | from mock import MagicMock
import pytest
from sonic_platform_base.sonic_xcvr.api.public.cmis import CmisApi
from sonic_platform_base.sonic_xcvr.mem_maps.public.cmis import CmisMemMap
from sonic_platform_base.sonic_xcvr.xcvr_eeprom import XcvrEeprom
from sonic_platform_base.sonic_xcvr.codes.public.cmis import CmisCodes
... |
1767314 | level_packs = [
("one", ["intro", "level0", "level1", "level3", "level35", "level5"]),
("two", ["level33", "level20", "level19", "level21", "level18", "level16"]),
("three", ["level2", "level14", "level6", "level25", "level32", "level8"]),
("four", ["level15", "level10", "level22", "level12", "level4", ... |
1767319 | import json
import threading
import unittest
import onedrivesdk
from onedrived import get_resource, od_webhook
from tests.test_repo import get_sample_repo
class TestWebhookWorker(unittest.TestCase):
def setUp(self):
self.temp_config_dir, self.temp_repo_dir, self.drive_config, self.repo = get_sample_re... |
1767335 | import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from tqdm import tqdm
from utils.utils_metrics import evaluate
def get_lr(optimizer):
for param_group in optimizer.param_groups:
return param_group['lr']
def fit_one_epoch(model_train, model, loss_history,... |
1767343 | from __future__ import absolute_import, unicode_literals
import pytest
import logging
from psd_tools.api.psd_image import PSDImage
from psd_tools.api.shape import (
Rectangle, RoundedRectangle, Ellipse, Line, Invalidated
)
from ..utils import full_name
logger = logging.getLogger(__name__)
VECTOR_MASK2 = PSDImag... |
1767353 | from setuptools import find_packages, setup
setup(
name="pychallonge_async",
description="Module to manage Challonge tournaments within an async context",
author="<NAME> (fp12)",
author_email="<EMAIL>",
packages=find_packages(),
url="http://github.com/fp12/pychallonge_async",
version="1.0.0... |
1767354 | from vulnscan_parser.models.vshost import VSHost
class NessusHost(VSHost):
def __init__(self):
super().__init__()
self.ignored_dict_props.append('name')
self.plugins = set()
|
1767403 | from unittest import mock
import unittest
import os
import shutil
import zipfile
from datetime import datetime, timezone
from base64 import b64decode
from webscrapbook import WSB_DIR
from webscrapbook import util
from webscrapbook.scrapbook.host import Host
from webscrapbook.scrapbook.check import BookChecker
root_di... |
1767428 | from flask import Flask, request
from flask_restful import Resource, Api
import base64
app = Flask(__name__)
api = Api(app)
class ClassName(Resource):
# @jwt_required()
def post(self):
#get input parameters from POST request in json format
req_data = request.get_json()
# return out... |
1767433 | from argparse import ArgumentParser
import unicodecsv as csv
import os
import StringIO
from utility.pytskutil import TSKUtil
import olefile
REPORT_COLS = ['note_id', 'created', 'modified', 'note_text', 'note_file']
def main(evidence, image_type, report_folder):
tsk_util = TSKUtil(evidence, image_type)
note_... |
1767442 | from django.db import models
from django.conf import settings
from django.utils.translation import gettext_lazy as _
from cms.models.pluginmodel import CMSPlugin
from cms.models.fields import PageField
import logging
# Define logger for this file
logger = logging.getLogger(__name__)
class PayAtDoorFormModel(CMSPlu... |
1767481 | import unittest
import subprocess
import os
import sys
import re
_container_image=None
class TestGPUSupport(unittest.TestCase):
"""
These tests verify that the GPU resources and configurations (device files,
libraries and value of LD_LIBRARY_PATH) are correctly set inside the container.
"""
_GPU... |
1767577 | from main import metrics
@metrics.summary('test_by_status', 'Test Request latencies by status', labels={
'code': lambda r: r.status_code
})
def test() -> dict:
return {'version': 'Test version'}
@metrics.content_type('text/plain')
@metrics.counter('test_plain', 'Counter for plain responses')
def plain() -> ... |
1767588 | import sys
import json
from sklearn import preprocessing
from sklearn import feature_extraction
from iologreg import IOLogisticRegression
features = []
labels = {}
invlabels = {}
# read labels and associated features
for line in open(sys.argv[1]):
(label, f) = line.strip().split('\t')
invlabels[len(labels)] = labe... |
1767604 | from comtypes.gen import _C866CA3A_32F7_11D2_9602_00C04F8EE628_0_5_4
globals().update(_C866CA3A_32F7_11D2_9602_00C04F8EE628_0_5_4.__dict__)
__name__ = 'comtypes.gen.SpeechLib' |
1767607 | import re
with open("README.md", "r", encoding="utf-8") as f:
text = f.read()
content = re.search("## Contents(.*?)##", text, flags = re.M|re.S).group()
libraries = re.findall("\[``(.*?)``\]", content)
for library in libraries:
detail = re.search(f"## {library}", text)
if not detail:
... |
1767631 | import pytest
import sys
import time
import ray
from ray.exceptions import RuntimeEnvSetupError
from ray.runtime_env import RuntimeEnv, RuntimeEnvConfig
bad_runtime_env_cache_ttl_seconds = 10
@pytest.mark.skipif(
sys.platform == "win32", reason="conda in runtime_env unsupported on Windows."
)
@pytest.mark.para... |
1767637 | import numpy as np
def writeFFDFile(fileName, nBlocks, nx, ny, nz, points):
"""
Take in a set of points and write the plot 3dFile
"""
f = open(fileName, "w")
f.write("%d\n" % nBlocks)
for i in range(nBlocks):
f.write("%d %d %d " % (nx[i], ny[i], nz[i]))
# end
f.write("\n")
... |
1767673 | def _lein_repository(repository_ctx):
java = _check_jdk(repository_ctx)
url = "https://raw.githubusercontent.com/technomancy/leiningen/%s/bin/lein" % (repository_ctx.attr.version,)
repository_ctx.download(
url = url,
output = "home/lein.sh.in",
sha256 = repository_ctx.attr.sha256,
... |
1767675 | from configobj import ConfigObj
class Settings(object):
def __init__(self):
self.conf = ConfigObj('config/config.ini')
def getValue(self, key):
try:
return self.conf[key]
except KeyError:
return None
def setValue(self, key, value):
... |
1767687 | from django.test import TestCase
from drynk import with_natural_key
from drynk.tests.models import (
TestModel1,
TestModel2,
TestModel3,
Category1,
Widget1,
Category2,
Widget2,
SubWidget)
class SanityTests(TestCase):
def test_reality(self):
"""
Make sure nothing b... |
1767920 | import _plotly_utils.basevalidators
class BoxValidator(_plotly_utils.basevalidators.CompoundValidator):
def __init__(self, plotly_name='box', parent_name='violin', **kwargs):
super(BoxValidator, self).__init__(
plotly_name=plotly_name,
parent_name=parent_name,
data_cla... |
1767923 | import pytest
from jina import Document
from .pages import Pages
from .utils.benchmark import benchmark_time
@pytest.mark.parametrize("num_docs", [100, 1000, 10_000])
def test_document_document_matches(num_docs, json_writer):
def _input_docs():
doc = Document(text="d1")
doc.matches = [Document(te... |
1767933 | from django.apps import apps
from django.core.exceptions import FieldDoesNotExist, ImproperlyConfigured
from django.db.models import Manager
from .conf import get_available_languages, get_default_language
from .fields import TranslationField, translated_field_factory
from .manager import MultilingualManager, transform... |
1767975 | import sklearn.neural_network
from autotabular.pipeline.components.regression.mlp import MLPRegressor
from .test_base import BaseRegressionComponentTest
class MLPComponentTest(BaseRegressionComponentTest):
__test__ = True
res = dict()
res['default_boston'] = 0.3622815479003514
res['default_boston_p... |
1767980 | import urizen.visualizers.vg_pillow
from urizen.visualizers.vg_pillow import vg_pillow_pixelated
import urizen.visualizers.vg_tiled
from urizen.visualizers.vg_tiled import vg_tiled |
1768050 | from __future__ import absolute_import
# getting all links example crawling jamescampbell.us
# author: <NAME>
# Date Created: 2015 05 22
# Date Updated: 2 July 2019
import argparse
from scrapy.spiders import CrawlSpider, Rule
from scrapy.linkextractors.lxmlhtml import LxmlLinkExtractor
from scrapy.item import Item, Fie... |
1768073 | import models
from fewshot_re_kit.data_loader import JSONFileDataLoader
from fewshot_re_kit.framework import FewShotREFramework
from fewshot_re_kit.sentence_encoder import CNNSentenceEncoder
from models.proto import Proto
from models.proto_hatt import ProtoHATT
import sys
model_name = 'proto_hatt'
N = 5
K = 5
noise_r... |
1768109 | import os
import hashlib
import numpy as np
from pybullet_envs import env_bases
from pybullet_envs import scene_abstract
from d4rl.pointmaze_bullet import bullet_robot
from d4rl.pointmaze import maze_model
from d4rl import offline_env
class MazeRobot(bullet_robot.MJCFBasedRobot):
def __init__(self, maze_spec):
... |
1768132 | from flask import Flask
def teardown_appcontext_middleware(app: Flask):
app.teardown_appcontext_funcs = [
# add middleware functions here
]
|
1768156 | from ..base import order as od
from .websocket import GmocoinWebsocketPrivate
from .api import GmocoinApi
from ..etc.util import unix_time_from_ISO8601Z
class GmocoinOrderManager(od.OrderManagerBase):
WebsocketPrivate = GmocoinWebsocketPrivate
def __init__(self, api, ws=None, retention=60):
wspr = se... |
1768229 | from typing import Any, Dict, Optional, Type
from abc import ABC
from datetime import datetime
from bson import ObjectId
from bson.objectid import InvalidId
from pydantic import BaseConfig, BaseModel
class OID:
@classmethod
def __get_validators__(cls):
yield cls.validate
@classmethod
def va... |
1768239 | from abc import ABC, abstractmethod
from typing import Any
import torch
import torch.nn as nn
from torch import Tensor
from .functions import *
# This is a work-in-progress attempt to use type aliases to indicate the shapes of tensors.
# T = 50 (TBTT length)
# B = 50 (batch size)
# I = 1/3/10 (IW... |
1768251 | import logging
import raco.rules
from raco import algebra
from raco.scheme import Scheme
from raco.backends import Language, Algebra
from raco.expression import UnnamedAttributeRef, \
NamedAttributeRef, \
AttributeRef
LOGGER = logging.getLogger(__name__)
# for gensym
counter = 0
class SPARQLLanguage(Langu... |
1768276 | from django.utils.translation import ugettext_noop as _
class LangMixin(object):
@property
def lang(self):
lang = self.request.GET.get('lang', 'en')
return str(lang) if lang else 'en'
from custom.up_nrhm.reports.asha_reports import ASHAReports
CUSTOM_REPORTS = (
(_('Custom Reports'), (
... |
1768293 | from typing import List, Optional, Callable
import numpy as np
import torch
import torch.nn as nn
import pytorch_lightning as pl
from pytorch_lightning.loggers import WandbLogger
from pytorch_lightning.utilities import rank_zero_only
import hydra
from omegaconf import OmegaConf, DictConfig
import src.utils as utils
im... |
1768295 | def containsAny(str, set):
"""Check whether 'str' contains ANY of the chars in 'set'"""
return 1 in [c in str for c in set]
def containsAll(str, set):
"""Check whether 'str' contains ALL of the chars in 'set'"""
return 0 not in [c in str for c in set]
if __name__ == "__main__":
# unit tests, must ... |
1768310 | import asyncio
from io import BytesIO
import pytest
from scrapli.exceptions import ScrapliConnectionNotOpened, ScrapliTimeout
def test_handle_control_characters_response_empty_control_buf_iac(asynctelnet_transport):
asynctelnet_transport.stdin = BytesIO()
actual_control_buf = asynctelnet_transport._handle_c... |
1768325 | import contextlib
import os
import shutil
import subprocess
import sys
import tempfile
import urllib.request
import xml.etree.ElementTree as ET
"""Fetch and install missing Mikero's tools"""
toms_depot = 'http://tom4897.info/app/tools/community/'
disk_location = r'C:\Program Files (x86)\Mikero\DePboTools\bin' + '\\'
... |
1768389 | from test_include import *
import numpy as np
'''
# of queries: 5, number of bins in ISOMER: 7
# of queries: 10, number of bins in ISOMER: 30
# of queries: 15, number of bins in ISOMER: 80
# of queries: 20, number of bins in ISOMER: 203
# of queries: 25, number of bins in ISOMER: 603
# of queries: 30, number of bins i... |
1768399 | from geopy import Nominatim
from geopy.distance import geodesic
from src.config import MAPS_DISTANCES_LIST
from src.helper import log
_geo_locator = Nominatim()
def filter_by_around(coordinates_dict, latitude, longitude):
# Compute distance
distance_dict = dict()
current_coordinates = (latitude, longit... |
1768440 | import boto3
from botocore.exceptions import ClientError
import logging
from django.conf import settings
logger = logging.getLogger('django')
SENDER = '<NAME> <<EMAIL>>'
AWS_REGION = 'us-east-1'
CHARSET = 'UTF-8'
client = boto3.client('ses', region_name=AWS_REGION)
def send_email(receiver, subject, html):
if ... |
1768473 | from flask import Flask, render_template, request
#declare the app
app = Flask(__name__)
#start an app route
@app.route('/')
#declare the main function
def main():
return render_template('index.html')
#form submission route
@app.route('/send', methods=['POST'])
def send():
try:
if request.method == ... |
1768502 | import numpy as np
from pyemto.examples.emto_input_generator import *
folder = os.getcwd() # Get current working directory.
emtopath = folder+"/bcc_fcc_ssos" # Folder where the calculations will be performed.
latpath = emtopath
# bcc SSOS-1
prims = np.array([[0.0,2.0,3.0],
[-0.5,2.5,... |
1768520 | import pyb
# This script is intended to be installed as boot.py. It will flash the
# Red LED for 2 seconds. If you press the USR switch during those 2
# seconds then it will cycle between the blue, yellow, and green LEDs to
# allow the USB mode to b eslected.
#
# Blue - CDC+MSC
# Yellow - CDC+HID
# Green - CDC only... |
1768542 | import os
import unittest
from new_zealand import new_zealand
# import new_zealand
from pprint import pprint
_SOURCE_ID = "placeholder_ID"
_SOURCE_URL = "placeholder_URL"
_caseReference = {"sourceId": "placeholder_ID", "sourceUrl": "placeholder_URL"}
_NZ = {
"country": "New Zealand",
"name": "New Zealand",
... |
1768553 | import argparse
from typing import Callable
import tensorflow as tf
import tensorflow_addons as tfa
from dataset import load, Split
from nfnet import NFNet, nfnet_params
NUM_CLASSES = 1000
NUM_IMAGES = 1281167
def parse_args():
"""Parse command line arguments."""
ap = argparse.ArgumentParser()
ap.add_... |
1768576 | from msi_recal.math import ppm_to_sigma_1
# This file is WIP
def test_ppm_to_sigma_1_tof():
assert ppm_to_sigma_1(1, "tof", 1) == 1e-6
assert ppm_to_sigma_1(2, "tof", 1) == 2e-6
assert ppm_to_sigma_1(2, "tof", 4) == 2.5e-7
def test_ppm_to_sigma_1_orbitrap():
assert ppm_to_sigma_1(1, "orbitrap", 200... |
1768604 | from py_algorithms.strings import new_boyer_moore_find
class TestBoyerMooreFind:
def test_correct_substring(self):
string = "zasallaerer"
substring = string[3:8]
algo = new_boyer_moore_find()
assert algo(string, substring) == 3
def test_null_substring(self):
string = "... |
1768621 | from py4j.java_gateway import JavaGateway, launch_gateway, GatewayParameters, CallbackServerParameters, get_field
import sys, os, glob
def find_jar_path():
# assume the jar is bundled with python egg
current_dir = os.path.dirname(os.path.realpath(__file__))
search = [
current_dir,
os.path.... |
1768634 | import grpc
from controller.array_action import errors as array_errors
from controller.array_action.config import REPLICATION_DEFAULT_COPY_TYPE
from controller.array_action.storage_agent import get_agent
from controller.common.csi_logger import get_stdout_logger
from controller.common.utils import set_current_thread_n... |
1768643 | class Policy(object):
def __init__(self, policy_lambda):
self.policy_lambda = policy_lambda
def get_action(self, state):
return self.policy_lambda(state)
|
1768647 | from Bio.SubsMat import MatrixInfo
from Bio.Alphabet import IUPAC
from collections import OrderedDict
import numpy as np
import pandas as pd
import re
import os
import pickle
def Embed_Seq_Num(seq,aa_idx,maxlength):
seq_embed = np.zeros((1, maxlength)).astype('int64')
if seq != 'null':
n = 0
fo... |
1768651 | import logging
import pandas as pd
from zenml.steps import step
class IngestData:
"""
Data ingestion class which ingests data from the source and returns a DataFrame.
"""
def __init__(self) -> None:
"""Initialize the data ingestion class."""
pass
def get_data(self... |
1768676 | import unittest
from pprint import pprint
from vit.list_batcher import ListBatcher
DEFAULT_BATCH_FROM = list('abcdefghijklmnopqrstuvwxyz')
def default_batcher():
batch_to = []
return ListBatcher(DEFAULT_BATCH_FROM, batch_to), batch_to
class TestListBatcher(unittest.TestCase):
def test_batch_default_bat... |
1768693 | import os
import tqdm
import torch
import importlib
import numpy as np
from trainers.base_trainer import BaseTrainer
from trainers.utils.loss_utils import *
from evaluation.evaluation_metrics import *
class Trainer(BaseTrainer):
def __init__(self, cfg, args):
self.cfg = cfg
self.args = args
... |
1768704 | import warnings
import numpy as np
from ..data import units
from ..computation import Transformer, Graph
from .util import apply, apply_to_axis
from ..computation.nodes import Add, Subtract, Multiply, Divide, Constant
from .queries import Slice
__all__ = [
'Add',
'Subtract',
'Multiply',
'Divide',
... |
1768705 | from .babel import * # noqa
from .base import * # noqa
from .coffeescript import * # noqa
from .handlebars import * # noqa
from .less import * # noqa
from .livescript import * # noqa
from .scss import * # noqa
from .stylus import * # noqa
|
1768769 | import logging
import multiprocessing
import random
import signal
import time
import unittest
from coapthon.client.helperclient import HelperClient
from Entity.attack import Attack
from Entity.input_format import InputFormat
from protocols import CoAP as PeniotCoAP
class CoAPPayloadSizeFuzzerAttack(Attack):
"""... |
1768845 | import sys
IS_PY_2 = sys.version_info.major < 3
def textureFileString(path):
if IS_PY_2:
return path.encode('utf-8', 'strict')
return path |
1768885 | import sys
import typing
# workaround for old CPython bug
# https://github.com/pfnet/pfio/issues/28
if sys.version_info < (3, 5, 3):
class DummyOptional(object):
def __getitem__(self, *args, **kwargs):
return typing.Any
Optional = DummyOptional()
class DummyUnion(object):
de... |
1768934 | exception_handler_params = [
(404, "The resource cannot be found."),
(407, "Proxy Error - cannot connect to proxy. Either try clearing the 'Use system proxy' check-box or"
"check the host, authentication details and connection details for the proxy."),
(500, "The server encountered an internal err... |
1768936 | from __future__ import division, print_function, absolute_import
import numpy as np
# Expansion of polar term
aij = np.array([[0.3043504, 0.9534641, -1.1610080],
[-0.1358588, -1.8396383, 4.5258607],
[1.4493329, 2.0131180, 0.9751222],
[0.3556977, -7.3724958, -12.281038],
... |
1768955 | import json
import os
from argparse import ArgumentParser
from glob import glob
import jsonschema
import ruamel.yaml as yaml
def validate_spec(fpath_spec, fpath_schema):
"""
Validate a yaml specification file against the json schema file that
defines the specification language. Can be used to validate ch... |
1768971 | from .__init__ import *
def gen_func(maxPrinciple=10000,
maxRate=10,
maxTime=10,
format='string'):
p = random.randint(1000, maxPrinciple)
r = random.randint(1, maxRate)
n = random.randint(1, maxTime)
a = round(p * (1 + r / 100)**n, 2)
if format == 'string':
... |
1768976 | from RFEM.initModel import Model, GetAddonStatus
from RFEM.enums import AddOn
class MeshSettings():
ComonMeshConfig: dict = {
'general_target_length_of_fe': None,
'general_maximum_distance_between_node_and_line': None,
'general_maximum_number_of_mesh_nodes': None,
'members_number_of... |
1769040 | import pathlib
import pytest
from mkdocs.structure.files import File, Files
from mkdocs_literate_nav import exceptions, plugin
@pytest.mark.golden_test("nav/**/*.yml")
def test_nav(tmp_path_factory, golden):
src_dir, dest_dir = map(tmp_path_factory.mktemp, ["src", "dest"])
files = []
for fn, content in... |
1769094 | from utils import colors
# Segments colors.
USERATHOST_BG = colors.BLUEISH
USERATHOST_FG = colors.WHITE
SSH_BG = colors.LIGHT_ORANGE
SSH_FG = colors.WHITE
CURRENTDIR_BG = colors.MID_GREY
CURRENTDIR_FG = colors.LIGHT_GREY
READONLY_BG = colors.LIGHT_GREY
READONLY_FG = colors.RED
EXITCODE_BG = colors.RED
EXITCODE_FG... |
1769095 | import unittest
from propnet.core.registry import Registry
class RegistryTest(unittest.TestCase):
def test_basic_registry(self):
test_reg = Registry("test")
test_reg2 = Registry("test")
test_reg3 = Registry("test2")
self.assertIsInstance(test_reg, dict)
self.assertTrue(te... |
1769096 | from paraview.simple import *
# Load the distributed plugin.
LoadDistributedPlugin("VTKmFilters" , ns=globals())
# Now use a filter from that plugin.
# We don't really care if the filter works correctly in this test,
# we're just verifying that the plugin can be loaded correctly.
Wavelet()
UpdatePipeline()
VTKmContou... |
1769101 | from dataiku.runnables import Runnable
import dataiku
import urllib2, sys
import requests
import json
import os
import dl_image_toolbox_utils as utils
import pandas as pd
import constants
import time
# We deactivate GPU for this script, because all the methods only need to
# fetch information about model and do not m... |
1769102 | import torch
from torch import cuda
from torch.nn import parallel
def get_device(device='auto'):
if device == 'auto':
if cuda.is_available():
device = torch.device('cuda')
else:
device = torch.device('cpu')
else:
device = torch.device(device)
return device
... |
1769121 | import sys
import pysam
if len(sys.argv) != 6:
sys.exit('Usage: python sc_atac_window_counter.py [Input Bam file] [Input Index table] [Window BED] [Output file] [Include sites with no reads? (True/False)]')
inbam = sys.argv[1]
indextable = sys.argv[2]
type1bed = sys.argv[3]
outfile = sys.argv[4]
includezeroes = sys.... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.