id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
24159 | import os
import shutil
import pychemia
import tempfile
import unittest
class MyTestCase(unittest.TestCase):
def test_incar(self):
"""
Test (pychemia.code.vasp) [INCAR parsing and writing] :
"""
print(os.getcwd())
iv = pychemia.code.vasp.read_incar('tests/data/vasp_0... |
24180 | import copy
import logging
import warnings
from kolibri.plugins.registry import registered_plugins
logger = logging.getLogger(__name__)
def __validate_config_option(
section, name, base_config_spec, plugin_specs, module_path
):
# Raise an error if someone tries to overwrite a base option
# except for th... |
24211 | import unittest
from huobi.rest.client import HuobiRestClient
from huobi.rest.error import (
HuobiRestiApiError
)
import os
from os.path import join, dirname
from dotenv import load_dotenv
dotenv_path = join(dirname(dirname(dirname(dirname(__file__)))), '.env')
load_dotenv(dotenv_path)
class TestCommonEndpoint(... |
24226 | from django.apps import AppConfig
class TextGeneratorConfig(AppConfig):
name = 'text_generator'
|
24245 | from uncertainties import ufloat
from utilities import min_value, max_value
def main():
print 'Plate motion rate parallel to section'
print plate_motion()
print 'Shortening (including ductile) from bed-length'
print bed_length_shortening()
print 'Estimated total shortening accomodated by OOSTS'
... |
24251 | from unittest.mock import ANY, Mock, patch
import pytest
from streamlit_server_state.server_state_item import ServerStateItem
@pytest.fixture
def patch_is_rerunnable():
with patch(
"streamlit_server_state.server_state_item.is_rerunnable"
) as mock_is_rerunnable:
mock_is_rerunnable.return_val... |
24269 | import dns
import dns.resolver
import dns.rdatatype
def dns_resolve(domain: str) -> list:
addrs = []
resolver = dns.resolver.Resolver(configure=False)
# Default to Google DNS
resolver.nameservers = ['8.8.8.8', '8.8.4.4']
try:
for answer in resolver.resolve(domain, 'A').response.answer:
... |
24271 | import numpy as np
def pline(x1, y1, x2, y2, x, y):
px = x2 - x1
py = y2 - y1
dd = px * px + py * py
u = ((x - x1) * px + (y - y1) * py) / max(1e-9, float(dd))
dx = x1 + u * px - x
dy = y1 + u * py - y
return dx * dx + dy * dy
def psegment(x1, y1, x2, y2, x, y):
px = x2 - x1
py =... |
24277 | import os
from typing import List, Optional
import pickle
import numpy as np
from utilities import augment_long_text, tokenize, tokenize_long_text, to_chars, align
from config import Config as cf
PAD = 0 # TODO: choose appropriate index for these special chars
UNK = 1
DEFAULT = {'PAD': PAD, 'UNK': UNK}
DEFAULT_C = {''... |
24284 | import configparser as parser
import random
class config:
# load the configuration file
def __init__(self, config_filename):
self.load_config(config_filename)
def load_config(self, config_filename):
# create a config parser
config = parser.ConfigParser()
config.optionxform ... |
24286 | import sys
import gtk
from datetime import datetime
import gobject
from threading import Thread
class uiSignalHelpers(object):
def __init__(self, *args, **kwargs):
super(uiSignalHelpers, self).__init__(*args, **kwargs)
#print 'signal helpers __init__'
def callback(self, *args, **kwargs):
... |
24308 | from awx.main import signals
class TestCleanupDetachedLabels:
def test_cleanup_detached_labels_on_deleted_parent(self, mocker):
mock_labels = [mocker.MagicMock(), mocker.MagicMock()]
mock_instance = mocker.MagicMock()
mock_instance.labels.all = mocker.MagicMock()
mock_instance.labe... |
24329 | from dataclasses import dataclass, field
from typing import Dict
import perde
import pytest
from util import FORMATS, FORMATS_EXCEPT
"""rust
#[derive(Serialize, Debug, new)]
struct Plain {
a: String,
b: String,
c: u64,
}
add!(Plain {"xxx".into(), "yyy".into(), 3});
"""
@pytest.mark.parametrize("m", FORMATS)
d... |
24371 | from django.urls import path
from . import views
urlpatterns = [
path("draugiem/login/", views.login, name="draugiem_login"),
path("draugiem/callback/", views.callback, name="draugiem_callback"),
]
|
24376 | import sys
import requests
import json
import argparse
import time
parser = argparse.ArgumentParser(description='Collects monitoring data from Pingdom.')
parser.add_argument('-u', '--pingdom-user-name', help='The Pingdom User Name', required=True)
parser.add_argument('-p', '--pingdom-password', help='The Pingdom Passw... |
24381 | import logging
from typing import Any, List, Optional
from homeassistant.components.climate.const import (
HVAC_MODE_AUTO,
HVAC_MODE_COOL,
HVAC_MODE_FAN_ONLY,
)
from gehomesdk import ErdAcFanSetting
from ..common import OptionsConverter
_LOGGER = logging.getLogger(__name__)
class AcFanModeOptionsConverte... |
24392 | from typing import Dict
# The rest of the codebase uses mojos everywhere.
# Only use these units for user facing interfaces.
units: Dict[str, int] = {
"cryptodoge": 10 ** 6, # 1 cryptodoge (XCD) is 1,000,000 mojo (1 million)
"mojo:": 1,
"colouredcoin": 10 ** 3, # 1 coloured coin is 1000 colouredcoin mojo... |
24413 | import torch
import torch.nn as nn
from cogdl.utils import spmm
class GINLayer(nn.Module):
r"""Graph Isomorphism Network layer from paper `"How Powerful are Graph
Neural Networks?" <https://arxiv.org/pdf/1810.00826.pdf>`__.
.. math::
h_i^{(l+1)} = f_\Theta \left((1 + \epsilon) h_i^{l} +
... |
24420 | import json
import falcon
import time
import uuid
import requests
from apps.database import init_db, db_session
from apps.models import Account
from apps.restaccount.logging import logging
logger = logging.getLogger(__name__)
from decouple import config
ES_HOST = config('EVENTSTORE_HOST', default='eventstore')
ES_PO... |
24453 | import unittest
import paddle
import neural_renderer_paddle as nr
class TestLighting(unittest.TestCase):
def test_case1(self):
"""Test whether it is executable."""
faces = paddle.randn([64, 16, 3, 3], dtype=paddle.float32)
textures = paddle.randn([64, 16, 8, 8, 8, 3], dtype=paddle.fl... |
24475 | from typing import List, Optional
from pydantic import BaseModel
class Provider(BaseModel):
url: str
name: str
roles: Optional[List[str]] = None
|
24517 | from datetime import datetime, timezone
from io import StringIO
from unittest import mock
import freezegun
import pytest
from django.conf import settings
from django.core.management import call_command
from django.utils import timezone
from model_bakery import baker
from supportal.app.common.enums import CanvassResul... |
24556 | import unittest
from pyhmmer.easel import Alphabet
from pyhmmer.errors import UnexpectedError, AllocationError, EaselError, AlphabetMismatch
class TestErrors(unittest.TestCase):
def test_unexpected_error(self):
err = UnexpectedError(1, "p7_ReconfigLength")
self.assertEqual(repr(err), "Unexpected... |
24557 | import base64
STANDARD_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567'
CUSTOM_ALPHABET = 'abcdefghjkmnprstuvwxyz0123456789'
ENCODE_TRANS = str.maketrans(STANDARD_ALPHABET, CUSTOM_ALPHABET)
DECODE_TRANS = str.maketrans(CUSTOM_ALPHABET, STANDARD_ALPHABET)
PADDING_LETTER = '='
def encode(buffer):
assert type(buffer) ... |
24591 | import os
import re
import csv
import sys
import json
import yaml
import time
import socket
import connexion
import postgresql as psql
from flask import current_app
from urllib.parse import urlencode
from hashlib import md5
from bokeh.embed import server_document
from .processes import fetch_process, is_running, proce... |
24592 | import numpy as np
import chainer
from chainer import cuda, Function, gradient_check, Variable
from chainer import optimizers, serializers, utils
from chainer import Link, Chain, ChainList
import chainer.functions as F
import chainer.links as L
class normalNN(Chain):
def __init__(self, dim):
super().__ini... |
24596 | import json
import requests
from typing import List
from konlpy.tag import Okt
from requests.models import Response
class OktTokenizer:
"""
A POS-tagger based tokenizer functor. Note that these are just examples. The `phrases` function usually gives a better result than an ordinary POS tokenizer.
... |
24608 | from .alexnet import alexnet_V2
import tensorflow.compat.v1 as tf
import tensorflow.contrib.slim as slim
from utils import montage_tf
from .lci_nets import patch_inpainter, patch_discriminator
import tensorflow.contrib as contrib
# Average pooling params for imagenet linear classifier experiments
AVG_POOL_PARAMS = {'... |
24614 | import tvm
from functools import reduce
from ..utils import to_int, to_int_or_None
def get_need_tile(need_tile):
return [True if x.value == 1 else False for x in need_tile]
def get_factors(split_factor_entities):
return [[x.value for x in factors.factors] for factors in split_factor_entities]
def tile_axis(st... |
24645 | import io
from PIL import Image
from torchvision import models
import torch
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import urllib
import os
def get_model_from_global_agent():
global_model = models.squeezenet1_1(pretrained=True)
global_model.classifier[1... |
24659 | import torch
from torch import nn
from configs import ANCHOR_SIZES
class PostRes(nn.Module):
def __init__(self, n_in, n_out, stride=1):
super(PostRes, self).__init__()
self.conv1 = nn.Conv3d(n_in, n_out, kernel_size=3, stride=stride, padding=1)
self.bn1 = nn.BatchNorm3d(n_out)
self... |
24672 | from tir import Webapp
import unittest
from tir.technologies.apw_internal import ApwInternal
import datetime
import time
DateSystem = datetime.datetime.today().strftime('%d/%m/%Y')
DateVal = datetime.datetime(2120, 5, 17)
"""-------------------------------------------------------------------
/*/{Protheus.doc} PLSA809T... |
24707 | import abc
from config import MODEL_DIR
class Network:
__metaclass__ = abc.ABCMeta
@abc.abstractmethod
def __init__(self):
self.model = None
self.model_history = None
self.X_train = None
self.X_test = None
self.y_train = None
self.y_test = None
@abc.a... |
24715 | import os
def remove_comments_and_crlf(inp_path, comment_string=';', overwrite=False):
tmpfilename = os.path.splitext(os.path.basename(inp_path))[0] + '_mod.inp'
tmpfilepath = os.path.join(os.path.dirname(inp_path), tmpfilename)
with open (inp_path) as oldf:
with open(tmpfilepath, 'w') as newf:
... |
24717 | import re
import pprint
pp = pprint.PrettyPrinter(indent=4)
from sys import version_info # py3, for checking type of input
def combine_messages(messages):
""" Combines messages that have one or more integers in them, such as
"trial001" "trial002", into a single message like "trial# (#=1-2)".
Thi... |
24756 | from . import BasicType
class UserProfilePhotos(BasicType):
fields = {
'total_count': int,
}
def __init__(self, obj=None):
super(UserProfilePhotos, self).__init__(obj)
from . import photosize
UserProfilePhotos.fields.update({
'photos': {
'class': photosize.PhotoSize,
... |
24780 | import nengo
import pytest
from nengo_spinnaker.builder import Model
from nengo_spinnaker.builder.ports import OutputPort, InputPort
from nengo_spinnaker.node_io import ethernet as ethernet_io
from nengo_spinnaker.operators import SDPReceiver, SDPTransmitter
@pytest.mark.parametrize("transmission_period", [0.001, 0.... |
24788 | from rest_framework import serializers
from api.model.foodComment import FoodComment
from api.model.food import Food
from django.contrib.auth.models import User
from api.serializer.user import UserSerializer
class FoodCommentSerializer(serializers.ModelSerializer):
comment = serializers.CharField(max_length=255... |
24823 | import deepchem as dc
import numpy as np
import os
def test_numpy_dataset_get_shape():
"""Test that get_shape works for numpy datasets."""
num_datapoints = 100
num_features = 10
num_tasks = 10
# Generate data
X = np.random.rand(num_datapoints, num_features)
y = np.random.randint(2, size=(num_datapoints,... |
24856 | import logging
import sys
import os
from logging.handlers import RotatingFileHandler
from multiprocessing.pool import ThreadPool
from optparse import OptionParser
import requests
from requests.packages import urllib3
urllib3.disable_warnings()
# Workers configurations
ASYNC_WORKERS_COUNT = 100 # How many threads wi... |
24906 | from __future__ import division, print_function
from .. import __version__
from ._global_imports import *
try:
import h5py
except ImportError:
print('Install h5py to enable signal caching.')
raise
class _Cache(object):
""" Cache numerical model objects computed during likelihood evaluation.
:pa... |
24962 | from django import template
register = template.Library()
@register.inclusion_tag('quiz/correct_answer.html', takes_context=True)
def correct_answer_for_all(context, question):
"""
processes the correct answer based on a given question object
if the answer is incorrect, informs the user
"""
answe... |
24992 | import re
import string
import numpy as np
from tqdm import tqdm
from typing import List
from docqa.triviaqa.read_data import TriviaQaQuestion
from docqa.triviaqa.trivia_qa_eval import normalize_answer, f1_score
from docqa.utils import flatten_iterable, split
"""
Tools for turning the aliases and answer strings from... |
25004 | from django.shortcuts import render, redirect, reverse
from django.core.paginator import Paginator, PageNotAnInteger, EmptyPage
from django.db.models import Q
from django.views.generic import View
from .models import OrgInfo, CityInfo, TeacherInfo
from operations.models import UserLove
# Create your views here.
clas... |
25008 | from sys import path
path.append('..')
from armoryengine import *
TheBDM.setBlocking(True)
TheBDM.setOnlineMode(True)
if not os.path.exists('testmultiblock'):
os.mkdir('testmultiblock')
fout = []
fout.append([0, 101, 'testmultiblock/blk00000.dat'])
fout.append([0, 102, 'testmultiblock/blk00000_test1.dat']) #... |
25062 | from django.urls import reverse
from rest_framework import status
from conf_site.api.tests import ConferenceSiteAPITestCase
class ConferenceSiteAPIConferenceTestCase(ConferenceSiteAPITestCase):
def test_conference_api_anonymous_user(self):
response = self.client.get(reverse("conference-detail"))
... |
25087 | from tests.common.devices.base import AnsibleHostBase
class VMHost(AnsibleHostBase):
"""
@summary: Class for VM server
For running ansible module on VM server
"""
def __init__(self, ansible_adhoc, hostname):
AnsibleHostBase.__init__(self, ansible_adhoc, hostname)
@property
def e... |
25098 | from __future__ import absolute_import, division, print_function
import pytest
import telnyx
TEST_RESOURCE_ID = "f1486bae-f067-460c-ad43-73a92848f902"
class TestPortingOrder(object):
def test_is_listable(self, request_mock):
resources = telnyx.PortingOrder.list()
request_mock.assert_requested("... |
25217 | from bumblebee.bigquery_service import BigqueryService
from datetime import datetime
from abc import ABC
from abc import abstractmethod
from bumblebee.config import LoadMethod
class BaseLoader(ABC):
@abstractmethod
def load(self, query):
pass
class PartitionLoader(BaseLoader):
def __init__(sel... |
25241 | from distutils.version import StrictVersion as SV
import unittest
import minecraft
class VersionTest(unittest.TestCase):
def test_module_version_is_a_valid_pep_386_strict_version(self):
SV(minecraft.__version__)
def test_protocol_version_is_an_int(self):
for version in minecraft.SUPPORTED_PR... |
25258 | import datetime
import os
import sys
from optparse import make_option
from django.core.management.base import BaseCommand
from django.conf import settings
try:
from django.contrib.gis.utils import LayerMapping
except ImportError:
print("gdal is required")
sys.exit(1)
from tigerline.models import County
... |
25264 | from __future__ import print_function
import os
import time
import tensorflow as tf
import numpy as np
import sys
from zoneout_wrapper import ZoneoutWrapper
class SequencePredictor():
def add_placeholders(self):
"""Generates placeholder variables to represent the input tensors
"""
self.inp... |
25276 | from z3 import *
H = Int('H')
s = Solver()
t = 4 + 4 * (((H - 1) / 2) / 2)
s.add(H % 4 == 0)
s.check()
m = s.model()
def subterms(t):
seen = {}
def subterms_rec(t):
if is_app(t):
for ch in t.children():
if ch in seen:
continue
seen[ch] = ... |
25278 | from abc import ABC
class ProbeConfig(object):
def __init__(self):
self.directives = {}
def add_directive(self, directive):
name = directive.keyword
if name not in self.directives:
self.directives[name] = []
self.directives[name].append(directive)
def get_dire... |
25324 | import pytest
from flake8.exceptions import ExecutionError
from flake8_adjustable_complexity.config import DEFAULT_CONFIG
@pytest.mark.parametrize(
('args', 'max_mccabe_complexity'),
[
(['--max-mccabe-complexity=5'], 5),
(['--max-adjustable-complexity=10'], 10),
([], DEFAULT_CONFIG.ma... |
25333 | from django.utils.translation import get_language
def django_settings(request):
return {
"LANGUAGE": get_language(),
}
|
25351 | import math
import numpy as np
from numba import cuda, float32
from numba.cuda.testing import unittest
import numba.cuda.random
from numba.cuda.testing import skip_on_cudasim, CUDATestCase
from numba.cuda.random import \
xoroshiro128p_uniform_float32, xoroshiro128p_normal_float32, \
xoroshiro128p_uniform_flo... |
25431 | import os.path
import time
from moler.config import load_config
from moler.device.device import DeviceFactory
from moler.util.moler_test import MolerTest
def outage_callback(device_name, ping_times):
MolerTest.info("Network outage on {}".format(device_name))
ping_times["lost_connection_time"] = time.time()
... |
25449 | from config import args
from utils import delete_existing, get_img, get_img_files
import tensorbayes as tb
import tensorflow as tf
import numpy as np
import os
def push_to_buffer(buf, data_files):
files = np.random.choice(data_files, len(buf), replace=False)
for i, f in enumerate(files):
buf[i] = get_i... |
25503 | import humps
import pytest
from django import test
from django.contrib.auth.models import User
from django.urls import reverse
def test_profile_updates_correctly(
profile_admin_client: test.Client, user: User, update_profile_params
):
url = f"{reverse('admin_update_profile')}?email={user.email}"
res = pro... |
25549 | import time
import json
from wptserve.utils import isomorphic_decode, isomorphic_encode
def main(request, response):
headers = [(b'Content-Type', b'application/javascript'),
(b'Cache-Control', b'max-age=86400'),
(b'Last-Modified', isomorphic_encode(time.strftime(u"%a, %d %b %Y %H:%M:... |
25561 | import asyncio
import time
from collections import namedtuple
from http import HTTPStatus
import pytest
from aiojenkins.exceptions import JenkinsError
from aiojenkins.jenkins import Jenkins
from tests import CreateJob, get_host, get_login, get_password, is_ci_server
@pytest.mark.asyncio
async def test_invalid_host... |
25572 | from flax.geometry import Blob, Point, Rectangle, Size, Span
def test_blob_create():
rect = Rectangle(origin=Point(0, 0), size=Size(5, 5))
blob = Blob.from_rectangle(rect)
assert blob.area == rect.area
assert blob.height == rect.height
def test_blob_math_disjoint():
# These rectangles look like... |
25577 | from resolwe.flow.models import Data
from resolwe.test import tag_process
from resolwe_bio.utils.filter import filter_vcf_variable
from resolwe_bio.utils.test import BioProcessTestCase
class CheMutWorkflowTestCase(BioProcessTestCase):
@tag_process("workflow-chemut")
def test_chemut_workflow(self):
wi... |
25628 | from hearthbreaker.cards.base import SpellCard
from hearthbreaker.constants import CHARACTER_CLASS, CARD_RARITY
from hearthbreaker.tags.base import BuffUntil, Buff
from hearthbreaker.tags.event import TurnStarted
from hearthbreaker.tags.status import Stealth, Taunt, Frozen
import hearthbreaker.targeting
class TheCoin... |
25644 | import subprocess
import time
import sys
import signal
from testutils import assert_raises
is_unix = not sys.platform.startswith("win")
if is_unix:
def echo(text):
return ["echo", text]
def sleep(secs):
return ["sleep", str(secs)]
else:
def echo(text):
return ["cmd", "/C", f"echo {... |
25654 | from . import get_main_movies_base_data
from . import get_main_movies_full_data
from . import get_celebrities_full_data
from . import down_video_images
from . import down_celebrity_images
|
25661 | import random
from precise.skaters.managerutil.managertesting import manager_test_run
from precise.skaters.managers.equalmanagers import equal_daily_long_manager, equal_long_manager
from precise.skaters.managers.equalmanagers import equal_weekly_long_manager, equal_weekly_buy_and_hold_long_manager
from precise.skaterto... |
25672 | def main():
seed = 0x1234
e = [0x62d5, 0x7b27, 0xc5d4, 0x11c4, 0x5d67, 0xa356, 0x5f84,
0xbd67, 0xad04, 0x9a64, 0xefa6, 0x94d6, 0x2434, 0x0178]
flag = ""
for index in range(14):
for i in range(0x7f-0x20):
c = chr(0x20+i)
res = encode(c, index, seed)
if... |
25706 | import arcpy, os
#walk through all subdirectories and change mxd to store relative paths
for root, dirs, files in os.walk(r"Q:\Geodata\shape"):
for f in files:
if f.endswith(".mxd"):
filepath = root + '\\' + f
print filepath
try:
... |
25721 | from django.contrib.auth.models import User
from django.test import TestCase
from adminlte_log.models import AdminlteLogType, AdminlteLog
class AdminlteLogTest(TestCase):
def setUp(self):
AdminlteLogType.objects.create(name='test', code='test')
self.user = User.objects.create_user(username='boha... |
25778 | import numpy as np
import torch
import torch.nn as nn
import torch.optim as optim
from rl.dataset import ReplayBuffer, RandomSampler
from rl.base_agent import BaseAgent
from rl.policies.mlp_actor_critic import MlpActor, MlpCritic
from util.logger import logger
from util.mpi import mpi_average
from util.pytorch import ... |
25793 | from rest_framework import generics, permissions
from rest_framework import filters as filters_rf
from django_filters import rest_framework as filters
from allauth.socialaccount.models import SocialAccount, SocialApp, SocialToken
from .serializers import SocialAppSerializer, SocialAppExtendedSerializer, SocialAccountS... |
25798 | import os
import json
import re
import sys
import logging
import hashlib
import uuid
import jsonschema
import tempfile
import controller
import anchore_utils
import anchore_auth
from anchore.util import contexts
_logger = logging.getLogger(__name__)
default_policy_version = '1_0'
default_whitelist_version = '1_0'
de... |
25805 | import ROOT,sys
from larlite import larlite as fmwk1
from larcv import larcv as fmwk2
from ROOT import handshake
io1=fmwk1.storage_manager(fmwk1.storage_manager.kBOTH)
io1.add_in_filename(sys.argv[1])
io1.set_out_filename('boke.root')
io1.open()
io2=fmwk2.IOManager(fmwk2.IOManager.kREAD)
io2.add_in_file(sys.argv[2])
... |
25826 | from flask import Flask
from flask_sqlalchemy import SQLAlchemy
from flask_script import Manager
from flask_migrate import Migrate, MigrateCommand
app = Flask(__name__)
app.config[
'SQLALCHEMY_DATABASE_URI'] = 'postgres://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
db = SQLAlchemy(app)
migrate = Migrate(app, db)
manage... |
25837 | from django.conf import settings
from django.conf.urls import url
from django.urls import LocalePrefixPattern, URLResolver, get_resolver, path
from TWLight.i18n.views import set_language
# Direct rip from django.conf.urls.i18n, but imports our local set_language
# from GitHub
def i18n_patterns(*urls, prefix_default_... |
25840 | from __future__ import absolute_import
import chainer
import chainer.functions as F
from .convolution import ConvolutionND
def _pair(x, ndim=2):
if hasattr(x, '__getitem__'):
return x
return [x]*ndim
class PixelShuffleUpsamplerND(chainer.Chain):
"""Pixel Shuffler for the super resolution.
Th... |
25899 | import alignments
import re
import read
import binaryIO
import math
import os
import preprocess
import time
class Compressor:
aligned = None
# 0 - zlib
# 1 - lzma
# 2 - bz2
compressMethod = 0
covSize = 0
totalSize = 0
def __init__(self, frag_len_cutoff):
if self.compressMetho... |
25914 | import inspect
from collections import defaultdict
from typing import Dict, List, NamedTuple
from .core import PluginFinder, PluginSpec
from .discovery import PackagePathPluginFinder
class EntryPoint(NamedTuple):
name: str
value: str
group: str
EntryPointDict = Dict[str, List[str]]
def discover_entry... |
25986 | from transformers import model_paths
def test_candy_model():
assert model_paths.CANDY_FAST_NEURAL_TRANSFER_MODEL == "models/candy.t7"
def test_feathers_model():
assert model_paths.FEATHERS_FAST_NEURAL_TRANSFER_MODEL == "models/feathers.t7"
def test_mosaic_model():
assert model_paths.MOSAIC_FAST_NEURAL_TRANSFER... |
26021 | from watchFaceParser.elements.basicElements.imageSet import ImageSet
class Icon:
definitions = {
1: { 'Name': 'Images', 'Type': ImageSet},
2: { 'Name': 'NoWeatherImageIndex', 'Type': 'long'},
}
|
26028 | from data_importers.management.commands import BaseHalaroseCsvImporter
class Command(BaseHalaroseCsvImporter):
council_id = "SCE"
addresses_name = "2021-11-10T10:12:49.277177/polling_station_export-2021-11-10.csv"
stations_name = "2021-11-10T10:12:49.277177/polling_station_export-2021-11-10.csv"
elect... |
26044 | from beem.utils import formatTimeString, resolve_authorperm, construct_authorperm, addTzInfo
from beem.nodelist import NodeList
from beem.comment import Comment
from beem import Steem
from beem.account import Account
from beem.instance import set_shared_steem_instance
from beem.blockchain import Blockchain
import time ... |
26064 | import torch
import torch.nn as nn
import torch.nn.functional as F
from ..decoder import ConvDecoder
from ..encoder import build_encoder
from ..modules import conv, deconv
from ..similarity import CorrelationLayer
from ..utils import warp
from .build import MODEL_REGISTRY
@MODEL_REGISTRY.register()
class PWCNet(nn.M... |
26129 | import FWCore.ParameterSet.Config as cms
import TrackingTools.MaterialEffects.OppositeMaterialPropagator_cfi
#PropagatorWithMaterialESProducer
oppositeToMomElePropagator = TrackingTools.MaterialEffects.OppositeMaterialPropagator_cfi.OppositeMaterialPropagator.clone(
Mass = 0.000511,
ComponentName = '... |
26130 | from rdflib import plugin
from rdflib import store
plugin.register(
"SQLAlchemy",
store.Store,
"rdflib_sqlalchemy.store",
"SQLAlchemy",
)
|
26132 | import difflib
import discord
from discord.ext import commands
from discord.ext.commands import CommandNotFound
intents = discord.Intents.all()
client = commands.Bot(command_prefix="+", intents=intents, help_command=None)
@client.event
async def on_ready():
print("Bot Online")
@client.event
async def on_comma... |
26133 | import asyncio
import logging
import time
from typing import Optional, List
from hummingbot.core.data_type.user_stream_tracker_data_source import \
UserStreamTrackerDataSource
from hummingbot.logger import HummingbotLogger
from hummingbot.connector.exchange.bitfinex.bitfinex_order_book import BitfinexOrderBook
fro... |
26174 | import csv
def read_regressor_examples(num_of_features, num_of_decisions, file_path):
xs = []
ys = []
with open(file_path, mode='r', encoding='utf-8') as file:
reader = csv.reader(file, delimiter=' ')
for row in reader:
x = [float(value) for value in row[0 : num_of_features]]... |
26207 | class T:
WORK_REQUEST = 1
WORK_REPLY = 2
REDUCE = 3
BARRIER = 4
TOKEN = 7
class Tally:
total_dirs = 0
total_files = 0
total_filesize = 0
total_stat_filesize = 0
total_symlinks = 0
total_skipped = 0
total_sparse = 0
max_files = 0
total_nlinks = 0
total_nlinke... |
26256 | def _init():
from som.vm.universe import create_universe
return create_universe()
current_universe = _init()
|
26261 | import re
# crawl roster
faulty_prof = {
'Francis,J)' : 'Francis,J (jdf2)',
'Glathar,E)' : 'Glathar,E',
'Cady,B)' : 'Cady,B'
}
section_types = set()
day_pattern = {
'M': 1,
'T': 1<<1,
'W': 1<<2,
'R': 1<<3,
'F': 1<<4,
'S': 1<<5,
'U': 1<<6
}
def to_bool(s):
return True if ... |
26291 | import time
from typing import Any, List
import pytest
from yarl import URL
from neuro_sdk import Action, FileStatus, FileStatusType
from neuro_sdk.storage import DiskUsageInfo
from neuro_cli.formatters.storage import (
BaseFilesFormatter,
BSDAttributes,
BSDPainter,
DiskUsageFormatter,
FilesSorte... |
26306 | import time
import asyncio
import random
import pyee
import logging
from plugins.input_fsx import fsx_pb2
from hexi.service import event
_logger = logging.getLogger(__name__)
class UDPServer(asyncio.DatagramProtocol):
def __init__(self, manager, token):
super().__init__()
self.manager = manager
self... |
26311 | import argparse
from collections import defaultdict
import pickle
import re
import lightgbm as lgb
import pandas as pd
import numpy as np
import xgboost as xgb
from ..data_utils import SEG_FP, get_encoded_classes
from ..utils import print_metrics
from ..metric import get_metrics
from .blend import (
score_predict... |
26319 | from anuga.utilities import plot_utils as util
from matplotlib import pyplot as pyplot
import numpy
verbose= True
swwfile = 'merewether_1m.sww'
p=util.get_output(swwfile)
p2=util.get_centroids(p)
# Time index at last time
tindex = len(p2.time)-1
if verbose: print('calculating experimental transect')
x_data = ... |
26344 | import time
from typing import Callable
from functools import wraps
def timeit(metric_callback: Callable, **labels):
def wrapper(func):
@wraps(func)
def func_wrapper(*args, **kwargs):
start = time.time()
result = func(*args, **kwargs)
metric_callback(time.time()... |
26363 | from myhdl import Signal, intbv, always, always_comb, block, instances
from hdmi.cores.primitives import dram16xn
@block
def convert_30_to_15(reset, clock, clockx2, data_in, tmds_data2, tmds_data1, tmds_data0):
"""
The block converts the 30-bit data into 15-bit data.
Args:
reset: The reset sig... |
26468 | from __future__ import division
import numpy as np
from sklearn.utils import shuffle
from sklearn.metrics import *
"""
Module with different fitness functions implemented to be used by the CRO algorithm.
The functions' only argument must be an individual (coral) and return its fitness, a number.
The fitness might re... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.