id
stringlengths
3
8
content
stringlengths
100
981k
1791020
import unittest import os from shutil import rmtree import numpy as np import torch import torch.nn as nn from inferno.trainers.basic import Trainer from torch.utils.data.dataset import TensorDataset from torch.utils.data.dataloader import DataLoader from inferno.trainers.callbacks.logging.tensorboard import Tensorboa...
1791059
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os, logging from pprint import pprint from utils import config as cfg if cfg.ROOT_DIR.startswith('/home'): import torch os.environ['TF_CPP_MIN_LOG_LEVEL'] = '2' # set tensorflow logger to WARNING...
1791072
from __future__ import absolute_import __author__ = 'katharine' from enum import IntEnum from .base import PebblePacket from .base.types import * __all__ = ["MetaProtocolMessage"] class MetaProtocolMessage(PebblePacket): class Meta: endpoint = 0x00 class Type(IntEnum): Disallowed = 0xdd ...
1791101
import time import numpy as np import argparse import sys sys.path.append("../../") import grpc from grpc_ps import ps_service_pb2_grpc from grpc_ps.client import ps_client # algorithm setting NUM_EPOCHS = 10 NUM_BATCHES = 1 MODEL_NAME = "w.b" LEARNING_RATE = 0.1 def handler(event, context): s...
1791108
from kqueen.kubeapi import KubernetesAPI from kubernetes.client.rest import ApiException from pprint import pprint as print import pytest import yaml import kubernetes def fake_raise(exc): def fn(self, *args, **kwargs): raise exc return fn class TestKubeApi: def test_missing_cluster_param(self...
1791110
from metagraph import translator from metagraph.plugins import has_scipy, has_networkx, has_grblas, has_pandas import numpy as np if has_scipy: import scipy.sparse as ss from .types import ScipyEdgeMap, ScipyEdgeSet, ScipyGraph @translator def edgemap_to_edgeset(x: ScipyEdgeMap, **props) -> ScipyEdgeS...
1791115
from docs_snippets_crag.concepts.io_management.output_config import execute_my_job_with_config def test_execute_job(): execute_my_job_with_config()
1791158
import math, random import numpy as np from PuzzleLib.Backend import gpuarray from PuzzleLib.Backend.Kernels.Costs import ctcLoss, ctcLossTest from PuzzleLib.Cost.Cost import Cost class CTC(Cost): def __init__(self, blank, vocabsize=None, normalized=False): super().__init__() self.normalized = normalized i...
1791160
from datetime import datetime import os from sqlalchemy import Column, DateTime, String, BigInteger, Integer, ForeignKey from sqlalchemy.orm import relationship from sqlalchemy.schema import Table from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.dialects.postgresql import JSON from sqlalchemy im...
1791164
import FWCore.ParameterSet.Config as cms from RecoParticleFlow.PFTracking.particleFlowDisplacedVertex_cfi import *
1791167
from itertools import chain from cvxopt import blas, lapack, solvers from cvxopt import matrix, spmatrix, sin, mul, div, normal, spdiag solvers.options['show_progress'] = 0 def get_second_derivative_matrix(n): """ :param n: The size of the time series :return: A matrix D such that if x.size == (n,1), D ...
1791191
import sys import numpy as np sys.path.insert(0, "./") from bayes_optim.extension import PCABO, RealSpace np.random.seed(123) dim = 5 lb, ub = -5, 5 def fitness(x): x = np.asarray(x) return np.sum((np.arange(1, dim + 1) * x) ** 2) space = RealSpace([lb, ub]) * dim opt = PCABO( search_space=space, ...
1791197
from ggplib import interface from ggplib.player.proxy import ProxyPlayer class CppRandomPlayer(ProxyPlayer): def meta_create_player(self): return interface.create_random_player(self.sm, self.match.our_role_index) class CppLegalPlayer(ProxyPlayer): def meta_create_player(self): return interfa...
1791222
class Alert: """Maps a Rule to an Action, and triggers the action if the rule matches on any stock update""" def __init__(self, description, rule, action): self.description = description self.rule = rule self.action = action def connect(self, exchange): self.exchange = ...
1791246
import torch import torch.nn as nn import torch.nn.functional as F from .aspp import ASPP_Module up_kwargs = {'mode': 'bilinear', 'align_corners': False} norm_layer = nn.BatchNorm2d class _ConvBNReLU(nn.Module): def __init__(self, in_channels, out_channels, kernel_size, stride=1, padding=0, di...
1791249
import requests url = "http://localhost:8080/local" for i in -4,-2,2,4,6: data = {"rom":"psos","type":"temp", "device":"1wire", "ip":"", "gpio":"", "i2c":"", "usb":"","name":"psos","value":i} r = requests.post(url,json=data) data = {"rom":"press","type":"press","device":"usb", "ip":"", "gpio":"", "i2c":"", "us...
1791264
from sys import version_info from pytest import fixture from mock import Mock, call if version_info[0] == 3: unicode = str bytes_type = bytes else: unicode = lambda k: k.decode('utf8') bytes_type = str def mocked_smtp(*args, **kwargs): smtp = Mock() smtp.return_value = smtp smtp(*args, *...
1791287
from toee import * def OnBeginSpellCast( spell ): print "Read Magic OnBeginSpellCast" print "spell.target_list=", spell.target_list print "spell.caster=", spell.caster, " caster.level= ", spell.caster_level #game.particles( "sp-divination-conjure", spell.caster ) def OnSpellEffect( spell ): print "Read Magic OnS...
1791289
import random import torch import torchvision from pathlib import Path import utils.logging as logging import data.utils as utils from data.build import DATASET_REGISTRY logger = logging.get_logger(__name__) @DATASET_REGISTRY.register() class UCF101(torch.utils.data.Dataset): """ UCF101 video loader. Cons...
1791384
import sys def hanoi(n: int, start: int, by: int, end: int) -> None: if n == 1: move.append([start, end]) else: hanoi(n - 1, start, end, by) move.append([start, end]) hanoi(n - 1, by, start, end) n = int(sys.stdin.readline()) move = [] hanoi(n, 1, 2, 3) print(len(move)) print...
1791407
import rospy import datetime import os import json from std_msgs.msg import String from sensor_msgs.msg import Image from acrv_apc_2017_perception.msg import autosegmenter_msg import cv_bridge import cv2 NUM_IMGS = 7 seen_items = [ "plastic_wine_glass", "hinged_ruled_index_cards", "black_fashion_gloves"...
1791463
from starkware.starknet.business_logic.state import BlockInfo from starkware.starknet.public.abi import get_selector_from_name import logging from ast import Constant import pytest from enum import Enum import asyncio from starkware.starknet.testing.starknet import Starknet from utils import ( Signer, uint, str_to_...
1791554
import numpy as np from .pyramid import Pyramid from .filters import parse_filter from .c.wrapper import corrDn, upConv class WaveletPyramid(Pyramid): """Multiscale wavelet pyramid Parameters ---------- image : `array_like` 1d or 2d image upon which to construct to the pyramid. height : '...
1791568
from shared_config import * word_size = 7 num_words = 256 words_per_row = 4 local_array_size = 25 output_extended_config = True output_datasheet_info = True netlist_only = True nominal_corner_only = True
1791594
from twitchbot import BaseBot, Mod, Event def test_base_bot_events_are_set(): for event in Event: assert event.name in BaseBot.__dict__, f'BaseBot must implement event {event}' def test_mod_events_are_set(): for event in Event: assert event.name in Mod.__dict__, f'Mod must implement event {e...
1791632
import claripy from ..shellcode import Shellcode class X86SetRegister(Shellcode): os = ["cgc", "unix"] arches = ["X86"] name = "setregister" codes = { 'eax': [b"\xb8", b"\xbb", b"\xff\xe3"], 'ebx': [b"\xbb", b"\xb8", b"\xff\xee"], 'ecx': [b"\xb9", b"\xbb", b"\xff\...
1791636
import torch def adjust_log_weights(log_weights, component_log_probs): ''' Adjust log_weights for multivariate mixture distributions. Uses that `sum_m w_m p_m1(x_1) p_m2(x_2|x_1) p_m3(x_3|x_2,x_1) = [sum_m w_m1 p_m1(x_1)] [sum_m w_m2 p_m2(x_2|x_1)] [sum_m w_m3 p_m3(x_3|x_2,x_1)]`. This computes `[w_m...
1791650
from click.testing import CliRunner from tiletanic import cli def test_tiletanic(): """Basic call to root command""" runner = CliRunner() result = runner.invoke(cli.cli) assert result.exit_code == 0 def test_version(): runner = CliRunner() result = runner.invoke(cli.cli, ['--version']) as...
1791653
from triggerflow.dags import DAG from triggerflow.dags.operators import ( IBMCloudFunctionsCallAsyncOperator, IBMCloudFunctionsMapOperator ) dag = DAG(dag_id='fault-tolerance') first_task = IBMCloudFunctionsCallAsyncOperator( task_id='first_task', function_name='echo', function_package='triggerflo...
1791686
import argparse import itertools as it import json import math import matplotlib.pyplot as plt import os import pathlib _here = pathlib.Path(__file__).resolve().parent def main(dataset, models, forward, accepts, rejects): assert not (accepts and rejects) if forward: if accepts: string = ...
1791688
from typing import Callable import pytest from mimesis.locales import DEFAULT_LOCALE from mimesis.schema import Field _CacheCallable = Callable[[str], Field] @pytest.fixture(scope='session') # noqa: PT005 def _mimesis_cache() -> _CacheCallable: # noqa: PT005 cached_instances = {} def factory(locale: str)...
1791691
import argparse import re import os import ray from ray.tune import run_experiments from ray.tune.registry import register_trainable, register_env, get_trainable_cls import ray.rllib.contrib.maddpg.maddpg as maddpg from rllib_multiagent_particle_env import env_creator from util import parse_args def setup_ray(): ...
1791729
import os import tempfile import unittest import logging from pyidf import ValidationLevel import pyidf from pyidf.idf import IDF from pyidf.surface_construction_elements import MaterialNoMass log = logging.getLogger(__name__) class TestMaterialNoMass(unittest.TestCase): def setUp(self): self.fd, self.pa...
1791766
class Solution(object): def mySqrt(self, x): """ :type x: int :rtype: int """ if x < 2: return x left, right = 0, x // 2 while left <= right: mid = left + (right - left) // 2 num = mid * mid if num > x: ...
1791778
from circuits import Event class MessageReceivedEvent(Event): """event""" class ContextCreatedEvent(Event): """event""" class NLPConfidenceLowEvent(Event): """event""" class ChatRequestedEvent(Event): """event""" class SkillRequestedEvent(Event): """event""" class EntitiesPreprocessedEvent(Eve...
1791850
from django.db import models from filingcabinet.models import ( AbstractDocument, AbstractDocumentCollection, DocumentManager as FCDocumentManager, DocumentCollectionManager as FCDocumentCollectionManager, get_page_image_filename, Page, ) from froide.helper.auth import ( can_read_object_au...
1791860
from substance.monads import * from substance.logs import * from substance import (Engine, Command) from substance.exceptions import (SubstanceError) class Sshinfo(Command): def getUsage(self): return "substance sshinfo [ENGINE NAME]" def getHelpTitle(self): return "Obtain the ssh info confi...
1791878
import torch from pytorchltr.datasets.list_sampler import ListSampler from pytorchltr.datasets.list_sampler import UniformSampler from pytorchltr.datasets.list_sampler import BalancedRelevanceSampler from pytest import approx def rng(seed=1608637542): gen = torch.Generator() gen.manual_seed(seed) return ...
1791880
import ocean idx = ocean.index[[1,2,3],:,...,-2] idx2 = ocean.gpu[0](idx) ocean.cpu(idx2, True) idx3 = idx2.setDevice(ocean.gpu[0]) idx2.setDevice(ocean.gpu[0],True)
1791887
import torch from omegaconf import DictConfig from torch import nn from code2seq.model.modules import PathEncoder class TypedPathEncoder(PathEncoder): def __init__( self, config: DictConfig, n_tokens: int, token_pad_id: int, n_nodes: int, node_pad_id: int, ...
1791890
from .delete import Delete from .get_many import GetMany from .get_single import GetSingle from .post import Post from .patch import Patch from .defs import HttpMethods __all__ = ['HttpMethods', 'Delete', 'GetMany', 'GetSingle', 'Post', 'Patch']
1791910
import logging import os import sys import cv2 import numpy as np import torch import torch.nn as nn import _init_paths from config import cfg, update_config from models.utils import _gather_feat, _transpose_and_gather_feat from tensorrt_model import TRTModel from utils.image import get_affine_transform, transform_pr...
1791924
def register_routes(api, app, root="app"): from app.api.model import register_routes as attach_model from app.api.meta import register_routes as attach_meta from app.api.pipelines import register_routes as attach_pipelines from app.api.composer import register_routes as attach_composer from app.api....
1791942
from .basenotifier import BaseNotifier as Base from ..config import config class Pushdeer(Base): def __init__(self): self.name = 'Pushdeer' self.token = config.PUSHDEER_KEY self.retcode_key = 'code' self.retcode_value = 0 def send(self, text, status, desp): url = 'http...
1791965
import os, time, sys, datetime from random import randint from huepy import * __version__ = "1.3.6" def cc_gen(bin): cc = "" if len(bin) != 16: while len(bin) != 16: bin += 'x' else: pass if len(bin) == 16: for x in range(15): if bin[x] in ("0", "...
1792009
from imports import * from rescale_numeric_feature import * """ This class calculates feature importance Input: """ class calculate_shap(): def __init__(self): super(calculate_shap, self).__init__() self.param = None def xgboost_shap(self, model, X): # explain the model's predict...
1792031
from ifem import test_solve_system test_solve_system() from applications import test_uniform_bar test_uniform_bar()
1792035
from django.core.management.base import BaseCommand, CommandError from django.db.models.loading import AppCache from django.conf import settings import simpledb class Command(BaseCommand): help = ("Sync all of the SimpleDB domains.") def handle(self, *args, **options): apps = AppCache() check...
1792045
from django.core.cache import cache from django.dispatch import Signal from speedbar.utils import DETAILS_PREFIX, TRACE_PREFIX, loaded_modules from speedbar.modules.base import RequestTrace DETAILS_CACHE_TIME = 60 * 30 # 30 minutes request_trace_complete = Signal(providing_args=['metrics', 'request', 'response']) ...
1792046
from __future__ import absolute_import import click from .run import run @click.command() def shell(): """Start the Django shell.""" run.main(["python", "manage.py", "shell"])
1792104
from metadata.metadata import AI_MODEL from mlalgms.hpaprediction import checkHPAAnomaly class hpametricinfo(object): def __init__(self, priority, metricType, currentdataframe, algorithm=None, mlmodel=None, hpaproperties=None, modelparameters=None): self.priority = priority self.metricType = metricType self....
1792111
from os.path import join import pytest from pyleecan.Functions.load import load from pyleecan.definitions import DATA_DIR @pytest.mark.IPMSM def test_material_dict(): Toyota_Prius = load(join(DATA_DIR, "Machine", "Toyota_Prius.json")) mat_dict = Toyota_Prius.get_material_dict() # Check only names fo...
1792117
plot(t, rad2deg(y[:, 3:])) xlabel('Time [s]') ylabel('Angular Rate [deg/s]') legend(["${}$".format(vlatex(s)) for s in speeds])
1792156
class Solution: def climbStairs(self, n: int) -> int: if n <= 1: return n s1 = 1 s2 = 2 for i in range(2, n): s = s1 + s2 s1, s2 = s2, s return s2
1792163
from setuptools import setup setup(name='amplification', version='0.1', install_requires=[ ] )
1792182
import sys import os, os.path import shutil if sys.version_info < (3,): range = xrange def CheckParameter(): outputPath = None searchStartDir = None isIncludeFolder = None excludePaths = None count = len(sys.argv)-1 if count >= 8: for i in range(1, count): if sys.argv[i] == "-OutputPath": ou...
1792202
from ceo.tools import ascupy from ceo.pyramid import Pyramid import numpy as np import cupy as cp from scipy.ndimage import center_of_mass class PyramidWFS(Pyramid): def __init__(self, N_SIDE_LENSLET, N_PX_LENSLET, modulation=0.0, N_GS=1, throughput=1.0, separation=None): Pyramid.__init__(self) sel...
1792280
from .builder import CUDAOpBuilder from .kernel_builder import KernelBuilder from .transformer_builder import TransformerBuilder from .adam_builder import AdamBuilder # TODO: infer this list instead of hard coded # List of all available ops __op_builders__ = [ KernelBuilder(), TransformerBuilder(), AdamBui...
1792302
from ffi_navigator import langserver from ffi_navigator.util import join_path, normalize_path import logging import os curr_path = os.path.dirname(os.path.realpath(os.path.expanduser(__file__))) def run_find_definition(server, path, line, character): uri = langserver.path2uri(path) res = server.m_text_docume...
1792315
from django.utils.translation import ugettext_lazy as _ from django.apps import AppConfig class DatabankConfig(AppConfig): name = _('databank')
1792348
from .. import testing class CountIfTest(testing.FunctionalTestCase): filename = "IF.xlsx" def test_evaluation_ABCDE_1(self): for col in "ABCDE": cell = f'Sheet1!{col}1' excel_value = self.evaluator.get_cell_value(cell) value = self.evaluator.evaluate(cel...
1792389
def gcd(a: int, b: int) -> int: return a if b == 0 else gcd(b, a % b) def lcm(a: int, b: int) -> int: return a * b // gcd(a, b)
1792399
import torch from torch import nn from typing import Optional from typing import NamedTuple from .discriminators import DiscriminatorOutput from ....misc.toolkit import get_gradient class GANTarget(NamedTuple): is_real: bool labels: Optional[torch.Tensor] = None class GradientNormLoss(nn.Module): def ...
1792443
from __future__ import unicode_literals from django.shortcuts import render def allowed(request): return render(request, 'default.html')
1792492
import traceback import uuid import humanfriendly from flask import Flask, request, render_template, abort, send_from_directory from functools import wraps, update_wrapper from datetime import datetime from flask import make_response from panoptes.database import init_db, db_session from panoptes.models import Workfl...
1792546
from rete.common import BetaNode, Token class PNode(BetaNode): kind = 'p' def __init__(self, children=None, parent=None, items=None, **kwargs): """ :type items: list of Token """ super(PNode, self).__init__(children=children, parent=parent) self.items = items if items...
1792576
import math import traceback from pathlib import Path from typing import Any, Callable, Iterator, List, NoReturn, Optional, Union from seutil import IOUtils, LoggingUtils from tqdm import tqdm logger = LoggingUtils.get_logger(__name__) class FilesManager: """ Handles the loading/dumping of files in a datase...
1792608
import unittest import os from wtrie import Trie from rtrie import value_for_vid, vid_for_value pwd = os.getcwd() if os.path.basename(pwd) != 'test': fixture = os.path.join(pwd, 'test/fixtures/keys') else: fixture = os.path.join(pwd, 'fixtures/keys') class TestStressWTrie(unittest.TestCase): def test_st...
1792641
from microbit import * from neopixel import NeoPixel class neo16x16: def __init__(self, pin): self.np = NeoPixel(pin, 256) self.color = (0,0,8) def clear(self): self.np.clear() def set(self, n, color=''): if color!='': self.np[n] = color else: ...
1792669
import numpy as np from sklearn.decomposition import PCA from statsmodels.tsa.adfvalues import mackinnoncrit from statsmodels.tsa.adfvalues import mackinnonp from statsmodels.tsa.stattools import adfuller from ._utils import rms def aeg_pca(X0, X1, trend): __sqrteps = np.sqrt(np.finfo(np.double).eps) # Comp...
1792671
import asyncio from cleo import Command from cleo.helpers import option from netaudio.dante.browser import DanteBrowser class SubscriptionAddCommand(Command): name = "add" description = "Add a subscription" options = [ option("rx-channel-name", None, "Specify Rx channel by name", flag=False), ...
1792730
import os, sys from AnyQt.QtWidgets import QSizePolicy, QStyle, QMessageBox, QFileDialog from AnyQt.QtCore import QTimer from Orange.misc import DistMatrix from Orange.widgets import widget, gui from Orange.data import get_sample_datasets_dir from Orange.widgets.utils.filedialogs import RecentPathsWComboMixin from Or...
1792735
from selenium import webdriver from time import sleep from selenium.webdriver.common.keys import Keys from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.wait import WebDriverWait def Like_by_keyword(driver, keyword, num): '''...
1792771
import cartography.intel.aws.ec2 import cartography.intel.aws.iam import tests.data.aws.ec2.instances import tests.data.aws.iam from cartography.util import run_analysis_job TEST_ACCOUNT_ID = '000000000000' TEST_REGION = 'us-east-1' TEST_UPDATE_TAG = 123456789 def test_load_ec2_instances(neo4j_session, *args): "...
1792775
from sklearn.metrics import roc_auc_score, accuracy_score, precision_score, recall_score from sklearn.metrics import mean_squared_error, mean_absolute_error, r2_score, f1_score from sklearn import metrics from sklearn.metrics import precision_recall_curve from dataset import dataset_names import numpy as np import torc...
1792811
class H52VTR: """Convert HDF5 file to rectilinear VTR file. Args: h5file (str): input HDF5 filename axisnames (str): ('elev', 'lat', 'axial') dataname (str): 'arfidata' vtrname (str): 'rectilinear' """ def __init__(self, h5file=None, axisnames=('elev', 'lat', 'axial'), ...
1792829
import sys sys.path.insert(1,"../../") import h2o from tests import pyunit_utils import pandas as pd def pubdev_7119(): # Test 1 pd_df = pd.DataFrame({'col1': [1,2], 'col2': ['foo"foo\nfoo','foo2'], 'col3': [1,2]}) h2o_df = h2o.H2OFrame(pd_df) pd_df2 = h2o_df.as_data_frame() print(pd_df) ...
1792837
import numpy as np import matplotlib.image as io import matplotlib.pyplot as plt alpha = 30 seedX = 998244353 seedY = 1000000007 ''' First alpha = 5 oriFile = "qrcode.png" waterMarkFile = "testwm.png" outFile = "watermarked.png" ''' ''' Second alpha = 30 oriFile = "test.png" waterMarkFile = "website.png" outFile = "...
1792854
import attr import json import numpy as np from text2qdmr.datasets.utils.extract_values import GroundingKey, ValueUnit from text2qdmr.datasets.qdmr import QDMRStepArg def to_dict_with_sorted_values(d, key=None): return {k: sorted(v, key=key) for k, v in d.items()} def to_dict_with_set_values(d): result = {}...
1792862
import yaml def read_config(config_path): with open(config_path, "r") as f_config: config = yaml.load(f_config) return config
1792865
load("@io_bazel_rules_docker//container:load.bzl", "container_load") BUILD_BAZEL = """ java_import( name = "server", jars = ["buildfarm-server_deploy.jar"], visibility = ["//visibility:public"], ) java_import( name = "worker", jars = ["buildfarm-worker_deploy.jar"], visibility = ["//visibility:...
1792887
import os import sentencepiece as spm DATAFILE = '../data/pg16457.txt' MODELDIR = 'models' spm.SentencePieceTrainer.train(f'''\ --model_type=bpe\ --input={DATAFILE}\ --model_prefix={MODELDIR}/bpe\ --vocab_size=500''') sp = spm.SentencePieceProcessor() sp.load(os.path.join(MODELDIR, 'bpe.model')) inp...
1792904
import sys import os import torch from allennlp.data.iterators import BucketIterator from allennlp.data.iterators import BasicIterator from allennlp.modules.text_field_embedders import TextFieldEmbedder import torch.optim as optim from acsa.acsc_pytorch.my_allennlp_trainer import Trainer from allennlp.data.vocabulary ...
1792950
import requests topics = { "topics": [ { "text": [ "Art_Event", "Celebrities", "Entertainment", "Fashion", "Food_Drink", "Games", "Literature", "Math", ...
1792997
import fasttext import numpy as np import joblib def dump_split(sents_f, embed_model_f, model_f, prefix): model = joblib.load(model_f) embed_model = fasttext.load_model(embed_model_f) sentences = [] embeddings = [] with open(sents_f) as handle: for new_line in handle: if len(n...
1793070
from io import BytesIO from buidl.helper import ( encode_varint, hash256, int_to_little_endian, read_varint, read_varstr, ) from buidl.siphash import SipHash_2_4 BASIC_FILTER_TYPE = 0 GOLOMB_P = 19 GOLOMB_M = int(round(1.497137 * 2 ** GOLOMB_P)) def _siphash(key, value): if len(key) != 16: ...
1793071
from tvm import relay import tvm from collage.pattern_manager.utils import is_function_node from collage.pattern_manager.cost_func import * from collage.optimizer.custom_fusion_pass import CustomFusionPass from workloads.torch_workloads import get_network_from_torch from workloads.relay_workloads import get_network_fro...
1793115
class Calculadora(object): """docstring for Calculadora""" memoria = 10 def suma(self, a, b): return a + b def resta(self, a, b): return a - b def multiplicacion(self, a, b): return a * b def division(self, a, b): return a / b @classmethod def numerosPrimos(cls, limite): rango = range(2, limite) ...
1793126
import logging from ._aioredis import redis_manager from ._aiomysql import mysql_manager logger = logging.getLogger(__name__) __all__ = ['db_manager', 'get_pool', 'get_manager'] db_manager_map = { 'mysql': mysql_manager, 'redis': redis_manager, } class DBManager: @staticmethod def get_manager(db...
1793128
try: a = int(input("Escolha entre 1 e 6")) if a < 1 or a > 6: print ("o valor deve ser entre 1 e 6") except ValueError: print ("Escolha uma opção válida") #https://pt.stackoverflow.com/q/433462/101
1793149
class Callback(object): '''Callback base class''' def __init__(self): pass def on_train_begin(self, train_iterator, num_epochs): pass def on_epoch_begin(self, train_iterator, num_epochs, epoch): pass def on_batch_begin(self, train_iterator, num_epochs, epoch, iteration, b...
1793150
import numpy as np import gym, gym.spaces import time import os from collections import OrderedDict import yaml EPS = 1e-5 def parse_config(config): with open(config, 'r') as f: config_data = yaml.load(f) return config_data class ToyEnv: def __init__(self, config_file, ...
1793173
import numpy as np import os, sys import copy import torch import torch.utils.data sys.path.append(os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..')) from common.geometry import Camera sys.path.append(os.path.dirname(os.path.abspath(__file__))) from mesh_dataset import MeshLoader class LoaderSingle(...
1793226
class Solution: def balancedStringSplit(self, s: str) -> int: cnt = tmp = 0 for i in s: if i == 'R': tmp += 1 if i == 'L': tmp -= 1 if not tmp: cnt += 1 return cnt
1793261
from collections import deque from hypothesis import given from hypothesis.strategies import (frozensets, integers, lists, one_of, sets, tuples) from tests.entities import (DataClassWithDeque, DataClassWithFrozenSet, DataClassWithList, DataClassWithOption...
1793275
import os import unittest from spotinst_sdk2 import SpotinstSession from spotinst_sdk2.models.managed_instance.aws import * class SimpleNamespace: def __init__(self, **kwargs): self.__dict__.update(kwargs) class AwsManagedInstanceTestCase(unittest.TestCase): def setUp(self): self.session =...
1793304
import math from datetime import timedelta from datetime import datetime MAX_GEE_PIXELS_DOWNLOAD = 1048576 GEE_ERROR_PLACEHOLDER = "ImageCollection.getRegion: Too many values: " __all__ = ('tile_coordinates', 'retrieve_max_pixel_count_from_pattern', 'cmp_coords', 'get_date_interval_array', 'make_polygon') ...
1793340
import nltk.tokenize.punkt from os import listdir from os import path import re import io import shutil import os import sys, getopt # load the sentence tokenizer ab_tokenizer = nltk.data.load("abkhaz_tokenizer.pickle") ru_tokenizer = nltk.data.load("russian.pickle") speech_tokenset = ( "иҳәеит", "рҳәеит", "сҳәеит", ...
1793347
import unittest from setup.settings import * from numpy.testing import * import numpy as np import dolphindb_numpy as dnp import pandas as pd import orca class FunctionMedianTest(unittest.TestCase): @classmethod def setUpClass(cls): # connect to a DolphinDB server orca.connect(HOST, PORT, "ad...
1793353
import pyutilib.component.app import pyutilib.misc import os import sys currdir = sys.argv[-1] + os.sep app = pyutilib.component.app.SimpleApplication("foo") pyutilib.misc.setup_redirect(currdir + "summary.out") app.config.summarize() pyutilib.misc.reset_redirect()