id
stringlengths
3
8
content
stringlengths
100
981k
185803
from zschema.leaves import * from zschema.compounds import * import zschema.registry from ztag.annotation import Annotation import zcrypto_schemas.zcrypto as zcrypto import zgrab2_schemas.zgrab2 as zgrab2 import zgrab2_schemas.zgrab2.mssql as zgrab2_mssql import zgrab2_schemas.zgrab2.oracle as zgrab2_oracle import z...
185828
from fastapi import FastAPI, Request from starlette.responses import JSONResponse app = FastAPI() @app.exception_handler(Exception) async def generic_exception_handler(request: Request, exc: Exception): return JSONResponse(status_code=200, content="It doesn't work!") @app.get("/") async def home(): raise E...
185889
from .inlinecallbackbutton import InlineCallbackButton from .inlinecallbackhandler import InlineCallbackHandler from .inlineactionhandler import InlineActionHandler
185895
import os import struct import sys import pytest from bonsai.active_directory.acl import ACL from bonsai.active_directory.sid import SID from conftest import get_config from bonsai import LDAPClient from bonsai.active_directory import SecurityDescriptor @pytest.fixture def client(): """ Create a client with aut...
185899
import yaml class MotionRecorder: def __init__(self, input_file=None): self.data = {} if input_file: with open(input_file, 'r') as file: self.data = yaml.safe_load(file) def append(self, object_name, pose): if object_name not in self.data: se...
185931
import numpy as np import torch """ This class define the parent class of operation Author: SunnerLi """ class OP(): """ The parent class of each operation The goal of this class is to adapting with different input format """ def work(self, tensor): """ The vir...
185974
import time from pkg_resources import resource_filename from typing import Dict, Union, List, Tuple, Optional, NamedTuple, Set, Iterable, Sequence import dtale import dtale.views import dtale.global_state from autoplot.extensions.autoplot_display import AutoplotDisplay from autoplot.extensions.toast import Toast, Toa...
186004
from typing import Callable import pytest from tests.taxonomy.conftest import TestDirectory, validate_taxonomy @pytest.mark.parametrize("defect", [(1, 1), (2, 56), (3, 22), (4, 29), (5, 42)]) def test_zsh(defect, defect_path: Callable[[int, int], TestDirectory], gitenv): index, case = defect test_dir = defe...
186101
import pickle from utils import * def visualize(_id, predict, label, masks, words, sent_attns=[1], msg=False, save_html=False, save_img=True): h5_string_list = list() h5_string_list.append('<div class="cam">') h5_string_list.append("<head><meta charset='utf-8'></head>") h5_string_list.append("Change Id...
186123
from math import hypot import pygame import rabbyt rabbyt.init_display((640,480)) rabbyt.set_viewport((640,480), projection=(0,0,640,480)) control_points = [rabbyt.Sprite(xy=xy) for xy in [(100,100),(200,50),(300,150),(400,100)]] grabbed_point = None path_followers = [] def generate_followers(): global ...
186136
from .__about__ import * import logging __all__ = ['__version__', '__classification__', '__author__', '__url__', '__email__', '__title__', '__summary__', '__license__', '__copyright__'] # establish logging paradigm logger = logging.getLogger(__name__) logger.setLevel(logging.WARNING...
186170
from collections import defaultdict from pprint import pprint from math import log # comparison values for n degrees freedom # These values are useable for both the chi^2 and G tests _ptable = { 1:3.841, 2:5.991, 3:7.815, 4:9.488, 5:11.071, 6:12.592, ...
186196
import numpy as np import os import pygame, sys from pygame.locals import * import sys sys.path.insert(0, os.getcwd()) import rodentia BLACK = (0, 0, 0) MAX_STEP_NUM = 60 * 30 class Display(object): def __init__(self, display_size): self.width = 640 self.height = 480 self.data_path = os...
186219
from petisco.base.domain.message.message import Message class RabbitMqMessageQueueNameFormatter: @staticmethod def format(message: Message, exchange_name: str = None) -> str: message_name = message.name.replace(".", "_") message_type = message.type if message.type != "domain_event" else "event...
186234
import numpy as np import paddle from paddlevision.models.alexnet import alexnet from reprod_log import ReprodLogger if __name__ == "__main__": paddle.set_device("cpu") # load model # the model is save into ~/.cache/torch/hub/checkpoints/alexnet-owt-4df8aa71.pth # def logger reprod_logger = Repr...
186290
from bokeh.plotting import figure, output_file, show output_file("styling_toolbar_autohide.html") # Basic plot setup plot = figure(width=400, height=400, title='Toolbar Autohide') plot.line([1,2,3,4,5], [2,5,8,2,7]) # Set autohide to true to only show the toolbar when mouse is over plot plot.toolbar.autohide = True ...
186303
import matplotlib.pyplot as plt import random import os import numpy as np import tensorflow as tf import logging from load_data import load_train_data, load_data_by_id, load_entity_by_id, \ load_candidates_by_id, load_mention_entity_prior2, load_entity_emb, load_voting_eid_by_doc, \ get_embeddi...
186353
from typing import Tuple from dexp.utils import xpArray from dexp.utils.backends import Backend def fit_to_shape(array: xpArray, shape: Tuple[int, ...]) -> xpArray: """ Pads or crops an array to attain a certain shape Parameters ---------- backend : backend to use array : array to pad sh...
186388
import csv """ This file does the analysis of true positives with no prior common neighbours as reported in Section 6.4 of the paper. """ def get_positives(input_data_file = 'test.tsv'): with open(input_data_file) as tsv: positives = [] for ind, line in enumerate(csv.reader(tsv, delimiter="\t")): ...
186399
from rlkit.samplers.util import rollout from rlkit.samplers.rollout_functions import multitask_rollout import numpy as np class InPlacePathSampler(object): """ A sampler that does not serialization for sampling. Instead, it just uses the current policy and environment as-is. WARNING: This will affect...
186442
import inspect import numpy as np from limix.core.type.exception import NotArrayConvertibleError def my_name(): return inspect.stack()[1][3] def assert_finite_array(*arrays): for a in arrays: if not np.isfinite(a).all(): raise ValueError("Array must not contain infs or NaNs") def asser...
186446
import urllib.request import os import argparse from bs4 import BeautifulSoup parser = argparse.ArgumentParser() parser.add_argument("url", type=str, nargs=1, help="Main url with list of recipe URLs") parser.add_argument("cuisine", type=str, nargs=1, help="Type of cuisine on the main url page") parser.add_argument("pa...
186454
questions = open('youtube_chat.txt', 'r').readlines() with open('question_dataset.txt', 'w+') as file: for s in set(questions): print(s.rstrip()[1:-1], file=file)
186462
import pymbar from fe import endpoint_correction from collections import namedtuple import pickle import dataclasses import time import functools import copy import jax import numpy as np from md import minimizer from typing import Tuple, List, Any import os from fe import standard_state from fe.utils import sanitiz...
186492
from flask import Flask, render_template, request, redirect, url_for import uuid class Task: def __init__(self, task): self.id = uuid.uuid1().hex self.task = task self.status = 'active' self.completed = False def toggle(self): if self.status == 'active': sel...
186501
import unittest from osm_export_tool.sources import Overpass from osm_export_tool.mapping import Mapping class TestMappingToOverpass(unittest.TestCase): def test_mapping(self): y = ''' buildings: types: - points select: - column1 ...
186539
db_config = { 'user': '##username##', 'passwd': '<PASSWORD>##', 'host': '##host##', 'db': 'employees', }
186565
import logging import numpy as np from tramp.models import glm_generative from tramp.experiments import save_experiments, BayesOptimalScenario from tramp.algos import EarlyStopping def run_perceptron(N, alpha, p_pos): model = glm_generative( N=N, alpha=alpha, ensemble_type="gaussian", prior_type="...
186594
import random, copy def read_file(name): """ Input the file name and return a dictionary to store the graph. """ with open(name, 'r') as data: line = data.read().strip().split("\n") graph_dict = {} for element in line: line_list = list(map(int, element.strip().split("\...
186599
from .queries import TerminalQuery, QueryParams from .search import Searcher from .services import SeqmotifService, SequenceService, StructureService, StructMotifService, TextService class Command: def __init__(self, url="https://search.rcsb.org/rcsbsearch/v1/query?", resp_type="entry", start=0, ...
186603
from abc import ABCMeta, abstractmethod from collections import OrderedDict from logging import getLogger from six import add_metaclass, iteritems logger = getLogger(__name__) @add_metaclass(ABCMeta) class Plugin(object): """ Base class for plugins. A plugin is used to add functionality related to framework...
186605
try: from setuptools import setup except ImportError: from distutils.core import setup config = { 'description': 'TRX', 'author': '<NAME>, based on Paterva\'s library', 'url': 'https://github.com/krmaxwell/TRX', 'download_url': 'https://github.com/krmaxwell/TRX', 'author_email': '<EMAIL>', ...
186641
from ..crypto import blake160 from ..crypto import get_account_id_from_public from .keytype import KeyType def key_from_public_key(key_type: KeyType, public_key: str) -> bytes: if key_type == KeyType.PLATFORM: return get_account_id_from_public(public_key) elif key_type == KeyType.ASSET: return...
186652
from .tensor import Tensor from .context import Context from .layer import Layer, Model from .parameter import Parameter from .allocator import Allocator from .memory import Memory from .device import Device from . import config
186690
from datetime import datetime from django.test import TestCase from calaccess_campaign_browser import models class ModelTest(TestCase): """ Create model objects and try out their attributes. """ def test_models(self): obj = models.Filer.objects.create( name="FooPAC", fi...
186716
from rest_framework.mixins import RetrieveModelMixin from rest_framework.viewsets import GenericViewSet from .models import Block from .serializers import BlockSerializer class BlockViewSet(RetrieveModelMixin, GenericViewSet): queryset = Block.objects serializer_class = BlockSerializer lookup_value_regex...
186730
import sublime_plugin class FileNameOnStatusBar(sublime_plugin.EventListener): def on_activated(self, view): path = view.file_name() if path: for folder in view.window().folders(): path = path.replace(folder + '/', '', 1) view.set_status('file_name', path) ...
186764
import pylayers.simul.simultraj as st from pylayers.measures.cormoran import * import numpy as np # load CorSer 6 (default) C = CorSer(serie=6,day=11) # create a Simulation from CorSer motion capture file S = st.Simul(C,verbose=True) # create a dictionnary from links llinks = S.N.links['ieee802154'] link={'ieee802154...
186768
from __future__ import print_function import time import numpy as np from scipy.special import gammaln, psi from six.moves import xrange from .utils import write_top_words from .formatted_logger import formatted_logger eps = 1e-20 logger = formatted_logger('RelationalTopicModel', 'info') class RelationalTopicMode...
186779
from PyObjCTools.TestSupport import * import socket, time, struct from CoreFoundation import * import CoreFoundation import sys try: unicode except NameError: unicode = str try: long except NameError: long = int try: buffer except NameError: buffer = memoryview def onTheNetwork(): try: ...
186780
from . import PynbodyPropertyCalculation class Masses(PynbodyPropertyCalculation): names = "finder_mass" def calculate(self, halo, existing_properties): return halo['mass'].sum() class MassBreakdown(PynbodyPropertyCalculation): names = "finder_dm_mass", "finder_star_mass", "finder_gas_mass" ...
186808
from django.apps import AppConfig class StorageConfig(AppConfig): default_auto_field = "django.db.models.AutoField" name = "storage"
186814
from .attr_snippets import AttributeSnippets from .counterfact import CounterFactDataset from .knowns import KnownsDataset from .zsre import MENDQADataset from .tfidf_stats import get_tfidf_vectorizer
186864
from btypes.big_endian import * from j3d.animation import Animation,IncompatibleAnimationError class Header(Struct): magic = ByteString(4) section_size = uint32 loop_mode = uint8 __padding__ = Padding(1) duration = uint16 shape_animation_count = uint16 show_count = uint16 show_selectio...
186902
import os # linesep = os.linesep.encode('ascii') linesep = b'\n' def dir_parts(dir: str) -> tuple[str]: return tuple(os.path.normpath(dir).split(os.sep)) def is_in_dir(dir: str, in_: tuple[str]) -> bool: return tuple(dir.split(os.sep, len(in_)))[:len(in_)] == in_ def is_in_dirs(dir: str, in_: tuple[tuple...
186923
import unittest from metalearn.metafeatures.base import collectordict class CollectorDictTestCase(unittest.TestCase): def test_no_init_args(self): try: cd = collectordict({'a': 1}) self.fail('collectordict should have failed when passed init args') except TypeError as e: ...
186984
import altair as alt from typing import Union, List import pandas as pd tooltipList = List[alt.Tooltip] def _preprocess_data(data): for indx in ("index", "columns"): if isinstance(getattr(data, indx), pd.MultiIndex): setattr( data, indx, pd.Inde...
186989
import extractInfo import detectPhishing import csv import tkinter as tk def handleClick(username,password): Status=[] #Files=extractInfo.extractFromEmail('<EMAIL>','<PASSWORD>') Files=extractInfo.extractFromEmail(username,password) extractInfo.extract_URL_From_Sub(Files) if Files: ...
187037
from __future__ import print_function import io import os.path import pickle import sys from googleapiclient.discovery import build from googleapiclient.http import MediaIoBaseDownload TOKEN = '<PASSWORD>/token.pickle' DOWNLOAD_LINK = "travis_files/download_link.txt" class GoogleDriveService: def __init__(sel...
187038
import math def simple(): ''' 3.14 * 0.5 = 1.57 1.57 / 40 = 0.03925 take half => 0.019625 20 mil diameter pads rond 6 mil fab rule? 20 mil hole, 10 mil ring each side should be fine eh pretty tight lets shrink slightly ''' D = 0.5 R = D / 2 P...
187096
import os import chainer from chainer import training from chainer.training import extensions from qanta.buzzer.nets import RNNBuzzer, MLPBuzzer, LinearBuzzer from qanta.buzzer.util import read_data, convert_seq from qanta.util.constants import BUZZER_TRAIN_FOLD, BUZZER_DEV_FOLD def main(model): train = read_da...
187119
class DummyScheduler(object): def __init__(self, optimizer): pass def step(self): pass
187121
from ucate.application.workflows.tarnet import train as train_tarnet from ucate.application.workflows.tlearner import train as train_tlearner from ucate.application.workflows.cevae import train as train_cevae from ucate.application.workflows.evaluation import evaluate from ucate.application.workflows.evaluation impo...
187128
import unittest import qnet import qnetu import numpy import numpy.random import mytime import netutils import estimation import yaml import arrivals import sampling import qstats import sys class TestLikDelta (unittest.TestCase): def test_mm1_delta (self): sampling.set_seed(68310) nreps =...
187193
import nltk import codecs import os import numpy as np from collections import defaultdict def data_directory(): return os.path.join(os.path.dirname(os.path.abspath(__file__)), 'data') stemmer = nltk.stem.PorterStemmer() manual_dir = os.path.join(data_directory(), 'manual_keywords_merged') eval_dir = os.path.joi...
187195
def drive(start, end, step, parameters): step_results = { "P:sir.out.S": list(), "P:sir.out.I": list(), "P:sir.out.R": list(), "P:sir.in.dt": list(), } S = parameters["P:sir.in.S"] I = parameters["P:sir.in.I"] R = parameters["P:sir.in.R"] for i in range(start, e...
187213
from binascii import hexlify import getpass import logging import os import paramiko def agent_auth(transport, username): """ Attempt to authenticate to the given transport using any of the private keys available from an SSH agent. """ agent = paramiko.Agent() agent_keys = age...
187271
import argparse import configparser import os import sys sys.path.append('..') sys.path.append('../..') # if running in this folder from vimms.Common import IN_SILICO_OPTIMISE_TOPN, load_obj, add_log_file, IN_SILICO_OPTIMISE_SMART_ROI, \ IN_SILICO_OPTIMISE_WEIGHTED_DEW from vimms.InSilicoSimulation import extrac...
187273
from socialreaper.apis import ApiError from socialreaper.iterators import Source, Iter, IterError from instaphyte.api import InstagramAPI class Instagram(Source): def __init__(self): super().__init__() self.api = InstagramAPI() class InstagramIter(Iter): def __init__(self, node, fun...
187293
from osrf_pycommon.process_utils import asyncio from osrf_pycommon.process_utils.async_execute_process import async_execute_process from osrf_pycommon.process_utils import get_loop # allow module to be importable for --cover-inclusive try: from osrf_pycommon.process_utils.async_execute_process_trollius import From...
187311
from __future__ import division import numpy as np import math def vectorAdd(v1, v2): ans = (v1[0]+v2[0], v1[1]+v2[1], v1[2]+v2[2]) return ans def vectorSum(vList): ans = (0, 0, 0) for v in vList: ans = vectorAdd(ans, v) return ans def vectorCross(v1, v2): v1 = li...
187322
import sys if sys.version_info < (3,): integer_types = (int, long) else: integer_types = (int,) if sys.version_info < (3,): string_types = (str, unicode) else: string_types = (str,)
187328
from glob import glob import os import string from tempfile import mkdtemp from dcmstack import parse_and_stack, NiftiWrapper def sanitize_path_comp(path_comp): result = [] for char in path_comp: if not char in string.letters + string.digits + '-_.': result.append('_') else: ...
187367
import numpy as np from sklearn.datasets import load_iris import matplotlib.pyplot as plt from sklearn.ensemble import RandomForestClassifier from matplotlib import cm s=20 X, y = load_iris(return_X_y=True) X = X[:, [2, 3]] f, ax = plt.subplots(figsize=(4, 2.2)) ax.set_xlim(0, 7) ax.set_ylim(0, 2.7) x_ = ax.set_xlab...
187403
import math from typing import TYPE_CHECKING, Any, Callable, Dict, Optional, Tuple from ... import embed from ..evaluation import Evaluator from .base import BaseCallback if TYPE_CHECKING: from docarray import DocumentArray from ..base import BaseTuner class EvaluationCallback(BaseCallback): """ A ...
187419
import pandas as pd from sklearn.model_selection import train_test_split data = pd.read_csv("boston_house_prices.csv") print("Number of samples: %d number of features: %d" % (data.shape[0], data.shape[1])) print("Columns:") print(data.columns) X = data.drop("MEDV", axis=1) y = data.MEDV X_train, X_test, y_tra...
187434
import os from ..praat import PraatAnalysisFunction from pyraat.parse_outputs import parse_track_script_output def track_pulse_parse_output(text): track_text = [] pulse_text = [] blank_count = 0 add_track = True for line in text.splitlines(): line = line.strip() if line: ...
187467
import math import numpy as np from scipy.spatial.transform import Rotation """ The rotations can of two types: 1. In a global frame of reference (also known as rotation w.r.t. fixed or extrinsic frame) 2. In a body-centred frame of reference (also known as rotation with respect to current frame of reference. It is ...
187475
import pytest import glob import os import sys import pathlib PATH_HERE = os.path.abspath(os.path.dirname(__file__)) PATH_PROJECT = os.path.abspath(PATH_HERE+"/../") PATH_DATA = os.path.abspath(PATH_PROJECT+"/data/abfs/") PATH_HEADERS = os.path.abspath(PATH_PROJECT+"/data/headers/") try: # this ensures pyABF is im...
187542
from confidant import settings from confidant.app import create_app if __name__ == '__main__': app = create_app() app.run( host=settings.get('HOST', '127.0.0.1'), port=settings.get('PORT', 5000), debug=settings.get('DEBUG', True) )
187556
import os from typing import Dict, List import uvicorn from dotenv import load_dotenv from fastapi import FastAPI, Security, Depends, HTTPException from fastapi.security.api_key import APIKeyHeader, APIKey from impl import extractor from pydantic import BaseModel from starlette.status import HTTP_403_FORBIDDEN load_d...
187561
import math import torch import torch.nn as nn from pytracking import TensorList from ltr.models.layers import activation class GNSteepestDescent(nn.Module): """General module for steepest descent based meta learning.""" def __init__(self, residual_module, num_iter=1, compute_losses=False, detach_length=float...
187620
import argparse from copy import copy from functools import partial from pathlib import Path from typing import Any from typing import Dict from chainer import cuda from chainer import optimizers from chainer import training from chainer.dataset import convert from chainer.iterators import MultiprocessIterator from ch...
187641
import codecs import os from random import randint, shuffle, sample, random from tqdm import tqdm from dialogentail.reader.swag_reader import SwagReader from dialogentail.util import stopwatch, nlp dull_responses = [ "I don't know.", "I don't know what you're talking about.", "I don't know what you mean....
187649
import getpass import json import pathlib import random import time from typing import List import torch import numpy as np from src.utils.log import create_base_logger, create_logdir from src.utils import measure_runtime, get_git_version from .experiment import Experiment class ExperimentSet: def __init__(self...
187689
from typing import List class TwoSum: def __call__(self, xs: List[int], lookup: int) -> List[int]: """ Coderbyte: Two sum problem Origin: https://coderbyte.com/algorithm/two-sum-problems Classic Two Sum problem. :param xs: list to perform lookup :param lookup: an i...
187700
import random from typing import Dict from spaceopt import SpaceOpt random.seed(123456) def search_space() -> Dict[str, list]: return { "a": [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20], "b": [-5.5, -4.4, -3.3, -2.2, -1.1, 0.0, 1.1, 2.2, 3.3, 4.4, 5.5], "c": ...
187749
from django.contrib.auth import authenticate from django.contrib.auth.models import User from django.test import TestCase from django.test.utils import override_settings class AuthBackendTests(TestCase): def setUp(self): self.existing_user = User.objects.create_user(username='test', email='<EM...
187767
import os import sys curdir = os.path.dirname(os.path.abspath(__file__)) sys.path.append(curdir) from .utils import * from .model import Model from .writer import Writer from .data_loader import get_loader from .radam import RAdam
187797
import gym import numpy as np from gym import spaces class NormalizedActionWrapper(gym.ActionWrapper): """Environment wrapper to normalize the action space to [-scale, scale] Args: env (gym.env): OpenAI Gym environment to wrap around scale (float): Scale for normalizing action. Default: 1.0. ...
187834
import unittest from katas.beta.sort_array_by_last_character import sort_me class SortMeTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(sort_me(['acvd', 'bcc']), ['bcc', 'acvd']) def test_equals_2(self): self.assertEqual(sort_me([ 'asdf', 14, '13', 'asdf']), ...
187839
from typing import Sequence, Union, Optional from jina.executors.evaluators.rank import BaseRankingEvaluator class ReciprocalRankEvaluator(BaseRankingEvaluator): """ Gives score as per reciprocal rank metric. :param args: Additional positional arguments :param kwargs: Additional keyword arguments ...
187852
from keepachangelog.version import __version__ from keepachangelog._changelog import to_dict, to_raw_dict, release, from_dict from keepachangelog._versioning import to_sorted_semantic
187856
from __future__ import annotations import enum class WitnessScope(enum.IntEnum): # Indicates that no contract was witnessed. Only sign the transaction. _None = 0 # Indicates that the calling contract must be the entry contract. The witness/permission/signature # given on first invocation will automa...
187862
import pandas as pd synonyms_dict = pd.read_csv('mark2cure/analysis/data/synonym_dictionary.txt', sep='\t', names=['dirty', 'clean'], index_col='dirty').to_dict()['clean']
187873
from Stephanie.configurer import config # noinspection SpellCheckingInspection class AudioRecognizer: def __init__(self, recognizer, UnknownValueError, RequestError): self.UnknownValueError = UnknownValueError self.RequestError = RequestError self.r = recognizer self.c = config ...
187951
from bip_utils.monero.mnemonic.monero_mnemonic_ex import MoneroChecksumError from bip_utils.monero.mnemonic.monero_mnemonic import ( MoneroLanguages, MoneroWordsNum, MoneroMnemonic, MoneroMnemonicDecoder, MoneroMnemonicEncoder ) from bip_utils.monero.mnemonic.monero_entropy_generator import MoneroEntropyBitLen, Mon...
187975
import pandas as pd url = "https://finance.naver.com/item/sise_day.nhn?code=066570" df = pd.read_html(url) print(df[0])
188007
import os import pymongo # Connect to database circuit_db_client = pymongo.MongoClient(os.environ['CIRCUIT_DB']) circuit_db = circuit_db_client.va_circuit_court_cases district_db_client = pymongo.MongoClient(os.environ['DISTRICT_DB']) district_db = district_db_client.va_district_court_cases print 'DISTRICT COURT' for...
188024
from matplotlib import pyplot as plt import pandas as pd import seaborn as sns import numpy as np def heatmap(x, y, freq_labels = 1, show_grid = True, invert_yaxis = False, **kwargs, ): color = kwargs.get('color', [1]*len...
188027
import os import pdb import pickle import logging import shutil import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from argparse import ArgumentParser import itertools from torch.utils.data import random_split from src.modules.trainer import OCRTrainer from src.utils.utils import E...
188061
from model import * from config import * import torch.optim as optim from collections import OrderedDict def load(path): state_dict = torch.load(path) state_dict_rename = OrderedDict() for k, v in state_dict.items(): name = k[7:] # remove `module.` state_dict_rename[name] = v #print(s...
188107
import alpenglow.Getter as rs import alpenglow as prs class SvdppExperiment(prs.OnlineExperiment): """SvdppExperiment(begin_min=-0.01,begin_max=0.01,dimension=10,learning_rate=0.05,negative_rate=20,use_sigmoid=False,norm_type="exponential",gamma=0.8,user_vector_weight=0.5,history_weight=0.5) This class imple...
188132
import gym import numpy as np from rltf.agents import LoggingAgent from rltf.memory import PGBuffer from rltf.monitoring import Monitor class AgentPG(LoggingAgent): def __init__(self, env_maker, model, gamma, lam, rollout_len, ...
188329
import ast from boa3.analyser.astanalyser import IAstAnalyser class ConstructAnalyser(IAstAnalyser, ast.NodeTransformer): """ This class is responsible for pre processing Python constructs The methods with the name starting with 'visit_' are implementations of methods from the :class:`NodeVisitor` class...
188333
from guizero import App app = App() app.info("Info", "This is a guizero app") app.error("Error", "Try and keep these out your code...") app.warn("Warning", "These are helpful to alert users") app.display()
188381
import os import unittest import tempfile import shutil from faceutils import detect_faces, io, face_landmarks, extract_face_features, features_distance class RecognitionTest(unittest.TestCase): """ Test methods in face recognition """ def __init__(self, *args, **kwargs): unittest.TestCase._...
188447
import unittest from types import SimpleNamespace import pytest from pyspark.sql import Row from snorkel.labeling.lf.nlp import NLPLabelingFunction from snorkel.labeling.lf.nlp_spark import ( SparkNLPLabelingFunction, spark_nlp_labeling_function, ) from snorkel.types import DataPoint def has_person_mention(...
188500
from django import dispatch presence_changed = dispatch.Signal( providing_args=["room", "added", "removed", "bulk_change"] )
188506
import logging from typing import List, Dict, Set, Union, cast, Type import pandas as pd from genomics_data_index.storage.SampleSet import SampleSet from genomics_data_index.storage.model.NucleotideMutationTranslater import NucleotideMutationTranslater from genomics_data_index.storage.model.QueryFeature import QueryF...