id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3385741 | import pytest
from pydantic import PydanticTypeError
def test_pydantic_error():
class TestError(PydanticTypeError):
code = 'test_code'
msg_template = 'test message template "{test_ctx}"'
def __init__(self, *, test_ctx: int) -> None:
super().__init__(test_ctx=test_ctx)
wi... |
3385782 | import argparse
import datetime
import json
import os
from PIL import Image
import pycococreatortools
def get_arguments():
parser = argparse.ArgumentParser(description="transform mask annotation to coco annotation")
parser.add_argument("--dataset", type=str, default='CIHP', help="name of dataset (CIHP, MHPv2... |
3385800 | from sightpy import *
# define materials to use
blue_glass = Refractive(n = vec3(1.5 + 4e-8j,1.5 + 4e-8j,1.5 + 0.j)) # n = index of refraction
green_glass = Refractive(n = vec3(1.5 + 4e-8j,1.5 + 0.j,1.5 + 4e-8j))
red_glass = Refractive(n = vec3(1.5 + 0.j,1.5 + 5e-8j,1.5 + 5e-8j))
floor = Glossy(diff_co... |
3385807 | import numpy as np
from pyspec import spectrum as spec
def test_parseval_1d(rtol=1.e-14, debug=False):
""" Make sure 1D spectrum satisfied Parseval relation """
N = np.array([10,11,21,500,871,1000,1001])
dta = np.array([.25,1.,1.67,6.,20.])
for dt in dta:
for n in N:
p... |
3385817 | import argparse
import sys
import struct
import binascii
def named(tuple,names):
return dict(zip(names,tuple))
def parse(fmt,data,names):
return named(struct.unpack(fmt,data),names)
def fileunpack(f, fmt, names):
n = struct.calcsize(fmt)
return parse(fmt, f.read(n), names)
class DfuFile:
def __i... |
3385826 | from typing import Optional
from typing import Tuple
import numpy as np
import onnx
from tests.utils.common import check_onnx_model
from tests.utils.common import make_model_from_nodes
def _test_clip(
input_shape: Tuple[int, int, int, int],
min_value: Optional[float] = None,
max_value: Optio... |
3385895 | def to_hex(val):
'''Return val as str of hex values concatenated by colons.'''
if type(val) is int:
return hex(val)
try:
# Python-2.x
if type(val) is long:
return hex(val)
except NameError:
pass
# else:
try:
# Python-2.x
return ":".join... |
3385944 | import hashlib
import json
import os
import pathlib
from argparse import ArgumentParser
from tensorflow.keras.utils import Progbar
def parse_args():
"""Parse CLI argument."""
parser = ArgumentParser()
parser.add_argument("--input", "-i", help="Path to directory with .h5 files.")
return parser.parse_a... |
3385976 | import sys
import json
import string
from collections import Counter
from nltk.tokenize import TweetTokenizer, sent_tokenize
# load text into memory
file_object = open(sys.argv[1], 'r')
text = file_object.read()
# count sentences and words
wordCount = 0
tokenizer_words = TweetTokenizer()
tokens_sentences = [tokenizer... |
3386119 | import itertools
from typing import List, Optional, Dict
from collections import Counter
import numpy as np
from hotpot.data_handling.dataset import ListBatcher, Dataset, QuestionAndParagraphsSpec, QuestionAndParagraphsDataset, \
Preprocessor, SampleFilter, TrainingDataHandler
from hotpot.data_handling.relevance_... |
3386121 | from abc import ABC
from recipe_db.analytics.recipe import RecipesPopularityAnalysis
from recipe_db.analytics.scope import RecipeScope, HopProjection, StyleProjection
from recipe_db.models import Hop, Style
from web_app.charts.utils import NoDataException, Chart, ChartDefinition
from web_app.plot import LinesChart
c... |
3386138 | import threading
from dataclasses import dataclass
from rx.disposable import SingleAssignmentDisposable, CompositeDisposable
from rxbp.multicast.multicastobserver import MultiCastObserver
from rxbp.multicast.typing import MultiCastItem
@dataclass
class MergeMultiCastObserver(MultiCastObserver):
observer: MultiC... |
3386141 | test = int(input())
while test > 0 :
n = int(input())
l = list(map(int,input().split()))
l.sort()
l.reverse()
count = 0
for i in range(0,n,2) :
count += l[i]
print(count)
test -= 1
|
3386160 | def test_socfaker_container_id(socfaker_fixture):
assert socfaker_fixture.container.id
def test_socfaker_container_name(socfaker_fixture):
assert socfaker_fixture.container.name
def test_socfaker_container_tags(socfaker_fixture):
assert socfaker_fixture.container.tags
def test_socfaker_container_runtime(... |
3386161 | from carla_utils import carla
import rospy
import numpy as np
from typing import List
from std_msgs.msg import Header, ColorRGBA
from geometry_msgs.msg import Point
from visualization_msgs.msg import Marker, MarkerArray
from tf2_msgs.msg import TFMessage
from ..world_map import Role, vehicle_frame_id
from . import c... |
3386218 | import enum
import lxml.html
from typing import List, Union
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .atserver import AternosServer
class Lists(enum.Enum):
whl = 'whitelist'
ops = 'ops'
ban = 'banned-players'
ips = 'banned-ips'
class PlayersList:
"""Class for managing operator... |
3386244 | from e2e.Libs.BLS import PrivateKey, AggregationInfo
from e2e.Tests.Errors import TestError
#Basic sanity test.
def BLSTest() -> None:
key: PrivateKey = PrivateKey(0)
if not key.sign(b"abc").verify(AggregationInfo(key.toPublicKey(), b"abc")):
raise TestError("Couldn't sign and verify a BLS signature from Pyth... |
3386255 | from fastapi import FastAPI, File, UploadFile
import torch
import io
import config
# Load model
model = config.model['cls'](**config.model['params']).eval().to(config.device)
app = FastAPI()
@app.post('/predict')
async def predict(input_file: UploadFile = File(...)):
input_file = io.BytesIO(input_file)
## ... |
3386258 | from api.models import Events, Article
from bot.app.events.notification_handler import EventNotificationHandler
from bot.app.events.social_handler import SocialHandler
from bot.app.notifications.news_notification_handler import NewsNotificationHandler
from bot.models import ArticleNotification
from spacelaunchnow impor... |
3386308 | from .. import vectors, matrices, units, Unit, UnitError, Variable
def from_rotvec(rotvec: Variable) -> Variable:
"""
Create rotation matrix (or matrices) from rotation vector(s).
This requires ``scipy`` to be installed, as is wraps ``Rotation.from_rotvec()``
from ``scipy.spatial.transform``.
A ... |
3386355 | import md5
import logging
import memcache
import tornado.httpserver
import tornado.ioloop
import tornado.options
import tornado.web
from tornado.options import define, options
define("port", default=8888, help="REST server port", type=int)
def log(tag, headers, msg):
logging.info("%s: headers=%s" % (tag, hea... |
3386358 | from tkinter import *
from PIL import Image,ImageTk
from tkinter import ttk, messagebox
import pymysql
class Register:
def __init__(self,root):
self.root = root
self.root.title("Registation Window")
# self.root.geometry("1530x790+0+0")
self.root.geometry("1470x750+40+25")
#... |
3386369 | import sublime
import sublime_plugin
from StatusMessage import status_message
class DefaultStatus(sublime_plugin.EventListener):
def on_selection_modified_async(self, view):
self._set_status(view)
def on_activated_async(self, view):
self._set_status(view)
def _set_status(self, view):
selections = ... |
3386433 | from pyrogram import Client,filters #-| Creating Client
api_id =2586462 #-|
api_hash = '68542129131999986899b84a10a6170c' #-|
bot = Client('amirairj-helper', api_id, api_hash,workers=300)#-|
#---------------------------------------... |
3386480 | from ..mapper import PropertyMapper, ApiInterfaceBase
from ..mapper.types import Timestamp, AnyType
from .user import User
__all__ = ['Media', 'MediaInterface']
class MediaInterface(ApiInterfaceBase):
image: str
id: int
user: User
expiring_at: Timestamp
comment_threading_enabled: bool
class Me... |
3386509 | from collections import defaultdict
import contextlib
import logging
import sys
import warnings
from ..fileio.adm.exceptions import AdmUnknownAttribute
class LimitedWarningPrint:
"""Utility to print a given number of warnings per line; to use, replace
warnings.showwarning with self.showwarning.
"""
d... |
3386525 | import tensorflow as tf
import glob
from collections import defaultdict
import os
def load_single_loss_file(logdir):
"""Load loss data from a single TF event file.
Args:
logdir(str): Path of the dir storing the event file,
e.g., 'stargan_celeba_sw_d_5/logs'
Returns:
loss(dict)... |
3386537 | import json
import boto3
import os
import re
import sys
import logging
logger = logging.getLogger()
logger.setLevel(logging.INFO)
from urllib.parse import unquote_plus
from elasticsearch import Elasticsearch, RequestsHttpConnection
from requests_aws4auth import AWS4Auth
esendpoint=os.environ['esendpoint']
esindex=os.en... |
3386547 | import pytest
from plenum.common.exceptions import RequestNackedException
from indy_node.test.state_proof.test_state_proof_for_get_requests import check_get_delta
from indy_node.test.anon_creds.conftest import send_revoc_reg_entry, send_revoc_reg_def, send_claim_def, claim_def
from indy_node.test.schema.test_send_ge... |
3386576 | import sys
import base64
import socket
import types
from collections import Mapping, Set
from abc import ABCMeta, abstractmethod
import cloudpickle
from msgpack import packb, unpackb, ExtType
from eventlet.queue import LightQueue
from eventlet.green import zmq
from pyrsistent import (PVector, PList, PBag,
... |
3386602 | sum_of_square = sum([x * x for x in range(1, 101)])
sqare_of_sum = sum(range(1, 101))
print(sqare_of_sum ** 2 - sum_of_square)
|
3386635 | from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from isi_sdk_8_1_0.api.antivirus_api import AntivirusApi
from isi_sdk_8_1_0.api.audit_api import AuditApi
from isi_sdk_8_1_0.api.auth_api import AuthApi
from isi_sdk_8_1_0.api.auth_groups_api import AuthGroupsApi
from isi_sdk_8_1_0.a... |
3386697 | from a10sdk.common.A10BaseClass import A10BaseClass
class MultipleFields(A10BaseClass):
"""This class does not support CRUD Operations please use parent.
:param field: {"description": "Field index number (Index of Field)", "minimum": 1, "type": "number", "maximum": 64, "format": "number"}
:param csv... |
3386709 | from __future__ import absolute_import
import tensorflow as tf
import numpy as np
from gpflow.model import GPModel
from gpflow.param import Param, DataHolder
from gpflow.mean_functions import Zero
from gpflow import likelihoods
from gpflow._settings import settings
from gpflow.densities import multivariate_normal
from ... |
3386812 | from random import randint
class PatternGenerator:
def __init__(self, lanes: list):
self.lanes = lanes
def generate_pattern(self):
rand = randint(0, 99)
if 0 <= rand <= 11:
return [[]]
elif rand <= 34:
return self._generate_one("./ressources/E_Obstacle.... |
3386834 | import numpy as np
def check_random_state(random_state):
'''
Handles seed or random state as an input. Provides consistent output.
'''
if random_state is None:
return np.random
if isinstance(random_state, (np.integer, int)):
return np.random.RandomState(random_state)
return rand... |
3386872 | from .rman_ui_base import ShaderPanel
from bpy.types import Panel
import bpy
class DATA_PT_renderman_world(ShaderPanel, Panel):
bl_context = "world"
bl_label = "World"
shader_type = 'world'
def draw(self, context):
layout = self.layout
world = context.scene.world
"""
D... |
3386905 | from src.config import MESSAGE_UNEXPECTED_ERROR
from src.helper import log
def make(error, message=None, response=None):
response_dict = dict(error=error)
if error:
assert isinstance(message, str)
response_dict['message'] = message
else:
assert isinstance(response, dict)
re... |
3386909 | from enum import Enum
from typing import Union, Any, Type
from src.alerter.alerts.contract.chainlink import (
ErrorNoSyncedDataSources, SyncedDataSourcesFound,
ErrorContractsNotRetrieved, ContractsNowRetrieved,
PriceFeedObservationsMissedIncreasedAboveThreshold, PriceFeedObservedAgain,
PriceFeedDeviati... |
3386915 | import argparse
from bookworm import *
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--path',
help='Path to the novel\'s .txt file',
required=True)
parser.add_argument('--d3',
help='Output a dicti... |
3386916 | import unittest
from tests.holodeck import Holodeck
from twilio.rest import Client
class IntegrationTestCase(unittest.TestCase):
def setUp(self):
super(IntegrationTestCase, self).setUp()
self.account_sid = 'AC' + 'a' * 32
self.auth_token = '<PASSWORD>'
self.holodeck = Holodeck()
... |
3386947 | from abc import ABC, abstractmethod
from typing import Any, Dict, Optional
from pandas.core.frame import DataFrame
from ..server_version.server_version import ServerVersion
from .graph_constructor import GraphConstructor
class QueryRunner(ABC):
@abstractmethod
def run_query(self, query: str, params: Optiona... |
3386976 | import numpy as np
import torch
eps = 1e-8
class metric_manager(object):
def __init__(self, task, save_dir, model, save_best_only=True):
if(
'ASC' not in task and
'SED' not in task and
'TAG' not in task
): raise ValueError('task unrecognized, got:{}'.format(ta... |
3387006 | import math
import json
import pathlib
import argparse
import collections
from functools import partial
from typing import List, Dict, Tuple
import torch
import numpy as np
from tqdm import tqdm
from torch.utils.data import TensorDataset
from torch.functional import Tensor
from transformers.models.bert.tokenization_b... |
3387035 | from quantdsl.application.with_multithreading import QuantDslApplicationWithMultithreading
from quantdsl.application.with_pythonobjects import QuantDslApplicationWithPythonObjects
class QuantDslApplicationWithMultithreadingAndPythonObjects(QuantDslApplicationWithMultithreading,
... |
3387036 | import os
from data.datasets import make_sr_dataset_from_folder
from data.transform_wrappers import get_sr_transform
DATASET_DIR = 'BSDS500'
TRAIN_DIR = 'images/train'
VAL_DIR = 'images/val'
TEST_DIR = 'images/test'
def get_train_set(conf, data_dir):
"""Get training dataset
Each entry consists of input, a rand... |
3387043 | import wx
import wx.aui
from GraphicsCanvas import GraphicsCanvas
from TreeCanvas import TreeCanvas
from InputModeCanvas import InputModeCanvas
from PropertiesCanvas import PropertiesCanvas
from ObjPropsCanvas import ObjPropsCanvas
from Ribbon import Ribbon
from HeeksConfig import HeeksConfig
class Frame(wx.Frame):
... |
3387049 | import os
import logging
import typing as t
from omegaconf import DictConfig, OmegaConf
from mlcube.shell import Shell
from mlcube.runner import (Runner, RunnerConfig)
__all__ = ['Config', 'SingularityRun']
from mlcube.validate import Validate
logger = logging.getLogger(__name__)
class Config(RunnerConfig):
"... |
3387050 | import json
from hello_world import app
def test_lambda_handler(apigw_event, lambda_context):
ret = app.lambda_handler(apigw_event, lambda_context)
expected = json.dumps({"message": "hello universe"}, separators=(",", ":"))
assert ret["statusCode"] == 200
assert ret["body"] == expected
|
3387051 | from django import forms
from multiupload.fields import MultiFileField
class UploadForm(forms.Form):
attachments = MultiFileField(min_num=1, max_num=3, max_file_size=1024*1024*5)
|
3387053 | import os
import numpy as np
from decimal import Decimal
import matplotlib.pyplot as plt
from matplotlib.lines import Line2D
import ipdb
st = ipdb.set_trace
result_folder = 'results'
exp_root = 'experiment_runners/exp_files'
units = 'deg'
folders = os.listdir(exp_root)
if not os.path.exists(result_folder):
os.mak... |
3387098 | def get_permitted_algorithm_names():
""" returns permitted algorithm names. """
return [
'RS256',
'RS384',
'RS512',
'ES256',
'ES384',
'ES512',
'PS256',
'PS384',
'PS512'
]
|
3387118 | from flask import flash, redirect, render_template, request, url_for
from flask_login import current_user, login_required
from sqlalchemy import or_
from . import tagValueNotes
from . forms import TagValueNoteForm
from .. import db
from .. decorators import permissionRequired
from .. models import ElementAttribute, Eve... |
3387122 | import torch
import torch.nn.functional as F
from torch import nn
from torch.nn import Conv2d, BatchNorm2d, PReLU, Sequential, Module
from torchvision.models.resnet import resnet34
from models.encoders.helpers import get_blocks, bottleneck_IR, bottleneck_IR_SE
from models.encoders.map2style import GradualStyleBlock
... |
3387153 | from __future__ import absolute_import
import numpy.random as npr
from .numpy_wrapper import wrap_namespace
wrap_namespace(npr.__dict__, globals())
|
3387156 | print('load TimeSliceAppendActivation')
# Utility function that implements time slicing based on activity detection.
from sklearn.preprocessing import StandardScaler
from sklearn.decomposition import PCA
from sklearn.cluster import KMeans
import librosa
def time_to_index(t,sr,l):
te=l/sr
t_f... |
3387207 | outer_top = ["어느 한 컴퓨터공학과 학생이 유명한 교수님을 찾아가 물었다."]
wrapper = [
'"재귀함수가 뭔가요?"',
'"잘 들어보게. 옛날옛날 한 산 꼭대기에 이세상 모든 지식을 통달한 선인이 있었어.',
"마을 사람들은 모두 그 선인에게 수많은 질문을 했고, 모두 지혜롭게 대답해 주었지.",
'그의 답은 대부분 옳았다고 하네. 그런데 어느 날, 그 선인에게 한 선비가 찾아와서 물었어."',
]
inner = ['"재귀함수가 뭔가요?"', '"재귀함수는 자기 자신을 호출하는 함수라네"']
end = ["라고 답변하였... |
3387225 | import torch
import torch.nn as nn
from arch_resnet38 import Resnet38
import torch.nn.functional as F
from torchvision import transforms
import numpy as np
import imutils
import os
import re
class BaseModel(nn.Module):
def initialize_weights(self):
for m in self.modules():
if isinstance(m, nn.C... |
3387290 | import torch
import torch.utils.model_zoo as model_zoo
from urllib.parse import urlparse
def load_weights(network, save_path, partial=True):
if urlparse(save_path).scheme != '':
pretrained_dict = model_zoo.load_url(save_path)
else:
pretrained_dict = torch.load(save_path)
if 'state_dict' in... |
3387326 | from collections import namedtuple
from config import settings
import os
import core.db.connection
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
class _superuser_connection():
superuser_con = None
def __init__(self, repo_base=None):
self.repo_base = repo_base
def __enter_... |
3387338 | class Solution(object):
def permute(self, nums):
return self.sub(nums)
"""
:type nums: List[int]
:rtype: List[List[int]]
"""
def sub(self, nums):
if len(nums) == 0:
return [[]]
if len(nums) == 1:
return [nums]
pattern = sel... |
3387391 | from fastapi import Depends, HTTPException, Path, status
from sqlalchemy import orm
from app.db.session import get_db
from app.models import rolemodels, shopmodels, usermodels
from app.service import roleservice, shopservice, userservice
def get_role_by_id_or_404(
db_session: orm.Session = Depends(get_db),
r... |
3387412 | def msum(iterable):
"Full precision summation using multiple floats for intermediate values"
# Rounded x+y stored in hi with the round-off stored in lo. Together
# hi+lo are exactly equal to x+y. The inner loop applies hi/lo summation
# to each partial so that the list of partial sums remains exact.
... |
3387438 | from __future__ import annotations
import os
from pathlib import Path
from typing import MutableMapping, Optional, Union, Mapping, cast, Dict, List
import numpy as np
import torch
from loguru import logger
from transformers import AdamW, BertConfig, BertModel
from codenets.codesearchnet.data import DatasetParams
fro... |
3387447 | import warnings
from contextlib import contextmanager
from decimal import Decimal
import webcolors
from . import BaseRenderer, renders
from ..operations import (BaseList, Bold, BulletList, CodeBlock, Footnote,
Format, Group, Heading, HyperLink, Image, InlineCode,
It... |
3387468 | import tensorflow
from keras import layers
from keras.models import Sequential
from get_data_v1 import *
# 构建模型
'''
这个模型需要在后续,针对每一个人来做
'''
# 设置tendorflow对显存使用按需增长
config = tensorflow.ConfigProto()
config.gpu_options.allow_growth = True
session = tensorflow.Session(config=config)
model_name = 'lstm'
HIDDEN_SIZE = 64... |
3387495 | from django.urls import path
from . import views
urlpatterns = [
path('', views.ProfileView.as_view(), name="profile"),
path('edit-avatar/', views.ProfileEditView.as_view(), name="edit-avatar"),
path('messages/', views.MessagesList.as_view(), name="messages"),
path('create-message/', views.Rooms.as_vi... |
3387496 | import socket
from pymavlink import mavutil
class UdpReceiver:
consumed_ports = []
@staticmethod
def get_ip_address():
s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
s.connect(("8.8.8.8", 80))
return s.getsockname()[0]
'''a UDP connection to receive data'''
def __... |
3387514 | import datetime
import newspaper
import scrapy
import locale
import datetime
locale.setlocale(locale.LC_ALL, "es_AR.utf8")
BASE_URL = 'https://www.ellitoral.com.ar/'
class ElLitoralSpider(scrapy.Spider):
name = "ellitoral"
def start_requests(self):
urls = [
'https://www.ellit... |
3387520 | from flow.core.generator import Generator
from collections import defaultdict
from lxml import etree
E = etree.Element
class SimpleGridGenerator(Generator):
"""Generator for nxm grid networks."""
def __init__(self, net_params, base):
super().__init__(net_params, base)
# this is a dictionar... |
3387554 | import unittest
import tests.envs as envs
import pykintone
from pykintone.application_settings.administrator import Administrator
import pykintone.application_settings.form_field as ff
from pykintone.application_settings.form import FormAPI
from pykintone.application_settings.view import View
class TestView(unittest.... |
3387564 | import json
import pytest
from mock import patch
from m3d.hadoop.algorithm.algorithm_configuration_hadoop import AlgorithmConfigurationHadoop
from m3d.util import util
from test.core.unit_test_base import UnitTestBase
class TestAlgorithmConfigurationHadoop(UnitTestBase):
default_m3d_config = "config/m3d/confi... |
3387569 | from .context import Doc, config_context
def test_default():
d = Doc("Ali topu tut. Ömer ılık süt iç.")
assert Doc.config['tf']['method'] == "log_norm"
assert d.builder.config['tf']['method'] == "log_norm"
def test_config_context():
for tf in ["binary", "raw"]:
with config_context(tf__metho... |
3387583 | import random
from xworld_task import XWorldTask
from py_gflags import get_flag
class XWorldRecBetweenToObject(XWorldTask):
def __init__(self, env):
super(XWorldRecBetweenToObject, self).__init__(env)
def idle(self):
if random.uniform(0, 1) < 0.9: ## tell goal
rec_goal = True
... |
3387606 | from __future__ import print_function
import boto3
import time
import sys
from lab_config import boto_args
def scan_table(tableName):
dynamodb = boto3.resource(**boto_args)
table = dynamodb.Table(tableName)
totalbytessent = 0
pageSize = 10000
fe = "responsecode <> :f"
eav = {":f": 200}
r... |
3387608 | from src.scripts.emr_add_autoscaling import lambda_handler as asg_add
from pprint import pprint
def test_emr_asg_add(create_cluster, lambda_context):
cluster_id = create_cluster.get('JobFlowId')
assert 'j-' in cluster_id
asg_add_request = {
"api_request_id": "test_asg_add",
"cluster_id": ... |
3387628 | from collections import defaultdict
class Graph:
def __init__(self, vertices):
self.V = vertices
self.graph = defaultdict(list)
def addEdge(self, u, v):
self.graph[u].append(v)
def DFSUtil(self, v, visited):
visited[v] = True
print(v)
for i in self.graph... |
3387632 | from .observable_dcmdir import ObservableDcmDir
from .observable_orthanc import ObservableOrthanc
from .observable_proxied_dicom import ObservableProxiedDicom
|
3387666 | import os
import unittest
from py4web.core import get_error_snapshot
class ErrorTest(unittest.TestCase):
def test_get_error_snapshot(self):
try:
1 / 0
except Exception:
snapshot = get_error_snapshot()
keys = list(sorted(snapshot.keys()))
self.assertEqual... |
3387711 | def extractStarrynightnovelsWordpressCom(item):
'''
Parser for 'starrynightnovels.wordpress.com'
'''
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or "preview" in item['title'].lower():
return None
tagmap = [
('Shini Yasui Kōshaku Reijō to Shichi-nin no Kikōsh... |
3387716 | from django.urls import path
from . import views
urlpatterns = [
path("", views.index, name="index"),
path("stock", views.stock, name="stock"),
path("predict", views.predict, name="predict"),
path("predict_stock/<str:symbol>/<str:period>/<int:sim>/<int:future>", views.stock_predict, name="predict_stoc... |
3387743 | import os.path
import pytest
from lemoncheesecake.fixture import load_fixtures_from_file, load_fixtures_from_files, load_fixtures_from_directory
@pytest.fixture()
def dir_with_fixtures(tmpdir):
module_content = """import lemoncheesecake.api as lcc
@lcc.fixture()
def bar():
pass
@lcc.fixture()
def foo(bar):... |
3387749 | import base64
import lycanthropy.sql.interface
import lycanthropy.sql.agent
import lycanthropy.sql.server
import lycanthropy.auth.client
import lycanthropy.crypto
import datetime
import requests
import hashlib
import urllib3
import json
import time
urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
... |
3387756 | from pymol import *
cmd.load("Psi_a_126_126-A.cube")
cmd.load("Psi_b_126_126-A.cube")
cmd.load("Psi_a_127_127-A.cube")
cmd.load("Psi_b_127_127-A.cube")
cmd.load("target.mol")
cmd.isomesh("HOMO_A", "Psi_a_126_126-A", -0.02)
cmd.isomesh("HOMO_B", "Psi_b_126_126-A", 0.02)
cmd.isomesh("LUMO_A", "Psi_a_127_127-A", 0.02)
cmd... |
3387762 | import datetime
import importlib.metadata
import os
from enum import Enum
import typer
from click.types import Choice
from semver import VersionInfo
class BumpType(str, Enum):
minor = "minor"
patch = "patch"
def get_current_version() -> VersionInfo:
version = importlib.metadata.version("odmantic")
... |
3387777 | import torch
import torch.nn as nn
import torch.nn.functional as F
class BasicBlock(nn.Module):
def __init__(self, in_planes, out_planes, stride):
super(BasicBlock, self).__init__()
self.bn1 = nn.BatchNorm2d(in_planes)
self.relu1 = nn.ReLU(inplace=True)
self.conv1 = nn.Conv2d(
... |
3387797 | import FWCore.ParameterSet.Config as cms
# -*-TCL-*-
from RecoMuon.MuonIsolationProducers.muIsoResultInputBlocks_cfi import *
from RecoMuon.MuonIsolationProducers.muIsolatorBlocks_cfi import *
muIsoResultM2C = cms.EDProducer("MuIsoCandidateResultProducer",
IsolatorByDepositR03,
VetoPSet = cms.PSet(
Sel... |
3387803 | from neo.UIntBase import UIntBase
class UInt160(UIntBase):
def __init__(self, data=None):
super(UInt160, self).__init__(num_bytes=20, data=data)
|
3387808 | from typing import Union, Tuple, List, Optional
import math
from torch import Tensor
from torch_geometric.data import Data
import torch
import torch.nn as nn
from gpn.distributions import Likelihood, ConjugatePrior
from gpn.utils import to_one_hot
import pyblaze.nn.functional as X
from .normalizing_flow import Normali... |
3387818 | import time
from argparse import ArgumentParser
from django.contrib.auth.models import User
from django.core.management.base import BaseCommand
from django.db.models import Q
class Command(BaseCommand):
help = 'Create test users'
def add_arguments(self, parser: ArgumentParser):
parser.add_argument('... |
3387891 | import astor
from json_codegen.astlib import python as ast
from json_codegen.core import SchemaParser, BaseGenerator
from json_codegen.types import PropertyType, PropertiesType, RequiredType
class Python2Generator(SchemaParser, BaseGenerator):
def generate(self):
# Add module imports
self._body =... |
3387908 | import json
from datetime import datetime
import pytz
from django.utils.timezone import now
from typing import List
from easy_eddie.clients import get_boto_client
from easy_eddie.helpers import get_cloud_watch_filter_pattern, get_cloud_watch_time_tuple_for_sms_events
from easy_eddie.models import SMSEvent
from easy_e... |
3387918 | import FWCore.ParameterSet.Config as cms
from JetMETCorrections.Configuration.JetCorrectorsAllAlgos_cff import *
from JetMETCorrections.Configuration.CorrectedJetProducers_cff import *
# L1 Correction Producers
ak7CaloJetsL1 = ak4CaloJetsL1.clone( src = 'ak7CaloJets' )
kt4CaloJetsL1 = ak4CaloJetsL1.clone( src = 'kt4C... |
3387947 | from .builder import build_model # noqa 401
from .model import GModel # noqa 401
from .registry import MODELS # noqa 401
|
3387958 | import pytest
from fastapi import BackgroundTasks
from typing import List, Tuple, Any
from PIL import Image
import numpy as np
import os
from src.constants import PLATFORM_ENUM
from tests.utils import floats_almost_equal, nested_floats_almost_equal, get_image_data
from src.app.ml.base_predictor import BaseData, BaseDa... |
3388022 | import numpy as np
from gensim.models import KeyedVectors
from gensim.models import Word2Vec
import time
from collections import defaultdict
from gensim.models.word2vec import LineSentence
from gensim.models import FastText
from gensim.models import KeyedVectors
from gensim.models import Word2Vec
from sklearn.metrics.p... |
3388084 | import os
import numpy as np
import torch
import torch.nn as nn
from tensorboardX import SummaryWriter
from torchsummaryX import summary
import utils
from dataset import generate_loader
class Solver():
def __init__(self, module, config):
self.device = torch.device(
"cuda" if torch.cuda.is_avail... |
3388088 | import os
import json
import glob
import shutil
import datetime
import logging
import bert
supported_albert_models = [
"albert_base_v2",
"albert_large_v2",
"albert_xlarge_v2",
"albert_xxlarge_v2",
]
supported_bert_models = [
"uncased_L-12_H-768_A-12",
"uncased_L-24_H-1024_A-16",
"cased_L-1... |
3388100 | import time
import re
import pymysql
"""
业务逻辑的拆分,和服务器分开,框架进行中间人
读取模板信息,返回自定义的前段模板
open在没有指明参数的话,默认模式是r
"""
#
# url_func_dict = {
# # 字典的方式,比较好一点,但是使用装饰器的话会更简洁
# "/index.html": index,
# "/center.html": center,
# "/login.html": login
# }
url_func_dict = dict()
def route(url):
def set_... |
3388110 | def _jinja2_template_impl(ctx):
out = ctx.actions.declare_file(ctx.attr.name)
ctx.actions.run_shell(
inputs = ctx.files.src,
tools = [ctx.executable._jinja2],
progress_message = "Generating " + out.short_path,
outputs = [out],
command = ctx.executable._jinja2.path + " " ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.