id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3322247 | from setuptools import setup, find_packages
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='muniverse',
version='0.1.1',
description='An API for controllin... |
3322255 | import typing as tp
from satella.coding.structures import Proxy
from satella.coding.typing import V, T
__all__ = ['call_if_nnone', 'iterate_if_nnone', 'Optional', 'extract_optional']
def iterate_if_nnone(iterable: tp.Optional[tp.Iterable]) -> tp.Iterable:
"""
Return a generator iterating over every element ... |
3322274 | from pyderman.util import downloader
import re
import json
def get_url(version='latest', _os=None, _os_bit=None):
beta = True
pattern = version
bit = ''
if not version or version == 'latest':
beta = False
pattern = ''
if _os == 'linux':
bit = '64' if _os_bit == '64' else 'i686'
for release in _releases():... |
3322308 | import logging
from datetime import date
from functools import cached_property
from typing import Any
from typing import Dict
from typing import Iterator
from typing import Optional
from typing import Sequence
from django.db import transaction
from certificates.models import Certificate
from certificates.models impor... |
3322322 | import datetime
import unittest
from ..iterators import DateIterator
class DateIteratorTestCase(unittest.TestCase):
def test_iterator(self):
iterator = DateIterator(
datetime.date(2015, 2, 25),
datetime.date(2015, 3, 2),
)
iter(iterator)
self.assertEqual... |
3322356 | import numpy as np
import os
import gzip
def bin_data(x, mini, maxi, n_bins):
"""
Bin data from continuous representation.
:param x: real valued data in shape (time-points, batch)
:param mini: minimum bin position
:param maxi: maximum bin position
:param n_bins: number of bins
:... |
3322370 | import torch.nn as nn
import torch
from functools import reduce
from operator import mul
import torch.nn.functional as F
"""Implements the EmbeddingMul class
Author: <NAME>
Date: Fall 2018
Unit test: embedding_mul_test.py
Modified: <NAME>; Date: Fall 2019
"""
class EmbeddingMul(nn.Module):
"""This class implem... |
3322447 | import commands
import unittest
from unittest import mock
from click.testing import CliRunner
class TestIgnoreCommand(unittest.TestCase):
@mock.patch("commands.os")
def test_repo_without_gitignore(self, os_mock):
os_mock.path.exists.return_value = False
gitignore_files = commands.get_gitignore... |
3322454 | from django.db import models
class Attachment(models.Model):
"""
An attachment to a Slack message.
"""
message = models.ForeignKey(
'Message', related_name='attachments', on_delete=models.CASCADE)
title = models.CharField(max_length=300, blank=True, null=True)
title_link = models.URLF... |
3322461 | import pytest
import os
import sys
from crestic import config_files
@pytest.fixture
def no_appdirs(monkeypatch):
monkeypatch.setitem(sys.modules, "appdirs", None)
def test_xdg_configfiles():
paths = config_files()
assert paths == [
os.path.expanduser('~/.config/crestic/crestic.cfg'),
'/... |
3322501 | import os
import subprocess
import sys
from tempfile import NamedTemporaryFile, TemporaryDirectory
from pydantic import BaseModel, Field
from opyrator.components.types import FileContent
class AudioSeparationInput(BaseModel):
audio_file: FileContent = Field(..., mime_type="audio/mpeg")
class AudioSeparationOu... |
3322502 | import torch
import torch.nn as nn
def iou(a, b):
area_a = torch.unsqueeze((a[:, 2] - a[:, 0]) * (a[:, 3] - a[:, 1]), dim=1)
area_b = (b[:, 2] - b[:, 0]) * (b[:, 3] - b[:, 1])
iw = torch.min(torch.unsqueeze(a[:, 2], dim=1), b[:, 2]) - torch.max(torch.unsqueeze(a[:, 0], dim=1), b[:, 0])
ih = torch.m... |
3322692 | from typing import Tuple, List
import tensorflow as tf
from tensorflow.keras import Model, activations, regularizers, initializers, constraints
from tensorflow.keras.layers import RNN, Embedding, Dense, Dropout
from rinokeras.layers import WeightNormDense
import numpy as np
from sacred import Ingredient
from tape.da... |
3322716 | import copy
from oictest import NotSupported
from rrtest.check import ERROR
from rrtest.check import WARNING
__author__ = 'roland'
def add_test_result(conv, status, message, tid="-"):
conv.test_output.append({"id": str(tid),
"status": status,
"message": me... |
3322718 | import torch
import numpy as np
import torch.nn as nn
import torch.nn.functional as F
class YOLONetV1(nn.Module):
def __init__(self, channel=3, height=448, width=448):
super(YOLONetV1, self).__init__()
self.conv1 = nn.Conv2d(channel, 64, 7, stride=2, padding=3)
self.pool1 = nn.AvgPool2d(2... |
3322797 | import usb4vc_shared
import os
import sys
import time
os.system("rm -rfv ./rpi_app")
os.system("sleep 0.1")
os.system("rm -fv ./*.zip")
os.system("sleep 0.1")
os.system("mkdir rpi_app")
os.system("sleep 0.1")
os.system("cp -v ./*.py rpi_app/")
os.system("cp -v ./*.ttf rpi_app/")
filename = f'usb4vc_src_{usb4vc_shared... |
3322799 | import os
def test_save_configuration(connect_to_slave, read_config, pytestconfig):
servo, net = connect_to_slave
assert servo is not None and net is not None
protocol = pytestconfig.getoption("--protocol")
filename = read_config[protocol]['save_config_file']
servo.save_configuration(filename)
... |
3322874 | from django.conf.urls import url
from .views import IndexView, MySearchView
# from apps.comment.views import MessageView
app_name = 'index'
urlpatterns = [
# 首页,自然排序
url(r'^$', IndexView.as_view(template_name='index.html'), name='index'),
# # 主页,按照编写排序
# url(r'^u/$', IndexView.as_view(), {'sort': 'updat... |
3322955 | def extractDsrealmCom(item):
'''
Parser for 'dsrealm.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Reincarnated As A Dragons Egg', 'Reincarnated As A Dragons Egg', ... |
3322993 | from overrides import overrides
from allennlp.common.util import JsonDict
from allennlp.data import Instance
from allennlp.predictors.predictor import Predictor
@Predictor.register('mrqa_predictor')
class MRQAPredictor(Predictor):
def predict_json(self, json_dict: JsonDict) -> JsonDict:
if 'header' in jso... |
3323013 | class CommonProperty(object):
"""A more flexible version of property()
Saves the name of the managed attribute and uses the saved name
in calls to the getter, setter, or destructor. This allows the
same function to be used for more than one managed variable.
As a convenience, the default function... |
3323083 | import falcon_kit.mains.gen_gfa_v2 as mod
import helpers
import pytest
import os
def test_help():
try:
mod.main(['prog', '--help'])
except SystemExit:
pass
def test_main_1(tmpdir, capsys):
# test_dir = os.path.join(helpers.get_test_data_dir(), 'gfa-1')
gfa_graph = mod.GFAGraph()
g... |
3323160 | import json
from mock import MagicMock
from tests.endpoints import AbstractEndpointTest
import vegadns.api.endpoints.apikeys
from vegadns.api import app
class TestApiKeys(AbstractEndpointTest):
def test_get_success(self):
k1 = '<KEY>'
s1 = '<KEY>'
mock_apikey_one = {
'apikey... |
3323165 | import gym
from gym.envs.registration import register
def register_env(env_name):
'''Register additional environments for OpenAI gym.'''
if env_name not in gym.envs.registry.env_specs:
if env_name == 'AntTruncatedObs-v2':
register(id='AntTruncatedObs-v2',
entry_point='... |
3323171 | import json
import os
import re
import subprocess
import time
from typing import Optional, List
from platypush.backend import Backend
from platypush.message.event.joystick import JoystickConnectedEvent, JoystickDisconnectedEvent, JoystickStateEvent, \
JoystickButtonPressedEvent, JoystickButtonReleasedEvent, Joysti... |
3323270 | import FWCore.ParameterSet.Config as cms
#
#Set pixel digitization default in CMSSW_2_1_X
#
#
# (do not forget to include any mixing like:
# include "SimGeneral/MixingModule/data/mixNoPU.cfi"
#
# Pixel's digitization
#
from SimRomanPot.SimFP420.FP420Digi_cfi import *
|
3323306 | from models import Event
def get_events_for_user(user, from_date=None, to_date=None):
"""Return events for user from_date to to_date. """
query = Event.objects.filter(attendees=user)
if from_date:
query = query.filter(start__gte=from_date)
if to_date:
query = query.filter(start__lt=to... |
3323312 | import torch
from torch import nn
class NonLocalAttention(nn.Module):
"""
Attention from all positions in object B to all positions in object A
"""
def __init__(self, in_channels=256, inter_channels=None, bn_layer=True):
super(NonLocalAttention, self).__init__()
self.in_channels =... |
3323321 | from typing import List, Optional, Tuple
from PyQt5.QtCore import pyqtSignal, QObject
from PyQt5.QtWidgets import (QGraphicsObject, QGraphicsItem, QAction)
from cadnano.cntypes import ( WindowT )
class AbstractTool(QGraphicsObject):
""" For use in place of None checks in the code
reduces boilerplate
"""
... |
3323353 | import numpy as np
import inspect
def start_indices(maximum: int, n: int):
'''
e[0] is the starting coordinate
e[1] is the ending coordinate
Args:
maximum: max integer to draw a number from
n: how many numbers to draw
Returns: starting index of the events to be inserted
''... |
3323357 | import numpy as np
import pandas as pd
import streamlit as st
import plotly.express as px
import plotly.graph_objects as go
from plotly.subplots import make_subplots
from core import (
convert_yearly_to_monthly_interest,
calculate_mortgage_over_time,
apply_interest_scalar,
apply_interest_series,
ap... |
3323385 | def test_setup_failure(testdir):
testdir.makepyfile(
"""
import pytest
import pytest_check as check
@pytest.fixture()
def a_fixture():
check.equal(1, 2)
def test_1(a_fixture):
pass
"""
)
result = testdir.runpytest()
result... |
3323401 | import torch as tc
import torch.nn as nn
import torch.nn.functional as F
from transformers import BertModel , BertTokenizer
import pdb
import math
from .graph_encoder import Encoder
from .matrix_transformer import Encoder as MatTransformer
class Model(nn.Module):
def __init__(self ,
bert_type = "bert-base-uncased... |
3323404 | import numpy as np
from itertools import chain
def getSingleSelection():
# Open a file dialog and get the path
return None
def getObjectByName(name):
# Does nothing
return None
def getObjectName(thing):
# Gets the basename from a path
return None
def getFaces(thing):
# loads the .obj or .abc ... |
3323465 | from dataset_utils import int64_feature, float_feature, bytes_feature
import decorations
import math
import os
import xml.etree.ElementTree as ElementTree
import shutil
import tensorflow as tf
tf.app.flags.DEFINE_string(
'path_to_decorations', '/home/paul/Data/decorations', 'path to decorations dataset')
tf.app.fl... |
3323485 | from build.management.commands.export_constructs import Command as ExportConstructs
class Command(ExportConstructs):
pass |
3323506 | class HowLongToBeatEntry:
"""
A simple class to collect all game data that are being read from the HTML code
The first value of each section contain the actual time (or -1/0 if not available)
The second value of each section contain the unit of the time (Minutes/Hours, or None if not available)
The ... |
3323540 | import os
import argparse
import torch
import numpy as np
from datetime import datetime
from cail.env import make_env
from cail.buffer import SerializedBuffer
from cail.algo.algo import ALGOS
from cail.trainer import Trainer
def run(args):
"""Train Imitation Learning algorithms"""
env = make_en... |
3323568 | from django.urls import path, include
from app import views
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import TemplateView
from django.contrib.auth import views as auth_views
from .forms import LoginForm
# from djago.allauth.account.views import LoginView
urlp... |
3323577 | from django.urls import re_path
from authlib.admin_oauth.views import admin_oauth
urlpatterns = [re_path(r"^admin/__oauth__/$", admin_oauth, name="admin_oauth")]
|
3323703 | from numpy.ma import logical_and, logical_or
from pandas import DataFrame, Series
from weaverbird.pipeline.conditions import (
ComparisonCondition,
Condition,
ConditionComboAnd,
ConditionComboOr,
InclusionCondition,
MatchCondition,
NullCondition,
)
def apply_condition(condition: Condition... |
3323708 | from ctypes import addressof
import os
import fire
import pefile
import sys
import numpy as np
import pickle
import json
from unicorn import *
from unicorn.x86_const import *
from capstone import *
from capstone.x86_const import *
BASE = 0x140000000
EMU_START = 0x1461743F0
EMU_END = EMU_START + 0x10000
REGISTER_MEM... |
3323726 | class Simple:
def hello(self):
return 'Hello'
def world(self):
return 'world!'
def hello_world(self):
return '%s %s' % (self.hello(), self.world())
|
3323780 | from pyradioconfig.parts.ocelot.calculators.calc_fec import CALC_FEC_Ocelot
class Calc_FEC_Bobcat(CALC_FEC_Ocelot):
pass |
3323808 | import numpy as np
import pyspawn
pyspawn.import_methods.into_simulation(pyspawn.qm_integrator.rk2)
pyspawn.import_methods.into_simulation(pyspawn.qm_hamiltonian.adiabatic)
pyspawn.import_methods.into_traj(pyspawn.potential.terachem_cas)
pyspawn.import_methods.into_traj(pyspawn.classical_integrator.vv)
... |
3323854 | import numpy as np
from sklearn.cluster import AgglomerativeClustering
from sklearn.metrics import silhouette_score
class OptimizedAgglomerativeClustering:
def __init__(self, max_cluster=10):
self.kmax = max_cluster
def fit_predict(self, X):
best_k = self._find_best_k(X)
... |
3323863 | import sys
sys.path.append("../../")
from appJar import gui
def test(): print("test")
with gui() as app:
app.label('hello world')
app.addToolbar(['help', 'save', 'open'], test, True)
app.button('PRESS', test, icon='help')
|
3323908 | import math
import tensorflow as tf
import numpy as np
import utils
def get_distance(point1, point2):
x1 = point1[0]
x2 = point2[0]
y1 = point1[1]
y2 = point2[1]
dist = math.sqrt(math.pow((x2 - x1), 2) + math.pow((y2 - y1), 2))
return dist
def get_distance_between_frames(frames, target_labels_all, last_f... |
3323930 | import json
from office365.sharepoint.client_context import ClientContext
from tests import test_team_site_url, test_client_credentials
ctx = ClientContext(test_team_site_url).with_credentials(test_client_credentials)
file_url = '/sites/team/Shared Documents/big_buck_bunny.mp4'
file = ctx.web.get_file_by_server_relat... |
3324010 | import os.path
from django.core.files.storage import FileSystemStorage, Storage
from storages.backends.s3boto3 import S3Boto3Storage
from django.conf import settings
class S3OverlayStorage(Storage):
"""Delegate paths starting with S3 magic to S3 storage
Delegate other paths to local storage
No extra field... |
3324059 | import unittest
from mltrace import Test, Component, set_db_uri
class TestTest(unittest.TestCase):
def setUp(self):
set_db_uri("test")
def testRunsAllTestFunc(self):
class DummyTest(Test):
def __init__(self):
super().__init__("Dummy")
def testCorrect(s... |
3324071 | import console
import editor
import keyword
import os
import string
import sys
ALLOWED_CHARS = set(string.ascii_letters + string.digits + string.whitespace + "_.")
DOCS = os.path.expanduser("~/Documents")
def preformat(name):
name = str(name).strip()
if name.startswith("from "):
name = name[len("from ... |
3324113 | import os.path as osp
import pytest
from mmgen.datasets import GrowScaleImgDataset
class TestGrowScaleImgDataset:
@classmethod
def setup_class(cls):
cls.imgs_root = osp.join(osp.dirname(__file__), '..', 'data/image')
cls.imgs_roots = {
'4': cls.imgs_root,
'8': osp.jo... |
3324118 | from galaxy_test.base.populators import (
DatasetPopulator
)
from galaxy_test.driver import integration_util
class DefaultPermissionsIntegrationTestCase(integration_util.IntegrationTestCase):
expected_access_status_code = 200
def setUp(self):
super().setUp()
self.dataset_populator = Datas... |
3324186 | from library.telegram.base import RequestContext
from nexus.bot.configs import config
from nexus.translations import t
from telethon import events
from .base import BaseHandler
class DonateHandler(BaseHandler):
filter = events.NewMessage(incoming=True, pattern='^/donate(@[A-Za-z0-9_]+)?$')
is_group_handler =... |
3324203 | import tensorflow as tf
import numpy as np
from matplotlib import pyplot as plt
import random
import time
import scipy
import pandas as pd
import tflearn
import copy
import os
import sys
currentpath = os.path.dirname(os.path.realpath(__file__))
project_basedir = os.path.join(currentpath,'..')
sys.path.append(project_b... |
3324220 | from moto.core.exceptions import RESTError
class InvalidParameterValueError(RESTError):
def __init__(self, message):
super().__init__("InvalidParameterValue", message)
class ResourceNotFoundException(RESTError):
def __init__(self, message):
super().__init__("ResourceNotFoundException", messa... |
3324226 | from dataset.rand_augment import rand_augment_transform
from PIL import ImageFilter
from dataset import auto_augment
import random
from PIL import Image
import numpy as np
import torchvision.transforms as transforms
import torch.nn as nn
import torch
mean_cifar = [0.5071, 0.4867, 0.4408]
std_cifar = [0.2675, 0.2565, ... |
3324236 | from app import db
import datetime
class SessionModel(db.Model):
__tablename__ = 'sessions'
id = db.Column(db.Integer, primary_key=True)
user_id = db.Column(db.Integer, default=0, index=True, nullable=True)
name = db.Column(db.String, default='', index=True, nullable=True)
description = db.Column(... |
3324242 | import torch
import os
import io
def save_load_name(args, name=''):
if args.aligned:
name = name if len(name) > 0 else 'aligned_model'
elif not args.aligned:
name = name if len(name) > 0 else 'nonaligned_model'
return name + '_' + args.model
def save_model(args, model, name=''):
# n... |
3324274 | import os
from unittest import TestCase
import pandas as pd
from nlp import load_dataset
from acl.trainer_utils import get_label_classes_from_nlp_dataset
from datasets.acl_docrel.acl_docrel import get_train_split, get_test_split
from experiments.environment import get_env
class TrainerTest(TestCase):
def __init... |
3324322 | import sys
import logging
from os import devnull
from math import ceil
from psutil import cpu_count, virtual_memory
from contextlib import contextmanager, redirect_stderr, redirect_stdout
ERRORS_TO_HANDLE = [AttributeError, ValueError, TypeError, KeyError]
try:
from numba.core.errors import TypingError
ERRORS... |
3324360 | import math
from abc import abstractmethod
import torch
import torch.nn as nn
import torch.nn.init as init
import torch.nn.functional as F
import torch.nn.utils.spectral_norm as SpectralNorm
from math import sqrt
def kaiming_init(module,
a=0,
mode='fan_out',
nonlinea... |
3324383 | from django import template
register = template.Library()
@register.filter
def meta_attr(obj, key):
"""Returns an attribute of an objects _meta class"""
return getattr(obj._meta, key, "")
|
3324413 | import sys
import re
sys.path.append('/usr/share/syndicate_md')
from SMDS.user import *
from SMDS.mdserver import *
from SMDS.mdapi import MDAPI
class IS_SMDS_USER:
"""
Validator for username fields--make sure that the user is a valid SMDS user.
"""
def __init__(self, error_message='Invalid User'):
... |
3324414 | import numpy as np
import scipy.sparse as ssp
import random
"""All functions in this file are from dgl.contrib.data.knowledge_graph"""
def _bfs_relational(adj, roots, max_nodes_per_hop=None):
"""
BFS for graphs.
Modified from dgl.contrib.data.knowledge_graph to accomodate node sampling
"""
visit... |
3324426 | import socket
import threading
import logging
import re
from status import Status
from streaming import TCPStreamingClient
from broadcaster import Broadcaster
class HTTPRequestHandler:
"""Handles the initial connection with HTTP clients"""
def __init__(self, port):
#response we'll send to the client, ... |
3324451 | from pathlib import Path
from PyQt5.QtCore import QSettings
from inselect.lib.utils import debug_print
class RecentDocuments(object):
KEY = 'recent_documents'
MAX_RECENT_DOCS = 5
def read_paths(self):
"""Returns a list of up to MAX_RECENT_DOCS Paths. The most recently
opened path is th... |
3324480 | from awsflow.templates.step import config_step_task
def CONFIG_STEP_SLACK(params=[]):
return config_step_task(name='slack-message', task_name='awsflow.slack', task_params=params)
|
3324501 | from ..utils import TranspileTestCase
class ComparisonTests(TranspileTestCase):
def test_is(self):
self.assertCodeExecution("""
x = 1
if x is 1:
print('Correct')
else:
print('Incorrect')
print('Done.')
""")
... |
3324503 | from .version import __version__ # noqa
from .buildsimhub import BuildSimHubAPIClient
import BuildSimHubAPI.htmlParser
import BuildSimHubAPI.helpers
import BuildSimHubAPI.measures
# import BuildSimHubAPI.postprocess
|
3324521 | import math
def mod(x, y):
return x - y * math.trunc(x / y)
a = 1
b = 2
sum = 0
while a < 4000000:
if mod(a, 2) == 0:
sum += a
c = a
a = b
b += c
print("%d\n" % sum, end='')
|
3324550 | from PIL import Image
from yuv_reader import YUVReader
from reprojection import Reprojection
from optparse import OptionParser
from six.moves import cPickle
import matplotlib.pyplot as plt
import numpy as np
import os
from dataset_preparation.ballet_camera import BalletCamera
def main():
parser = OptionParser()
... |
3324591 | from setuptools import setup
desc = ('%s\n\n%s' % (open('README.rst').read(), open('CHANGES.txt').read()))
setup(
name='roman',
version='3.4.dev0',
author="<NAME>",
author_email="<EMAIL>",
description="Integer to Roman numerals converter",
long_description=desc,
long_description_content_t... |
3324668 | import argparse
import glob
import logging
import logging.config
from os.path import dirname, join
from qac.evaluation import evaluation
from qac.experiments import preprocessing
logger = logging.getLogger(__name__) # pylint: disable=locally-disabled, invalid-name
def _filter_files(files):
return [file for fil... |
3324669 | import numpy as np
from lib import common
import matplotlib as mpl
mpl.use("Agg")
import matplotlib.pyplot as plt
Vmax = 10
Vmin = -10
N_ATOMS = 51
DELTA_Z = (Vmax - Vmin) / (N_ATOMS - 1)
def save_distr(vec, name):
plt.cla()
p = np.arange(Vmin, Vmax+DELTA_Z, DELTA_Z)
plt.bar(p, vec, width=0.5)
plt... |
3324688 | from typing import NamedTuple, Union
class ToyType(NamedTuple):
display_name: str
prefix: Union[str, None]
filter_prefix: str
cmd_safe_interval: float
class Color(NamedTuple):
r: int = None
g: int = None
b: int = None
|
3324693 | import scipy.io as sio
import numpy as np
import os
def sensing_method(method_name,specifics):
# a function which returns a sensing method with given parameters. a sensing method is a subclass of nn.Module
return 1
def computInitMx(Training_labels, specifics):
if(specifics['use_universal_matrix'] == True)... |
3324695 | class Solution(object):
# def isPowerOfThree(self, n):
# """
# :type n: int
# :rtype: bool
# """
# import math
# if n <= 0:
# return False
# # use round to check
# log_res = round(math.log(n, 3), 10)
# if log_res - int(log_res) > 0:... |
3324740 | import string
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
str = str.strip()
if not str:
return 0
start = 0
negative = False
if str[0] == "-":
start = 1
negative = True
... |
3324796 | import io
from pcapng.blocks import InterfaceDescription, SectionHeader
from pcapng.scanner import FileScanner
def test_read_block_interface_bigendian():
scanner = FileScanner(
io.BytesIO(
# ---------- Section header
b"\x0a\x0d\x0d\x0a" # Magic number
b"\x00\x00\x00\x... |
3324808 | import unittest
import numpy as np
class Tests(unittest.TestCase):
def test_random(self):
self.assertEqual(np.random.rand(), 0.417022004702574)
|
3324839 | class Solution:
def solve(self, board: List[List[str]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
if not board: return
row, col = len(board), len(board[0])
q = collections.deque()
for r in range(row):
for c in range(c... |
3324845 | from api.can_api_v2_definition import AggregateRegionSummaryWithTimeseries
from libs import dataset_deployer
def test_remove_root():
value = AggregateRegionSummaryWithTimeseries(__root__=[]).dict()
assert value == {"__root__": []}
result = dataset_deployer.remove_root_wrapper(value)
assert result == ... |
3324869 | from __future__ import division
from __future__ import print_function
import glob
import os
import subprocess
import sys
from hashlib import sha256
import pydot_ng as pydot
PY3 = not sys.version_info < (3, 0, 0)
if PY3:
NULL_SEP = b""
xrange = range
else:
NULL_SEP = ""
bytes = str
DOT_BINARY_PATH =... |
3324949 | from .. utils import TranspileTestCase, BuiltinFunctionTestCase
class ComplexTests(TranspileTestCase):
pass
class BuiltinComplexFunctionTests(BuiltinFunctionTestCase, TranspileTestCase):
function = "complex"
|
3325013 | import hid
zone_dict = {
"IO_LED" : (0x20,0x01),
"LED_CPU" : (0x21,0x02),
"LED_SID" : (0x23,0x08),
"LED_CX" : (0x24,0x10),
"D_LED1" : (0x25,0x20),
"D_LED2" : (0x26,0x40)
}
class AorusRGBController:
def __init__(self, vid=0x048d, pid=0x8297):
assert isinstance(vid, int), "Vendor... |
3325022 | import copy
import ast
class ReadableFields:
"""
This class is responsible for getting all fields from the constructors of
the classes that inherity from it
"""
def __init__(self):
"""
This constructor makes impossible to create a class without a __init__ mehtod.
"""
... |
3325070 | import pytest
from pytest import approx
import unblob._py as python_binding
try:
import unblob._rust as rust_binding
except ModuleNotFoundError:
rust_binding = None
@pytest.fixture(
params=[
pytest.param(python_binding, id="Python"),
pytest.param(
rust_binding,
id... |
3325071 | from util.arg_parser import ArgParser
from motionAE.src.motionGANTrainer import motionGANTrainer
from motionAE.src.motionCVAE2Trainer import motionCVAE2Trainer
from motionAE.src.motionCVAETrainer import motionCVAETrainer
from motionAE.src.motionVAEAdvInitFeedTrainer import motionVAEAdvInitFeedTrainer
from motionAE.src... |
3325087 | import discord
import logging
import time
from discord.ext import commands
from datetime import datetime
log = logging.getLogger('daijobuudes.events')
start_timestamp = time.time()
start_time = datetime.fromtimestamp(start_timestamp)
counter = 0
totalarg = 0
errarg = 0
totalcmd = 0
class Events(commands.Cog):
... |
3325132 | import collections
import datetime
import decimal
import json
import time
import unittest
import uuid
from unittest import TestCase
from unittest.util import safe_repr
import dateutil.parser
import django.test
import django.urls
import django.utils.timezone
import mock
import rest_framework.test
# noinspection PyUnres... |
3325138 | from datetime import timedelta
import datetime
import pandas as pd
import numpy as np
def smooth_with_rolling_average(
series: pd.Series,
window: int = 7,
include_trailing_zeros: bool = True,
exclude_negatives: bool = True,
):
"""Smoothes series with a min period of 1.
Series must have a date... |
3325177 | import serial, time
port = serial.Serial('/dev/ttyACM0', baudrate=57600, timeout=2)
data = '01234567890123456789012345678901234567890123456789'
#data = 'hellohello'
outLine = 'echo %s\n' % data
port.write('\n\n\n')
port.write('free\n')
line = port.readline(80)
while line != '':
print(line)
line = port.readl... |
3325188 | import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
import mod1
from dir_for_mod import mod2
mod1.func()
mod2.func()
|
3325200 | import bcrypt
def generate_password_hash(password):
"""Method to centralize the hashing of passwords
"""
password = password.encode('<PASSWORD>')
return bcrypt.hashpw(password, bcrypt.gensalt(12))
def verify_password_hash(password, password_hash):
"""Method to centralize the verification of pass... |
3325203 | import numpy as np
import os
import random
import cv2
import operator
import json
import time
from utils.tools import normalization, augment_bbox
# Change this path to the users own dataset path
desktop_path = os.path.expanduser("~\Desktop")
seq_path = os.path.join(desktop_path, "dataset", 'MOT')
class data():
d... |
3325284 | import unittest
from medcat.cat import CAT
from medcat.config import Config
from medcat.utils.model_creator import create_models
from pathlib import Path
class EntityLinkingTest(unittest.TestCase):
"""Test entity linking after creating MedCAT CDB and Vocab models.
During class setup, MedCAT CDB and Vocabular... |
3325296 | from app.helpers.render import render_template, render_json
from app.models.Language import Language
from app.server import server
from app.controllers import codepage as codepage_controller
from misc import path_for_icon, default_svg
from jinja2.exceptions import TemplateNotFound
from flask import request, abort, redi... |
3325310 | import os
import sys
import uuid
from os.path import exists
from os.path import join
from os.path import dirname
from os.path import splitext
def get_file_list_recursively(top_directory, allowed_extensions=[]):
"""
Get list of full paths of all files found under root directory "top_directory".
If a list o... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.