id
stringlengths
3
8
content
stringlengths
100
981k
11479073
from celery import shared_task from .utils import get_device_model @shared_task() def send_push_notification(device_id, message, url, badge_count, sound, extra, category, **kwargs): """ Sends a push notification message to the specified tokens """ device_model = get_device_model() device = device...
11479102
from __future__ import print_function import urllib import constants from bs4 import BeautifulSoup import re from constants import * url = "https://www.cia.gov/library/publications/the-world-factbook/geos/" country_table = [i.rstrip().split(";") for i in open("ciaCountryCode.txt").readlines()] def escape(text, char...
11479111
import threading from rich.align import Align from textual import events from textual.app import App from textual.reactive import Reactive from rich.panel import Panel from textual.widgets import ScrollView, Footer, Header, TreeClick, TreeControl, TreeNode from textual_app.get_log_task import GetLogTask from textual_wi...
11479119
import pytextnow as pytn client = pytn.Client("username") # You can also include the cookie in ther Client constructor # Here you should input your connect.sid cookie client.send_sms("number", "text")
11479125
import visualization.panda.world as wd import modeling.geometric_model as gm import basis.robot_math as rm import math import numpy as np base = wd.World(cam_pos=[1, 1, 1], lookat_pos=[0, 0, 0], toggle_debug=True) frame_o = gm.gen_frame(length=.2) frame_o.attach_to(base) # rotmat = rm.rotmat_from_axangle([1,1,1],math....
11479135
from decimal import Decimal from future.moves.urllib.parse import ParseResult from collections import OrderedDict from enum import Enum from uuid import UUID from datetime import date, datetime, time from attr._compat import iteritems from .functions import to_dict from .types import ( TypedSequence, TypedMapping...
11479153
from codecs import Codec, CodecInfo, register as lookup_function from typing import Union, Tuple from warnings import warn from iota.exceptions import with_context __all__ = [ 'AsciiTrytesCodec', 'TrytesDecodeError', ] class TrytesDecodeError(ValueError): """ Indicates that a tryte string could not ...
11479164
from unittest import TestCase from asserts import assert_equal from htmlgen import Image from test_htmlgen.util import parse_short_tag class ImageTest(TestCase): def test_attributes(self): image = Image("my-image.png", "Alternate text") assert_equal("my-image.png", image.url) assert_equ...
11479214
class CycleError(Exception): pass def _sort_graph_topologically(graph): """ Sort directed graph topologicaly. Args: graph: dict of lists (key is node name, value if list of neighbours) Returns: generator of nodes in topoligical order """ # calculate input degree (number o...
11479229
from shutil import copyfile copyfile("message2", "snakemake-tibanna-test/1/final_message") copyfile("message2", "snakemake-tibanna-test2/1/final_message")
11479234
import tqdm import argparse def read_file(file): with open(file,'r',encoding='utf-8') as f: text=f.readlines() return text def convert(input_file,output_file): texts=read_file(file=input_file) with open(output_file,'w+',encoding='utf-8') as f: for i in tqdm.tqdm(range(len(texts))): ...
11479250
response.title = settings.title response.subtitle = settings.subtitle response.meta.author = '%(author)s <%(author_email)s>' % settings response.meta.keywords = settings.keywords response.meta.description = settings.description response.menu = [ (T('Business Service Catalogue'),URL('default','index')==URL(),URL('defaul...
11479278
class Solution: def checkPalindromeFormation(self, a: str, b: str) -> bool: if len(a) == 1: return True if a[:2] == b[-2:][::-1]: return True if a[-2:][::-1] == b[:2]: return True return False
11479291
from setuptools import setup, find_packages setup( setup_requires=["pbr>=1.9", "setuptools>=17.1"], pbr=True, packages=find_packages(where="src"), package_dir={"": "src"}, )
11479305
import os import requests from selenium import webdriver from sys import platform from xml.etree import ElementTree BASE_DIR = os.path.dirname(os.path.abspath(__file__)) DRIVER_NAME = "chromedriver.exe" if platform == "win32" else "chromedriver" DRIVER_DIR = os.path.join(BASE_DIR, "plugins", DRIVER_NAME) JS_SCRIPT =...
11479311
import pytest from common.core import ( cleanup_process, ) from common.constants import ( INSTANCE_MANAGER_REPLICA, INSTANCE_MANAGER_ENGINE, ) from rpc.instance_manager.process_manager_client import ProcessManagerClient @pytest.fixture() def em_client(request, address=INSTANCE_MANAGER_ENGINE): c = Proc...
11479319
import torch import torch.nn as nn import torch.nn.functional as F class SciNet(nn.Module): def __init__(self, input_dim, output_dim, latent_dim, layer_dim): """Initialize SciNet Model. Params ====== input_dim (int): number of inputs output_dim (int): number of outputs latent_dim (int): number of la...
11479336
from collections import defaultdict from functools import cmp_to_key, wraps from typing import Optional, Dict import time from quart import * from _jwt import * import asyncio from models import * import json import hashlib import random import string import math def md5(v: str): return hashlib.md5(v.encode(enco...
11479351
import unittest from hbconfig import Config from kino.slack.template import MsgTemplate class MsgTemplateTest(unittest.TestCase): def setUp(self): Config("config_example") print(Config) def test_schedule(self): attachments = MsgTemplate.make_schedule_template("pretext", {}) s...
11479397
import sys; sys.dont_write_bytecode=True sys.path.insert(0, '../') import numpy as np import matplotlib matplotlib.use('agg') import matplotlib.pyplot as plt import util import pickle import hdf5_to_dict as io FIGX = 14 FIGY = 10 SIZE = 40 if len(sys.argv) != 3: util.warn('Format: python eht_plot.py [averages] [ou...
11479427
class ParameterSetting(): def __init__(self, csv_path='./', data_dir='furbo_only', save_root='snapshots', model_file='snapshots/final_model.pkl', model_name = 'CNN14', val_split=0, epochs=20, batch_size=128, lr=0.0001, num_class=2, time_drop_width=64, time_stripes...
11479430
import sublime from .debug import debug from .get_source_folders import get_source_folders from .get_exclude_patterns import get_exclude_patterns from .utils import error_message, status_message from .exec_command import run_command_async def update_source_modules(source_modules): source_folders = get_source_fold...
11479434
from battle_city.connection import PlayerConnection from asynctest.mock import CoroutineMock, call import pytest @pytest.mark.asyncio async def test_client_write_small_message(): writer = CoroutineMock() writer.drain = CoroutineMock() connection = PlayerConnection(reader=None, writer=writer) await co...
11479448
import os import sys import shutil from subprocess import check_output import pytest import loky from loky import cpu_count def test_version(): assert hasattr(loky, '__version__'), ( "There are no __version__ argument on the loky module") def test_cpu_count(): cpus = cpu_count() assert type(cp...
11479496
from collections import defaultdict import multiprocessing import numpy as np from lfd.rapprentice import math_utils, LOG def intersect_segs(ps_n2, q_22): """Takes a list of 2d nodes (ps_n2) of a piecewise linear curve and two points representing a single segment (q_22) and returns indices into ps_n2 of in...
11479505
from functools import total_ordering import json import os from random import SystemRandom import shutil from uuid import UUID from ethereum.slogging import get_logger from ethereum.tools import keys from ethereum.utils import privtopub from ethereum.utils import sha3, is_string, encode_hex, checksum_encode, to_string,...
11479522
import numpy as np import pandas as pd from ..data.dataset import TableDataset from ..mltypes import Identifier import typing as t def findna(dataset: TableDataset) -> TableDataset: data = dataset.table_data data = data.replace(('nan', 'NaN', 'NA', 'na', np.nan), None, inplace=False) return TableDataset(d...
11479529
from __future__ import absolute_import from __future__ import division from __future__ import print_function import torch import torch.nn as nn import torch.nn.functional as F from torchnlp.common.hparams import HParams from torchnlp.common.model import Model, gen_model_dir from torchnlp.modules import outputs impor...
11479533
import time import unittest from malcolm.core.timestamp import TimeStamp class TestAlarm(unittest.TestCase): def test_no_args(self): now = time.time() o = TimeStamp() self.assertAlmostEqual(now, o.to_time(), delta=0.2) def test_args(self): o = TimeStamp(1231112, 211255265, 43...
11479549
import pytest import array from uintset import UintSet WORD_SIZE = 64 def test_new(): s = UintSet() assert len(s) == 0 def test_new_from_iterable(): s = UintSet([1, 100, 3]) # beyond word 0 assert len(s) == 3 def test_add(): s = UintSet() s.add(0) assert len(s) == 1 def test_add_mu...
11479571
def my_marginalization(input_array, binary_decision_array): marginalization_array = input_array * binary_decision_array marginal = np.sum(marginalization_array, axis=0) # note axis marginal /= marginal.sum() # normalize return marginalization_array, marginal marginalization_array, marginal = my_mar...
11479616
class TextEditorMemento: def __init__(self, content: str): self.content = content def get_state(self): return self.content class TextEditor: def __init__(self, content: str): self.content = content def get_content(self): return self.content def add...
11479630
from abc import ABCMeta, abstractmethod from instagram_api.utils.http import ClientCookieJar __all__ = ['StorageInterface'] class StorageInterface(metaclass=ABCMeta): cookie_jar_class: type(ClientCookieJar) @abstractmethod def open(self, config: dict): raise NotImplementedError @abstractme...
11479645
from __future__ import division from __future__ import print_function import argparse import collections import datetime import itertools import os.path import time from scipy.stats import entropy BK_ENTROPY_CUTOFF = 2.5 LFM_ENTROPY_CUTOFF = 3.0 MIN_OCCURRENCES = 10 MIN_VALID_SEQ_LEN = 3 MAX_VALID_SEQ_LEN = 500 ...
11479678
import os import sys import six import atexit import weakref import logging import threading import queue import multiprocessing import asyncio from yggdrasil.tools import YggClass, sleep MPI = None _on_mpi = False _mpi_rank = -1 if os.environ.get('YGG_SUBPROCESS', False): if 'YGG_MPI_RANK' in os.environ: _...
11479748
from django.shortcuts import render from rest_framework import viewsets from rest_framework import mixins from .serializers import CtfSerializer from rest_framework.permissions import IsAuthenticated from rest_framework.authentication import SessionAuthentication from rest_framework_jwt.authentication import JSONWebTok...
11479761
import numpy as np import torch import torch.nn as nn import torch.nn.functional as F # class LeNet(nn.Module): # def __init__(self, n_classes): # super(LeNet, self).__init__() # self.conv1 = nn.Conv2d(1, 5, 5, 1) # self.conv2 = nn.Conv2d(5, 10, 5, 1) # self.fc1 = nn.Linear(4*4*10, ...
11479770
import numpy as np import xml.etree.cElementTree as ET from xml.dom import minidom from ase.data import atomic_masses from ase.units import eV, Hartree, Bohr, Ry, J import os from collections import Iterable, namedtuple from itertools import groupby from TB2J.utils import symbol_number import pickle def write_uppasd(...
11479776
from capreolus import Dependency, constants from . import Benchmark PACKAGE_PATH = constants["PACKAGE_PATH"] @Benchmark.register class Robust04(Benchmark): """Robust04 benchmark using the title folds from Huston and Croft. [1] Each of these is used as the test set. Given the remaining four folds, we split t...
11479855
import unittest import config from uri.base_uri import URI class TestURI(URI): fqdn = 'domain.com' path = '/test-uri-path' class TestEmbeddedParamsURI(URI): fqdn = 'domain.com' path = '/test/<embed>/uri' class TestBaseURI(unittest.TestCase): def test_uri(self): self.assertEqual('/test...
11479878
import torch import torch.nn as nn from GNN.GCN_layer import GraphConvolution from GNN.GCN_res_layer import GraphResConvolution device = torch.device("cuda" if torch.cuda.is_available() else "cpu") class GCN(nn.Module): def __init__(self, state_dim=256, feature_dim=256): ...
11479883
import time import board import busio from adafruit_mcp230xx.mcp23017 import MCP23017 from digitalio import Direction import adafruit_ble from adafruit_ble.advertising.standard import ProvideServicesAdvertisement import adafruit_ble_midi # These import auto-register the message type with the MIDI machinery. # pylint: ...
11479926
import sys from importlib import reload from django.urls import clear_url_caches import pytest pytestmark = pytest.mark.django_db DOCS_URL = "/docs/" @pytest.fixture def all_urlconfs(): return [ "apps.core.urls", "apps.users.urls", "conf.urls", # The ROOT_URLCONF must be last! ] ...
11479927
import os.path import pathlib import re import site import sysconfig import sys import tarfile import tempfile from urllib.parse import urlparse import zipfile from requests_download import download from .install import Installer address_formats = { 'github': (r'([\w\d_-]+)/([\w\d_-]+)(/(.+))?$', 'user/project[/c...
11479936
import os import sys import torch import pickle from torch import nn from torch import optim from torchvision.datasets import ImageFolder from torchvision import transforms from torch.optim.lr_scheduler import LambdaLR from tqdm import tqdm sys.path.append("../ocrd_typegroups_classifier") from ocrd_typegroups_classif...
11479940
import os from json import load from mp_api import MAPISettings from mp_api.routes.tasks.utils import calcs_reversed_to_trajectory def test_calcs_reversed_to_trajectory(): with open( os.path.join(MAPISettings().TEST_FILES, "calcs_reversed_mp_1031016.json") ) as file: calcs_reversed = load(fil...
11479959
from __future__ import print_function import numpy as np from sklearn.datasets import load_diabetes from sklearn.linear_model import LinearRegression, Ridge, Lasso, ElasticNet, RidgeCV, LassoCV, ElasticNetCV from sklearn.model_selection import cross_val_score # For reproducibility np.random.seed(1000) if __name__...
11479970
if __name__ == '__main__': import Recommender_System.utility.gpu_memory_growth from Recommender_System.data import data_loader, data_process from Recommender_System.algorithm.DeepFM.model import DeepFM_model from Recommender_System.algorithm.train import train n_user, n_item, train_data, test...
11479975
from __future__ import annotations import typing as t class ValidationFailedError(Exception): def __init__(self, errors: t.Union[t.List, t.Any]): if not isinstance(errors, list): errors = [errors] self.errors = errors class AuthorizationError(Exception): def __init__(self, error...
11480038
class NotFoundException(Exception): pass class RoleNotAllowedException(Exception): pass class PermissionDeniedException(Exception): pass
11480053
from abc import ABC from abc import abstractmethod import numpy as np class Recommender(ABC): def __init__(self, training_set, items): self.training_set = training_set self.items = items # Dictionary to store the recommended sequences self.cache = {} def recommend(self, seed...
11480086
import sys import os import pinproc import procgame.game import procgame.dmd import procgame.dmd.font import time import logging logging.basicConfig(level=logging.WARNING, format="%(asctime)s - %(name)s - %(levelname)s - %(message)s") class PlayerGame(procgame.game.BasicGame): anim_layer = None def __init__(sel...
11480089
from dataclasses import dataclass import hashlib # for mdb ids of prompts import json from typing import List, Optional import requests @dataclass class PromptResult: setting = "zero-shot" value: float = 0.0 plm: str = None metric: str = None """Example { "language": "en", "template": ...
11480094
import multiprocessing as mp from multiprocessing import pool class NoDaemonProcess(mp.Process): # make 'daemon' attribute always return False def _get_daemon(self): return False def _set_daemon(self, value): pass daemon = property(_get_daemon, _set_daemon) class MyPool(pool.Pool): ...
11480099
from unittest.mock import MagicMock import pytest from jange.base import DataStream, OperationCollection, Operation def test_can_iterate_all_underlying_data(): data = [1, 2, 3, 4] ds = DataStream(items=data) assert list(ds) == data def test_all_operations_are_applied(): data = [1, 2, 3, 4] ds = ...
11480137
import sys, os sys.path.append(os.path.join(os.path.dirname(__file__), '..')) import logging import numpy as np import tensorflow as tf from collections import defaultdict from data import * from utils.analysis import * from utils.experiments import * from models.visual import * from models.auditive i...
11480155
import theano.tensor as tt import dmgr import lasagne as lnn import spaghetti as spg from .. import augmenters class CrfLoss: def __init__(self, crf): self.crf = crf def __call__(self, prediction, target, mask): loss = spg.objectives.neg_log_likelihood(self.crf, target, mask) loss ...
11480195
from __future__ import print_function import argparse from math import log10 import os import torch import torch.nn as nn import torch.optim as optim from torch.autograd import Variable from torch.utils.data import DataLoader from torchvision import models import torch.backends.cudnn as cudnn from dbpn_v1 import Net a...
11480205
from __future__ import absolute_import, division, print_function import io import os.path import tarfile import tempfile from requests.utils import urlparse import appr.pack as packager from appr.client import ApprClient class FormatBase(object): media_type = NotImplementedError target = NotImplementedErro...
11480252
OCCLUSION_MARKERS = [ "robot0:ffocclusion", "robot0:mfocclusion", "robot0:rfocclusion", "robot0:lfocclusion", "robot0:thocclusion", ] OCCLUSION_DIST_CUTOFF = -0.0001 # neg; penetrated. def occlusion_markers_exist(sim): for marker in OCCLUSION_MARKERS: if marker not in sim.model.geom_n...
11480277
from ipware import get_client_ip from rest_framework import permissions from . import settings as api_settings class WhiteListPermission(permissions.BasePermission): def has_permission(self, request, view): ip_addr = get_client_ip(request)[0] return True if ip_addr in api_settings.REST_FRAMEWORK...
11480281
import numpy as np import pandas as pd from bs4 import BeautifulSoup import nltk import urllib.request from nltk.corpus import stopwords from nltk.tokenize import word_tokenize,sent_tokenize from string import punctuation from heapq import nlargest from collections import defaultdict import requests url...
11480291
from optimum.onnxruntime.modeling_ort import ( ORTModelForCausalLM, ORTModelForFeatureExtraction, ORTModelForQuestionAnswering, ORTModelForSequenceClassification, ORTModelForTokenClassification, ) task_ortmodel_map = { "feature-extraction": ORTModelForFeatureExtraction, "question-answering...
11480295
from samplics.sampling.selection import SampleSelection from samplics.sampling.size import ( SampleSize, SampleSizeOneMean, SampleSizeOneProportion, SampleSizeOneTotal, allocate, calculate_power, power_for_proportion, sample_size_for_mean_wald, sample_size_for_proportion_fleiss, ...
11480301
from django.shortcuts import render def plain_text_view(request, template_name): return render(request, template_name, content_type='text/plain')
11480303
from ast import literal_eval def decode_string(s): """Convert a string literal to a number or a bool. Args: s (str): String Returns: str,float,int or bool: Value decoded Examples: >>> decode_string('a') 'a' >>> val = decode_string('1.0') >...
11480309
from pysimm import system, lmps, forcefield def run(test=False): # use a smiles string to query the pubchem search database and read the mol file returned from the http request try: s = system.read_pubchem_smiles('CO') except: import os s = system.read_mol(os.path.join(os.path.dirna...
11480425
from django.db import models from profiles.models import Profile, ProfileHub from hubs.models import Hub, HubGeolocation class Offer(models.Model): title = models.CharField(max_length=100, blank=False) description = models.TextField(blank=False) number = models.CharField(max_length=10, blank=True) str...
11480460
import unittest import board_outline_stitcher P = board_outline_stitcher.Path class PathStitcherTest(unittest.TestCase): def test_start_point(self): p = P('M 1 2 L 3 4') self.assertEqual(p.start_point, [1.0, 2.0]) self.assertEqual(p.end_point, [3.0, 4.0]) def test_stitch_case_2(self): p1 = P('M 1...
11480464
import math import pypact as pp from tests.testerbase import Tester DECIMAL_PLACE_ACC = 6 class GroupStructuresUnitTest(Tester): def test_group66(self): g = pp.ALL_GROUPS[66] self.assertEqual(67, len(g), "Assert the length of group 66 is 67") self.assertEqual(2.50e7, g[0], "Ass...
11480470
def getHprot(f): sizes=[] genes=[] hprots=[] p='' G=0 H=0 with open(f) as inFile: for line in inFile: if line.strip()=='##FASTA': # Reached end of annotation break else: if line.strip()=='##gff-version 3' or '##sequence-region' ...
11480487
import os import json import boto3 from boto3.dynamodb.conditions import Key, Attr dynamodb = boto3.client('dynamodb') comprehend = boto3.client('comprehend') def lambda_handler(event, context): print('Received event: ' + json.dumps(event, indent=2)) ids = event['ID'].split(',') table_name=os.environ['table...
11480524
from escpos.printer import Usb from escpos.exceptions import USBNotFoundError import usb.core import usb.util def connectToPrinter(): try: p = Usb(0x0416, 0x5011, in_ep=81, out_ep=3) except USBNotFoundError: p = None print("Printer not connected") return p def printReciept(cart, date, invoiceId, bill, disco...
11480540
import torch import torch.nn as nn import torch.nn.functional as F import torch.optim as optim from torch.autograd import Variable import torch.utils.data as data from torchvision import datasets, transforms import os import pickle import numpy as np from PIL import Image import time import math LOAD_DIR = "." BATCH_S...
11480546
import torch import torch.nn as nn from pytorch3d.structures import Pointclouds from pytorch3d.renderer import compositing from pytorch3d.renderer.points import rasterize_points class RasterizePointsXYsBlending(nn.Module): """ Code inspired fromSynSin: End-to-end View Synthesis from a Single Image (CVPR 2020...
11480548
import math import torch import torch.nn as nn import torch.nn.functional as F from . import transformer from .adj_decoding import ( bron_kerbosch_decode, bron_kerbosch_pivoting_decode, brute_force_adj_decode, directed_trigger_graph_decode, directed_trigger_graph_incremental_decode, linked_dec...
11480568
import sys import os.path def locate_spy_module(module_name): """Tries to find shellpy module on filesystem. Given a module name it tries to locate it in pythonpath. It looks for a module with the same name and __init__.spy inside of it :param module_name: Filename without extension :return: Path to ...
11480570
from django.core.management.base import BaseCommand from ... import models from ...mixins import VerbosityAwareOutputMixin from ...settings import djstripe_settings class Command(VerbosityAwareOutputMixin, BaseCommand): """Command to process all Events. Optional arguments are provided to limit the number of...
11480578
def temperature_statistics(T): mean = 0 std = 0 # Your code goes here! return mean, std
11480583
import os from setuptools import setup, find_packages path = os.path.abspath(os.path.dirname(__file__)) with open(os.path.join(path, "README.md"), "r") as f: readme = f.read() setup( name="countrynames", version="1.10.6", description="A library to map country names to ISO codes.", long_descriptio...
11480609
from __future__ import unicode_literals from __future__ import print_function from __future__ import division from __future__ import absolute_import from future import standard_library standard_library.install_aliases() from builtins import range from builtins import * import geojson as gj import logging import bson.o...
11480611
import re from torch.utils.data import (DataLoader, RandomSampler, SequentialSampler, TensorDataset) from keras.preprocessing.sequence import pad_sequences from sklearn.metrics import confusion_matrix, roc_curve, precision_recall_fscore_support import matplotlib.pyplot as plt import re import numpy as np import torc...
11480680
from django.contrib.auth.models import User from django.core.management.base import BaseCommand from django.db import transaction, IntegrityError from core.models import Person class Command(BaseCommand): help = 'Creates the data management user and the admin user' def add_arguments(self, parser): p...
11480685
import random from tqdm.autonotebook import tqdm SEED = 11690 def _load_assorted_mistakes(file_path): """load assorted mistakes data; a dict of vocab along with the number of possible replacement candidates """ opfile = open(file_path, "r") mistakes_vocab = {} for i, line in enumerate(opfile): ...
11480697
from copy import copy from django.urls import reverse from resource_tracker.models import ResourceGroupAttributeDefinition, ResourcePool, ResourceGroup from tests.test_resource_tracker.base_test_resource_tracker import BaseTestResourceTracker class TestResourceGroupAttributeViews(BaseTestResourceTracker): def ...
11480710
import functools import time import pika.exceptions import pika import ssl from mlapp.handlers.message_queues.message_queue_interface import MessageQueueInterface class RabbitMQHandler(MessageQueueInterface): def __init__(self, settings): """ Initializes the ￿RabbitMQHandler with it's special conn...
11480767
import random, math def mk_initial_balances(accts, coins): o = [] for i in range(accts): o.extend([i] * random.randrange((coins - len(o)) * 2 // (accts - i))) o.extend([accts-1] * (coins - len(o))) return o def fragments(coins): o = 0 for i in range(1, len(coins)): if coins[i] ...
11480774
import importlib from unittest import mock from ..util import BaseCase warn_message = 'This might go badly' error_message = 'Something terrible happened' log_message = 'Data received' class ModuleTestInstance(BaseCase): def test_basereps_module_exists(self): importlib.import_module("pygsti.evotypes.bas...
11480779
from strips.hsp import compute_costs from strips.operators import Action from misc.functions import argmin, flatten, INF def get_layers(costs): num_layers = max(pair.level for pair in costs.values()) + 1 layers = [[] for _ in range(num_layers)] for value, (_, level) in costs.items(): layers[level]...
11480781
import h5py import pandas as pd from concise.preprocessing import encodeDNA df = pd.read_pickle("human_utrs_result.pkl") top_n = 2000 inputs = encodeDNA(df.utr)[:top_n] preds = df.retrained_pred.values.reshape((-1, 1))[:top_n] fw = h5py.File("expect.human_utrs.h5", 'w') fw.create_dataset('/inputs', data=inputs) fw.c...
11480784
from .base import License class MITLicense(License): ''' The MIT license ''' id = 'MIT' rpm = 'MIT' python = 'License :: OSI Approved :: MIT License' url = 'http://opensource.org/licenses/MIT' class BSD2ClauseLicense(License): ''' BSD 2-clause "Simplified" License ''' id ...
11480855
import unittest from typing import AnyStr import test.resources from spark3.types import ABI, ABIFunction, ABIFunctionElement from spark3.utils.abi import normalize_abi, filter_by_name, filter_by_type RESOURCE_GROUP = 'contract_test' def _get_resource_path(file_name: str) -> AnyStr: return test.get_resource_pa...
11480934
import webbrowser import json import requests import time import logging def keysearch(key): logging.basicConfig(level=logging.INFO, filename='Supreme_Log.log', filemode='a', format = " %(asctime)s %(message)s", datefmt="%m/%d/%Y %I:%M:%S %p ") starttime = time....
11480936
from time import time import os import psutil import math from typing import Iterator, List, Tuple import pandas as pd from google.cloud import bigquery from google.oauth2 import service_account from bqfetch.utils import * CREDS_SCOPES = [ "https://www.googleapis.com/auth/drive", "https://www.googleapis.com/...
11480954
import torch import torch.nn as nn import torch.backends.cudnn as cudnn import torchvision.transforms as transforms from torch import jit import io import time import argparse import cv2 from vgg import VGGNet from utils import try_load # Check device use_cuda = torch.cuda.is_available() device = torch.device('cud...
11480960
import requests from cartodb_services import StreetPointBulkGeocoder from cartodb_services.geocodio import GeocodioGeocoder from iso3166 import countries from cartodb_services.tools.country import country_to_iso3 class GeocodioBulkGeocoder(GeocodioGeocoder, StreetPointBulkGeocoder): MAX_BATCH_SIZE = 100 # Settin...
11480982
import pytest from magnus import catalog # pylint: disable=import-error from magnus import defaults # pylint: disable=import-error from magnus import pipeline # pylint: disable=import-error def test_get_run_log_store_returns_global_executor_run_log_store(mocker, monkeypatch): mock_global_executor = mocker.Mag...
11481087
import attr import numpy as np import collections import itertools import pyrsistent import json import os import torch import torch.nn as nn import torch.nn.functional as F from tensor2struct.models import abstract_preproc, decoder from tensor2struct.modules import attention, variational_lstm, lstm, embedders, rat f...
11481094
import torch from torch import nn import tqdm from typing import Callable, Generator HUGE = 1e15 def beam_search(model_func: Callable[[torch.Tensor, torch.Tensor], torch.Tensor], beam_size: int, max_len: int, eos_id: int, bos_id: int, ...
11481101
from evdev import InputDevice, list_devices, ecodes class Controller: # xbox one controller joystick max range (negative + positive range) JS_MAX_RANGE = 65534 # xbox one controller joystick center range JS_CENTER = JS_MAX_RANGE / 2 # xbox one controller trigger max range (pressed in all of th...