id
stringlengths
3
8
content
stringlengths
100
981k
3268528
import re from ztag.annotation import Annotation from ztag.annotation import OperatingSystem from ztag import protocols import ztag.test class FtpIis(Annotation): protocol = protocols.FTP subprotocol = protocols.FTP.BANNER port = None manufacturer_re = re.compile( "^220[- ]Microsoft FTP Servi...
3268555
from typing import List import tensorflow as tf import numpy as np import lunzi as lz from lunzi import nn, rl from boots import * from boots.envs.batched_env import BatchedEnv from boots.partial_envs import make_env, FLAGS as EnvFLAGS from boots.normalizer import Normalizers from boots.envs.virtual_env import Virtual...
3268562
import torch.nn as nn from typing import Tuple, Optional, Union, cast from .utils import remove_batchnorm, insert_after, insert_before from .condseq import CondSeq from torchelie.utils import kaiming, experimental from .interpolate import InterpolateBilinear2d def Conv2d(in_ch, out_ch, ks, stride=1, bias=True) -> nn....
3268572
import torch import torch.nn as nn import torch.nn.functional as F class SupConUnet(nn.Module): def __init__(self, num_classes, in_channels=1, initial_filter_size=64, kernel_size=3, do_instancenorm=True, mode="cls"): super(SupConUnet, self).__init__() self.encoder = UNet(num_class...
3268573
from typing import List from src.commons import VENDOR_OFFER_IGN from src.core.offer import Offer raw_vendor_offers = [ ("Orb of Regret", "Orb of Alchemy", 1), ("Orb of Scouring", "Orb of Regret", .5), ("Orb of Chance", "Orb of Scouring", .25), ("Orb of Fusing", "Orb of Chance", 1), ("Jeweller's Or...
3268575
import matplotlib.pyplot as plt import matplotlib as mpl import numpy as np import tensorflow as tf from model import LGGMVae from scipy.io import loadmat from collections import defaultdict mpl.use('agg') mpl.rcParams['figure.dpi'] = 300 mpl.rcParams['savefig.dpi'] = 300 def reconstruction_test_lg_vae(model, test_da...
3268588
from argparse import ArgumentParser import os def makedirs(name): """helper function for python 2 and 3 to call os.makedirs() avoiding an error if the directory to be created already exists""" import os, errno try: os.makedirs(name) except OSError as ex: if ex.errno == errno.EE...
3268610
import sys routing = sys.argv[1] print(routing) if routing == "ecmp": s1 = "ecmp.ECMPRoutingTable" s2 = "ECMPRoutingTable" s3 = "" else: print("Router configuration not supported") sys.exit(1) outfname = "out/MyRouter.ned" with open(outfname, "w") as outf: outf.write( """import approx...
3268637
import datasets from tango import Step from tango.integrations.datasets import DatasetsFormat from tango.integrations.transformers import Tokenizer # We need a step to tokenize the raw data. The result of this step will be passed # directly into the "torch::train" step. @Step.register("tokenize_data") class Tokenize...
3268676
print(b"".count(b"")) print(b"".count(b"a")) print(b"a".count(b"")) print(b"a".count(b"a")) print(b"a".count(b"b")) print(b"b".count(b"a")) print(b"aaa".count(b"")) print(b"aaa".count(b"a")) print(b"aaa".count(b"aa")) print(b"aaa".count(b"aaa")) print(b"aaa".count(b"aaaa")) print(b"aaaa".count(b"")) print(b"aaaa".cou...
3268715
from ..factory import Type class inputMessageInvoice(Type): invoice = None # type: "invoice" title = None # type: "string" description = None # type: "string" photo_url = None # type: "string" photo_size = None # type: "int32" photo_width = None # type: "int32" photo_height = None # type: "int32" paylo...
3268730
from django.db.models.deletion import SET_NULL from allauth.socialaccount.models import SocialAccount from django.contrib.postgres.fields import ArrayField, JSONField from django.db import models from django.db.models import Sum from user.related_models.profile_image_storage import ProfileImageStorage from user.relate...
3268764
import argparse import sys import qtim_tools class qtim_commands(object): def __init__(self): parser = argparse.ArgumentParser( description='A number of pre-packaged command used by the Quantiative Tumor Imaging Lab at the Martinos Center', usage='''qtim <command> [<args>] The f...
3268771
import tensorflow as tf import numpy as np from itertools import permutations def plot_signals(pl, x, y, n=5): for i in range(n): pl.subplot(n, 2, i * 2 + 1) pl.plot(x[i], color='black') ymin = np.min(x[i]) - .5 ymax = np.max(x[i]) + .5 axes = pl.gca() axes.set_ylim...
3268799
from __future__ import absolute_import, division, print_function import numpy as np from scipy import signal from math import log2, log10 from scipy.ndimage import generic_laplace,uniform_filter,correlate,gaussian_filter from .utils import _initial_check,_get_sigmas,_get_sums,Filter,_replace_value,fspecial,filter2,_pow...
3268810
import numpy as np from ._base import GraphWorld, grid_to_adj class OpenField(GraphWorld): """Open field task environment. Parameters ---------- reward : float Value of reward. punishment : float Value of punishment. Attributes ---------- states : array, shape ...
3268826
import numpy as np import os import os.path from itertools import * import pandas as pd import logging import time import pysnptools.util as pstutil from pysnptools.pstreader import PstReader from pysnptools.snpreader import SnpData import warnings import pysnptools.standardizer as stdizer from pysnptools.snpreader._di...
3268942
import zgui.guilocal as local import pygame import zgui from .guiglobal import * from .surface import * from .color import * def SafeSize(size): s = list(size) if size[0]<0: s[0] = 0 if size[1]<0: s[1] = 0 return int(s[0]),int(s[1]) def ResizeImage(img,size): if isinstance(img,zgui.surface.ExSurface): img = img...
3268949
import gc import glob import os import shutil import time import numpy as np import pandas as pd import tensorflow as tf from keras.callbacks import ModelCheckpoint from keras.models import load_model from sklearn.model_selection import KFold, StratifiedKFold, train_test_split from .utils import copytree class Kera...
3269004
import asyncio import datetime from collections import Counter from typing import Any, NamedTuple, Optional import asyncpg import discord from discord.ext import commands, menus, tasks from donphan import MaybeAcquire from ... import BotBase, Cog, Context, CONFIG from ...db.tables import Commands from ...utils.pagi...
3269015
from django.db import models from django.core.exceptions import ValidationError as DjangoValidationError from backend.utils.transliteration import transliteration_rus_eng_image as translite def create_path(instance, filename): """Определение пути сохранения изображения""" return '{}/{}/{}'.format(instance.__...
3269041
from __future__ import unicode_literals import transaction as db_transaction from freezegun import freeze_time from billy.renderers import company_adapter from billy.renderers import customer_adapter from billy.renderers import plan_adapter from billy.renderers import subscription_adapter from billy.renderers import ...
3269047
from typing import Any from ..components import TradeDirection class Position: deal_id: str size: int create_date: str direction: TradeDirection level: float limit: float stop: float currency: str epic: str market_id: str def __init__(self, **kargs: Any) -> None: ...
3269096
import logging import os.path import platform import re from re import RegexFlag from typing import Dict log = logging.getLogger(__name__) # OS -> List[regexp_strings] forbidden = { "windows": [".*\\/windows\\/.*", ".*SystemRoot.*"], "darwin": ["\\/System.*", "\\/Library.*"], "linux": [".*\\/etc\\/.*"], }...
3269100
import numpy as np from collections import UserDict, Iterable import pprint from wholeslidedata.labels import Labels class SpacingTypeError(Exception): pass class ShapeTypeError(Exception): pass class ShapeMismatchError(Exception): pass class Sample(np.ndarray): def __new__( cls, ...
3269123
import sys import numpy as np import cv2 import videoflow import videoflow.core.flow as flow from videoflow.core.constants import BATCH from videoflow.consumers import VideofileWriter from videoflow.producers import VideofileReader from videoflow_contrib.detector_tf import TensorflowObjectDetector from videoflow.proc...
3269155
import base64 import collections import phpserialize from Crypto.PublicKey import RSA try: from Crypto.Hash import SHA1 except ImportError: # pragma: no cover from Crypto.Hash import SHA as SHA1 try: from Crypto.Signature import PKCS1_v1_5 except ImportError: # pragma: no cover from Crypto.Signatur...
3269167
import asyncio import threading from abc import ABCMeta, abstractmethod from threading import Thread from typing import Callable from protoactor.actor.utils import Singleton class AbstractMessageInvoker(metaclass=ABCMeta): @abstractmethod def invoke_system_message(self, msg: object): raise NotImpleme...
3269184
import random import numpy as np from scipy.sparse import csc_matrix, lil_matrix def binary_search(array, x): """ Binary search :param array: array: Must be sorted :param x: value to search :return: position where it is found, -1 if not found """ lower = 0 upper = len(array) while ...
3269240
class NoneParameterException(Exception): def __init__(self, message: str = ""): self.error_message = message class InvalidConditionException(Exception): def __init__(self, message: str): self.error_message = message class EmptyCollectionException(RuntimeError): def __init__(self): ...
3269259
import torch as ch import numpy as np from lime.lime_text import LimeTextExplainer from tqdm import tqdm from wordcloud import WordCloud import matplotlib import matplotlib.pyplot as plt import seaborn as sns sns.set_style('darkgrid') import os from collections import defaultdict def make_lime_fn(model...
3269272
import time from contextlib import contextmanager import numpy as np @contextmanager def timer(): tick = time.perf_counter() yield lambda: tock - tick tock = time.perf_counter() def loglik(fit): """Log-likelihood of fitted model""" trials = fit["trials"] params = fit["params"] logrates ...
3269285
import numpy as np from retrieval.sparse import BM25Retrieval class ATIREBM25Retrieval(BM25Retrieval): def __init__(self, args): super().__init__(args) def calculate_score(self, p_embedding, query_vec): b, k1, avdl = self.b, self.k1, self.avdl len_p = self.dls p_emb_for_q = p_...
3269332
import mobula @mobula.op.register class AttSamplerGrid: def __init__(self, scale=1.0, dense=4, iters=5): self.scale = scale self.dense = dense self.iters = iters def forward(self, data, attx, atty):#data[1, 1, 224, 224] attx[1, 224, 1] F = self.F._mobula_hack # attx:...
3269342
from django.test import TestCase from django.core.urlresolvers import reverse from utils.auth_tokens import new_auth_token import json # Create your tests here. class GetPricesTestCase(TestCase): def test_missing_exchange(self): """When there is no 'exchange' parameter, an error should be return...
3269343
from .camera import Camera from .utils import Light, SmoothFloat __all__ = ["Camera", "SmoothFloat", "Light"]
3269350
from django.contrib.auth import authenticate from django.contrib.auth.models import User from rest_framework import generics, status from rest_framework.views import APIView from rest_framework.response import Response from .serializers import UserSerializer class UserCreate(generics.CreateAPIView): name = 'use...
3269370
import json import time from unittest.mock import patch from requests import Response from raindropio import * def test_refresh() -> None: api = API( { "access_token": "old", "refresh_token": "<PASSWORD>", "expires_at": time.time() - 100000, } ) with p...
3269377
from termpixels import App def main(): app = App() run_count = 0 @app.on("start") def start(): nonlocal run_count run_count += 1 app.screen.print("Run {}".format(run_count), 0, 0) app.screen.print("Press any key to restart...", 0, 1) app.screen.update() ...
3269389
import numpy as np from tuun.main import Tuun from examples.branin.branin import branin config = { 'seed': 11, 'acqfunction_config': {'name': 'default', 'acq_str': 'ei', 'n_gen': 500}, 'acqoptimizer_config': {'name': 'neldermead', 'n_init_rs': 10}, 'model_config': {'name': 'standistmatgp'}, } tu = Tuun...
3269409
from django.utils.translation import ugettext_lazy as _ from event_log import registry registry.register( name='access.cbacentry.created', message=_('A CBAC entry for {entry.person} was created by {entry.created_by}: {entry.other_fields}'), ) registry.register( name='access.cbacentry.deleted', messa...
3269430
class Node: def __init__(self,data): self.data = data self.next = None class Solution: def display(self,head): current = head while current: print current.data, current = current.next def insert(self,head,data): new_node = Node(data) if...
3269489
from orchestration import plugin ESSENTIAL_FIXTURES = ['all_events', 'kill_switch', 'result_reporter'] def get_path(): return __file__ def generate_test(name, test_time_sec, setup_fixtures): def generated_test(*args): orchestrator = plugin.Orchestrator(test_time_sec, *args) orchestrator.ru...
3269490
import unittest from tilecloud import BoundingPyramid, Bounds, TileCoord class TestBoundingPyramid(unittest.TestCase): def test_empty(self) -> None: bp = BoundingPyramid() self.assertEqual(len(bp), 0) self.assertFalse(TileCoord(0, 0, 0) in bp) self.assertRaises(StopIteration, next...
3269509
from cifar_configs import * from imagenet_configs import * from config_factory import get_config, get_config_from_json
3269556
from __future__ import annotations import builtins import inspect import sys from inspect import isasyncgenfunction, iscoroutinefunction from typing import Callable, Generic, List, Mapping, Optional, TypeVar, Union from cached_property import cached_property # type: ignore from strawberry.annotation import Strawber...
3269587
from backpack.core.derivatives.conv_transpose3d import ConvTranspose3DDerivatives from backpack.extensions.firstorder.sum_grad_squared.sgs_base import SGSBase class SGSConvTranspose3d(SGSBase): def __init__(self): super().__init__( derivatives=ConvTranspose3DDerivatives(), params=["bias", "wei...
3269591
import os from collections import namedtuple import mimetypes import re from lxml import html from lxml.html.clean import Cleaner from .common_utils import (is_valid_url, get_unique_filename_from_url, get_user_home_dir, make_dir, dir_filename) from .external.parse import search as parse_sear...
3269695
import datetime from sklearn.model_selection import train_test_split from sklearn.preprocessing import OneHotEncoder from tensorflow.python.keras.callbacks import EarlyStopping, ModelCheckpoint import tensorflow as tf from tensorflow.python.keras import Sequential, Model from tensorflow.python.keras.layers import Ti...
3269715
import unittest import os import sys if os.environ.get('USELIB') != '1': sys.path.insert(0, os.path.join(os.path.dirname(__file__), '..')) from pyleri import ( KeywordError, create_grammar, Sequence, Keyword, ) # nopep8 class TestSequence(unittest.TestCase): def test_sequence(self): ...
3269723
from __future__ import annotations import typing import toolsql from ctc import spec from ... import schema_utils async def async_upsert_contract_creation_block( address: spec.Address, block_number: int, network: spec.NetworkReference | None = None, *, conn: toolsql.SAConnection, ) -> None: ...
3269727
import re import typing from cauldron import environ def confirm(question: str, default: bool = True) -> bool: """ Requests confirmation of the specified question and returns that result :param question: The question to print to the console for the confirmation :param default: The de...
3269735
from github import Github import base64 def print_repo(repo): # repository full name print("Full name:", repo.full_name) # repository description print("Description:", repo.description) # the date of when the repo was created print("Date created:", repo.created_at) # the date of the last gi...
3269769
import importlib import sys from inspect import iscoroutinefunction import asyncio from dpyConsole.converter import Converter import inspect import logging import traceback import shlex from dpyConsole.errors import CommandNotFound logger = logging.getLogger("dpyConsole") class Console: """ Handles console ...
3269772
from scrapy import signals from scrapy import version_info as SCRAPY_VERSION if SCRAPY_VERSION <= (1, 0, 0): from scrapy.contrib.exporter import CsvItemExporter, JsonItemExporter else: from scrapy.exporters import CsvItemExporter, JsonItemExporter class ExportData(object): def __init__(self): sel...
3269813
from unittest import TestCase from atlassian.bitbucket import Bitbucket from .mockup import mockup_server class TestWebhook(TestCase): def setUp(self): self.bitbucket = Bitbucket( "{}/bitbucket/server".format(mockup_server()), username="username", password="password" ) self.p...
3269821
import os import tempfile from pywrap.parser import Parser, Includes, ClangError from nose.tools import (assert_true, assert_equal, assert_is_not_none, assert_is_none, assert_raises_regexp) from pywrap.testing import assert_warns_message def test_include_string(): inc = Includes() inc....
3269822
exps = {} groups = {} ############## dataset settings ############## SIZE = 20 SIZE_val = 20 SIZE_test = 20 groups['replica_3_3_6_bounds'] = [ 'XMIN = -3.0', # right (neg is left) 'XMAX = 3.0', # right 'YMIN = -3.0', # down (neg is up) 'YMAX = 3.0', # down 'ZMIN = 0.0', # forward 'ZMAX = 6.0...
3269845
import pycxsimulator from pylab import * width = 50 height = 50 populationSize = 3000 evaporationRate = 0.02 diffusionCoefficient = 0.8 hillClimbingProb = 0.95 def initialize(): global time, agents, envir, nextenvir time = 0 agents = [] for i in range(populationSize): ...
3269868
import unittest import craft_ai from . import settings from .utils import generate_entity_id from .data import valid_data, invalid_data class TestGetAgentStatesSuccess(unittest.TestCase): @classmethod def setUpClass(cls): cls.client = craft_ai.Client(settings.CRAFT_CFG) cls.agent_id = generat...
3269877
from .multi_threads import multiple_process from .make_predict_dataset import save_predict_in_dataset
3269901
from resources import INFERSENT_PATH, W2V_PATH, VEC_DIM from scorer.auto_metrics.infersent_model import InferSent import torch import numpy as np def _norm(x): z = np.linalg.norm(x) return x/z if z > 1e-10 else 0 * x class InferSentScorer: def __init__(self,gpu=False): self.version = 1 par...
3269969
from django.db import models from .equipment import Equipment from .users import User import datetime class InvestmentBase(models.Model): date = models.DateField("Date of the Investment", blank=True, default=datetime.date.today) base_equipment = models....
3269983
import numpy as np def direct_sphere(d,r_i=0,r_o=1): """Direct Sampling from the d Ball based on <NAME>. Statistical Mechanics: Algorithms and Computations. Oxford Master Series in Physics 13. Oxford: Oxford University Press, 2006. page 42 Parameters ---------- d : int dimension of the ball ...
3270010
import unittest from unittest.mock import patch from common.repository import Repository from wallets.config import NETWORK_ID, NETWORKS from wallets.dao.wallet_data_access_object import WalletDAO from wallets.service.wallet_service import WalletService from wallets.wallet import Wallet class TestWalletService(unitt...
3270042
from prml.nn.function import Function class Matmul(Function): @staticmethod def _forward(x, y): return x @ y @staticmethod def _backward(delta, x, y): dx = delta @ y.T dy = x.T @ delta return dx, dy def matmul(x, y): return Matmul().forward(x, y) def rmatmul(x...
3270099
import argparse import torch.nn.parallel import torch.backends.cudnn as cudnn import torch.optim import torch.utils.data import torch.utils.data.distributed import torchvision.transforms as transforms import torchvision.datasets as datasets import Model as Net import numpy as np from utils import * import random import...
3270111
import requests from lib.base import OpscenterAction class GetNodesInfoAction(OpscenterAction): def run(self, node_ip, node_property=None, cluster_id=None): if not cluster_id: cluster_id = self.cluster_id url_parts = [cluster_id, 'nodes', node_ip] if node_property: ...
3270127
import datetime from termcolor import colored from terminaltables import AsciiTable def colorize_value(value): if value < 0: return colored(value, "red") else: return colored(value, "green") # def render_signal_details(signals): # out = [["Indicator", "Signal", "Details"]] # for s in...
3270160
from featuretools.primitives import AggregationPrimitive from featuretools.variable_types import Numeric from tsfresh.feature_extraction.feature_calculators import mean class Mean(AggregationPrimitive): """Returns the mean of x. Docstring source: https://tsfresh.readthedocs.io/en/latest/api/tsfresh.featu...
3270178
import databench class Parameters(databench.Analysis): @databench.on def test_fn(self, first_param, second_param=100): """Echo params.""" yield self.emit('test_fn', (first_param, second_param)) @databench.on def test_action(self): """process an action without a message""" ...
3270262
from sqlalchemy import Column from sqlalchemy.sql.ddl import CreateTable from clickhouse_sqlalchemy import types, engines, Table from tests.testcase import CompilationTestCase class DateTime64CompilationTestCase(CompilationTestCase): table = Table( 'test', CompilationTestCase.metadata(), Column('...
3270331
from xoto3.dynamodb.utils.serde import dynamodb_prewrite_empty_str_in_dict_to_null_transform def test_no_empty_strings_in_maps(): d = dict(a="", b="b") assert dynamodb_prewrite_empty_str_in_dict_to_null_transform(d) == dict(a=None, b="b")
3270370
from judger.judger import Judger INPUT='input/small/' OUTPUT = 'output/' jud = Judger('accu.txt', 'law.txt') res = jud.test(INPUT, OUTPUT) print(res) scor = jud.get_score(res) print(scor) print('FIN')
3270382
from ..objects.list import ObjectList from ..objects.method import Method from .base import ResourceBase class Methods(ResourceBase): def get_resource_object(self, result): return Method(result) def all(self, **params): """List all mollie payment methods, including methods that aren't activat...
3270413
import xlwings as xw import random @xw.func @xw.arg("n", numbers=int) @xw.arg("m", numbers=int) @xw.ret(expand='table') def test_bdh(n, m): return [ [ "%s x %s : %s, %s" % (n, m, i, j) for j in range(m)] for i in range(n) ] @xw.func @xw.arg("n", numbers=int) @xw.arg("m", numbers=int) def te...
3270448
from tensorflow.keras import backend as K def dummy_function(x): return x * x def loss_selector(loss_type): if loss_type == "mean_squareroot_error": return mean_squareroot_error if loss_type == "annealed_loss": return annealed_loss else: return loss_type def annealed_loss(y...
3270459
import picam from PIL import Image from array import array import time width = 100 height = 100 THRESHOLD = 15 QUANITY_MIN = 50 frame1 = picam.takeRGBPhotoWithDetails(width,height) while True: frame2 = picam.takeRGBPhotoWithDetails(width,height) (_,q) = picam.difference(frame1,frame2,THRESHOLD) print q ...
3270461
import math import shutil from datetime import datetime from distutils.dir_util import copy_tree from pathlib import Path import yaml from jinja2 import Environment, FileSystemLoader, select_autoescape models_path = Path(__file__).absolute().parent.resolve() / "../models" template_path = Path(__file__).absolute().pa...
3270469
class Solution: def get_revsersed_num(self, x): a = -x if x < 0 else x length = len(str(a)) num = 0 for i in range(1, length+1): m = int(a%(10**i)/(10**(i-1))) num += m*(10**(length-i)) return -num if x < 0 else num def reverse(self, x: int) -> int...
3270512
from pprint import pprint import re import os from datetime import datetime import json import copy import yaml from scrapli import Scrapli from scrapli.exceptions import ScrapliException from rich.console import Console from rich.table import Table from solution_1_get_all_ports_info import collect_ports_info def g...
3270516
import torch.utils.data as data import torch from scipy.ndimage import imread import os import os.path import glob import numpy as np from torchvision import transforms def make_dataset(root, train=True): dataset = [] if train: dir = os.path.join(root, 'train') for fGT in glob.glob(os.path.join(dir, ...
3270519
import logging from functools import partial import sys import pandas as pd from joblib import Parallel, delayed from typing import Iterable from argparse import Namespace from epic.src.find_islands import _find_islands_cython def find_islands(dfs, score_threshold, args): # type: (Iterable[pd.DataFrame], float...
3270545
import os, glob, cv2 import torch import random import linecache import numpy as np from torch.utils.data import Dataset from PIL import Image class MAKEUP(Dataset): def __init__(self, image_path, transform, mode, transform_mask, cls_list): self.image_path = image_path self.transform = transform ...
3270592
import pytest class Checkers: @staticmethod def check_feed(feed, pairs, **kargs): print(feed) for pair in pairs: (quote, base) = pair.split(':') assert base in feed assert quote in feed[base] for f in ['volume', 'price']: assert f ...
3270597
from opta.commands.init_templates.helpers import set_module_field from opta.commands.init_templates.template import TemplateVariable dnsDomainVariable = TemplateVariable( prompt="DNS domain (e.g. mydomain.dev)", applier=set_module_field("dns", ["domain"]), )
3270604
import numpy as np import logging # custom modules import graph_ltpl # custom packages import trajectory_planning_helpers as tph class VpForwardBackward(object): """ Class providing interfaces and relevant calculations for the forward-backward velocity planner. :Authors: * <NAME> <<EMAIL>> ...
3270621
from rest_framework import viewsets, filters from .models import Snippet, Comment from .serializers import SnippetSerializer, CommentSerializer class SnippetViewSet(viewsets.ModelViewSet): queryset = Snippet.objects.all() serializer_class = SnippetSerializer filter_backends = (filters.OrderingFilter,) ...
3270622
from pybindgen import * from PBGutils import * from ref_return_value import * from CXXTypesModule import generateStdVectorBindings from PhysicsModule import generatePhysicsVirtualBindings #------------------------------------------------------------------------------- # The class to handle wrapping this module. #---...
3270625
class Solution(object): def letterCombinations(self, digits): """ :type digits: str :rtype: List[str] """ pnDict = { '2' : ['a', 'b', 'c'], '3' : ['d', 'e', 'f'], '4' : ['g', 'h', 'i'], '5' : ['j', 'k', 'l'], '6' : ['m', 'n', 'o'], ...
3270634
from datetime import datetime from Entity.Entity import * class UserAccounts(db.Model): __tablename__ = 'UserAccounts' def __init__(self , UserName , Password , FBuserID , FBAccessToken , CreateDate=datetime.now() ...
3270635
from torch import nn import torch from imix.utils.registry import Registry, build_from_cfg EMBEDDING = Registry('embedding') ENCODER = Registry('encoder') BACKBONES = Registry('backbone') COMBINE_LAYERS = Registry('combine_layers') POOLERS = Registry('pooler') HEADS = Registry('head') LOSSES = Registry('loss') VQA_MOD...
3270653
from ._abstract import AbstractScraper from ._utils import get_minutes, normalize_string, get_yields YIELDS = ['Makes', 'Serves', 'For'] TAGS = ["Occasion", "Recipe Course", "Meal", "Cooking Method", "Dietary Consideration", "Type of Dish"] class Cookstr(AbstractScraper): @classmethod def host(self): ...
3270657
from __future__ import absolute_import from __future__ import division from __future__ import print_function import shutil import sys import tempfile from observations.r.workinghours import workinghours def test_workinghours(): """Test module workinghours.py by downloading workinghours.csv and testing shape of...
3270671
import json from grpcalchemy.orm import ( BooleanField, BytesField, Int32Field, Int64Field, RepeatedField, MapField, Message, ReferenceField, StringField, ) from grpcalchemy.types import Map, Repeated from tests.test_grpcalchemy import TestGRPCAlchemy class TestORMMessage(Message)...
3270693
def main(): import dtlpy as dl import numpy as np import matplotlib.pyplot as plt # Get project and dataset project = dl.projects.get(project_name='Food') dataset = project.datasets.get(dataset_name='BeansDataset') # get item from platform item = dataset.items.get(filepath='/image.jpg'...
3270696
import src.third_party.imageAugmentation.imgaug as libRoot from src.third_party.imageAugmentation.imgaug import augmenters as lib import time import numpy as np import settings.DataSettings as dataSettings def _augmentedByAllMethods(): sometimes = lambda aug: lib.Sometimes(0.5, aug) augmentMethod = lib.Sequential([ ...
3270697
import hoi4 import hoi4 import pyradox import os.path from unitstats import * files = {} for unit_type in base_columns.keys(): files[unit_type] = open("out/%s_units.txt" % unit_type, "w") columns = { "land" : ( ("Unit", compute_unit_name), ("Year", "%(year)d"), ("Manpower", "%(manp...
3270700
import os import re import requests import shutil import urllib.request as request import tempfile import logging import json from contextlib import closing from bs4 import BeautifulSoup from .rir import RIR class ARIN(RIR): LOGIN_URL = "https://accountws.arin.net/public/seam/resource/rest/auth/login" BASE_...
3270707
import torch import torch.autograd as autograd import torch.nn as nn import torch.nn.functional as F import numpy as np from torch.autograd import Variable from torch.nn import functional, init # Implementation of Classifier class AttClassifier(nn.Module): def __init__(self, data): super(AttClas...