id
stringlengths
3
8
content
stringlengths
100
981k
11503024
from inspect import isclass from _dependencies.exceptions import DependencyError from _dependencies.injectable import _function_args from _dependencies.spec import _Spec class Value: """Evaluate given function during dependency injection. Returned value is used as value of the dependency. Used as funct...
11503041
from dataclasses import dataclass, field from typing import List, Union, Dict, Any from pyball.models.draft.round import Round @dataclass class Draft: draftYear: int = None rounds: List[Union[Round, Dict[str, Any]]] = field(default_factory=list) def __post_init__(self): self.rounds = [ ...
11503045
from __future__ import annotations import numpy as np import re from .._types import Slices __all__ = ["str_to_slice", "key_repr", "axis_targeted_slicing"] def _range_to_list(v:str) -> list[int]: """ "1,3,5" -> [1,3,5] "2,4:6,9" -> [2,4,5,6,9] """ if ":" in v: s, e = v.split(":") r...
11503062
from boa.interop.System.App import RegisterAppCall from boa.interop.System.Runtime import Log from boa.interop.System.ExecutionEngine import GetExecutingScriptHash # Here "8ef4b22b006b49a85f5a9a4fe4cd42ce1ab809f4" should your OPE4 contract hash, pls note it's not reversed hash OEP4Contract = RegisterAppCall('8ef4b22b0...
11503084
from scapy.all import * # pylint: disable=unused-wildcard-import import random import string from pprint import pprint from binascii import hexlify from scapy.utils import PcapWriter from scapy.config import conf import os inside = "18.0.0.0/28" outside = "1.1.1.0/28" random.seed(0) PKT_TEMPLATE = """ Definition {} ...
11503109
from .helpers import * from .behavior import trivia_behavior from io import BytesIO DELAY = 20 async def premise(item): _, data = item state_image_url = 'https:{}'.format(data['map_url']) state_image = await Utils.fetch(state_image_url) return dict( file_path=BytesIO(state_image), f...
11503114
from abc import ABCMeta, abstractmethod class AbstractProductY(): """ Abstract interface for products of type Y """ __metaclass__ = ABCMeta @abstractmethod def feature(self): pass
11503127
from featureMan.lib.properties import glyphBase, glyphProperty from featureMan.lib.tags import languageTags import re from itertools import permutations rtlScripts = set(['arab', 'hebr', 'syrc', 'thaa']) def wrap(string, width=70): comment = '' if string[0] == '#': comment = '# ' if string: ...
11503132
from telegram_coin_bot.db.schema import Money, Session, db def create_tables(): with db: db.create_tables([Session, Money])
11503137
import math import pytest import torch from snowfall.models.tdnnf import FactorizedTDNN, Tdnnf1a, _constrain_orthonormal_internal torch.manual_seed(20200130) def test_constrain_orthonormal(): def compute_loss(M): P = torch.mm(M, M.t()) P_PT = torch.mm(P, P.t()) trace_P = torch.trace(P)...
11503149
import os, sys; sys.path.append(os.path.dirname(os.path.realpath(__file__))) from GeoTableUtil import GeoTableUtil
11503163
import graphlayer as g import graphlayer.sqlalchemy as gsql from .. import database from . import authors Book = g.ObjectType("Book", fields=lambda: ( g.field("author", type=authors.Author), g.field("title", type=g.String), )) class BookQuery(object): @staticmethod def select(type_query): r...
11503219
from django.conf.urls import url, include from rest_framework.routers import DefaultRouter from rest_framework_swagger.views import get_swagger_view from . import views, views_api # Django REST framework router = DefaultRouter() router.register(r'election', views_api.ElectionInterface) router.register(r'district', vi...
11503254
import logging import asyncio import aiohttp.web import aiopg import psycopg2.extras import api_hour from . import endpoints LOG = logging.getLogger(__name__) class Container(api_hour.Container): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.config is None: ...
11503256
import argparse import random import numpy as np from sklearn.model_selection import train_test_split import torch import torch.nn as nn from torch import optim from torch.utils.data import Dataset, DataLoader import dataLoader as loader import preprocessing as pproc import models device = torch.device("cuda" if torch...
11503265
import datetime import io import logging import unittest from django.contrib.auth import get_user_model from django.test import TestCase from django.utils import timezone class CreateUserMixin(TestCase): def setUp(self): super().setUp() self.user = self.create_user() def create_user(self, us...
11503278
from __future__ import print_function import argparse import csv import hashlib import os import pytsk3 import pyewf import sys from tqdm import tqdm """ MIT License Copyright (c) 2017 <NAME>, <NAME> Please share comments and questions at: https://github.com/PythonForensics/PythonForensicsCookbook or email <...
11503289
from .base import ConstituencyParser from ...tags import * from ...data_manager import DataManager class StanfordParser(ConstituencyParser): """ Constituency parser based on stanford parser. :Requirements: * java """ TAGS = { TAG_English } def __init__(self): self.__...
11503382
from pharmpy.rxcui import RxCUIEngine import unittest import time class RxCUIEngineTestCase(unittest.TestCase): def test_cui(self): rce = RxCUIEngine() out = rce.get_rxcui("50090347201") self.assertEqual(out, "665044") out = rce.get_rxcui(["50090347201"]) self.assertEqual(...
11503395
import numpy as np import matplotlib.pyplot as plt from hyperion.model import ModelOutput from hyperion.util.constants import pc # Read in the model m = ModelOutput('quantity_cartesian.rtout') # Extract the quantities g = m.get_quantities() # Get the wall positions in pc xw, yw = g.x_wall / pc, g.y_wall / pc # Mak...
11503404
import numpy as np import json from sklearn.preprocessing import KBinsDiscretizer from sklearn.tree import DecisionTreeClassifier from sklearn.model_selection import train_test_split class DecisionTreeDiscretizer(): def __init__(self, n_bins): self.n_bins = n_bins def fit_transform(self, X, y): ...
11503427
from contentbase.auditor import ( AuditFailure, audit_checker, ) from contentbase import simple_path_ids from contentbase.schema_utils import validate @audit_checker('item', frame='object') def audit_item_schema(value, system): context = system['context'] registry = system['registry'] if not conte...
11503438
from pandaharvester.harvestercore import core_utils from pandaharvester.harvestercore.plugin_base import PluginBase from pandaharvester.harvestercloud.googlecloud import compute, ZONE, PROJECT from pandaharvester.harvestercore.queue_config_mapper import QueueConfigMapper import googleapiclient base_logger = core_utils...
11503450
if exists("1579792079784.png"): click(Pattern("1579792079784.png").targetOffset(4,15)) sleep(1) type(Key.F4, KeyModifier.ALT) exit(0) if exists("1596467122234.png"): click(Pattern("1596467122234.png").targetOffset(1,13)) sleep(1) type(Key.F4, KeyModifier.ALT) exit(0) exit(0) ...
11503455
from app import db class BuyerEmailDomain(db.Model): __tablename__ = 'buyer_email_domains' id = db.Column(db.Integer, primary_key=True) domain_name = db.Column(db.String(), nullable=False, unique=True) def serialize(self): return { "id": self.id, "domainName": self.do...
11503456
class Solution(object): def longest_substr(self, string, k): if string is None: raise TypeError('string cannot be None') if k is None: raise TypeError('k cannot be None') low_index = 0 max_length = 0 chars_to_index_map = {} for index, char in ...
11503502
from __future__ import division ''' This function converts memory mem string to integer ''' def mem_common_form(mem, **kwargs): if mem.endswith('M'): mem = mem[:-1] mem = int(mem) mem = mem * 1024 elif mem.endswith('G'): mem = mem[:-1] mem = in...
11503561
from contracts.main import new_contract __all__ = [] try: import numpy # @UnusedImport except ImportError: # pragma: no cover new_contract('float', 'Float') new_contract('int', 'Int') new_contract('number', 'float|int') else: new_contract('float', 'Float|np_scalar_float|(np_scalar, array(flo...
11503580
from rest_framework.reverse import reverse from rest_framework.status import ( HTTP_200_OK, HTTP_400_BAD_REQUEST, HTTP_404_NOT_FOUND) from allegation.factories import ( OfficerFactory, PoliceWitnessFactory, OfficerAllegationFactory) from common.tests.core import SimpleTestCase class MobileOfficerViewTest(Simp...
11503624
import matplotlib.pyplot as plt from oneibl.one import ONE import brainbox.plot as bbp one = ONE() eid = one.search(lab='wittenlab', date='2019-08-04')[0] probe_label = 'probe00' spikes = one.load_object(eid, 'spikes', collection=f'alf/{probe_label}') trials = one.load_object(eid, 'trials', collection='alf') # For ...
11503635
import os from math import ceil import _path_cheesecake from _helper_cheesecake import DATA_PATH from cheesecake.cheesecake_index import Cheesecake, CodeParser class TestIndexDocstrings(object): def setUp(self): self.cheesecake = Cheesecake(path=os.path.join(DATA_PATH, "package2.tar.gz")) module...
11503638
from .abasearchitecture import ABaseArchitecture from .dcgan import DcganEncoder, DcganDecoder, DcganAutoEncoder from fusion.utils import ObjectProvider architecture_provider = ObjectProvider() architecture_provider.register_object('DcganEncoder', DcganEncoder) architecture_provider.register_object('DcganDecoder', D...
11503639
import json import numpy as np import argparse from pathlib import Path import logging from logging.config import fileConfig import cv2 from typing import List, Tuple import deeptennis.utils as utils def mask_image(img: np.ndarray, pts: np.ndarray, dilate=False) -> np.ndarray: """ Zero out the irrelevant par...
11503679
import os from typing import Optional LOG_FILENAME: Optional[str] = os.getenv("ROBOCORP_CODE_DAP_LOG_FILENAME", None) # Make sure that the log level is an int. try: LOG_LEVEL = int(os.getenv("ROBOCORP_CODE_DAP_LOG_LEVEL", "0")) except: LOG_LEVEL = 3 DEBUG = LOG_LEVEL > 1 TERMINAL_NONE = "none" TERMINAL_INTE...
11503691
from django.apps import AppConfig class FollowSystemConfig(AppConfig): name = "apps.follow_system" label = "follow_system"
11503722
import argparse import asyncio import logging import os import ssl from .admin_server import AdminServer from .gateway_server import GatewayServer async def _main(): parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter ) parser.add_argument('--host', default='1...
11503781
import re from tps import modules as md from tps.symbols import valid_symbols_map from tps.utils import cleaners class Lower(md.Processor): def process(self, string: str, **kwargs) -> str: return string.lower() class Cleaner(md.Processor): def __init__(self, charset): super().__init__() ...
11503802
import logging import jwt import importlib from typing import List, Iterable from abc import ABC, ABCMeta, abstractmethod from aiohttp import web, hdrs from datetime import datetime, timedelta from asyncdb.utils.models import Model from cryptography import fernet import base64 from navigator.conf import ( NAV_AUTH_...
11503811
import gym import pytest from utilities.Utility_Functions import flatten_action_id_to_actions from utilities.data_structures.Config import Config config = Config() config.seed = 1 config.environment = gym.make("Taxi-v2") config.env_parameters = {} config.num_episodes_to_run = 1000 config.file_to_save_data_results = ...
11503813
import numpy as np def np_to_string(n): """ Converts a one dimensional numpy array into a string format to be stored in db """ # Squeeze out dims n = np.squeeze(n) return np.array_str(n)[1:-1] def string_to_np(s): """ Converts string to numpy array. """ return np.fromst...
11503831
from typing import Set, Dict, List, NamedTuple import joblib from transformers.tokenization_utils import PreTrainedTokenizer from allennlp.data import Token from allennlp.common import FromParams from luke.utils.entity_vocab import EntityVocab, Entity from luke.utils.interwiki_db import InterwikiDB from .entity_db i...
11503844
from .iob_to_docs import iob_to_docs # noqa: F401 from .conll_ner_to_docs import conll_ner_to_docs # noqa: F401 from .json_to_docs import json_to_docs # noqa: F401 from .conllu_to_docs import conllu_to_docs # noqa: F401
11503910
import cube import unittest class TestCube(unittest.TestCase): def test_0(self): self.assertEqual(cube.cube(0), 0) def test_1(self): self.assertEqual(cube.cube(1), 1) def test_2(self): self.assertEqual(cube.cube(2), 8) def test_3(self): self.assertEqual(cube.cube(3)...
11503921
import os import subprocess import CheckPython # Make sure everything we need is installed CheckPython.ValidatePackages() import Vulkan # Change from Scripts directory to root os.chdir('../') if (not Vulkan.CheckVulkanSDK()): print("Vulkan SDK not installed.") if (not Vulkan.CheckVulkanSDKDebugLibs()): ...
11503928
import numpy from matchms import Spectrum from matchms.filtering import correct_charge def test_correct_charge_no_ionmode(): """Test if no charge is added for empty ionmode.""" spectrum_in = Spectrum(mz=numpy.array([], dtype='float'), intensities=numpy.array([], dtype='float'), ...
11503942
if __name__ == '__main__': f = open('downloaded_summaries/all_text.txt', 'r') s = f.read() summaries = s.split('---###<summary>###---') print(len(summaries))
11503959
from geosnap import Community import numpy as np columns = ["median_household_income", "p_poverty_rate", "p_unemployment_rate"] reno = Community.from_census(msa_fips="39900") reno = reno.harmonize(intensive_variables=columns, target_year=2010, allocate_total=True, extensive_variables=['n_total_pop']) reno = reno.clus...
11503984
from HABApp.openhab.connection_handler.http_connection import is_disconnect_exception def test_aiohttp_sse_client_exceptions(): list = [ConnectionError, ConnectionRefusedError, ConnectionAbortedError] for k in list: try: raise k() except Exception as e: assert is_discon...
11503988
from unittest import TestCase from terraform_compliance.common.bdd_tags import look_for_bdd_tags from terraform_compliance.common.exceptions import Failure from tests.mocks import MockedStep, MockedTags class TestBddTags(TestCase): def test_unchanged_step_object(self): step = MockedStep() look_fo...
11503992
import unittest from lsml.initializer.provided.threshold import ThresholdInitializer class TestThresholdInitialize(unittest.TestCase): def test_square_image(self): import numpy as np random_state = np.random.RandomState(1234) mask = np.pad(np.ones((5, 5), dtype=bool), 5, 'constant') ...
11504006
from ....Functions.Geometry.comp_flower_arc import comp_flower_arc from ....Classes.Arc1 import Arc1 from ....Classes.Segment import Segment from ....Methods import ParentMissingError from numpy import pi, sqrt, exp def get_bore_line(self, prop_dict=None): """Return the bore line description Parameters -...
11504015
import os, re import numpy as np import tensorflow as tf # ---------------------------------------------------------------------------- # # decorator # ---------------------------------------------------------------------------- # def tf_scope(func): """ decorator: automatically wrap a var scope """ def scopp...
11504063
import pytest import supriya.nonrealtime def test_01(): """ With Session.at(...) context manager. """ session = supriya.nonrealtime.Session() with session.at(0): group_one = session.add_group() group_two = session.add_group() node = group_one.add_synth() with session.a...
11504074
import sys import os.path import binascii from pathlib import Path from cryptography.hazmat.backends import default_backend from cryptography import x509 from cryptography.hazmat.primitives.serialization import Encoding from cryptography.hazmat.primitives.asymmetric import ec from cryptoauthlib import * from certs_hand...
11504075
import datetime import itertools import os import shutil import subprocess import tempfile from collections import defaultdict from pathlib import Path import ast import json import hydra import numpy as np import yaml from omegaconf import DictConfig from covid19sim.plotting.utils import env_to_path from covid19sim....
11504084
import os import time import pytest from geth.wrapper import spawn_geth from geth.utils.dag import is_dag_generated from geth.utils.timeout import ( Timeout, ) @pytest.mark.skipif( 'TEST_DAG_WAIT' not in os.environ, reason="'TEST_DAG_WAIT' environment variable is not set", ) def test_waiting_for_dag_ge...
11504104
import config import typing from api.services import http from urllib.parse import quote_plus DISCORD_ENDPOINT = "https://discord.com/api" SCOPES = ["identify"] async def exchange_code( *, code: str, scope: str, redirect_uri: str, grant_type: str = "authorization_code" ) -> typing.Tuple[dict, int]: """Exch...
11504125
from typing import Literal from pydantic import BaseModel class MsgShow(BaseModel): title: bool = True picID: bool = False picWebUrl: bool = True page: bool = True author: bool = True authorID: bool = False authorWebUrl: bool = True picOriginalUrl: bool = True tags: bool = True ...
11504128
from framework.fuzzer.fuzzobjects import FuzzRequest class PluginResult: def __init__(self): self.source = "" self.issue = "" class PluginRequest(): def __init__(self): self.source = "" self.request = None self.rlevel = 0 @staticmethod def from_fuzzRes(res, url, source): fr = FuzzRequest.from_f...
11504193
from pyrogram import filters from pyrogram.errors import RPCError from pyrogram.types import User from app.config import conf from app.utils import Client, Message from app.utils.decorators import doc_args @Client.on_message(filters.me & filters.command("mention", prefixes=".")) @doc_args("username.optional text") a...
11504203
import tensorflow as tf from examples.crystal_volume import optimize_crystal_volume as ocv from tensorflow.keras import layers from rlmolecule.crystal.builder import CrystalBuilder from rlmolecule.crystal.crystal_state import CrystalState from rlmolecule.crystal.preprocessor import CrystalPreprocessor from rlmolecule....
11504206
from setuptools import setup setup( name='dnd.py', version='1.0', description='Do not distract yourself!', author='<NAME>', author_email='<EMAIL>', url='https://github.com/papachristoumarios/dnd.py', scripts=['dnd.py'] )
11504279
from __future__ import print_function from __future__ import division from __future__ import absolute_import def parse_label_map(path_to_labels: str): ''' - Arguments: - path_to_labels (str): path to pbtx file - Returns: - dict of form { id(int) : label(str)} ''' with open(path_to_...
11504321
import os import subprocess import sys import click from hatch.commands.utils import ( CONTEXT_SETTINGS, echo_failure, echo_info, echo_success, echo_waiting, echo_warning ) from hatch.config import get_proper_pip, get_venv_dir from hatch.env import install_packages from hatch.utils import ( NEED_SUBPROCES...
11504334
from termpixels.util import corners_to_box from termpixels.util import set_ambiguous_is_wide from termpixels.util import terminal_char_len from termpixels.util import terminal_len from termpixels.util import terminal_printable from termpixels.util import splitlines_print from termpixels.util import wrap_text from unico...
11504348
import sys from imutils import paths import cv2 from PIL import Image sys.path.insert(0, '/home/ihab/ihabgit/zevision') import lib.util as predict imagePaths = list(paths.list_images("db_test")) for image in imagePaths: response = predict.recognize_objects(image) print(response) print("\n\n\n\n") # ...
11504397
import argparse import time from django.core.management import BaseCommand from django.conf import settings import botocore import boto3 from collections import deque from voter.utils import process_new_zip, out s3client = boto3.client('s3') s3client.meta.events.register('choose-signer.s3.*', botocore.handlers.disa...
11504480
import subprocess import pandas as pd primer_table = pd.read_csv(snakemake.input.primer_t, index_col="Probe", na_filter=False).to_dict("index") if not snakemake.params.bar_removed: r1_barcode = primer_table[snakemake.wildcards.sample + "_" + snakemake.wildcards.unit]["Barcode_forward"] r2_barcode ...
11504512
import re class TestLang: def __init__(self, test=""): self.test = test def parse(self): for token in self.test.split(' '): letters, numbers = re.match('([A-Za-z]*)([0-9]*)', token).groups() if letters+numbers != token: raise Exception("Bad token: %s" % ...
11504519
import cv2 import xml.etree.ElementTree as ET from GeoPointCloud import GeoPointCloud import json import math import numpy as np import overpy import time import tgc_definitions status_print_duration = 1.0 # Print progress every N seconds spline_configuration = None # Returns left, top, right, bottom def nodeBoundi...
11504550
import os import sys import torch import numpy as np from datetime import datetime """ How To: Example for running from command line: python <path_to>/ProvablyPowerfulGraphNetworks/main_scripts/main_10fold_experiment.py --config=configs/10fold_config.json --dataset_name=COLLAB """ # Change working directory to project...
11504553
import testutil import test_engine class TestDependencies(test_engine.EngineTestCase): sample_desc = { "SCHEMA": [ [1, "Table1", [ [1, "Prev", "Ref:Table1", True, "Table1.lookupOne(id=$id-1)", "", ""], [2, "Value", "Numeric", False, "", "", ""], [3, "Sum", "Nu...
11504600
from streaming.transparency.api.sources import Sources from streaming.transparency.api.records import Records from streaming.transparency.api.merkle import MerkleTree
11504602
import a0 import time EVENT_TOPIC = a0.cfg(a0.env.topic(), "/event_topic", str) print(f"{EVENT_TOPIC} initialized") i = 0 p = a0.Publisher(f"{EVENT_TOPIC}") while True: msg = f"data {i}" print(msg) p.pub(msg) i += 1 time.sleep(10)
11504604
import math import torch import torch.nn as nn from ..utils import common_functions as c_f # https://github.com/pytorch/pytorch/blob/master/torch/nn/modules/linear.py def reset_parameters_helper(weight, bias): nn.init.kaiming_uniform_(weight, a=math.sqrt(5)) if bias is not None: fan_in, _ = nn.init....
11504645
import asyncio import math from typing import ( Awaitable, Callable, Iterable, Optional, Sized, Tuple, Any, ) async def as_completed_return_exception(coros: [Iterable[Awaitable], Sized]): """ Wrapper for asyncio.as_completed. Equivalent return_exceptions=True from asyncio.gather. ...
11504648
from .para_sen_routes import TOK_BLUEPRINT from .para_sen_routes import TOK_BLUEPRINT_wf from .para_sen_routes import TOK_BLOCK_BLUEPRINT_wf
11504686
import json import pytuya # Specify the smoker and get its status d = pytuya.OutletDevice('<gwID>', '<IP>', '<productKey>') data = d.status() # Enable debug to see the raw JSON Debug = False #Debug = True if Debug: raw = json.dumps(data, indent=4) print(raw) # Simple if statement to check if the smoker is on...
11504698
from .panosuncg import PanoSunCG from .threeD60 import ThreeD60 from .stanford2d3d import Stanford2D3D from .matterport3d import Matterport3D
11504699
import RPi.GPIO as GPIO from time import sleep import math class motor_ctrl: def __init__(self): self.in1 = 26 self.in2 = 19 self.en = 21 # self.temp1=1 #self.i...
11504712
import random from metrics import rmse import numpy as np from svd import SVDRecommender def chunk(xs, n): ys = list(xs) random.shuffle(ys) ylen = len(ys) size, leftover = divmod(ylen, n) chunks = [ys[size*i : size*(i+1)] for i in xrange(n)] edge = size*n for i in xrange(leftover): ...
11504728
from django.conf import settings from django.conf.urls import url, include from django.contrib import admin from django.conf.urls.static import static from django.contrib.auth.views import LogoutView from django.views.generic import RedirectView from .views import HomeView, instruction_view from accounts.views import ...
11504758
import numpy as np import scipy as sp import warnings from sklearn.exceptions import DataConversionWarning from sklearn.base import BaseEstimator, RegressorMixin from sklearn.utils.validation import check_is_fitted from sklearn.utils.extmath import safe_sparse_dot from sklearn.utils import check_X_y, check_array from...
11504766
import os.path import argparse from PIL import Image from hugsvision.inference.TorchVisionClassifierInference import TorchVisionClassifierInference parser = argparse.ArgumentParser(description='Image classifier') parser.add_argument('--path', type=str, default="./OUT_TORCHVISION/HAM10000/", help='The model pat...
11504770
from skimage.io import imread from gSLICrPy import __get_CUDA_gSLICr__, CUDA_gSLICr def main(): image = imread('./example.jpg') img_size_y, img_size_x = image.shape[0:2] image = image[:, :, ::-1].flatten().astype('uint8') __CUDA_gSLICr__ = __get_CUDA_gSLICr__() CUDA_gSLICr(__CUDA_gSLICr__, ...
11504776
from __future__ import absolute_import from __future__ import print_function import veriloggen import dataflow_sort expected_verilog = """ module test ( ); reg CLK; reg RST; reg signed [32-1:0] din0; reg signed [32-1:0] din1; reg signed [32-1:0] din2; reg signed [32-1:0] din3; reg signed [32-1:0] din4...
11504778
from .algorithm import AStarAlgorithm from .manager import GridManager from .memory import AppDatabase
11504847
import time import numpy as np def jacobian_singular_value(args, model, sess, dataset, flag): print('-- Check Jacobian singular values [{}]'.format(flag)) t_start = time.time() jsv = [] generator = dataset.get_generator('epoch', 'train', True) batch_size = 10 nitr = dataset.num_example['train'...
11504853
from .users import UserViewSet, UserSuccessViewSet from .token import TokenViewSet from .article import ArticleViewSet from .equipment import EquipmentViewSet from .parity import ParityViewSet, ParityLatestViewSet from .comment import ArticleCommentViewSet, EquipmentCommentViewSet from .mobile_app import latest_mobile_...
11504866
class Solution: # @param strs, a list of strings # @return a list of strings def anagrams(self, strs): d = {} res = [] for i, s in enumerate(strs): key = self.make_key(s) # First occurence of an anagram if key not in d: d[key] = [s]...
11504922
from acqdp.tensor_network import TensorNetwork import numpy as np from acqdp.circuit import CNOTGate, CZGate, Circuit, HGate, Measurement, PlusState, State, Trace, ZeroMeas, ZeroState from demo.QEC.noise_model import add_idle_noise, add_noisy_surface_code params = { 'T_1_inv': 1 / 30000.0, 'T_phi_inv'...
11504941
import copy import brian2 import numpy as np import matplotlib.pyplot as plt P = {'c_m': 1 * brian2.uF / brian2.cm ** 2, 'g_L': 0.1 * brian2.mS / brian2.cm ** 2, 'e_L': -65 * brian2.mV, 'g_na': 35 * brian2.mS / brian2.cm ** 2, 'e_na': 55 * brian2.mV, 'phi': 5, 'g_k': 9 * brian2.mS / bri...
11504949
from kivy.uix.floatlayout import FloatLayout from kivy.uix.popup import Popup class P(FloatLayout): pass def show_popup(): show = P() popupWindow = Popup(title="load", content=show, size_hint=(None, None), size=(400, 400)) popupWindow.open()
11504964
import uuid import pytest from server import create_app DATASOURCES_ENDPOINT = "/v1/api/datasources" NUM_DATASOURCES_IN_DB = 1 @pytest.fixture def client(tmpdir): # temp_db_file = f"sqlite:///{tmpdir.dirpath()}/" app = create_app() app.config["TESTING"] = True with app.test_client() as client: ...
11504968
from dataclasses import dataclass, field from typing import Dict, Optional from pyhanko.pdf_utils import generic __all__ = [ 'ShapeResult', 'FontEngine', 'FontSubsetCollection', 'FontEngineFactory' ] from pyhanko.pdf_utils.writer import BasePdfFileWriter ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def generate_su...
11504983
from ...models.timer import Timer from unicorn.arm_const import * def systick_config(uc): #rate = qemu.regs.r0 # TODO: Figure out the systick rate. rate = 2000 systick_irq = 15 print("Setting SysTick rate to %#08x" % rate) Timer.start_timer('SysTick', rate, systick_irq) uc.reg_write(UC_ARM_...
11504984
from ..param import * from .component import * from . import generic name_space( "multiplayer", name="Multiplayer", description=( "Multiplayer options pertaining to how the game is run, such as" " friendly fire, buy-anywhere, team managment, etc." ) ) @Component("autokick", "auto_ki...
11505057
from mypy_extensions import TypedDict class WidgetInterface(TypedDict, total=False): widget_id: int name: str purpose: str
11505065
import torch import torch.nn as nn import math def weights_init(m): # Initialize filters with Gaussian random weights if isinstance(m, nn.Conv2d): n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels m.weight.data.normal_(0, math.sqrt(2. / n)) if m.bias is not None: m.bi...
11505066
import json from django.contrib.auth import get_user_model from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from helium.auth.models import UserSettings, UserProfile from helium.auth.tests.helpers import userhelper __author__ = "<NAME>" __copyright__ = "Cop...