id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9923387 | import os
import sys
import re
import types
import itertools
from CGATReport.Tracker import *
from collections OrderedDict as odict
from RnaseqTranscriptsReport import *
import numpy
class TrackerGeneCounts(RnaseqTranscriptsTracker):
'''tracker with gene counts.'''
pattern = "(\S+)_gene_counts$"
class T... |
9923420 | from .construction import BuildDialogues
from .download import DownloadRawFile
from .filtering import FilterRawSubmissions, FilterRawComments
from .packaging import ZipDataset
from .sampling import SampleDialogues
__all__ = [BuildDialogues, DownloadRawFile, FilterRawSubmissions, FilterRawComments, ZipDataset, SampleDi... |
9923440 | import unittest
import random
import string
import functools
import sys
from python_unit_test import Serialize, Deserialize, Marshal, Unmarshal, GetRuntimeSchema
import python_unit_test as test
def atleast_python3():
return sys.version_info[0] >= 3
def random_string():
return ''.join(random.sample(string.asci... |
9923452 | import pytest
from simobility.core import GeographicPosition
def test_position():
p1 = GeographicPosition(-0.39276123046875, 39.444147324430396)
p2 = GeographicPosition(-0.3577423095703125, 39.50404070558415)
assert pytest.approx(p1.distance(p2), 0.2) == 7.31
assert p1.distance(p2) == p2.distance(p1)... |
9923472 | import torch
import numpy as np
import cv2
class Activations():
def __init__(self, target_layer, target_layer_names):
self.target_layer = target_layer
self.target_layer_names = target_layer_names
def __call__(self, in_out):
outputs = []
for name, module in self.target_layer._m... |
9923485 | import warnings
from .std import TqdmExperimentalWarning
with warnings.catch_warnings():
warnings.simplefilter("ignore", category=TqdmExperimentalWarning)
from .autonotebook import tqdm, trange
__all__ = ["tqdm", "trange"]
|
9923513 | import onnx
import onnx_graphsurgeon as gs
import sclblonnx as so
H=192
W=640
MODEL1=f'lite_hr_depth_k_t_encoder_{H}x{W}.onnx'
MODEL2=f'lite_hr_depth_k_t_depth_{H}x{W}.onnx'
MODEL3=f'lite_hr_depth_k_t_encoder_depth_{H}x{W}.onnx'
graph1 = gs.import_onnx(onnx.load(MODEL1))
for n in graph1.nodes:
for cn in n.inputs:... |
9923517 | from ctypes import *
import math
import random
import os
import cv2
import numpy as np
import time
import darknet
import argparse
# !python darknet_video -v -c -w
# augument parser
ap = argparse.ArgumentParser()
ap.add_argument("-v" ,"--video", type=str, required=True,
help="Path to input video")
ap.... |
9923560 | import threading
import time
import logging
logger = logging.getLogger('KingPhisher.Plugins.SFTPClient.tasks')
class TaskQueue(object):
"""
Task queue used for transfer tasks that handles thread and task management
in a way to prevent errors.
"""
def __init__(self):
self.mutex = threading.RLock()
self.not_em... |
9923598 | import random
from os import path
import pytest
import subprocess
import time
import common.cmd as cmd
from common.core import ( # NOQA
open_replica, cleanup_controller, cleanup_replica,
get_dev, get_blockdev, verify_read, verify_data,
random_string,
cleanup_replica_dir,
create_backup, rm_backups,... |
9923610 | import sys
sys.path.append('..')
import torch
import torch.nn as nn
import torch.nn.functional as F
import torch.optim as optim
import dgl
import dgl.function as fn
from dgl.data import MiniGCDataset
from bijou.data import DGLDataLoader, DataBunch
from bijou.callbacks import DGLInterpreter
from bijou.metrics import ac... |
9923614 | from __future__ import print_function
# import
## batteries
import os
import sys
import argparse
import functools
from itertools import product,cycle
## 3rd party
import numpy as np
import pandas as pd
## package
from pyTecanFluent import Utils
from pyTecanFluent import Fluent
from pyTecanFluent import Labware
# func... |
9923619 | import os
import numpy
import moderngl
import moderngl_window
from moderngl_window.conf import settings
from moderngl_window.resources import programs
from moderngl_window.meta import ProgramDescription
settings.PROGRAM_DIRS.append(os.path.join(os.path.dirname(__file__), "programs"))
class MeshProgram:
"""
... |
9923663 | import json
import os
class PackageTranslator:
"""The PackageTranslator creates working modules out of the metacode files."""
def __init__(self, package_dir):
self.module_name_separator = '___'
self.package_name = os.path.basename(package_dir)
f = open(package_dir+'/'+self.package_n... |
9923665 | import sys
print "\n"
print "python | changeSAMmapQ.py | Input.sam | Output.sam"
print "\n"
fi=open(sys.argv[1])
fo=open(sys.argv[2],'w')
for line in fi:
seq=line.rstrip().split('\t')
if len(seq)>10:
seq[4]='30'
fo.write('\t'.join(seq)+'\n')
else:
fo.write(line)
|
9923690 | from .test import BaseTest
try:
# python3
from urllib.request import Request, urlopen, HTTPError
except ImportError:
# fall back to python2
from urllib2 import Request, urlopen, HTTPError
class Test_Jsonld(BaseTest):
label = 'JSON-LD Media Type'
level = 1
category = 7
versions = [u'2.0'... |
9923701 | import unittest
from pybacklogpy.BacklogConfigure import BacklogComConfigure
class Test(unittest.TestCase):
def test_config(self):
_ = BacklogComConfigure(space_key='kitadakyou',
api_key='dummy_api_key')
self.assertTrue(True, msg='プログラムからのspaceid, apikey の設定に失敗')
... |
9923708 | def perturb_text(s: str, sentence: str):
perturbed_texts = []
desc = sentence
# case1:
if desc.__contains__("ARGM-COM") and desc.__contains__("ARGM-TMP"):
perturbed_texts.append(exchange_args(s, desc, "ARGM-COM", "ARGM-TMP"))
# case2:
if (
desc.__contains__("ARG0")
and ... |
9923737 | import setuptools
# get long description
with open("README.md", "r") as fh:
long_description = fh.read()
exec(open('sclblonnx/version.py').read())
setuptools.setup(
name="sclblonnx",
version=__version__,
author="<NAME>",
author_email="<EMAIL>",
description="Python package containing Scailable... |
9923758 | from __future__ import print_function, division
import os
import argparse
from torch.utils.data import DataLoader
from model.cnn_geometric_model import CNNGeometric
from data.pf_dataset import PFDataset
from data.download_datasets import download_PF_willow
from image.normalization import NormalizeImageDict, normalize_i... |
9923760 | from slugify import slugify
class HitchStoryException(Exception):
pass
class CannotMixKeywordArgs(HitchStoryException):
"""
**kwargs and regular args cannot be mixed in story step methods.
"""
pass
class CannotUseVarargs(HitchStoryException):
"""
*args is not usable in step method.
... |
9923767 | from math import floor
import operator
from operator import attrgetter
from renpy import store
from .actions import * # NOQA: F403
from .labels import Labels
from .entry_sorting import push_locked_to_bottom
from .eventemitter import EventEmitter
class Encyclopaedia(EventEmitter, store.object):
"""... |
9923779 | import torch
from torch.nn.utils.rnn import pad_sequence
def combine_batches(batches, bars_per_sequence=8, description_flavor='none', device=None):
if device is None:
device = batches[0]['input_ids'].device
batch_size = batches[0]['input_ids'].size(0)
zero = torch.zeros(1, device=device, dtype=torch.int)
... |
9923796 | import numpy as np
arr = np.random.randn(5, 2)
print(arr)
first, second, third = np.split(arr, [1, 3]) # [1,3] is index for spliting
print(first)
print(second)
print(third)
'''
[[-0.70076809 -2.36798352]
[ 0.75375456 0.66272309]
[-1.71648405 -1.00858617]
[-0.56885428 0.21669237]
[-0.27057993 -0.05... |
9923810 | class Prod:
def __init__(self, value):
self.value = value
def __call__(self, other):
return self.value * other
x = Prod(2)
print x(3)
print x(4) |
9923813 | import io
import os
import re
from ast import literal_eval
from typing import Any
RE_TPL_VAR = re.compile('(\${([^}]+)})')
def cast_type(value: str) -> Any:
"""Try to cast value into Python native type.
Returns non casted on errors.
:param value:
"""
result = value
try:
result = l... |
9923830 | from torch import nn
from jcopdl.layers import conv_block, linear_block
class CNN(nn.Module):
def __init__(self):
super().__init__()
self.conv = nn.Sequential(
conv_block(3, 8),
conv_block(8, 16),
conv_block(16, 32),
conv_block(32, 64),
... |
9923831 | from django.apps import AppConfig
class SqlDbAppConfig(AppConfig):
name = 'corehq.sql_db'
def ready(self):
from corehq.sql_db import ( # noqa: F401
check_db_tables,
check_standby_configs,
check_standby_databases,
custom_db_checks
)
|
9923834 | from tests import utils
import bpy
class TestOgf(utils.XRayTestCase):
def test_import_general(self):
bpy.ops.xray_import.ogf(
directory=self.relpath(),
files=[{'name': 'test_fmt_ogf_st.ogf'}],
)
bpy.ops.xray_import.ogf(
directory=self.relpath(),
... |
9923846 | import numpy as np
mtx = np.mat('621.11352456 0. 327.39163094; 0. 620.88453231 232.87088353; 0. 0. 1.')
dist = np.array([ 0.13589782, -0.4714084, -0.00517676, 0.00815842, 1.22439717]) |
9923852 | from test_base import BaseTestCase
import unittest
import flask_testing
class TestRaisApiTests(BaseTestCase):
def test_should_respond_ok_to_rais_path(self):
response = self.client.get('/rais/year/')
self.assert_200(response)
def test_should_check_if_all_years_are_loaded(self):
respon... |
9923914 | from django.conf.urls import url
from django.views.generic.base import TemplateView
urlpatterns = [
url(
'^scss-file/$',
TemplateView.as_view(template_name='app/template-with-scss-file.html'),
name='scss-file'
),
url(
'^scss-inline/$',
TemplateView.as_view(template_... |
9923936 | import re
import sys
from ..reporter_demo import Candidate, Requirement
from .generate import generate_html
from .reporter import GraphGeneratingReporter
def process_arguments(function, args):
function_arg_info = {
"starting": [],
"starting_round": [int],
"ending_round": [int, ...],
... |
9923943 | import json
import unittest
from unittest import mock
from tests.fixtures import Fixtures
from awsxenos.scan import Scan
from awsxenos.report import Report
class ReportTests(unittest.TestCase):
@mock.patch("awsxenos.scan.Scan.get_bucket_acls", return_value=Fixtures.mock_get_bucket_acl())
@mock.patch("awsxen... |
9924024 | import pandas as pd
def research(series, length=3):
"""
The feature which is also used in the research paper by <NAME> al.
Args:
series (pandas.Series): Series of the Google Trends data.
length (int, optional): Length of the moving average used in the
calculation. Defaults to ... |
9924038 | import json
import os
from nltk.tokenize import wordpunct_tokenize
with open(os.path.join('testdata', 'treebank_sents.json')) as d:
data = json.load(d)
words = []
for s in data:
words.append(wordpunct_tokenize(s))
with open(os.path.join('testdata', 'word_punct.json'), 'w') as f:
json.dump(words, f, inde... |
9924055 | import click
import pandas as pd
import matplotlib.pyplot as plt
@click.command()
@click.option("--csv", default="result.csv")
def main(csv):
df = pd.read_csv(csv, index_col="second")
df.drop(["agressiveAvgFlying", "bothAvgFlying"], axis=1, inplace=True)
df.plot()
plt.show()
if __name__ == "__main__":... |
9924073 | import paddle
import numpy as np
from ppcuop.ctc_decoder import CTCDecoder
class SeqAcc(paddle.metric.Metric):
def __init__(self, blank=0, *args, **kwargs):
super(SeqAcc, self).__init__()
self.blank = blank
self.match_true_num = 0
self.match_label_num = 0
self.include_true... |
9924086 | import cv2
import numpy as np
import torch
import torch.nn as nn
import math
class YoloLoss(nn.Module):
def __init__(self, input_shape, classes, branch_num, anchor, batch_size, loss_type='diou'):
super().__init__()
self.input_shape = input_shape
self.classes = classes
self.branch_n... |
9924104 | import json
import os
from pbpstats import NBA_STRING, G_LEAGUE_STRING
from pbpstats.data_loader.stats_nba.web_loader import StatsNbaWebLoader
class StatsNbaGameFinderWebLoader(StatsNbaWebLoader):
"""
A ``StatsNbaGameFinderWebLoader`` object should be instantiated and passed into ``StatsNbaGameFinderLoader`... |
9924112 | from django_x509.apps import DjangoX509Config
class SampleX509Config(DjangoX509Config):
name = 'sample_x509'
verbose_name = 'sample_x509'
|
9924154 | from mermaid_demos.rdmm_synth_data_generation.create_poly import Poly
import numpy as np
class Triangle(Poly):
def __init__(self, setting,scale=1.):
name, img_sz, center_pos, height, width, rotation =setting['name'], setting['img_sz'], setting['center_pos'], setting['height'], setting['width'], setting['ro... |
9924155 | from autobahn.twisted.websocket import ConnectionDeny
from twisted.internet import defer, task
from twisted.trial.unittest import TestCase
from ..ws import ASGIWebSocketServerFactory, ASGIWebSocketServerProtocol
from .utils import DummyApplication
class DummyASGIWebSocketServerProtocol(ASGIWebSocketServerProtocol):... |
9924262 | import pytest
from pretalx.common.plugins import get_all_plugins
from tests.dummy_app import PluginApp
@pytest.mark.django_db
def test_get_all_plugins():
assert PluginApp.PretalxPluginMeta in get_all_plugins(), get_all_plugins()
@pytest.mark.django_db
@pytest.mark.parametrize(
"event,expected", ((None, Tru... |
9924271 | import re
from django.core.exceptions import ValidationError
from django.test import SimpleTestCase
from testil import assert_raises
from corehq.apps.registry.schema import REGISTRY_JSON_SCHEMA
from corehq.util.test_utils import generate_cases
from corehq.util.validation import JSONSchemaValidator
class RegistrySch... |
9924310 | import random
import os
from alttprbot.tournament.core import TournamentConfig
from alttprbot_discord.bot import discordbot
from .sglcore import SGLRandomizerTournamentRace
class Z2R(SGLRandomizerTournamentRace):
async def configuration(self):
guild = discordbot.get_guild(590331405624410116)
retu... |
9924314 | from will.plugin import WillPlugin
from will.decorators import respond_to, periodic, hear, randomly, route, rendered_template, require_settings
from will import settings
import datetime
import pygerduty
class PagerDutyPlugin(WillPlugin):
@staticmethod
def _associate_pd_user(email_address, pager):
tr... |
9924328 | import os
import adafruit_sdcard
import board
import busio
import digitalio
import storage
# Use any pin that is not taken by SPI
SD_CS = board.D0
# Connect to the card and mount the filesystem.
spi = busio.SPI(board.SCK, board.MOSI, board.MISO)
cs = digitalio.DigitalInOut(SD_CS)
sdcard = adafruit_sdcard.SDCard(spi,... |
9924335 | import asyncio
import logging
import struct
from ...inputs import LinearActuator
from .udp_input import UdpInput
class UdpActuator(LinearActuator, UdpInput):
"""Class for udp-controlled actuator.
:param cmd: udp byte that identifies the control id
:type cmd: int
:param multiplier: multiplier of the ... |
9924354 | import tools
import torch
a = torch.randn(1,6).cuda()
b = tools.stereographic_project(a)
c = tools.stereographic_unproject(b)
print (tools.normalize_vector(a))
print (tools.normalize_vector(b))
print (tools.normalize_vector(c)) |
9924357 | from youtube2notion.youtube_subtitle import SubtitleElement
class Markdown:
@classmethod
def generate(cls, title: str, subtitle_elements: list[SubtitleElement],
images_dir: str) -> str:
md = ''
md += '# ' + title + '\n'
md += '\n'
for element in subtitle_elem... |
9924363 | import numpy as np
from nsgt.fft import rfftp, irfftp, fftp, ifftp
import unittest
class TestFFT(unittest.TestCase):
def __init__(self, methodName, n=10000):
super(TestFFT, self).__init__(methodName)
self.n = n
def test_rfft(self):
seq = np.random.random(self.n)
ft = rfftp()
... |
9924414 | import mxnet as mx
from mxnet import nd, init, autograd, gluon
from mxnet.gluon import nn
from mxnet.gluon.data.vision import datasets, transforms
import time
# Device configuration
device = mx.cpu() if len(mx.test_utils.list_gpus()) == 0 else mx.gpu()
print ('current ctx =>', device)
# Hyper-parameters
num_epochs = ... |
9924433 | import os
import sys
from flask import Flask
sys.path.insert(1, ".")
from flask_discord_interactions import DiscordInteractions
from flask_discord_interactions.context import ApplicationCommandType
app = Flask(__name__)
discord = DiscordInteractions(app)
app.config["DISCORD_CLIENT_ID"] = os.environ["DISCORD_CLIEN... |
9924434 | import logging
import multiprocessing
import os
from datetime import date
import numpy as np
import pandas as pd
from gensim.models.doc2vec import Doc2Vec, TaggedDocument
from keras.layers import Dense, Input
from keras.models import Model, load_model
from scipy.spatial.distance import cosine
from skimage.filters impo... |
9924457 | import tweepy
# Melissa
from melissa import profile
from melissa.tts import tts
WORDS = {'post_tweet': {'groups': ['tweet']}}
def post_tweet(text):
if profile.data['twitter']['consumer_key'] == "xxxx" \
or profile.data['twitter']['consumer_secret'] == "xxxx" \
or profile.data['twitter']... |
9924462 | import plotly.io as pio
import os, sys
atlas_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
reports_dir = os.path.join(atlas_dir, "report")
sys.path.append(os.path.join(atlas_dir, "scripts"))
pio.templates.default = "simple_white"
HTML_PARAMS = dict(
include_plotlyjs=False,
full_html=... |
9924471 | import os
BASEDIR = os.path.abspath(os.path.dirname(__file__))
def full_path(local_file):
return os.path.join(BASEDIR, local_file)
|
9924499 | import IECore
import Gaffer
import GafferArnold
import GafferScene
import imath
import ldtgaffer
class LDTAtttributeRead(GafferScene.SceneNode):
def __init__(self, name="LDTAtttributeRead"):
super(LDTAtttributeRead, self).__init__(name)
self.setName("LDTAtttributeRead")
self["in"] = GafferS... |
9924507 | from unittest import TestCase, mock
from requests import HTTPError, codes
from basketball_reference_web_scraper.client import player_box_scores
from basketball_reference_web_scraper.errors import InvalidDate
from basketball_reference_web_scraper.http_service import HTTPService
class TestPlayerBoxScores(TestCase):
... |
9924589 | from torch import nn
ATTENTION_LINEARS = ["k_proj", "v_proj", "q_proj", "out_proj", "k", "v", "q", "o"]
def replace_layers(model, adapter_class, n_tasks, n_skills, skills, only_attention=True):
for name, module in model.named_children():
if len(list(module.children())) > 0:
replace_... |
9924602 | from unittest import TestCase, mock
import pytest
from pyramid import testing
from pyramid.httpexceptions import HTTPNotFound
from pyramid_restful import pagination
from pyramid_restful.pagination.pagenumber import Paginator, InvalidPage, PageNotAnInteger, EmptyPage, Page
class ValidAdjacentNumsPage(Page):
de... |
9924629 | import logging
import json
from ...processing_instructions import ProcessingInstructions
from abc import ABCMeta, abstractmethod
from typing import Dict, Any, cast, Optional, TYPE_CHECKING
if TYPE_CHECKING:
from ....db import DBDriver # noqa
from mypy_extensions import TypedDict
from pandas import DataFram... |
9924636 | from django.contrib.auth.models import User
from django.core.cache import cache
from django.http import HttpResponseRedirect
from django.utils.deprecation import MiddlewareMixin
class FirstRunRedirect(MiddlewareMixin):
"""
This middleware will redirect all requests to the setup page (not /sms/).
This wil... |
9924643 | import re
from json import JSONDecodeError
from typing import Text, List, Dict, Match, Optional, NamedTuple, Any
import logging
import rasa.shared.nlu.training_data.util
from rasa.shared.constants import DOCS_URL_TRAINING_DATA_NLU
from rasa.shared.exceptions import InvalidEntityFormatException
from rasa.shared.nlu.con... |
9924653 | from django.contrib.contenttypes.models import ContentType
from django.core.management.base import BaseCommand
from home.models import HomePage, BannerIndexPage, FooterIndexPage, SectionIndexPage
class Command(BaseCommand):
def handle(self, *args, **options):
homepage_content_type, __ = ContentType.obje... |
9924741 | import os
import torch
import torch.nn.functional as F
import random
def multilabel_categorical_crossentropy(y_true, y_pred, margin=0., gamma=1.):
"""
y_true: positive=1, negative=0, ignore=-1
"""
y_true = y_true.clamp(-1, 1)
if len(y_pred.shape) > 2:
y_true = y_true.view(y_true.shape[0], 1, 1, -1)
... |
9924758 | from enum import Enum, auto
class Color(Enum):
RED = auto()
BLUE = auto()
print(Color.RED.value)
#> 1
print(Color.BLUE.value)
#> 2
|
9924788 | from __future__ import absolute_import
from .kitti_model_config import kitti_model_config
from .kitti_vgg16_config import kitti_vgg16_config
from .kitti_res50_config import kitti_res50_config
from .kitti_squeezeDet_config import kitti_squeezeDet_config
from .kitti_squeezeDetPlus_config import kitti_squeezeDetPlus_confi... |
9924789 | class Solution:
def maxSlidingWindow(self, arr: List[int], k: int) -> List[int]:
i = 0
j = k-1
out = []
n = len(arr)
if n==0:
return []
if n <= k:
return [max(arr)]
# Create the heap and heapify
heap = arr[i:j + 1]
hea... |
9924800 | import numpy as np
from tqdm import tqdm
from sklearn.model_selection import GroupShuffleSplit
def aa_encoding(adata, read_col, ohe_col=None, label_col=None, length_col=None, pad=False, aa_to_id=None, start_end_symbol=True):
"""
Encoding of protein or nucleotide sequence inplace, either one-hot-encoded or as index ... |
9924812 | from math import ceil
from .gamma import tileManager
class Map:
def __init__(self,
# optional parameters
tiles = None,
tileSize = 32,
name = None,
alpha = 255,
mapImages = None
):
self.MAX_MAPSIZE = 512
self.tileSize = tileSize
... |
9924861 | from inspect import iscoroutinefunction
from mcstatus.protocol.connection import (
TCPAsyncSocketConnection,
UDPAsyncSocketConnection,
)
def test_is_completely_asynchronous():
conn = TCPAsyncSocketConnection()
assertions = 0
for attribute in dir(conn):
if attribute.startswith("read_"):
... |
9924903 | from django.conf import settings
from redis import StrictRedis
from tenacity import retry, stop_after_attempt, wait_exponential
@retry(wait=wait_exponential(multiplier=1, min=1, max=5), stop=stop_after_attempt(5))
def get_connection(**kwargs):
return StrictRedis.from_url(settings.REDIS_CACHE_URL, **kwargs)
|
9924913 | import argparse
import ctypes
import sys
import PyTango
import numpy
import pygame
from PyTango.server import Device, DeviceMeta, attribute
from pykinect2 import *
from pykinect2 import PyKinectRuntime
from pykinect2 import PyKinectV2
import _ctypes
import threading
import time
KINECT_FPS = 30
if sys.he... |
9924915 | import open3d as o3d
from .o3d_aliases import GICP, PointToPlane, PointToPoint
def get_te_method(str_method):
if str_method == "gicp":
return GICP()
if str_method == "p2p":
return PointToPoint()
if str_method == "p2l":
loss = o3d.pipelines.registration.HuberLoss(0.5)
retur... |
9924945 | import json
from django.contrib.auth import get_user_model
from django.test import TestCase
from rest_framework.test import APIClient
from ralph.assets.models.choices import ObjectModelType
from ralph.assets.tests.factories import (
DataCenterAssetModelFactory,
EnvironmentFactory,
ServiceEnvironment,
... |
9924949 | from django.urls import path
from . import views
app_name = "core"
urlpatterns = [
# path(r'^test-404/$', 'core.views.error404'),
path('events/', views.events, name='events'),
path('events/map/', views.events_map, name='events_map'),
path('events/calendar.ics', views.events_ical, name='icalendar'),
... |
9924967 | from Tree_py import *
def test_root_node_is_non_null():
t = Tree(2)
assert(t)
assert(t.data())
def test_left_node_is_non_null():
t = Tree(2)
lt = t.left_subtree()
assert(lt)
assert(lt.data())
def test_right_node_is_non_null():
t = Tree(2)
rt = t.right_subtree()
assert(rt)
... |
9924969 | def get_blueprint(endpoint_name):
blueprint = endpoint_name
if '.' in endpoint_name:
blueprint = endpoint_name.split('.')[0]
return blueprint
|
9924988 | import pandas as pd
from sklearn.model_selection import train_test_split
class SimpleDataFrame:
"""
wrapper to have one class for all dataframes
"""
def __init__(
self,
train_data: pd.DataFrame,
test_data: pd.DataFrame = None,
random_state: int = 42,
... |
9924997 | import argparse
import itertools
from pathlib import Path
import torch
from torch import optim
from torch.utils.data.dataloader import DataLoader
from typing import Tuple
from models.tacotron import Tacotron
from trainer.taco_trainer import TacoTrainer
from utils import hparams as hp
from utils.checkpoints import res... |
9925034 | import json
import pytest
import python_jsonschema_objects as pjo
schema = """
{
"title":"whatever",
"properties": {
"test": {"type": "number"}
}
}
"""
@pytest.fixture
def schema_json():
return json.loads(schema)
def test_literals_support_comparisons(schema_json):
builder = pjo.ObjectBu... |
9925060 | import warnings
from typing import Union, Optional, Dict
import torch
from falkon import sparse
from falkon.kernels.diff_kernel import DiffKernel
from falkon.options import FalkonOptions
from falkon.sparse import SparseTensor
def validate_diff_float(num: Union[float, torch.Tensor], param_name: str) -> torch.Tensor:... |
9925077 | from django.apps import AppConfig
class SmsConfig(AppConfig):
name = 'apps.sms'
verbose_name = verbose_name_plural = "短信服务"
|
9925112 | from typing import Any, Callable, Union
from ..asgi.router import Controller
from ..controllers.background_task import BackgroundTask, make_background_task
from ..exceptions import InvalidRouteArgumentsError, MethodNotFoundError
from ..method import MethodType
from .factory import make_route
RoutedControllerTypeHint... |
9925159 | from MLFeatureSelection import tools
import sys
import numpy as np
def check_length(a,b):
print(len(tools.readlog(a,b)))
if __name__ == "__main__":
check_length(sys.argv[1],np.float(sys.argv[2]))
|
9925210 | import datetime
import webbrowser
import interface
import tkinter #for Linux you must install tkinter and scrot
import numpy as np #pip install numpy
import cv2 as cv #pip install opencv-python
import pyautogui #pip install PyAutoGUI
status = ""
# Find the time for name
def find_time():
x = date... |
9925225 | import os
import sys
import copy
from napalm_yang import helpers
from napalm_yang.parsers import get_parser
import logging
logger = logging.getLogger("napalm-yang")
if sys.version_info[0] > 2:
unicode = str
class Parser(object):
def __init__(
self,
model,
device=None,
pro... |
9925226 | from pseudo.pseudo_tree import Node, call, method_call, typename, to_node, attr
from pseudo.api_handlers import BizarreLeakingNode, NormalLeakingNode
def normalize(f, from_, to):
if to.type == 'int':
if to.value < 0:
if from_.type != 'int':
return Node('binary_op',
... |
9925266 | from __future__ import with_statement
from StringIO import StringIO
from django.core import management
from django.core.management.base import CommandError
from django.test import TestCase
from django.utils import translation
class CommandTests(TestCase):
def test_command(self):
out = StringIO()
... |
9925270 | import asyncio
import socket
import logging
from prometheus_push_client import compat
log = logging.getLogger("prometheus.udp")
class BaseUdpTransport:
def __init__(self, host, port, mtu=508, datagram_lines=25):
self.host = host
self.port = int(port)
self.transport = None
self._... |
9925296 | from __future__ import print_function
from django.conf import settings
JALALI_DATE_DEFAULTS = {
'Strftime': {
'date': '%y/%m/%d',
'datetime': '%H:%M:%S _ %y/%m/%d',
},
'Static': {
'js': [
'admin/js/django_jalali.min.js',
# or
# 'admin/jquery.ui.d... |
9925306 | import torch
from allennlp.common.util import END_SYMBOL, START_SYMBOL
from allennlp.data.vocabulary import DEFAULT_PADDING_TOKEN, Vocabulary
from allennlp.training.metrics import Metric
from overrides import overrides
from typing import Dict, List, Optional, Union
from summarize.common.util import SENT_START_SYMBOL, ... |
9925313 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch_geometric.nn.inits import zeros
from utils.harmonic import magnitudes
class ComplexNonLin(nn.Module):
r"""Adds a learned bias and applies the nonlinearity
given by fnc to the radial component of complex features
Args:
n... |
9925317 | import copy
import logging
import os
from typing import List
import numpy as np
import torch
import torch.nn as nn
import torch.nn.functional as F
from yarr.agents.agent import Agent, Summary, ActResult, \
ScalarSummary, HistogramSummary
from arm import utils
from arm.utils import stack_on_channel
NAME = 'TD3Age... |
9925330 | import numpy as np
import tensorflow as tf
import pandas as pd
import pickle
import shutil
from tensorflow import keras
from sklearn.model_selection import train_test_split
from preprocessor import PreProcessor
from os import mkdir
from os.path import join, normpath, dirname
from sklearn import metrics
REMOVE_PREVIOU... |
9925360 | import pytest
from requests import Response
from requests.cookies import RequestsCookieJar
from novelsave_sources import BaseHttpGateway, novel_source_types, UnavailableException
class MockGateway(BaseHttpGateway):
class RequestException(Exception):
pass
def request(
self,
method: st... |
9925365 | from elasticsearch import Elasticsearch
from app import webapp
from app import mysql
from app.models import Utils, Item
import unicodedata
class Indexer():
def __init__(self, index='items_alias'):
self.es_url = webapp.config['ES_NODES'].split(',')
self.es = Elasticsearch(self.es_url)
self... |
9925370 | import threading
from rx.disposable import CompositeDisposable, SingleAssignmentDisposable
from rxbp.acknowledgement.ack import Ack
from rxbp.acknowledgement.single import Single
def _merge_all(source: Ack):
class MergeAllAck(Ack):
def subscribe(self, single: Single):
group = CompositeDispos... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.