id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9984131 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import unittest
import numpy as np
from vectormath import Vector2, Vector2Array, Vector3, Vector3Array
class TestVMathVector2(unittest.TestCase):
def test_init_ex... |
9984182 | from tradersbot import TradersBot
import sys
from datetime import datetime, timedelta
import random
import numpy as np
import pandas as pd
C = 0.00004 # 1/25000
CASE_LENGTH = 450
CLOSE_OUT_MARGIN = 25 # when do we stop trading and balance our position
CURRENCY = 'USD'
DARK_TICKER = 'TRDRS.DARK'
INITIAL_CASH = 100000
O... |
9984193 | def Descending_Order(num):
""" descending_order == PEP8 """
return int(''.join(sorted(str(num), reverse=True)))
|
9984202 | from django import forms
from django.contrib import messages
from django.core.exceptions import PermissionDenied
from django.http import HttpResponseRedirect
from django.utils.translation import ugettext_lazy as _
from django.views.generic.detail import (
BaseDetailView,
SingleObjectTemplateResponseMixin,
)
fro... |
9984220 | import os
from alttprbot.alttprgen.randomizer import ssr
from alttprbot.tournament.core import TournamentConfig
from alttprbot_discord.bot import discordbot
from .sglcore import SGLRandomizerTournamentRace
class SSR(SGLRandomizerTournamentRace):
async def configuration(self):
guild = discordbot.get_guil... |
9984230 | import autodisc as ad
import numpy as np
import plotly
# plotly_box
def plotly_box(data=None, config=None, **kwargs):
'''
param repetition_ids: Either scalar int with single id, list with several that are used for each experiment, or a dict with repetition ids per experiment.
'''
default_config = dict(... |
9984241 | import glob
import os
import time
import unittest
import elasticsearch
import nose.tools as nt
from elasticsearch.exceptions import ConnectionError
from nose.plugins.skip import SkipTest
from topik.fileio import TopikProject
from topik.fileio.tests import test_data_path
# make logging quiet during testing, to keep T... |
9984250 | from typing import Dict, List, Any
import json
from pytest import raises
from e2e.Classes.Merit.Blockchain import Blockchain
from e2e.Meros.Meros import MessageType
from e2e.Meros.RPC import RPC
from e2e.Meros.Liver import Liver
from e2e.Tests.Errors import TestError, SuccessError
from e2e.Tests.Merit.Verify import... |
9984267 | import unittest
from unittest.mock import Mock
from zaifbot.rules import Exit
class TradeForExitTest:
def exit(self):
pass
class TestEntry(unittest.TestCase):
def setUp(self):
self._trade_mock = Mock(spec=TradeForExitTest)
self._exit = Exit()
def test_can_exit(self):
sel... |
9984273 | from sacrerouge.data.eval_instance import EvalInstance
from sacrerouge.data.jackknifers import Jackknifer
from sacrerouge.data.metrics import Metrics
from sacrerouge.data.metrics_dict import MetricsDict
from sacrerouge.data.pyramid import Pyramid, PyramidAnnotation
|
9984275 | import sys
from loguru import logger
from . import config
logger.configure(**config.logger_config())
try:
from nextcord.ext import commands
except ImportError as e:
logger.exception(e)
sys.exit(1)
bot = commands.Bot("$")
|
9984310 | import logging
from gefyra.configuration import default_configuration, ClientConfiguration
logger = logging.getLogger("gefyra")
def probe_docker(config: ClientConfiguration = default_configuration):
logger.debug("Probing: Docker")
try:
config.DOCKER.containers.list()
config.DOCKER.images.pul... |
9984350 | import os
import sys
import time
import glob
import numpy as np
import torch
import utils
import logging
import argparse
import torch.nn as nn
import torch.utils
import torch.nn.functional as F
import torchvision.datasets as dset
import torch.backends.cudnn as cudnn
from torch.autograd import Variable
from model_searc... |
9984379 | from functools import wraps
from unittest.mock import patch, Mock, mock_open
from rekcurd_dashboard.models import db, KubernetesModel
from test.base import BaseTestCase, TEST_PROJECT_ID
def mock_decorator():
"""Decorator to mock for dashboard.
"""
def test_method(func):
@wraps(func)
def... |
9984396 | from amuse.lab import *
def hydro_sink_particles(sinks, gas):
removed_particles = Particles()
for s in sinks:
xs,ys,zs=s.x,s.y,s.z
radius_squared = s.radius**2
insink=gas.select_array(lambda x,y,z: (x-xs)**2+(y-ys)**2+(z-zs)**2 < radius_squared,['x','y','z'])
if len(insink)==0... |
9984442 | import torch.nn as nn
import torch.nn.init as init
def init_params(net):
"""Init layer parameters."""
for m in net.modules():
if isinstance(m, nn.Conv2d):
init.kaiming_normal_(m.weight, mode="fan_out")
if m.bias is not None:
init.constant_(m.bias, 0)
eli... |
9984476 | result = open('myapp.data', 'rb').readlines()
def handler(environment, start_response):
start_response('200', '')
return result
|
9984479 | import os
import sys
import argparse
import yaml
import numpy as np
import pandas as pd
from tqdm import tqdm
from pathlib import Path
from numpy.random import multinomial, multivariate_normal
from sklearn.mixture import GaussianMixture
# from sklearn.mixture._gaussian_mixture import _estimate_gaussian_parameters
impor... |
9984488 | from pyppeteer import launch
import asyncio
async def get_screenshot(selector, url, save_path):
browser = await launch({"args": ["--no-sandbox"]})
flag = True
exception_summary = ''
try:
page = await browser.newPage()
await page.goto(url)
await page.tap(selector)
await ... |
9984507 | from .. import utils as test_utils
before = test_utils.read_config_file("config/shell_command_before_session.yaml")
expected = test_utils.read_config_file(
"config/shell_command_before_session-expected.yaml"
)
|
9984520 | import numpy as np
import pytest
import qcelemental as qcel
from qcelemental.testing import compare_recursive, compare_values
import qcengine as qcng
from qcengine.testing import using
@using("qcore")
@pytest.mark.parametrize(
"method, energy, gradient_norm",
[
({"method": "gfn1"}, -5.765990520597323... |
9984559 | import time
from nose.tools import *
def test_benchmark():
TRIALS = range(1000000)
integer = 1
float = 3.0
long = 293203948032948023984023948023957245
# attempt isinstance
stime = time.clock()
for i in TRIALS:
answer = isinstance(integer, (int, float, long, complex))
ok_... |
9984584 | from django.contrib.auth.models import Group, User
import testapp.rules # noqa .imported to register rules
from testapp.models import Book
ISBN = "978-1-4302-1936-1"
class TestData:
@classmethod
def setUpTestData(cls):
adrian = User.objects.create_user(
"adrian", password="<PASSWORD>", ... |
9984588 | from django.test import TestCase
from utils.aws import http_to_s3
class AWSUtilsTests(TestCase):
def setUp(self):
self.bucket = 'researchhub-paper-prod'
self.key = '/uploads/papers/2019/12/05/858589.full.pdf'
self.https_pdf_url = (
f'https://{self.bucket}.s3.us-west-2.amazona... |
9984609 | import pytest
import numpy as np
from automates.model_assembly.networks import GroundedFunctionNetwork
@pytest.fixture
def basic_assignment_grfn():
"""
Modeled code:
def function(x):
y = x + 5
return y
def main():
input = 4
output = function(... |
9984639 | import pytest
import boto3
from moto import mock_secretsmanager
from acme import acme
@mock_secretsmanager
def test_secrets_manager_client():
conn = boto3.client("secretsmanager", region_name="us-east-1")
conn.create_secret(Name="test/otter/credentials",
SecretString='{"username": "air... |
9984640 | import rospy
from nav_msgs.msg import Odometry
from geometry_msgs.msg import Twist
import numpy as np
import tf.transformations
from plotter import plotter
class husky_pi():
def __init__(self, set_point, dt = 0.1, Teval = 1., simulation = True):
self.position = np.zeros(3)
self.vel_v = np.zeros(... |
9984641 | import numpy as np
import torch
from torch import nn
from torch.nn import Module, Parameter, ParameterList
from torch.nn import functional as F
from torch.nn import init
from torch.autograd import Variable
from ..rnn import StatefulBaseCell
from ..candecomp import CPLinear
from ...utils.helper import torchauto, tenso... |
9984663 | import torch
from .learned_encoder import LearnedEncoder
from .learned_decoder import LearnedDecoder
class LearnedAutoEncoder(torch.nn.Module):
"""
Auto encoder.
"""
def __init__(self, encoder, decoder):
"""
Initialize encoder.
:param N_font: length of first one-hot vector
... |
9984716 | import unittest
import atlassian_jwt_auth
class TestKeyModule(unittest.TestCase):
""" tests for the key module. """
def test_key_identifier_with_invalid_keys(self):
""" test that invalid key identifiers are not permitted. """
keys = ['../aha', '/a', r'\c:a', '<KEY> 'a../../a', 'a/;a',
... |
9984725 | from setuptools import setup, find_packages
setup(
name="pyfuncol",
description="Functional collections extension functions for Python",
long_description=open("README.md").read(),
long_description_content_type="text/markdown",
url="https://github.com/didactic-meme/pyfuncol",
author="<NAME>",
... |
9984731 | from ..types import Post
from .archive import archiver
from .common import SELENIUM_EXCEPTIONS, click_button, wait_xpath, force_mobile
from .config import settings
from selenium.webdriver.common.action_chains import ActionChains
import time
# Used as a threshold to avoid running forever
MAX_POSTS = settings["MAX_POST... |
9984743 | from __future__ import print_function
import os
import logging
import wget
import numpy as np
from torchvision.datasets import VisionDataset
from torchvision.datasets.utils import download_and_extract_archive
from PIL import Image
class DomainNet(VisionDataset):
"""DomainNet dataset from 'Moment Matching for Mult... |
9984759 | import json
####################
# Listas
####################
# Simple lista con los números del 0 al 10
lista1 = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
# Creamos una lista vacía y la llenamos con los números pares existentes en lista1
lista2 = []
for i in lista1:
if i % 2 == 0:
lista2.append(i)
# 1er ejemplo de li... |
9984776 | import functools
import math
import re
import warnings
from contextlib import contextmanager
from numbers import Number
from typing import Tuple, Callable, Any
import numpy as np
from . import extrapolation as e_
from ._shape import (BATCH_DIM, CHANNEL_DIM, SPATIAL_DIM, INSTANCE_DIM, Shape, EMPTY_SHAPE,
... |
9984778 | from pydub.silence import split_on_silence, detect_nonsilent
from pydub import AudioSegment
from tqdm import tqdm
def split(
file,
min_silence_len=500,
silence_thresh=-20,
max_len=7,
keep_silence=1000,
):
audio = AudioSegment.from_mp3(file)
audio_chunks = split_on_silence(
audio,
... |
9984784 | import argparse
import pytest
from check_jsonschema.parse_cli import parse_args
class CustomArgError(ValueError):
pass
class CustomArgParser(argparse.ArgumentParser):
def error(self, message):
raise CustomArgError(message)
def _call_parse(args):
return parse_args(args, cls=CustomArgParser)
... |
9984796 | import os
import codecs
from django.core.urlresolvers import reverse
from django.contrib.auth import authenticate
from rest_framework.test import APIRequestFactory
from onadata.apps.main.tests.test_base import TestBase
from onadata.apps.logger.models import Attachment
from onadata.apps.logger.models import Instance
... |
9984797 | class Component:
def __init__(self, game_object):
self.game_object = game_object
self.transform = game_object.transform
|
9984842 | def test_systemd_override(host):
smgr = host.ansible("setup")["ansible_facts"]["ansible_service_mgr"]
if smgr == 'systemd':
fname = '/etc/systemd/system/pdns-recursor.service.d/override.conf'
f = host.file(fname)
assert f.exists
assert f.user == 'root'
assert f.group == ... |
9984862 | from NIENV import *
class SetVar_NodeInstance(NodeInstance):
def __init__(self, params):
super(SetVar_NodeInstance, self).__init__(params)
self.special_actions['make passive'] = {'method': M(self.action_make_passive)}
self.active = True
self.var_name = ''
def update_event(se... |
9984864 | primes = [2, 3, 5, 7, 11, 13]
print 'The first', len(primes), 'primes are:'
for prime in primes:
print prime
|
9984908 | import magma as m
from magma.testing import check_files_equal
import logging
import pytest
import coreir
class And2(m.Circuit):
name = "And2"
io = m.IO(I0=m.In(m.Bit), I1=m.In(m.Bit), O=m.Out(m.Bit))
@pytest.mark.parametrize("target,suffix",
[("verilog", "v"), ("coreir", "json")])
d... |
9984943 | import json, csv, os
import boto3
from user_info import get_slack_username
#Located in Lambda Environment Variable
EVENT_TABLE = os.getenv('TABLE_NAME', 'slack_attendance_check_default')
USER_TABLE = EVENT_TABLE+'_users'
def db2csv(query_date=None, sorting_key=None, reverse=None):
dynamodb = boto3.resource('dyn... |
9984948 | import ast
import logging
import sys
import argparse
from timeit import default_timer as timer
from config import load_parameters
from captioner import check_params
from captioner.training import train_model
from captioner.apply_model import sample_ensemble
logging.basicConfig(level=logging.DEBUG, format='[%(asctime)s... |
9984960 | import uvicore
from base64 import b64decode
from uvicore.http import status
from uvicore.typing import Tuple, Dict
from uvicore.http import Request
from uvicore.support import module
from uvicore.support.dumper import dump, dd
from fastapi.security import SecurityScopes
from uvicore.http.exceptions import HTTPException... |
9984971 | import torch
import torch.nn.functional as F
from torch.autograd import Function
from torch.autograd.function import once_differentiable
from . import grid_sampler_cuda
class _GridSampler(Function):
@staticmethod
def forward(ctx, input, grid, mode_enum, padding_mode_enum, align_corners):
ctx.save_fo... |
9984981 | from PIL import Image
from osr2mp4.ImageProcess.Animation.easing import easingout
from osr2mp4.ImageProcess import imageproc
from osr2mp4.ImageProcess.Objects.Components.AScorebar import AScorebar
class Flashlight(AScorebar):
COMBO_100= 0
COMBO_200 = 1
COMBO_BIG = 2
BREAK = 3
def __init__(self, frames, setting... |
9985063 | from typing import Optional
from typing import Tuple
from typing import Union
import torch
class FullyConnected(torch.nn.Module):
r"""A fully connected neural network.
All parameters and buffers are moved to the GPU with
:py:meth:`torch.nn.Module.cuda` if :py:func:`torch.cuda.is_available`.
Args:
... |
9985116 | def extractTintantonWordpressCom(item):
'''
Parser for 'tintanton.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('<NAME>', '<NAME>o, nazeka Darehitori Sudatou to Shinai Ken ... |
9985137 | import sublime
import sublime_plugin
import os
import copy
import json
# ----------------------------------------------------------
# Config
# ----------------------------------------------------------
def get_api_url():
return r'https://mp.weixin.qq.com/debug/wxadoc/dev/api/'
def get_component_url():
retur... |
9985264 | import os
import io
import contextlib
import tempfile
import shutil
import errno
import zipfile
@contextlib.contextmanager
def tempdir():
"""Create a temporary directory in a context manager."""
td = tempfile.mkdtemp()
try:
yield td
finally:
shutil.rmtre... |
9985267 | import einops
import keras
import keras.layers
import keras.metrics
import numpy as np
import tensorflow as tf
from attrdict import AttrDict
import models.eval_metrics
import models.model_trainer
import models.util
import tfu
import tfu3d
from options import FLAGS
class Metro(keras.Model):
def __init__(self, bac... |
9985269 | from .interpolator import RaveTrajectoryWrapper, SplineInterpolator
from .constraint import (
JointAccelerationConstraint,
JointVelocityConstraint,
DiscretizationType,
SecondOrderConstraint,
)
from .algorithm import TOPPRA
import numpy as np
import logging
import time
logger = logging.getLogger(__name_... |
9985287 | from scipy.sparse import data
import tensorflow_hub as hub
import tensorflow as tf
import numpy as np
import tensorflow_datasets as tfds
import pandas as pd
import downloader
import os
from scipy.spatial import distance
from sklearn.model_selection import train_test_split
from tensorflow.keras import layers
def run_de... |
9985289 | import os
from setuptools import setup, find_packages
def read(fname):
return open(os.path.join(os.path.dirname(__file__), fname)).read()
setup(
name='click-man',
version='0.4.2',
url='https://github.com/click-contrib/click-man',
license='MIT',
description='Generate man pages for click based... |
9985329 | from typing import Sequence, Union, Dict
from turf.helpers import Feature
from turf.invariant import (
get_coords_from_features,
get_geometry_from_features,
get_geometry_type,
)
from turf.bbox import bbox as bounding_box
from turf.utils.error_codes import error_code_messages
from turf.utils.exceptions impo... |
9985335 | import io
import random
from PIL import Image, ImageDraw, ImageFont
from betty.cropper.models import Ratio
from betty.conf.app import settings
def placeholder(ratio, width, extension):
if ratio.string == "original":
ratio = Ratio(random.choice((settings.BETTY_RATIOS)))
height = int(round((width * ra... |
9985341 | from pymarc import Field
import urllib.request, urllib.parse, urllib.error
from core.config import Configuration
from core.marc import (
Annotator,
MARCExporter,
)
from core.model import (
ConfigurationSetting,
Session,
)
class LibraryAnnotator(Annotator):
def __init__(self, library):
supe... |
9985350 | import numpy as np
import matplotlib.pyplot as plt
from ....Classes.OptiObjective import OptiObjective
def get_pareto_index(self):
"""Return index of individuals in the pareto
Parameters
----------
self: XOutput
Returns
-------
idx_non_dom: list
list of index of non dominated ind... |
9985434 | import torch
from torch import nn as nn
from torch.nn import functional as F
from horch.models.modules import Conv2d
def fast_normalize(w, eps=1e-4, dim=0):
w = torch.relu(w)
w = w / (torch.sum(w, dim=dim, keepdim=True) + eps)
return w
class BottomUpFusion2(nn.Module):
def __init__(self, f_channels... |
9985441 | import copy
from pip_run import deps
class TestInstallCheck:
def test_installed(self):
assert deps.pkg_installed('pip-run')
def test_not_installed(self):
assert not deps.pkg_installed('not_a_package')
def test_installed_version(self):
assert not deps.pkg_installed('pip-run==0.0'... |
9985456 | from django.contrib import admin
from funny.models import FunnyPost, FunnyComment
from django_summernote.admin import SummernoteModelAdmin
# Register your models here.
class FunnyPostAdmin(SummernoteModelAdmin):
summernote_fields = ('funny_content',)
list_display = ('funny_title', 'created_on', 'st... |
9985469 | CONF_API_SERVER = "api_server"
CONF_AUTO_UPVOTE = "auto_upvote"
CONF_IGNORE_UNLISTED = "ignore_unlisted"
CONF_SEGMENT_CHAIN_MARGIN_MS = "segment_chain_margin_ms"
CONF_SHOW_SKIPPED_DIALOG = "show_skipped_dialog"
CONF_SKIP_COUNT_TRACKING = "skip_count_tracking"
CONF_USER_ID = "user_id"
CONF_VIDEO_END_TIME_MARGIN_MS = "vi... |
9985487 | import os
from .corner_plotter import plot_eccentricity_posteriors, plot_posteriors
from .histogram_plotter import plot_priors
from .matplotlib_plots import MatplotlibPlotter
from .plotly_plots import PlotlyPlotter
if os.environ.get("INTERACTIVE_PLOTS", default="False") == "TRUE":
plot_lightcurve = PlotlyPlotter.... |
9985571 | from itertools import permutations
class BoxLoader:
def mostItems(self, boxX, boxY, boxZ, itemX, itemY, itemZ):
def c(box, item):
return reduce(lambda a, (b, i): a * (b / i), zip(box, item), 1)
box, item = [boxX, boxY, boxZ], [itemX, itemY, itemZ]
return max(map(lambda i: c(bo... |
9985580 | from django.db import models
class Room(models.Model):
# location coordinates of the room
location_x = models.IntegerField()
location_y = models.IntegerField()
location_z = models.IntegerField()
# can someone enter the room
has_room = models.BooleanField(default=True)
# list of character... |
9985642 | import os
import os.path as osp
import torch
from torch_geometric.data import InMemoryDataset, download_url, extract_zip
from torch_geometric.read import read_tu_data
class TUDataset(InMemoryDataset):
url = 'https://ls11-www.cs.uni-dortmund.de/people/morris/' \
'graphkerneldatasets'
def __init__(s... |
9985664 | import sys
from optparse import OptionParser
from datetime import *
from git import *
if __name__=="__main__":
usage = """
%prog outfile.txt"""
parser = OptionParser(usage=usage)
(options, args) = parser.parse_args()
if len(args)==1:
sys.stdout = open(args[0], 'w')
git=Repo(search_parent_directories=True).git
... |
9985674 | from django.urls import path, include
from rest_framework.authtoken.views import obtain_auth_token
from .views import *
app_name = 'django_app'
urlpatterns = [
path('auth/', include('djoser.urls')),
path('auth/token/', obtain_auth_token, name='token'),
path('workers', WorkerListView.as_view()),
path(... |
9985675 | from django import forms
from django.forms import ModelForm
#from .models import tweet
class SearchForm(forms.Form):
keyword = forms.CharField(label='', max_length=100, required=False)
keyword.widget.attrs['class'] = 'form-control mr-sm-2 my-2'
keyword.widget.attrs['placeholder'] = 'Search for tweets.' |
9985701 | import torch
import torch.nn.functional as F
import math
class MultivariateNormal(object):
def __init__(self, dim):
self.dim = dim
self.dim_params = None
def transform(self, raw):
raise NotImplementedError
def log_prob(self, X, params):
raise NotImplementedError
def s... |
9985723 | import requests, json, datetime, boto3, time
currencies = ['USD','GBP','EUR']
rates = {}
session = boto3.Session(profile_name='default')
kinesis_client = session.client('kinesis')
while True:
for currency in currencies:
req = requests.get('https://api.coindesk.com/v1/bpi/currentprice/{}.json'.format(currency))... |
9985726 | from smol_evm.context import ExecutionContext, Calldata
def with_stack_contents(context, some_iterable) -> ExecutionContext:
for x in some_iterable:
context.stack.push(x)
return context
def with_calldata(context, some_iterable) -> ExecutionContext:
context.calldata = Calldata(bytes(some_iterable))... |
9985756 | from .config import config
from peewee import Model as PeeWeeModel, MySQLDatabase, PostgresqlDatabase
if str(config['database']['mode']).lower() == "mysql":
DATABASE = MySQLDatabase(
str(config['database']['name']),
user=str(config['database']['user']),
... |
9985796 | import time
from ..save import *
from ..seed import *
from .base_cb import *
import shutil
import json
class AutoResumeCb(Callback):
"""auto save and resume for all callbacks and model, with multiple checkpoints
Args:
n_save_cycle: -1 to ignore, default: n_ep_itr
resume: using save mode, witho... |
9985814 | import subprocess
import sys
# Validate command-line arguments
if len(sys.argv) < 2 or (not (sys.argv[1] == "METRICS" and len(sys.argv) == 3) and not (sys.argv[1] == "FULL" and len(sys.argv) == 7 and sys.argv[3].isdigit() and all([x.isdigit() for x in sys.argv[4].split("_")]) and sys.argv[5].lstrip("-").isdigit() and ... |
9985827 | import json
from django.test import Client
from django.test import TestCase
from django.urls import reverse
from comments.models import Comment
from . import database_population
from ..models import Datapackage
from ..views import get_name_from_datapackage
class HomePageViewTest(TestCase):
def test_get(self):
... |
9985832 | import datetime
from sacred import Ingredient
# flake8: noqa
general_ingredient = Ingredient('general')
ppo_ingredient = Ingredient('ppo')
bc_ingredient = Ingredient('bc')
hierarchy_ingredient = Ingredient('hierarchy')
log_ingredient = Ingredient('log')
train_ingredient = Ingredient('train', ingredients=[
general_... |
9985839 | import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import AgglomerativeClustering
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split
from sklearn.neighbors import NearestNeighbors
from sklearn.neural_network import MLPClassifier
from explainer_ta... |
9985913 | import logging
import colander
from cornice.validators import colander_validator
from pyramid import httpexceptions
from pyramid.security import NO_PERMISSION_REQUIRED
from kinto.core import Service, errors
from kinto.core.errors import ErrorSchema
from kinto.core.resource.viewset import CONTENT_TYPES
from kinto.core... |
9985923 | from itertools import chain
import pytest
from PIL import Image # type: ignore
import esparto._content as co
import esparto._layout as la
from tests.conftest import _EXTRAS, content_list
if _EXTRAS:
def test_all_content_classes_covered(content_list_fn):
test_classes = {type(c) for c in content_list_fn}... |
9985963 | from datetime import datetime
import pathlib
import cv2
import numpy as np
import pandas as pd
from PyQt5.QtCore import pyqtSignal, QObject
from yarppg.rppg.camera import Camera
def write_dataframe(path, df):
path = pathlib.Path(path)
if path.suffix.lower() == ".csv":
df.to_csv(path, float_format="%... |
9985976 | from databaseconnect import clear_table
print("---------------------------------------")
print(" CLEARING TABLES")
print("---------------------------------------")
print(" Options Menu")
print("1. ALL TABLES")
print("2. chat_table")
print("3. question_table and statement_table")
print("Enter the r... |
9986085 | from expression import *
# programming the GPIO by BCM pin numbers
#TRIG = servo['Sensor']['ultrasonic']['trigger']
#ECHO = servo['Sensor']['ultrasonic']['echo']
TRIG = 24
ECHO = 23
GPIO.setup(TRIG,GPIO.OUT) # initialize GPIO Pin as outputs
GPIO.setup(ECHO,GPIO.IN) # initialize GPIO... |
9986106 | from setuptools import find_packages
from setuptools import setup
version = '0.0.0'
setup(
name='chainer_dense_fusion',
version=version,
packages=find_packages(),
install_requires=open('requirements.txt').readlines(),
description='',
long_description=open('README.md').read(),
author='<NA... |
9986141 | from .profile import WhyProfileSession, new_profiling_session
__ALL__ = [
WhyProfileSession,
new_profiling_session,
]
|
9986144 | import unittest
from recordclass import litelist
import gc
import pickle
import sys
class litelistTest(unittest.TestCase):
def test_len(self):
a = litelist([])
self.assertEqual(len(a), 0)
a = litelist([1])
self.assertEqual(len(a), 1)
def test_items(self):
a = ... |
9986158 | from unittest import mock
import pytest
from asserts import assert_cli_runner
from meltano.cli import cli
from meltano.core.project_settings_service import (
ProjectSettingsService,
SettingValueStore,
)
from meltano.core.tracking import GoogleAnalyticsTracker
class TestCliUi:
def test_ui(self, project, c... |
9986159 | import asyncio
import discord
from redbot.vendored.discord.ext import menus
from .game import Game
TRANS = {
0: "\N{BLACK LARGE SQUARE}",
1: "\N{RED APPLE}",
2: "\N{LARGE GREEN CIRCLE}",
3: "\N{LARGE GREEN SQUARE}",
}
GET_DIR = {
"w": "up",
"s": "down",
"a": "left",
"d": "right",
... |
9986168 | from .tui import curses_init, term_resize, KeyboardDisplay
from .interface import KeyboardInterface
|
9986170 | import logging
import snap7
# for setup the Logo connection please follow this link
# http://snap7.sourceforge.net/logo.html
logging.basicConfig(level=logging.INFO)
# Siemens LOGO devices Logo 8 is the default
Logo_7 = True
logger = logging.getLogger(__name__)
plc = snap7.logo.Logo()
plc.connect("192.168.0.41",0... |
9986206 | from schema_registry.client import errors, schema # noqa
from schema_registry.client.client import AsyncSchemaRegistryClient, SchemaRegistryClient # noqa
__all__ = ["SchemaRegistryClient", "AsyncSchemaRegistryClient"]
|
9986255 | from copy import deepcopy
import numpy as np
import pandas as pd
import pytest
from etna.datasets import TSDataset
from etna.models import NaiveModel
from etna.transforms.missing_values import TimeSeriesImputerTransform
from etna.transforms.missing_values.imputation import _OneSegmentTimeSeriesImputerTransform
@pyt... |
9986256 | import nibabel as nib
from tqdm import tqdm
from scipy.ndimage import label, generate_binary_structure
from pathlib import Path
import json
import numpy as np
from ivadomed import postprocessing as imed_postpro
from typing import List
def run_uncertainty(image_folder):
"""Compute uncertainty from model prediction... |
9986262 | import numpy as np
def top_k_spans(start_probs, end_probs, n, k):
"""
Returns top k non overlapping spans for a passage
sorted by start/end probabilities
"""
probs = []
argmax_spans = []
for i in range(k + 1):
probs.append([])
argmax_spans.append([])
for j in range(n... |
9986277 | import torch
from torch import mean, nn
from collections import OrderedDict
from torch.nn import functional as F
import numpy as np
from numpy import random
from se_block import SEBlock
def setup_seed(seed):
torch.manual_seed(seed)
torch.cuda.manual_seed_all(seed)
np.random.seed(seed)
random.seed(s... |
9986283 | class MessageManager:
reaction_events = dict()
bot = None
@classmethod
def on_startup(cls, bot):
cls.bot = bot
@classmethod
async def send_message(cls, medium, content):
await medium.send(content)
@classmethod
async def edit_message(cls, message, content):
try:... |
9986286 | from clickhouse_driver.util.helpers import column_chunks
import numpy as np
import pandas as pd
from dateutil import parser
class QAPanelDataStruct():
"""
paneldata
"""
def __init__(self, data, dtype) -> None:
self.data = data
self.type = dtype
def get_loc(self, codelist, st... |
9986318 | import datetime
from unittest import TestCase
from asserts import (
assert_false,
assert_true,
assert_is_none,
assert_equal,
assert_is,
assert_raises,
)
from htmlgen import (
Span,
Form,
Input,
TextInput,
SubmitButton,
Button,
NumberInput,
SearchInput,
Passw... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.