id
stringlengths
3
8
content
stringlengths
100
981k
11519890
from builtins import super from functools import partial import torch import torch.nn as nn import torch.nn.functional as F from scipy import ndimage from vgn.ConvONets.conv_onet.config import get_model def get_network(name): models = { "vgn": ConvNet, "giga_aff": GIGAAff, "giga": GIGA, ...
11519970
import os import sys import time import signal from models.exchange.binance import WebSocketClient as BWebSocketClient def cls(): os.system("cls" if os.name == "nt" else "clear") def signal_handler(signum, frame): if signum == 2: print(" -> not finished yet!") return try: websocket = B...
11519975
from CoreUtils.NmapAPI import Nmapper def Port_Scan(target, port, scan_type): nmapper = Nmapper() nmapper.Scan(target, port, scan_type)
11520027
import sys import numpy as np import pandas as pd from scipy import sparse import itertools import os import CoEmbedding DATA_DIR = '/media/O_o/UB/research/dataset/20newsgroups/CoEmbedding/' dwmatrix_pt = DATA_DIR+'dw_matrix.csv' vocab_pt = DATA_DIR+'vocab.txt' n_docs = 18827 n_words = 20678 def tfidf(D...
11520029
from typing import TYPE_CHECKING from itests.pages.base import BasePage if TYPE_CHECKING: from selenium.webdriver.remote.webelement import WebElement from typing import List class PermissionCreatePage(BasePage): @property def allowed_patterns(self): # type: () -> List[str] patterns =...
11520047
from django.db import models from django.http import Http404 from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.admin.edit_handlers import FieldPanel class HomePage(Page): body = RichTextField(blank=True) def route(self, request, path_components): # Check...
11520092
from cloudfn.pubsub import handle_pubsub_event import jsonpickle def pubsub_handler(message): print jsonpickle.encode(message) handle_pubsub_event(pubsub_handler)
11520101
from mock import Mock, patch from unittest import TestCase from samtranslator.model.function_policies import FunctionPolicies, PolicyTypes, PolicyEntry from samtranslator.model.exceptions import InvalidTemplateException class TestFunctionPolicies(TestCase): def setUp(self): self.policy_template_processor...
11520114
import logging from rocketchat.calls.base import RocketChatBase logger = logging.getLogger(__name__) class GetUsers(RocketChatBase): endpoint = '/api/v1/users.list' def build_endpoint(self): return self.endpoint def post_response(self, result): users = [] try: _us...
11520120
from ucollections import deque d = deque((), 1) d.append(1) d.append(2) assert d.popleft() == 2 d = deque((), 1, 1) d.append(1) try: d.append(2) assert False except IndexError: pass
11520130
import pytest from paho.mqtt.client import MQTTMessage from HABApp.mqtt.mqtt_payload import get_msg_payload @pytest.mark.parametrize( 'payload, expected', ( ('none', None), ('None', None), ('true', True), ('True', True), ('false', False), ('False', False), ...
11520131
import os import infra.basetest class TestPythonBase(infra.basetest.BRTest): config = infra.basetest.BASIC_TOOLCHAIN_CONFIG + \ """ BR2_TARGET_ROOTFS_CPIO=y # BR2_TARGET_ROOTFS_TAR is not set """ interpreter = "python" def login(self): cpio_file = os.path.join(sel...
11520149
from showml.losses import BinaryCrossEntropy from showml.optimizers import RMSProp from showml.linear_model.regression import LogisticRegression from showml.utils.dataset import Dataset from showml.losses.metrics import accuracy, binary_cross_entropy from showml.utils.data_loader import load_wine X_train, y_train = l...
11520178
import asyncio class Streams: def __init__(self): self.inbox = asyncio.Queue() self.outbox = asyncio.Queue()
11520182
import tvm import time import numpy as np import torch import random from tvm.tensor_graph.testing.models import capsule_tg as capsule from tvm.tensor_graph.testing.pytorch_examples import resnet_annotated from tvm.tensor_graph.nn.layers import Layer, Conv2d, BatchNorm2d, ReLU, \ AvgP...
11520191
import unittest from scipy.stats import norm import warnings import pickle import tensorflow as tf import sys import os import numpy as np import scipy.stats as stats sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) from cde.density_estimator import NormalizingFlowEstimator from cde.d...
11520197
from __future__ import print_function import numpy as np # import sys # sys.path.append('../Python') from ..util.flag_dionysus import computePersistence import dionysus as d import time import torch from torch.autograd import Variable, Function dtype=torch.float32 # torch.double #torch.float32 PLOT = True ''' OBS: -1....
11520260
import inflection class NamedElement(object): def __init__(self, **kwargs): super(NamedElement, self).__init__() self.name = kwargs.pop('name', "unnamed") self.description = kwargs.pop('description', "") def __getattribute__(self, name): lam = {'CamelCase': lambda: inflection....
11520277
from pathlib import Path from io import StringIO from unittest import mock import pytest from snowfakery.data_generator import generate from snowfakery import data_gen_exceptions as exc from snowfakery.standard_plugins.datasets import SQLDatasetRandomPermutationIterator class TestExternalDatasets: def test_csv_...
11520305
import infrastructure.intake as intake import infrastructure.log as log import core.vision as vision import numpy as np import cv2 def run(img, logOn=True): white_balanced_image = vision.white_balance(img) hsv = cv2.cvtColor(white_balanced_image, cv2.COLOR_BGR2HSV) if logOn: log.hsvOrGreyImage(hsv) ...
11520320
import os, sys, vcs.testing.regression as regression import vcs from vcsaddons import EzTemplate import cdms2,vcs,sys ## 12 plots 1 legend per row on the right ## Initialize VCS x = vcs.init() x.drawlogooff() bg = True M = EzTemplate.Multi(rows=4,columns=3) M.legend.direction='vertical' for i in range(12): t=M.get...
11520358
import logging from datetime import timedelta, datetime from typing import Optional, List from django.conf import settings from django.contrib.auth.models import User from django.template.loader import get_template from django.utils import timezone from django.utils.translation import gettext as _ from elasticsearch_d...
11520362
import os import os.path import shutil import sys import textwrap import unittest import pyperformance from pyperformance import tests class FullStackTests(tests.Functional, unittest.TestCase): maxDiff = 80 * 100 @classmethod def setUpClass(cls): # pyperformance must be installed in order to ru...
11520369
import json import os import unittest import tempfile from flask import jsonify import app as nftserver from utils import nft_utils class NFTServerCreateRuleTests(unittest.TestCase): def setUp(self): nftserver.app.config['TESTING'] = True self.app = nftserver.app.test_client() def tearDown...
11520419
import logging from typing import List import numpy as np import tensorflow as tf from transformers_keras.common.metrics import ExactMatch, F1ForSequence from transformers_keras.datapipe.sa_dataset import DatasetForAspectTermExtraction, ExampleForAspectTermExtraction class BaseMetricForAspectTermExtraction(tf.keras....
11520424
import datetime import functools import inspect import random import time import six _DEFAULT_RETRIES = 3 _DEFAULT_DELAY_INITIAL = 0.1 _DEFAULT_DELAY_MULTIPLIER = 2.0 _DEFAULT_DELAY_MAXIMUM = 60 _DEFAULT_DELAY_JITTER = (0, 1) _SAFE_VALID_ASSIGNMENTS = ("__doc__",) def _name_of_func(f): module = inspect.getmodul...
11520429
import unittest import pytest import numpy as np import pyuvdata as uv import os, copy, sys from scipy.integrate import simps, trapz from .. import pspecdata, pspecbeam, conversions, container, utils, testing from hera_pspec.data import DATA_PATH from pyuvdata import UVData, UVCal, utils as uvutils from hera_cal import...
11520504
import argparse import os from os import path import time import copy import torch torch.set_default_tensor_type('torch.cuda.FloatTensor') from mpl_toolkits.mplot3d import Axes3D # noqa: F401 unused import import matplotlib matplotlib.use('Agg') import sys sys.path.append('submodules') # needed to make import...
11520515
from aiohttp import web from waio import Bot, Dispatcher from waio.states import StatesGroup, BaseState, FSMContext from waio.types import Message from waio.logs import loguru_filter from waio.storage import RedisStorage loguru_filter.set_level('DEBUG') bot = Bot( apikey='API_KEY', src_name='SRC_NAME', ph...
11520521
import os import time import fnmatch from random import shuffle import numpy as np import tensorflow as tf from image_ops import get_image, save_images def generate_z(sample_size, z_dim): """Helper function to generate noise vector. Can replace this with a different noise function. Args: sample_s...
11520553
from midca.modules._plan import modified_pyhop import time def point_at_m(state, objectID): return [("block_until_seen", objectID), ("point_to", objectID)] def pickup_m(state, objectID): #if get_last_position(state, objectID) == "table": #if get_last_clear_status(state, object) == 'clear': return [("reach_to_pic...
11520558
import time from math import factorial import scipy.special import scipy.spatial import numpy as np import tectosaur as tct from tectosaur.mesh.modify import concat from tectosaur.fmm.tsfmm import * import tectosaur.util.gpu as gpu def fmm_tester(K_name, far_only = False, one_cell = False): np.random.seed(123987)...
11520601
import ee from ee_plugin import Map image = ee.Image('USDA/NAIP/DOQQ/m_3712213_sw_10_1_20140613') Map.setCenter(-122.466123, 37.769833, 17) Map.addLayer(image, {'bands': ['N', 'R','G']}, 'NAIP')
11520610
import asyncio import json from time import time from typing import Optional import pytest from slack_sdk.oauth.installation_store.async_installation_store import ( AsyncInstallationStore, ) from slack_sdk.signature import SignatureVerifier from slack_sdk.web.async_client import AsyncWebClient from slack_bolt.app...
11520625
import streamlit as st import pandas as pd st.write(1234) st.write( pd.DataFrame({"first column": [1, 2, 3, 4], "second column": [10, 20, 30, 40]}) )
11520651
import glob import os import freetype import pytest test_folder = os.path.realpath(os.path.dirname(__file__)) def test_load_ft_face(): """A smoke test.""" p = os.path.join(test_folder, "..", "examples", "Vera.ttf") assert freetype.Face(p) def test_load_ft_face_from_memory(): """Another smoke test....
11520678
from copy import copy from hwt.doc_markers import internal from hwt.hdl.types.bits import Bits from hwt.hdl.types.defs import INT from hwt.hdl.value import HValue from hwt.synthesizer.rtlLevel.mainBases import RtlSignalBase def slice_member_to_hval(v): if isinstance(v, RtlSignalBase): # is signal assert...
11520701
import pytest from returns.context import ( RequiresContext, RequiresContextFutureResult, RequiresContextIOResult, RequiresContextResult, ) from returns.converters import flatten from returns.future import Future, FutureResult from returns.io import IO, IOFailure, IOSuccess from returns.maybe import No...
11520711
import FWCore.ParameterSet.Config as cms from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer rpcrechitprobability = DQMEDAnalyzer('RPCRecHitProbability', SaveRootFile = cms.untracked.bool(False), RootFileName = cms.untracked.string('RPCRe...
11520729
from django import forms from django.utils.translation import gettext as _ from taggit.utils import edit_string_for_tags, parse_tags class TagWidget(forms.TextInput): def format_value(self, value): if value is not None and not isinstance(value, str): value = edit_string_for_tags(value) ...
11520761
from typing import Optional from cython_vst_loader.vst_constants import VstEventTypes class VstEvent: def __init__(self): self.type: Optional[int] = None self.byte_size: Optional[int] = None self.delta_frames: Optional[int] = None self.flags: Optional[int] = None self.data...
11520777
import base64 from urllib.parse import quote from aiohttp import web from . import settings from .core import Magnet2Torrent from .utils import FailedToFetchException routes = web.RouteTableDef() @routes.get("/") async def get_torrent(request): if settings.SERVE_APIKEY and request.query.getone("apikey", None) ...
11520785
from collections import defaultdict from scispacy.abbreviation import AbbreviationDetector from scispacy.linking import EntityLinker class EntityLink: def __init__(self, nlp, linkage_mode, data): self.sents = data self.nlp = nlp self.linkage_mode = linkage_mode def umls_entlink(self)...
11520790
import nn_closed_loop.example as ex import numpy as np from tabulate import tabulate import pandas as pd import datetime import os import glob import matplotlib.pyplot as plt import argparse import nn_closed_loop.dynamics as dynamics import nn_closed_loop.analyzers as analyzers import nn_closed_loop.constraints as con...
11520833
import torch import torch.nn as nn from torch.autograd.function import Function import torch.nn.functional as F from torch.nn import Parameter import numpy as np import os import math import pdb import time import copy import mmcv from sklearn.cluster import KMeans # This file contains implementations of some algorit...
11520865
import requests import json from django.core.management.base import BaseCommand from user.models import User from researchhub.settings import AMPLITUDE_API_KEY API_URL = 'https://api.amplitude.com/2/httpapi' class Command(BaseCommand): def get_user_props(self, user, user_email): # Makes one less db ca...
11520893
import functools from matplotlib import artist as martist, cbook, transforms as mtransforms from matplotlib.axes import subplot_class_factory from matplotlib.transforms import Bbox from .mpl_axes import Axes import numpy as np class ParasiteAxesBase: def get_images_artists(self): artists = {a for a in ...
11520906
import pytest from tartiflette import Resolver, create_engine _SDL = """ type A { b: String c: String } type Query { a: A } """ @pytest.mark.asyncio async def test_issue140(): @Resolver("Query.a", schema_name="test_issue140") async def resolver_query_a(*args, **kwargs): return {"b": "mp...
11520936
data = ( 'Yu ', # 0x00 'Cui ', # 0x01 'Ya ', # 0x02 'Zhu ', # 0x03 'Cu ', # 0x04 'Dan ', # 0x05 'Shen ', # 0x06 'Zhung ', # 0x07 'Ji ', # 0x08 'Yu ', # 0x09 'Hou ', # 0x0a 'Feng ', # 0x0b 'La ', # 0x0c 'Yang ', # 0x0d 'Shen ', # 0x0e 'Tu ', # 0x0f 'Yu ', # 0x10 'Gua ',...
11520940
import unittest from katas.beta.count_inversions import count_inversion class CountInversionsTestCase(unittest.TestCase): def test_equal_1(self): self.assertEqual(count_inversion((1, 2, 5, 3, 4, 7, 6)), 3) def test_equal_2(self): self.assertEqual(count_inversion((0, 1, 2, 3)), 0) def te...
11520942
from create_grids import create_grids from run_model import run_model from plot_testcase import plot_testcase #------------------------------------------------------------------------------- def run_ridging_island_testcase(): # create grids create_grids() # run the model run_model() # plot test...
11520972
from plone.app.layout.icons.icons import CatalogBrainContentIcon class FontAwesomeIconReplacer(CatalogBrainContentIcon): """ Custom IContentIcon adapter. This is used by @@ploneview to determine which icons to render. We want to prevent the rendering of icons, so that FontAwesome fonts wi...
11520980
from collections import OrderedDict from rop import Rop, Ret, Load from relocatable import SceWebKit_base, SceLibKernel_base, SceLibc_base, SceLibHttp_base, SceNet_base, data_base from util import p32, u32 class Gadgets360: ldm_r1_stuff = SceWebKit_base + 0x54c8 # 54c8: e891a916 ldm r1, {r1, r2, r4, r8, fp, sp, ...
11521015
import numpy as np import tensorflow as tf from config import Config import model as _model from data_loader import get_datasets import matplotlib.pyplot as plt plt.style.use("seaborn-darkgrid") flags = tf.app.flags FLAGS = flags.FLAGS flags.DEFINE_string( "config", "conf/SML2010.json", "Path to json fi...
11521031
class RegistryAccessRule(AccessRule): """ Represents a set of access rights allowed or denied for a user or group. This class cannot be inherited. RegistryAccessRule(identity: IdentityReference,registryRights: RegistryRights,type: AccessControlType) RegistryAccessRule(identity: str,registryRights: Regi...
11521044
import copy from typing import Dict, Union, List from pathlib import Path from zsvision.zs_utils import memcache, concat_features from typeguard import typechecked from utils import memory_summary from base.base_dataset import BaseDataset class ActivityNet(BaseDataset): @staticmethod @typechecked def d...
11521055
from .card import Card, Cards, Batch, Deck from .ranked import Leaderboard from .match import Match, MatchHistory from .status import Status
11521107
from visual_mpc.video_prediction.setup_predictor import setup_predictor from visual_mpc.video_prediction.vpred_model_interface import VPred_Model_Interface from video_prediction.models.savp_model import SAVPVideoPredictionModel import video_prediction base_dir = video_prediction.__file__ base_dir = '/'.join(str.split(...
11521126
import urllib.parse import requests import datetime import xml.etree.ElementTree as ET from .resource import Bill, EDM, Division, Member, parse_data, MemberList from .parties import Parties class Parliament(object): LDA_ENDPOINT = "http://lda.data.parliament.uk/" MEMBERS_NAMES_ENDPOINT = ( "http://da...
11521149
import tensorflow as tf import tensorflow_datasets as tfds from t5.data import preprocessors as prep import functools import t5 import gin vocab = 'gs://mesolitica-tpu-general/t5-data-v2/sp10m.cased.ms-en.model' tpu = tf.distribute.cluster_resolver.TPUClusterResolver( 'node-7', zone='europe-west4-a', project='mes...
11521208
from starlette.requests import Request from starlette.responses import RedirectResponse from starlette.status import HTTP_303_SEE_OTHER def redirect(request: Request, view: str, **params): return RedirectResponse( url=request.app.admin_path + request.app.url_path_for(view, **params), status_code=H...
11521224
import numpy as np import os import cv2 import cv2.cv as cv from skimage import transform as tf from PIL import Image, ImageDraw import threading from time import ctime,sleep import time import sklearn import matplotlib.pyplot as plt import skimage import sklearn.metrics.pairwise as pw import triplet._init_paths import...
11521253
import unittest import warnings import torch from tqdm import tqdm from data.utils import get_db_container, get_db_info from utils import get_dataloader, get_train_val_test_datasets dataset_names = ('acquirevaluedshopperschallenge', 'homecreditdefaultrisk', 'kddcup2014') class Tes...
11521269
from os.path import dirname, basename from django.conf import settings from django.core.management import call_command from django.core.management.base import BaseCommand, CommandError from django.db.models import get_apps, get_models, signals from django.utils.importlib import import_module from django.utils.module_l...
11521293
import pandas as pd import numpy as np from sklearn import metrics import streamlit as st from sklearn.svm import SVC from sklearn.linear_model import LogisticRegression from sklearn.neighbors import KNeighborsClassifier from sklearn.naive_bayes import GaussianNB df=pd.read_csv("data.csv") df = df.drop(['ID','Experien...
11521303
import os import pytest from statuscheck.services import SERVICES from statuscheck.utils import get_available_services, get_statuscheck_api BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def test_get_available_services(): services = get_available_services() assert services serv...
11521304
from doepy.doe_functions import ( build_full_fact, build_frac_fact_res, build_plackett_burman, build_sukharev, build_box_behnken, build_central_composite, build_lhs, build_space_filling_lhs, build_random_k_means, build_maximin, build_halton, build_uniform_random, ) def ...
11521356
from __future__ import annotations from asyncio import CancelledError from typing import TYPE_CHECKING, Any, List, Optional from ....jsonrpc2.protocol import rpc_method from ....utils.async_event import async_tasking_event from ....utils.logging import LoggingDescriptor from ..has_extend_capabilities import HasExtend...
11521361
import os from conans import ConanFile, CMake, tools from conans.errors import ConanInvalidConfiguration class GladConan(ConanFile): name = "glad" description = "Multi-Language GL/GLES/EGL/GLX/WGL Loader-Generator based on the official specs." topics = ("conan", "glad", "opengl") url = "https://github...
11521440
import pytest from antu.io import Vocabulary from collections import Counter class TestVocabulary: def test_extend_from_pretrained_vocab(self): vocab = Vocabulary() # Test extend a vocabulary from a simple pretained vocab pretrained_vocabs = {'glove': ['a', 'b', 'c']} vocab.exten...
11521445
import argparse from datetime import datetime from dateutil.parser import isoparse def parse_args(arguments=[]): """Example of argparse with different inputs. Args: arguments (list): Arguments passed as a list of strings. This argument can be used when calling the functi...
11521484
import numpy as np from scipy.io import loadmat from collections import Counter from keras.utils import to_categorical from sklearn.model_selection import train_test_split def mat2array(): data_mat = loadmat('Indian_pines_corrected.mat') gt_mat = loadmat('Indian_pines_gt.mat') data = data_mat['indian_pin...
11521509
from juliabox.jbox_util import gen_random_secret from juliabox.db import JBPluginDB, JBoxDBItemNotFound __author__ = 'barche' class EmailVerifyDB(JBPluginDB): provides = [JBPluginDB.JBP_TABLE_RDBMS] NAME = 'jbox_email_verify' TABLE = None KEYS = ['user_id'] ATTRIBUTES = ['email', 'verification...
11521517
import os import sys sys.path.append('/solution') import matplotlib import matplotlib as mlp mlp.rcParams['font.family'] = u'NanumGothic' mlp.rcParams['font.size'] = 10 import pandas as pd pd.set_option('io.hdf.default_format', 'table') # default hdf format 'table' from pandas import Series, DataFrame import numpy a...
11521536
from setuptools import find_packages, setup from setuptools.extension import Extension with open('README.rst') as readme: long_description = readme.read() setup( name='weighted_levenshtein', version='0.2.1', description=( 'Library providing functions to calculate Levenshtein distance, Optima...
11521559
from os import path from django.contrib.auth.models import User from django.test import TestCase from django.urls import reverse from files.models import CaptionedFile fixture_dir = path.join(path.abspath(path.dirname(__file__)), 'fixtures') class CaptionedFileTestCase(TestCase): def setUp(self): self...
11521598
import sys import os from pathlib import Path from appdirs import user_config_dir from .version import Version __all__ = ("__version__", "appdata", "cachepath", "cache", "lang", "theme") __version__ = Version(180501) appdata = user_config_dir('omnitool', "", roaming=True) cachepath = os.path.join(appdata, "cache.di...
11521617
import torch from mmaction.datasets import CutmixBlending, MixupBlending def test_mixup(): alpha = 0.2 num_classes = 10 label = torch.randint(0, num_classes, (4, )) mixup = MixupBlending(num_classes, alpha) # NCHW imgs imgs = torch.randn(4, 4, 3, 32, 32) mixed_imgs, mixed_label = mixup(i...
11521619
import copy import numpy as np from sarsa import Sarsa class DoubleQLearning(Sarsa): def __init__(self, env, step_size=0.1, gamma=1, eps=0.1, pol_deriv=None): super().__init__(env, step_size, gamma, eps, pol_deriv) self.greedy_pol = self.eps_gre(eps=0) self.reset() print(f"gamma={self.gamma}") ...
11521638
from diplomas.services.diploma_generator import DiplomaGenerator from diplomas.services.diploma_regenerator import DiplomaRegenerator __all__ = [ 'DiplomaGenerator', 'DiplomaRegenerator', ]
11521687
from simtk import unit import sys import numpy as np import matplotlib as mpl mpl.use('Agg') from openmmtools.constants import kB import matplotlib.pyplot as plt ################################################################################ # NUMBER OF ATTEMPTS #######################################################...
11521694
from __future__ import print_function import argparse import os import random import sys sys.path.append(os.getcwd()) import pdb import time import numpy as np import json import progressbar import torch import torch.nn as nn import torch.nn.functional as F import torch.nn.parallel import torch.backends.cudnn as cudn...
11521726
import sympy import sys import unittest import sophus import functools class Se3: """ 3 dimensional group of rigid body transformations """ def __init__(self, so3, t): """ internally represented by a unit quaternion q and a translation 3-vector """ assert isinstance(so3, sophus.So...
11521750
from kratos import Generator, TestBench, initial, assert_, delay, Sequence def tb_dut_setup(): dut = Generator("mod") dut.wire(dut.output("out", 1), dut.input("in", 1)) dut.wire(dut.var("val", 1), dut.ports["in"]) tb = TestBench() tb.add_child("dut", dut) in_ = tb.var("in", 1) out_ = tb....
11521771
from binascii import hexlify from hashlib import sha256 from os import urandom # RFC 3526 - More Modular Exponential (MODP) Diffie-Hellman groups for # Internet Key Exchange (IKE) https://tools.ietf.org/html/rfc3526 primes = { # 1536-bit 5: { "prime": int( "FFFFFFFFFFFFFFFFC90FDAA22168C234...
11521823
from tests.unit import unittest from tests.unit import AWSMockServiceTestCase from boto.vpc import VPCConnection, CustomerGateway class TestDescribeCustomerGateways(AWSMockServiceTestCase): connection_class = VPCConnection def default_body(self): return """ <DescribeCustomerGatewaysResp...
11521830
import torch.nn as nn from .Encoder import Encoder from .Decoder import Decoder class Seq2Seq(nn.Module): def __init__(self, encoder, attention, decoder): super().__init__() self.encoder = encoder self.attn = attention self.decoder = decoder def forward(self, x): # c i...
11521850
import itertools import pytest from examples.my_heart_counts.six_minute_walk_activity import pipeline @pytest.fixture def dataframe(scope="module"): dataframe = pipeline.process()[0] return dataframe def test_data_is_correctly_loaded(dataframe): assert list(dataframe.columns) == ["recordId", "numberOf...
11521853
from manga_py.crypt import Puzzle from manga_py.fs import get_temp_path, rename from manga_py.provider import Provider class TonariNoYjJp: provider = None div_num = 4 multiply = 8 matrix = None temp_path = None def __init__(self, provider: Provider): self.provider = provider s...
11521880
import pytest from .graphql import assert_query @pytest.mark.django_db def test_image(client): assert_query(client, 'image', '1') @pytest.mark.django_db def test_image_with_focal_point(client): assert_query(client, 'image', '2') @pytest.mark.django_db def test_image_with_rendition(client): assert_quer...
11522024
import pytorch_lightning as pl import torch import torch.nn as nn from quickvision.models.components import create_torchvision_backbone from quickvision.models.detection.faster_rcnn import create_fastercnn_backbone from quickvision.models.detection.utils import _evaluate_iou, _evaluate_giou from torchvision.models.dete...
11522026
import torch import os import sklearn.model_selection def pad(channel, maxlen): channel = torch.tensor(channel) out = torch.full((maxlen,), channel[-1]) out[: channel.size(0)] = channel return out def subsample(X, y, subsample_rate): if subsample_rate != 1: X = X[:, :, ::subsample_rate] ...
11522078
import pycuda.autoinit from pycuda import gpuarray import numpy as np from skcuda import cublas from time import time m = 5000 n = 10000 k = 10000 def compute_gflops(precision='S'): if precision=='S': float_type = 'float32' elif precision=='D': float_type = 'float64' else: return -1 A = np.random.r...
11522099
import objc as _objc __bundle__ = _objc.initFrameworkWrapper( "OpenDirectory", frameworkIdentifier="com.apple.OpenDirectory", frameworkPath=_objc.pathForFramework( "/System/Library/Frameworks/OpenDirectory.framework" ), globals=globals() )
11522133
import os import sys import json import logging import numpy as np logging.basicConfig(level=logging.INFO) from robo.solver.hyperband_datasets_size_original_incumbent import HyperBand_DataSubsetsOriginalIncumbent from hpolib.benchmarks.ml.svm_benchmark import SvmOnMnist, SvmOnVehicle, SvmOnCovertype, SvmOnAdult, Svm...
11522148
import argparse import asyncio import datetime import logging import os import shutil import subprocess """ async def fb(cmd): import select proc = subprocess.Popen( cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE) poller = select.poll() poller.register(proc.stdout, select....
11522171
from typing import Generator, List import twitch.tmi as tmi from twitch.api import API from twitch.baseresource import BaseResource class Chatters(BaseResource['tmi.Chatter']): def __init__(self, api: API, user: str): super().__init__(api=api, path='group/user/{user}/chatters') self._api = api ...
11522198
import numpy as np import pickle # Custom scaler to easily normalize features along the time axis. class InputScaler(): def __init__(self): self.X_means = list() self.X_stds = list() self.T_mean = 0 self.T_std = 0 def fit(self, X, T): for f in range(X.shape[2]): ...
11522203
from bread.bread import LabelValueReadView, EditView from django import forms from django.contrib import messages from django.utils.translation import ungettext, ugettext_lazy as _ from django_filters import FilterSet from audit.models import Discrepancy, VumiLog, SMSTrail from libya_elections.libya_bread import Pagin...
11522230
import json from flask import Blueprint, request from apps.extention.business.cidata import CiDataBusiness, CiJobBusiness from apps.extention.extentions import parse_list_args2, parse_json_form, validation from apps.public.models.public import Config from library.api.render import json_detail_render, json_list_render...