id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9873392 | from django.conf.urls import patterns, include, url
# Uncomment the next two lines to enable the admin:
from django.contrib import admin
admin.autodiscover()
from browse.views import display_all, display_time, display_category, display_rank
from manage.views import settings, post, artmanage, catemanage
from manage.vi... |
9873414 | from typing import Optional, Any, List
from pycurd.types import RecordMapping
class UserNotifLastInfo(RecordMapping):
id: bytes = None
last_be_commented_id: bytes = b'\x00'
last_be_replied_id: bytes = b'\x00'
last_be_followed_id: bytes = b'\x00'
last_be_mentioned_id: bytes = b'\x00'
last_be_b... |
9873416 | from flask import Flask
from flask.ext.superadmin import Admin, BaseView, expose
class MyView(BaseView):
@expose('/')
def index(self):
return self.render('index.html')
app = Flask(__name__)
admin = Admin(app)
admin.add_view(MyView(name='Hello 1', endpoint='test1', category='Test'))
admin.add_view(MyV... |
9873425 | from flask import Blueprint, jsonify, request
from flask_cors import CORS
from flask_jwt_extended import get_jwt_identity, jwt_required
from server.user.models import User
import openml
import os
task_blueprint = Blueprint(
"task", __name__, static_folder="server/src/client/app/build"
)
CORS(task_blueprint)
@ta... |
9873462 | import csv
import json
import logging
import os
from abc import ABC
import torch
from pytorch_transformers import BertTokenizer
from torch.utils.data import TensorDataset, SequentialSampler, DataLoader, RandomSampler
from utils.file_utils import read_lines, read_jsonl_lines
logging.basicConfig(format='%(asctime)s - ... |
9873470 | import io
from twisted.internet import reactor
from ygo.card import Card
from ygo.duel_reader import DuelReader
from ygo.parsers.duel_parser import DuelParser
from ygo.utils import process_duel
def msg_select_chain(self, data):
data = io.BytesIO(data[1:])
player = self.read_u8(data)
size = self.read_u8(... |
9873503 | import cv2
import numpy as np
import random
import pdb
# https://github.com/opencv/opencv/pull/8004
data = list()
classes = list()
test = np.array([[1,2,3,4,5]]).astype(np.float32)
for i in range(20):
entry = list()
for j in range(5):
entry.append(int(random.random() * 10))
data.append(entry)
dat... |
9873574 | from Packetbuilder.packetbuilder import create_valid_complete_packet, create_example_frame
test = b"\00" * 68
def to_hex_dump(bytes):
offset = 0
f = open("dump.hex", "w")
for part in range(0, len(bytes), 16):
hexpart = bytes[part:part + 16].hex()
hexpart = ' '.join(a + b for a, b in zip(h... |
9873588 | import os
import pytest
is_pyd = os.environ.get('PYD')
is_pynih = os.environ.get('PYNIH')
def test_std_socket_protocol():
if is_pyd:
with pytest.raises(ImportError):
from phobos import Protocol
else:
from phobos import Protocol, ProtocolType
protocol = Protocol()
... |
9873615 | import logging
import sublime
PACKAGE_NAME = __package__.split(".", 1)[0]
logging.basicConfig(level=logging.ERROR, format="%(name)s [%(levelname)s]: %(message)s")
logger = logging.getLogger(PACKAGE_NAME)
def load_logger():
"""
Subscribe to Preferences changes in to get log level from user settings.
Mus... |
9873634 | import jax
import jax.numpy as jnp
import numpy as np
import pytest
import equinox as eqx
def test_is_array(getkey):
objs = [
1,
2.0,
[2.0],
True,
object(),
jnp.array([1]),
jnp.array(1.0),
np.array(1.0),
np.array(1),
eqx.nn.Linear(1,... |
9873642 | import unittest
from pypidb._exceptions import IncompletePackageMetadata, InvalidPackage
from unittest_expander import expand, foreach
from tests.data import bad_metadata, expected, failures
from tests.test_fedora import _fedora_packages
from tests.test_top import _all as _top_all
from tests.utils import _stdlib, _T... |
9873667 | from django import forms
from crispy_forms_gds.choices import Choice
from crispy_forms_gds.helper import FormHelper
from crispy_forms_gds.layout import HTML, Button, Field, Hidden, Layout, Size
class RadiosForm(forms.Form):
name = forms.ChoiceField(
choices=(("yes", "Yes"), ("no", "No")),
widget... |
9873675 | import time
import numpy as np
import torch.optim
from torchts.nn.models.dcrnn import DCRNN
from torchts.utils import data as utils
model_config = {
"cl_decay_steps": 2000,
"filter_type": "dual_random_walk",
"horizon": 12,
"seq_len": 12,
"input_dim": 2,
"max_diffusion_step": 2,
"num_layer... |
9873687 | from . import BaseTestCase
from os import linesep
class TestMarkdownReferences(BaseTestCase):
def test_href_notation(self):
self.test_document.enable_TOC = False
self.test_document.writeTextLine(
self.test_document.generateHrefNotation(
"This text takes you i... |
9873688 | import warnings
from abc import ABC, abstractmethod
from typing import Union
import numpy as np
import psutil
import torch as T
from gym import Env
from gym.vector import VectorEnv
from pearll import settings
from pearll.common.enumerations import TrajectoryType
from pearll.common.type_aliases import Observation, Tra... |
9873723 | import googlemaps
import urllib
import config
from constants import BASE_URL
import logging
import logger_config
log = logging.getLogger(__name__)
log.info("Entered module: %s" % __name__)
try:
gmaps = googlemaps.Client(config.key) # global variable gmaps
except ValueError as e:
logging.debug(e)
gmaps = ... |
9873743 | from unittest import TestCase
from aws_lambda_builders.architecture import X86_64, ARM64
from aws_lambda_builders.actions import CopySourceAction
from aws_lambda_builders.exceptions import WorkflowFailedError
from aws_lambda_builders.workflows.custom_make.workflow import CustomMakeWorkflow
from aws_lambda_builders.wor... |
9873768 | import sys
import os.path
from co2tools.mergers import merge
from co2tools.stl import solidify
from co2tools.__version__ import __version__
from yaml import load, SafeLoader
def help():
print('co2tools [options] [action] [group]')
print('Options:')
print('\t--version\tPrint version')
print('\t--base=f... |
9873784 | import logging
from zentral.core.exceptions import ImproperlyConfigured
logger = logging.getLogger('zentral.core.events')
# Event deserializer
# The event_types are populated by "register_event_type"
# "register_event_type" is called after an event class definition in an zentral contrib app events module.
# the eve... |
9873801 | import os
import testinfra.utils.ansible_runner
testinfra_hosts = testinfra.utils.ansible_runner.AnsibleRunner(
os.environ['MOLECULE_INVENTORY_FILE']).get_hosts('all')
def test_cron_not_installed(host):
"""When worker is out of service, no crontab should be installed."""
cron = host.file('/etc/cron.d/ck... |
9873812 | class camera():
def __init__(self, cameraID, X, Y, databaseID, name, Ctype):
self.cameraID = cameraID
self.coorX = X
self.coorY = Y
self.databaseID = databaseID
self.name = name
self.Ctype = Ctype
|
9873897 | import torch
import torch.nn as nn
import functools
class UnetWithEmbeddingsGenerator(nn.Module):
"""Create a Unet-based generator with embeddings"""
def __init__(self, input_nc, output_nc, num_downs, ngf=64, nef=0, norm_layer=nn.BatchNorm2d, use_dropout=False,p=0.2):
"""Construct a UnetWithEmbeddings... |
9873900 | import os
import timm
import torch.hub
from torch.nn import Dropout2d
from torch.utils import model_zoo
encoder_params = {
"resnet34": {
"decoder_filters": [48, 96, 176, 192],
"last_upsample": 32
}
}
default_decoder_filters = [48, 96, 176, 256]
default_last = 48
import torch
from torch impor... |
9873905 | import pytest
import numpy as np
import podpac
from podpac.core.data.ogr import OGR, OGRRaw
@pytest.mark.skip(reason="No test file available yet")
class TestOGRRaw(object):
source = "TODO"
driver = "ESRI Shapefile"
layer = "TODO"
attribute = "TODO"
def test_extents(self):
node = OGRRaw(s... |
9873959 | import sys
import maya.OpenMaya as OpenMaya
import maya.OpenMayaMPx as OpenMayaMPx
import maya.cmds as cmds
__author__ = '<NAME>'
__copyright__ = 'Copyright (C) 2016 - Duiker Research Corp'
__license__ = ''
__maintainer__ = '<NAME>'
__email__ = '<EMAIL>'
__status__ = 'Production'
__major_version__ = '1'
__minor_versi... |
9873964 | from QueueAdapter.BaseAdapter import Adapter
from pymongo import MongoClient,errors as pyerrors
import time,threading,os,json
try:
# Python 3.x
from urllib.parse import quote_plus
except ImportError:
# Python 2.x
from urllib import quote_plus
class QueueAp(Adapter):
db = None
runner = None
... |
9874000 | from functools import wraps
def print_return_value(fn):
@wraps(fn)
def _inner(*args, **kwargs):
return_value = fn(*args, **kwargs)
print(return_value)
return return_value
return _inner
|
9874004 | from __future__ import division
import unittest
import numpy as np
from numpy import testing as np_testing
from pax.plugins.peak_processing.BasicProperties import integrate_until_fraction, put_w_in_center_of_field
class TestPeakProperties(unittest.TestCase):
def test_integrate_until_fraction(self):
# Te... |
9874020 | import unittest
import os
import zserio
from testutils import getZserioApi, getApiDir
class ChoiceWithArrayTest(unittest.TestCase):
@classmethod
def setUpClass(cls):
cls.api = getZserioApi(__file__, "choice_types.zs").choice_with_array
def testArray8(self):
testChoice = self.api.TestChoic... |
9874032 | import sys
from .entity import EntityType, Entity
from .validator import PropertyValidator
from .ref import ref
from .action import action as Action
from .blueprint import blueprint
from calm.dsl.log import get_logging_handle
LOG = get_logging_handle(__name__)
# Simple Blueprint
class VmBlueprintType(EntityType):... |
9874057 | from compas_slicer.geometry import Path
from compas_slicer.geometry import Layer
import logging
import progressbar
from compas.geometry import intersection_segment_plane
from compas_slicer.slicers.slice_utilities import ContoursBase
logger = logging.getLogger('logger')
__all__ = ['create_planar_paths']
def create_p... |
9874072 | import uuid
def hamming(s1, s2):
count_diff = 0
for i1, i2 in zip(s1, s2):
if i1 != i2:
count_diff += 1
return count_diff
def at_least_distance(query, existing, d=3):
for e in existing:
if hamming(query, e) < d:
return False
return True
def create_ids(n,... |
9874215 | import logging
def test_deep_update():
import cryptoadvance.specter.helpers as helpers
base_value = {
"pli": {"pla": "blub", "yes": "yes"},
"pli2": ["arrayelm1", "arrayelm2", "arrayelm3"],
"pli3": "aStringValue",
}
assert len(base_value) == 3
assert len(base_value["pli"]) ... |
9874224 | from django import forms
from servers.models import Server
class ServerForm(forms.ModelForm):
class Meta:
model = Server
fields = "__all__"
labels = {"uid": "Linode ID", "root_password": "<PASSWORD>"}
widgets = {
"services": forms.Textarea(
attrs={
... |
9874225 | from django import forms
from orcamentos.utils.lists import GENDER, CUSTOMER_TYPE, PERSON_TYPE
from orcamentos.crm.models import Person, Employee, Customer
class SelectDateWidget(forms.SelectDateWidget):
def create_select(self, *args, **kwargs):
old_state = self.is_required
self.is_required = Fal... |
9874307 | from typing import Optional
from dataclasses import dataclass, field
@dataclass
class RetrievalTrainingArguments:
"""
Arguments pertaining to what data we are going to input our model for training and eval.
"""
dense_train_dataset: Optional[str] = field(
default="squad_kor_v1", metadata={"hel... |
9874360 | import math
import torch
def reduceNet(net, architecture):
children = list(net.children())
if children != []:
for child in children:
architecture = architecture + reduceNet(child, [])
return architecture
else:
return [net]
def extractParams(architecture):
convnet ... |
9874372 | from django.contrib import admin
from django.utils.safestring import mark_safe
from reviews.models import *
class ReviewImageInline(admin.TabularInline):
model = ReviewImage
class OwnerCommentInline(admin.TabularInline):
model = OwnerComment
@admin.register(Review)
class ReviewAdmin(admin.ModelAdmin):
... |
9874385 | import attr
from viberio.utils.safe import ensure_cls
from .data_types.contact import Contact
from .message import TypedMessage
@attr.s
class ContactMessage(TypedMessage):
type: str = attr.ib(default='contact')
text: str = attr.ib(default=None)
contact: Contact = attr.ib(default=None, convert=ensure_cls(... |
9874390 | import maya.cmds as cmds
import maya.mel as mel
import unittest
import hdmaya_test_utils
class TestCommand(unittest.TestCase):
def test_invalidFlag(self):
self.assertRaises(TypeError, cmds.mtoh, nonExistantFlag=1)
def test_listRenderers(self):
renderers = cmds.mtoh(listRenderers=1)
s... |
9874440 | import numpy as np
import pytest
from mmcv.utils import assert_dict_has_keys
from mmaction.datasets.pipelines import (CenterCrop, Flip, Fuse,
MultiScaleCrop, RandomCrop,
RandomResizedCrop, Resize)
from .base import check_crop, check_flip... |
9874451 | from django.conf.urls import url
from graphql_django_view import GraphQLView
from .schema import Schema
urlpatterns = [
url(r'^graphql', GraphQLView.as_view(schema=Schema, pretty=True)),
]
|
9874510 | import numpy
try:
import accupy
fdot = accupy.fdot
def fsum(complex_array):
if not complex_array.dtype.name.startswith('complex'):
return accupy.fsum(complex_array)
return accupy.fsum(numpy.real(complex_array)) + 1j * accupy.fsum(numpy.imag(complex_array))
except ImportError ... |
9874528 | import os
import sys
from datetime import datetime
if __name__ == '__main__':
if len(sys.argv) != 2:
sys.exit(1)
if sys.argv[1] == "debug":
if os.path.isfile("version.h"):
print 'Already Exist'
sys.exit(0)
version_h = open('../../src/MdCharm/version.h.in').read()
... |
9874559 | import pytest
from brainscore.benchmarks.majajhong2015 import load_assembly
from . import check_standard_format
@pytest.mark.private_access
class TestAssembly:
def test_majajhong2015_V4(self):
assembly = load_assembly(average_repetitions=True, region='V4')
check_standard_format(assembly)
... |
9874564 | import KratosMultiphysics.KratosUnittest as UnitTest
import turbulence_modelling_test_case
import periodic_turbulence_modelling_test_case
class MonolithicKOmegaSSTTest(turbulence_modelling_test_case.TurbulenceModellingTestCase):
@classmethod
def setUpClass(cls):
super(MonolithicKOmegaSSTTest, cls).set... |
9874584 | import os
import re
import textwrap
from typing import List
import aiohttp
from discord import Color, Embed, utils
from discord.ext.commands import Cog, CommandError, Context, command
from discord.ext.commands.errors import CommandInvokeError
import html2text
from bot import config
from bot.core.bot import Bot
with ... |
9874603 | from MidiOutFile import MidiOutFile
from MidiOutStream import MidiOutStream
from MidiInFile import MidiInFile
class NoteOnPrinter(MidiOutStream):
ppm=96
spp=60000000/120
currTime=0
notes = [0]*90
def header(self, a, b, division=96):
self.ppm=division
print "Found a header!"
... |
9874630 | from rl_coach.agents.dqn_agent import DQNAgentParameters
from rl_coach.base_parameters import (
EmbedderScheme,
MiddlewareScheme,
PresetValidationParameters,
VisualizationParameters,
)
from rl_coach.core_types import (
EnvironmentEpisodes,
EnvironmentSteps,
MaxDumpFilter,
RunPhase,
S... |
9874651 | from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.models import User
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .models import Classroom,Topic,ClassroomTeachers
from posts.models import Assignment,SubmittedAssignment,Assig... |
9874665 | class Solution:
"""
@param intervalList:
@param number:
@return: return True or False
"""
def isInterval(self, intervalList, number):
# Write your code here
return "True" if any(interval[0] <= number <= interval[1] for interval in intervalList) else "False"
|
9874756 | from __future__ import division, print_function, absolute_import
import glob
import os
import os.path as osp
from ..dataset import ImageDataset
from SoccerNet.Downloader import SoccerNetDownloader as SNdl
import zipfile
class Soccernetv3(ImageDataset):
"""Soccernet-v3 train and valid sets. When set as "source" in... |
9874770 | import torch.nn as nn
from utils.masked_loss import masked_cross_entropy
from utils.statistics import JointLossStatistics
from utils.time_log import time_since
from validation import evaluate_loss
import time
import math
import logging
import torch
import sys
import os
from utils.report import export_train_and_valid_lo... |
9874771 | from schema import And, Optional
class SchedulingRuleSchemas:
register = {
"flight_id": And(str),
"frequency": And(str),
"parameters": And(dict),
"ends_at": And(str)
}
edit = {
"flight_id": And(str),
"frequency": And(str),
"parameters": And(dict),
... |
9874783 | import sys
class listenerlibrary3:
ROBOT_LISTENER_API_VERSION = 3
ROBOT_LIBRARY_SCOPE = "TEST CASE"
def __init__(self):
self.ROBOT_LIBRARY_LISTENER = self
def start_suite(self, data, result):
result.doc = (result.doc + ' [start suite]').strip()
result.metadata['suite'] = '[sta... |
9874786 | def configure(*args, **kwargs):
pass
class EBay(object):
"""An object that helps to wrap around raw api calls.
EBay object initializes an object which take the dev keys and
certificates and configures the parameters being passed to the
url calls.
Instead of keys, the path to file can be ... |
9874787 | from poop.hfdp.factory.pizzaaf.dough import Dough
class ThinCrustDough(Dough):
def __str__(self) -> str:
return "Thin Crust Dough"
|
9874813 | import typing
import pytest
from sitri.providers.contrib.consul import ConsulConfigProvider
from .mock import ConsulMock
@pytest.fixture(scope="module")
def consul_connection() -> typing.Callable:
return lambda: ConsulMock()
@pytest.fixture(scope="module")
def consul_config(consul_connection) -> ConsulConfig... |
9874887 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import sys
import os
import numpy as np
import cv2
import time
from sklearn import preprocessing
from sklearn.metrics.pairwise import pairwise_distances
from sklearn import metrics
sys.path.append("..")
from ... |
9874980 | class CorrectiveRule(object):
def __init__(self, backend_host, backend_port):
self.backend_host = backend_host
self.backend_port = backend_port
@staticmethod
def description():
"""
:return: A short description of the rule
"""
pass
def check(self, query, ... |
9874981 | from pymongo import MongoClient
import os
client = MongoClient(os.environ.get('MONGOLAB_URI'))
db = client[os.environ.get('MONGOLAB_URI').split('/')[-1]]
|
9875015 | import sys
import os
import pytest
import pgzip
import gzip
DATA1 = b""""Beautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
"""
def test_write_wb(tmpdir):
filename = os.path.join(tmpdir, "test.gz")
with pgzip.open(filename, "wb... |
9875035 | import bpy
def find_armatures():
armatures = []
for obj in bpy.context.scene.collection.objects:
if isinstance(obj.data, bpy.types.Armature):
if find_bone_by_tag(obj, 0):
armatures.append(obj)
return armatures
def find_bone_by_tag(armature, tag):
bpy.context.view_l... |
9875036 | import pygame
import random
from .. import scenes
import math
from .. import container
from . import plasma
from . import anchors
from . import mutator
from . import decor
from . import gapfiller
from . import converter
from . import prep
from . import rooms
from .rooms import Room
from . import architect
from . impor... |
9875104 | def extractHimikochouWordpressCom(item):
'''
Parser for 'himikochou.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Affection: Call of the King', 'Affection: Call of the King... |
9875108 | import sys
import Tkinter
class Style(object):
COLOR_BG = 'white'
BORDER_COLOR = '222222'
ERROR_COLOR = 'red'
OK_COLOR = 'green'
FONT_HEADER = ("Helvetica",8,"bold")
FONT_NORMAL = ("Helvetica",8,"normal")
class OpenLabel(Tkinter.Label):
def __init__(sel... |
9875152 | import os
import time
from typing import Tuple
from grpc._channel import _Rendezvous
from clarifai_grpc.channel.clarifai_channel import ClarifaiChannel
from clarifai_grpc.grpc.api import service_pb2, service_pb2_grpc
from clarifai_grpc.grpc.api.status import status_code_pb2
DOG_IMAGE_URL = "https://samples.clarifai.... |
9875154 | import pytest
import spacy
import os
from spacy.language import Language
from spacy_lefff import POSTagger, LefffLemmatizer
from spacy_lefff.melt_tagger import DATA_DIR, PACKAGE
@Language.factory('french_lemmatizer')
def create_french_lemmatizer(nlp, name):
return LefffLemmatizer()
@Language.factory('french_lemm... |
9875201 | import itertools
from collections import namedtuple
def matrix(n):
for i in range(1, n + 1):
for j in range(1, n + 1):
yield f'{i} x {j} = {i * j}'
list(itertools.islice(matrix(10), 10, 20))
l1 = ['x1', 'x2', 'x3', 'x4']
l2 = ['y1', 'y2', 'y3']
for x in l1:
for y in l2:
print(... |
9875225 | import math
from abc import ABC, abstractmethod
import numpy as np
import skimage.transform
import torch
from fastmri_utils.data import transforms
from fastmri_utils.data.transforms import fftshift, ifftshift
# ----- Utilities -----
class RadialMaskFunc(object):
""" Generates a golden angle radial spokes mas... |
9875228 | from filepath.file_relative_paths import FilePaths
import cv2
import pytesseract as tess
import sys
import os
import inspect
import ctypes
import requests
import json
import traceback
def _async_raise(tid, exctype):
tid = ctypes.c_long(tid)
if not inspect.isclass(exctype):
exctype = type(exctype)
... |
9875259 | from importlib import import_module
def object_name(obj):
"""Get the qualified name of an object. This will obtain both the module
name from `__module__` and object name from `__name__`, and concatenate
those with a '.'. Examples:
>>> from math import sin
>>> object_name(sin)
'math.sin'
... |
9875297 | import numpy as np
import pandas as pd
from collections import Counter
from sklearn.cluster import KMeans
from .splitters import get_min_mistakes_cut
from .splitters import get_min_surrogate_cut
try:
from graphviz import Source
graphviz_available = True
except Exception:
graphviz_available = False
BASE_TR... |
9875317 | from collections import OrderedDict
from typing import Mapping
class Serializable:
def state_dict(self) -> OrderedDict:
pass
def load_state_dict(self, state_dict: Mapping) -> None:
if not isinstance(state_dict, Mapping):
raise TypeError("Argument state_dict should be a dictionary... |
9875345 | import typing as t
from functools import update_wrapper
from pca.data.values import (
Owner,
Value,
)
from pca.utils.collections import freeze
# noinspection PyPep8Naming
class reify: # noqa: N801
"""
Taken from `pyramid.decorator`.
Use as a class method decorator. It operates almost exactly ... |
9875377 | from django.apps import AppConfig
class SearchConfig(AppConfig):
label = "search"
name = "edd.search"
verbose_name = "Search"
def ready(self):
# make sure to load/register all the signals
from . import signals # noqa: F401
|
9875402 | import numpy as np
import pandas as pd
import pygrib
from powersimdata.network.usa_tamu.constants.zones import id2abv
from powersimdata.utility.distance import ll2uv
from scipy.spatial import KDTree
from tqdm import tqdm
from prereise.gather.winddata.hrrr.helpers import formatted_filename
from prereise.gather.winddata... |
9875403 | import os
import logging
from bs4 import BeautifulSoup
from urllib.parse import urlparse, unquote
from ..utils.takeout_html_parser import TakeoutHtmlParser
class MyActivityChrome(object):
def parse_chrome_log_body(dic_my_activity_chrome, chrome_logs):
list_chrome_event_logs = TakeoutHtmlParser.find_log_bo... |
9875407 | import genshin
async def test_wish_history(lclient: genshin.Client, authkey: str):
history = await lclient.wish_history(200, limit=20).flatten()
assert history[0].banner_type == 200
assert history[0].banner_name == "Permanent Wish"
async def test_merged_wish_history(lclient: genshin.Client, authkey: st... |
9875408 | from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from ..base import Base
class NovelUrl(Base):
__tablename__ = "novel_urls"
id = Column(Integer, primary_key=True)
url = Column(String, nullable=False)
novel_id = Column(Integer, ForeignKey("novels.id"... |
9875422 | from __future__ import absolute_import
import pandas as pd
import numpy as np
import pyaf.ForecastEngine as autof
csvfile_link = "https://raw.githubusercontent.com/antoinecarme/pyaf/master/data/ozone-la_missing_signal.csv"
csvfile_link = "data/ozone-la_missing_signal.csv"
df = pd.read_csv(csvfile_link);
import dat... |
9875436 | import json
import codecs
import sys
import re
import nltk
from tqdm import tqdm
from nltk.corpus import stopwords
from nltk.stem.porter import PorterStemmer
json_load = lambda x: json.load(codecs.open(x, 'r', encoding='utf-8'))
json_dump = lambda d, p: json.dump(d, codecs.open(p, 'w', 'utf-8'), indent=2, ensure_ascii... |
9875458 | from ddt import data, ddt
from rest_framework import status, test
from waldur_core.quotas.tests import factories
from waldur_core.structure import models as structure_models
from waldur_core.structure.tests import fixtures as structure_fixtures
@ddt
class QuotaUpdateTest(test.APITransactionTestCase):
def setUp(s... |
9875470 | from collections import OrderedDict
import numpy as np
import torch
import torch.nn as nn
import torch.distributions
# Categorical
FixedCategorical = torch.distributions.Categorical
old_sample = FixedCategorical.sample
FixedCategorical.sample = lambda self: old_sample(self).unsqueeze(-1)
log_prob_cat = FixedCatego... |
9875525 | from arm.logicnode.arm_nodes import *
class SetScaleNode(ArmLogicTreeNode):
"""Sets the scale of the given object."""
bl_idname = 'LNSetScaleNode'
bl_label = 'Set Object Scale'
arm_section = 'scale'
arm_version = 1
def arm_init(self, context):
self.add_input('ArmNodeSocketAction', 'In'... |
9875545 | import pandas as pd
import os
from tqdm import tqdm
import argparse
def save_text_file(path, text):
with open(path, 'w+', encoding='utf-8') as out:
out.write(text)
def save_predicted_output(out_csv, dest):
df = pd.read_csv(out_csv)
dest = os.path.abspath(dest)
os.makedirs(dest, exist_ok=True)
... |
9875566 | from collections import deque
import random
from typing import NamedTuple, Optional, List, Iterable
import numpy as np
class ReplayBufferItem(NamedTuple):
state: np.ndarray
action_mask: np.ndarray # action数次元のnp.float32ベクトルで、合法手に1、それ以外に0を代入
action: int # 実際に選んだ行動
next_state: Optional[np.ndarray] # ... |
9875568 | from typing import Dict, List, Mapping, Tuple, Union
import aesara
import aesara.tensor as at
from aesara.graph import optimize_graph
from aesara.graph.basic import Variable
from aesara.graph.opt import EquilibriumOptimizer
from aesara.graph.unify import eval_if_etuple
from aesara.ifelse import ifelse
from aesara.tens... |
9875613 | import sys
sys.path.insert(0, '..')
from imgaug import augmenters as iaa
from config.config import *
from utilities.augment_rand import *
import random
import torchvision
def train_multi_augment1(image, **kwargs):
seq = iaa.SomeOf(1, [
iaa.Noop(),
iaa.Fliplr(p=1),
])
image = seq.augment_images([image])[... |
9875624 | import math
import numpy as np
from tf_explain.core.occlusion_sensitivity import OcclusionSensitivity
def test_should_get_sensitivity_map(convolutional_model, random_data, mocker):
x, y = random_data
patch_size = 4
predict_return_value = (
np.ones(
(
math.ceil(x[0].s... |
9875631 | import os
from pathlib import Path
import random
from farm.eval import Evaluator
from farm.modeling.adaptive_model import AdaptiveModel
from farm.modeling.optimization import initialize_optimizer
from farm.modeling.language_model import LanguageModel
from farm.modeling.prediction_head import TextClassificationHead, Ne... |
9875640 | import datetime
import dateutil.parser
from oauth2client.service_account import ServiceAccountCredentials
from googleapiclient.discovery import build
from PIL import ImageFont
from quietpaper import logger
QP_CALENDAR_FONT = ImageFont.truetype('/usr/share/fonts/truetype/wqy/wqy-microhei.ttc', 12)
class CalendarWidget... |
9875663 | import copy
import hashlib
import json
import re
import time
import uuid
import requests
import responses
from networking_nsxv3.common import config
from networking_nsxv3.plugins.ml2.drivers.nsxv3.agent import provider_nsx_mgmt
from networking_nsxv3.tests.unit.provider import Inventory
from neutron.tests import base
f... |
9875676 | load(
"@rules_cc//cc:defs.bzl",
_cc_library = "cc_library",
)
load(
"@flatbuffers//:build_defs.bzl",
_flatbuffer_cc_library = "flatbuffer_cc_library",
)
def micro_copts():
return []
def cc_library(**kwargs):
kwargs.pop("build_for_embedded", False)
_cc_library(**kwargs)
def flatbuffer_cc_l... |
9875696 | from flask import abort, flash
from flask_login import current_user
from functools import wraps
def requires_roles(*roles):
"""
View function wrapper that allows to check whether
currently logged-in user has one of specified roles.
"""
def wrapper(f):
@wraps(f)
def wrapped(*args, ... |
9875701 | import copy
from abc import abstractmethod
import torch
from ...utils import accuracy_torch_dataloader
class BaseFLKnowledgeDistillationAPI:
"""Abstract class for API of federated learning with knowledge distillation.
Args:
server (aijack.collaborative.core.BaseServer): the server
clients (... |
9875705 | def jump_to_target(num):
abs_num = abs(num)
if abs_num < 2:
return abs_num
point, new_point = None, 0
jump = 1
while new_point <= abs_num:
point = new_point
new_point += jump
jump += 1
jump -= 2
return (2 * (abs_num - point)) + jump
# Tests
assert jump_to_... |
9875724 | import os
import pytest
def pytest_addoption(parser):
parser.addoption("--pyom2-lib", default=None, help="Path to PyOM2 library (must be given for consistency tests)")
parser.addoption("--backend", choices=["numpy", "jax"], default="numpy", help="Numerical backend to test")
def pytest_configure(config):
... |
9875749 | r"""The ``images`` module provides the core functionality of MPoL via :class:`mpol.images.ImageCube`."""
import numpy as np
import torch
import torch.fft # to avoid conflicts with old torch.fft *function*
from torch import nn
from . import utils
from .coordinates import GridCoords
from .gridding import _setup_coords... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.