id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3263077 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer
BTVHLTOfflineSource = DQMEDAnalyzer("BTVHLTOfflineSource",
dirname = cms.untracked.string("HLT/BTV"),
processname = cms.string("HLT"),
verbose = cms.untracked.bool... |
3263079 | from __future__ import print_function
from builtins import range
import sys
sys.path.insert(1,"../../../")
import h2o
from tests import pyunit_utils
from h2o.estimators import H2OGradientBoostingEstimator
from h2o.grid.grid_search import H2OGridSearch
import random
def get_hyperparams_dict_return_correct_params():
... |
3263083 | from typing import Sequence
from fastapi import FastAPI, Request, HTTPException, status, Response
from fastapi.middleware.wsgi import WSGIMiddleware
import flask
import flask_admin
from wtforms.fields import StringField
from wtforms import validators
from flask_admin.contrib.sqla import ModelView
from .database impor... |
3263102 | from lightning_transformers.core.nlp.seq2seq.config import HFSeq2SeqConfig, Seq2SeqDataConfig # noqa: F401
from lightning_transformers.core.nlp.seq2seq.data import Seq2SeqDataModule # noqa: F401
from lightning_transformers.core.nlp.seq2seq.finetuning import FreezeEmbeddings # noqa: F401
from lightning_transformers.c... |
3263112 | import FWCore.ParameterSet.Config as cms
candidateVertexMerger = cms.EDProducer("CandidateVertexMerger",
secondaryVertices = cms.InputTag("inclusiveCandidateVertexFinder"),
maxFraction = cms.double(0.7),
minSignificance = cms.double(2)
)
|
3263114 | import numpy as np
from matplotlib import pyplot as plt
from scipy import linalg
from scipy import sparse
from scipy.sparse import linalg as sl
def Problem1():
# the students should have timed the code 4 times.
# their runtimes should be similar to what is below
runtimes = [8.95, 36.7, 144, 557]
input... |
3263131 | from contextlib import contextmanager
from copy import deepcopy
import numpy as np
from numpy import linalg as npl
from meshpy import tet
from scipy.spatial import cKDTree
from mesh_sphere_packing import logger, TOL
@contextmanager
def redirect_tetgen_output(fname='./tet.log'):
"""Context manager to redirect st... |
3263182 | from jinja2 import Environment, FileSystemLoader, StrictUndefined
from jinja2.exceptions import UndefinedError
from .logging import getLogger
from .process import fail
logger = getLogger(__name__)
class JinjaRenderer():
def __init__(self, facts):
self.facts = facts
def render(self, template_file) ->... |
3263222 | import torch.optim as optim
import dlm.fcn_tools as tools
from dlm import unet
import path_config as dirs
# Settings for the Unet
class ModelUnetAxial1:
def __init__(self):
self.model = unet.UNet(in_channels=1, out_classes=1, padding=0)
self.metric = tools.dice_score_tensor
self.logits_to_... |
3263231 | import datanator.config.core
from datanator.util import mongo_util
from datanator.util import file_util, chem_util
from datanator.util import molecule_util
import requests
from xml import etree
import libsbml
import re
import datetime
import bs4
import html
import csv
import pubchempy
import sys
import Bio.Alphabet
imp... |
3263277 | from typing import Tuple, List, Optional
import torch
from hearthstone.simulator.agent.actions import Action
from hearthstone.training.common.state_encoding import EncodedActionSet, State
from hearthstone.training.pytorch.replay import ActorCriticGameStepDebugInfo
def _tensorize_batch(batch: List[Tuple[State, Encod... |
3263279 | import tensorflow as tf
import numpy as np
import math
import glob
#import msssim
from scipy import misc
import matplotlib.animation as animation
from pylab import *
from frame_interpolator import *
import matplotlib
# matplotlib.use('Agg')
import matplotlib.pyplot as plt
def normalize_frames(frames, medians):
r... |
3263282 | import wisse
from gensim.models.keyedvectors import KeyedVectors as vDB
import argparse
import logging
# sys.argv[1]: Input embeddings model (w2v format)
# sys.argv[2]: Output direcory for indexed format
# sys.argv[3]: Input format (default: binary)
logging.basicConfig(format='%(asctime)s : %(levelname)s : %(message)s... |
3263307 | from pagedb import PageDB
import ipaddress
from bs4 import BeautifulSoup
import re
def addSuffix(line, dict):
#not empty or comment line or consist of invalid charachters
if((line != '') and (line[:2] != '//') and (line.find('?') == -1)):
domains = line.split('.')
TLD = domains[-1]
if(TLD not in dict):
dict... |
3263310 | import urllib.request
def download(url, file_name):
with urllib.request.urlopen(url) as response, open(file_name, 'wb') as out_file:
data = response.read() # a `bytes` object
out_file.write(data)
if __name__ == "__main__":
download("http://ovh.net/files/1Mb.dat", "downloaded_file.dat") |
3263313 | from qtrade_client.api import QtradeAPI
import random
import json
import time
import os
import sys
from log import Logger
from datetime import datetime
import requests
from dateutil import parser
from auth import QtradeAuth
DEBUG = False
DEMO = False
DEMO_MARKETS = ["NYZO", "BIS"]
log_obj = Logger("qtrader.log", "W... |
3263333 | import config
import os
import sys
import math
import random
import numpy as np
import tensorflow as tf
import data_processer
import lib.seq2seq_model as seq2seq_model
def show_progress(text):
sys.stdout.write(text)
sys.stdout.flush()
def read_data_into_buckets(enc_path, dec_path, buckets):
"""Read twee... |
3263336 | import sys
import setuptools
if sys.version_info < (3, 7, 0):
raise OSError(f'Streamlit requires Python 3.7 and above, but yours is {sys.version}')
try:
with open('README.md', encoding='utf8') as fp:
_long_description = fp.read()
except FileNotFoundError:
_long_description = ''
setuptools.setup... |
3263370 | from rest_framework import serializers
class SimpleDictSerializer(serializers.Serializer):
"""A serializer for data that is already ready for JSON"""
def to_representation(self, instance):
"""Takes in instances that are more or less dicts and simply returns them"""
return instance
|
3263393 | import numpy as np
import pytest
from experimentator import yaml
from tests.test_design import make_heterogeneous_tree
@pytest.mark.parametrize('data', [
np.random.randn(5),
1+1j,
np.array([1, 1+1j, 1j]),
np.arange(200, 220),
make_heterogeneous_tree(),
])
def test_round_trip(data):
cmp = yaml... |
3263405 | import os
imports = ('od',)
broker_url = 'redis://guest@redis/0'
if os.environ is not None and 'WORKER_BROKER' in os.environ.keys():
broker_url = os.environ['WORKER_BROKER']
result_backend = 'redis://guest@redis/0'
worker_pool_restarts = True
task_routes = {
'od.detect': {'queue': 'od'}
}
|
3263428 | import json
class coreDecision(object):
# the init method where we get the limit parameters from the parameters.json file
def __init__(self):
with open('parameters.json', 'r') as file:
self.parametros = json.load(file)
file.close()
# Here are the rules based on the paramete... |
3263445 | import numpy as np
import torch.nn as nn
import torch.nn.functional as F
import torch
from sequence_models.losses import VAELoss, SequenceCrossEntropyLoss
from sequence_models.vae import FCDecoder, FCEncoder, VAE, Conductor
if torch.cuda.is_available():
device = torch.device('cuda')
else:
device = torch.devic... |
3263478 | import pickle, sys, random,logging,os,json
from operator import itemgetter
logger=logging.getLogger(__name__)
IGNORE_TAG='None'
def prepare_document_report(o,l,p,encoded_documents,output_dir):
logger.info('Preparing the documents reports with the IGNORE_TAG = \'{0}\' ( This is case sensitive)'.format(IGNORE_TAG))
... |
3263506 | import tempfile
import warnings
from pathlib import Path
import pandas as pd
import pytest
from gobbli.dataset.cmu_movie_summary import MovieSummaryDataset
from gobbli.dataset.newsgroups import NewsgroupsDataset
from gobbli.experiment.classification import (
ClassificationExperiment,
ClassificationExperimentR... |
3263538 | import yt
import numpy as np
import pylab
def powerspectrum(ds, nindex_rho=0.0, zrange=None):
"""Compute a density-weighted velocity power spectrum. In particular,
this computes:
1 1 ^ ^*
E(k) = - integral - V(k) . V(k) dS
N 2
n
... |
3263541 | from .builder import build_rectificator # noqa 401
from .spin import SPIN # noqa 401
from .tps_stn import TPS_STN # noqa 401
|
3263548 | from collections import namedtuple
# data structure mimicking a task for use with the metadata API classes
TaskContext = namedtuple("TaskContext", ["org_config", "project_config", "logger"])
|
3263552 | from PyPDF2 import PdfFileWriter, PdfFileReader
print("What is the file that you would like to modify?\n[Provide file address]")
file = str(input())
inputFile = PdfFileReader(file)
pagesToDelete = []
print("How many pages do you need to delete?")
n = int(input())
print("Enter the page numbers of the files ... |
3263557 | import unittest
from fastHan import FastHan
class TestFastHan(unittest.TestCase): # 继承了unittest.TestCase这样可以直接利用unittest的一些function
def test_init(self):
# 测试是否可以正确initialize
model = FastHan()
model = FastHan('large')
def test_call(self):
sentence=['一行人下得山来,走不多时,忽听前... |
3263583 | import traceback
from _pydev_bundle.pydev_is_thread_alive import is_thread_alive
from _pydev_imps._pydev_saved_modules import threading
from _pydevd_bundle.pydevd_constants import get_thread_id
from _pydevd_bundle.pydevd_dont_trace_files import DONT_TRACE
from _pydevd_bundle.pydevd_kill_all_pydevd_threads import kill_... |
3263625 | from __future__ import (
absolute_import,
unicode_literals,
)
from pysoa.client.client import Client
def test_send_receive_redis5_redis6_round_robin(pysoa_client: Client): # noqa: E999
for i in range(10):
response = pysoa_client.call_action('echo', 'status', body={'verbose': False})
asse... |
3263653 | from tool.runners.python import SubmissionPy
class JonSubmission(SubmissionPy):
def run(self, s):
l = [int(x) for x in s.strip().split()]
s1 = set(l)
if 1010 in s1:
if l.count(1010) >= 2:
return 1010**2
s1.discard(1010)
s2 = {2020-x for x ... |
3263656 | from sklearn.externals import joblib
import unicodedata
import re
from sklearn.externals import joblib
import pandas as pd
import os
import json
import urllib
path = os.path.dirname(os.path.abspath(__file__)) + "\\"
def _assign_geo_cluster(lat_long):
geo_cluster_model = joblib.load(path + 'geo_cluster_model.pkl'... |
3263715 | import FWCore.ParameterSet.Config as cms
XMLIdealGeometryESSource_CTPPS = cms.ESSource("XMLIdealGeometryESSource",
geomXMLFiles = cms.vstring('Geometry/CMSCommonData/data/materials.xml',
'Geometry/CMSCommonData/data/rotations.xml',
'Geometry/CMSCommonData/data/normal/cmsextent.xml',
'Geo... |
3263724 | import json
import uuid
import boto3
stream_name = "smartcity-emergency-system-events"
message_json = {
"record_id": "18742",
"date_and_time": "2020-11-14T15:53:00.000",
"notificationtype": "Weather",
"notification_title": "Coastal Flood Statement (BK)",
"email_body": "Notification issued 11-15-2020 at 3:53... |
3263729 | pkgname = "xcbproto"
pkgver = "1.14.1"
pkgrel = 0
build_style = "gnu_configure"
configure_args = ["--enable-legacy"]
hostmakedepends = ["pkgconf", "python", "automake"]
depends = ["python"]
pkgdesc = "XML-XCB (X C Bindings) protocol descriptions"
maintainer = "q66 <<EMAIL>>"
license = "MIT"
url = "https://xcb.freedeskt... |
3263747 | from django import template
from system.models import Configuration
register = template.Library()
@register.assignment_tag
def get_config(conf_name=None):
if conf_name is None:
raise Exception("Invalid config name")
c = Configuration.get_by_name_all_fields(conf_name)
if not c:
return Non... |
3263763 | import json
import requests
import base64
from splunk_alexa import alexa
channl=""
token=""
resp=""
def set_data(Channel,Token,Response):
global channl,token,resp
channl=Channel
token=Token
resp=Response
def send_data(text):
global channl,token,res
print(channl)
resp = requests.... |
3263764 | import fenics
import matplotlib
N = 4
mesh = fenics.UnitSquareMesh(N, N)
P1 = fenics.FiniteElement('P', mesh.ufl_cell(), 1)
P2 = fenics.VectorElement('P', mesh.ufl_cell(), 2)
mixed_element = fenics.MixedElement([P1, P2, P1])
W = fenics.FunctionSpace(mesh, mixed_element)
psi_p, psi_u, psi_T = fenics.TestFuncti... |
3263866 | import json
from tqdm import tqdm
from glob import glob
import os
from PIL import Image
label_file = '/tcdata/tile_round2_train_20210204_update/train_annos.json'
target_file = 'data/annotations/train_round2_1.json'
with open(label_file, 'r', encoding='utf-8') as f:
labels = json.load(f)
categoryid2name = {
# ... |
3263886 | import unittest
import numpy as np
from spyne import Tensor, Constant
class TestTensor(unittest.TestCase):
""" A set of tests to validate tensor definitions, attributes, functionality etc..."""
def setUp(self):
self.data = np.array(
[
[[1, 2, 3],
[4, 5, 6]... |
3263936 | from qtpy.QtWidgets import QWidget, QLabel, QVBoxLayout, QHBoxLayout, QComboBox
from qtpy.QtCore import Slot
from .useful_widgets import RangeManager, set_tooltip, global_gui_variables
from ..model.lineplot import MapTypes, MapAxesUnits
from matplotlib.backends.backend_qt5agg import (
FigureCanvasQTAgg as FigureC... |
3263990 | import re, sys
from pydoc import help as python_help
try:
import visit
except:
pass
#
# Define an override for standard python `help` method
# It calls normal python help but also returns an apropos
# result if it would be useful.
#
def visit_help(thing):
try:
python_help(thing)
except:
... |
3264109 | import turtle
t=turtle.Turtle()
t.penup()
t.left(45)
t.backward(125)
t.right(45)
t.pendown()
for c in ['red', 'green', 'yellow', 'blue']:
t.color(c)
t.forward(75)
t.left(90)
t1=turtle.Turtle("turtle")
t1.penup()
t1.pendown()
t1.width(3)
for c in ['red', 'blue', 'yellow', 'green', 'purple', 'brown']:
... |
3264116 | import wot.tmap
def chain_transport_maps(tmap_model, pairs_list):
"""
Chains the transport maps corresponding to the list of pairs for the OTModel.
Parameters
----------
tmap_model : wot.tmap.TransportMapModel
The TransportMapModel whose transport maps are to be chained.
pairs_list : ... |
3264124 | import factory
from factory.django import DjangoModelFactory
from ..models.repository import Repository
class RepositoryFactory(DjangoModelFactory):
url = factory.Faker('url')
display_name = factory.Faker('pystr', max_chars=80)
team = factory.SubFactory('v1.teams.factories.team.TeamFactory')
class M... |
3264160 | from pydantic import BaseModel, Extra
class UserSerializer(BaseModel):
id: int
email: str
name: str
class Config:
orm_mode = True
extra = Extra.allow
|
3264167 | import unittest
from dart.engine.no_op.metadata import NoOpActionTypes
from dart.model.action import ActionData, Action
from dart.model.exception import DartValidationException
from dart.schema.action import action_schema
from dart.schema.base import default_and_validate
class TestActionSchema(unittest.TestCase):
... |
3264181 | import os.path
from setuptools import find_packages, setup
with open(os.path.join(os.path.dirname(__file__), 'README.md')) as f:
LONG_DESCRIPTION = f.read()
DESCRIPTION = LONG_DESCRIPTION.splitlines()[0].lstrip('#').strip()
PROJECT_URLS = {
'Bug Tracker': 'https://github.com/nolar/looptime/issues',
'... |
3264192 | import FWCore.ParameterSet.Config as cms
#
# Hcal fake calibrations
#
#
# please note: in the future, it should load Hcal_FakeConditions.cfi from this same directory
# for 130 is was decided (by DPG) to stick to the old config, hence I load
#
#include "CalibCalorimetry/HcalPlugins/data/Hcal_FakeConditions.cfi"
from Ca... |
3264286 | import setuptools
INSTALL_REQUIREMENTS = ['numpy', 'torch', 'torchvision', 'Pillow', 'scikit-image', 'opencv-python', 'tqdm', 'imageio']
setuptools.setup(
name='human_inst_seg',
url='https://github.com/Project-Splinter/human_inst_seg',
description='A Single Human Instance Segmentor runs at 50 FPS on GV100... |
3264294 | from matplotlib.animation import FuncAnimation
import matplotlib.pyplot as plt
import pandas
import os
import sys
args = sys.argv
if len(args) != 2:
print("Incorrect number of arguments, terminating...")
sys.exit(-1)
gpath = sys.argv[1]
def animate(k):
plt.cla()
data = pandas.read_csv(gpath)
... |
3264300 | from savu.plugins.plugin_tools import PluginTools
class DezingerSimpleDeprecatedTools(PluginTools):
"""A plugin for cleaning x-ray strikes based on statistical evaluation of
the near neighbourhood
"""
def define_parameters(self):
"""
outlier_mu:
visibility: basic
... |
3264353 | from django.core import management
from django.core.exceptions import ValidationError
from django.core.management.base import BaseCommand, CommandError
from django.db import transaction
from ctflex import constants
from ctflex import settings
from ctflex.management.commands import helpers
from ctflex.models import Tea... |
3264408 | import os
def get_result_folder(name : str):
"""
Returns the absolute path to a subfolder denoted by 'name' without a trailing slash.
:param name: the name of the subfolder
:return: the absolute path to that subfolder
"""
current_dir = os.path.split(__file__)[0]
path = os.path.abspath(os.path.join(curren... |
3264413 | from .multigrid_models import MultigridNetwork
from .minihack_models import MiniHackAdversaryNetwork, NetHackAgentNet |
3264428 | from rest_framework.routers import DefaultRouter
from systori.apps.timetracking.api import TimerModelViewSet
router = DefaultRouter()
router.register(r"timer", TimerModelViewSet)
urlpatterns = router.urls
|
3264443 | from quasimodo.web_search.archit_submodule import ArchitSubmodule
class YoutubeCountSubmodule(ArchitSubmodule):
def __init__(self, module_reference):
super().__init__(module_reference)
self._name = "Youtube count"
self._index = 5
|
3264503 | from pylab import *
import skrf as rf
import pdb
c = 3e8
def create_sdrkits_ideal(skrf_f):
# create ideal cal kit
media = rf.media.Freespace(skrf_f)
sdrkit_open = media.line(42.35, 'ps', z0 = 50) ** media.open() # 42.35
sdrkit_short = media.line(26.91, 'ps', z0 = 50) ** media.short()
# TODO: add ... |
3264611 | from random import randint, choice, random
from string import ascii_letters, digits
COLOR_ALPHABET = "ABCDEF" + digits
with open("generators/names") as names_file:
NAMES = names_file.read().split('\n')
with open("generators/user-agents") as user_agents_file:
USER_AGENTS = user_agents_file.read().split('\n')
... |
3264685 | from tests.utils import W3CTestCase
class TestFlexbox_AlignContentStretch(W3CTestCase):
vars().update(W3CTestCase.find_tests(__file__, 'flexbox_align-content-stretch'))
|
3264743 | from workbench.tools import admin
from . import models
@admin.register(models.PublicHoliday)
class PublicHolidayAdmin(admin.ReadWriteModelAdmin):
list_display = ["date", "name", "fraction"]
@admin.register(models.Milestone)
class MilestoneAdmin(admin.ModelAdmin):
list_display = ["project", "date", "title"]... |
3264789 | import bpy
import bpy_extras
import math
bl_info = {
"name": "Times Table",
"location": "View3D > Add > Mesh",
"category": "Add Mesh",
"description": "Add a cool mathematical design",
"author": "<NAME>",
"version": (1, 0),
"blender": (2, 82, 0),
}
class Params(bpy.types.Prope... |
3264793 | XK_Serbian_dje = 0x6a1
XK_Macedonia_gje = 0x6a2
XK_Cyrillic_io = 0x6a3
XK_Ukrainian_ie = 0x6a4
XK_Ukranian_je = 0x6a4
XK_Macedonia_dse = 0x6a5
XK_Ukrainian_i = 0x6a6
XK_Ukranian_i = 0x6a6
XK_Ukrainian_yi = 0x6a7
XK_Ukranian_yi = 0x6a7
XK_Cyrillic_je = 0x6a8
XK_Serbian_je = 0x6a8
XK_Cyrillic_lje = 0x6a9
XK_Serbian_lje =... |
3264805 | import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
dbpn_df = pd.read_csv('/home/ser606/ZhenLi/super_resolution/experiments/DBPN_in3f64b4_x4/results/train_results.csv')
ddbpn_df = pd.read_csv('/home/ser606/ZhenLi/super_resolution/experiments/D-DBPN_in3f64b4_x4/results/train_results.csv')
plt.plot(d... |
3264812 | from mitmproxy import http
from mitmproxy import ctx
from mitmutils import utils
import os
import re
import time
CONFIG_FILE = './record-request.yaml'
def response(flow: http.HTTPFlow) -> None:
matches = utils.readFile(CONFIG_FILE)
url = flow.request.url
if matches is not None:
for patternURL, d... |
3264830 | import pytest
import qobuz
import responses
from tests.resources.responses import album_get_json
from tests.resources.fixtures import album
@pytest.fixture
def app():
qobuz.api.register_app(app_id="<EMAIL>")
def get_url(album_id):
return (
qobuz.api.API_URL
+ "album/get"
+ "?album_i... |
3264856 | import os
import unittest
from linkml.generators.sssomgen import SSSOMGenerator
from tests.test_generators.environment import env
import yaml
SCHEMA = env.input_path("kitchen_sink_sssom.yaml")
OUTPUT_DIR = os.path.join(
os.path.abspath(os.path.dirname(__file__)), "output/ks/sssom"
)
OUTPUT_FILENAME = "test_sssom.t... |
3264909 | from dataclasses import dataclass
from typing import Optional
from hooqu.analyzers.analyzer import (
DoubledValuedState,
NonScanAnalyzer,
Entity,
)
from hooqu.dataframe import DataFrameLike
@dataclass
class NumMatches(DoubledValuedState["NumMatches"]):
num_matches: int
def sum(self, other) -> "... |
3265010 | from dataclasses import dataclass
from typing import List, Optional
__all__ = ("Embed", "EmbedImage")
@dataclass
class EmbedImage:
"""Represents a dataclass for an embed image.
.. versionadded: 1.1.3
.. versionchanged: 1.5.0
Made as a dataclass rather then a standalone class.
"""
url:... |
3265045 | from __future__ import annotations
from typing import TYPE_CHECKING, Mapping, Sequence, Union
if TYPE_CHECKING:
from meerkat.block.abstract import AbstractBlock
from meerkat.columns.abstract import AbstractColumn
class BlockRef(Mapping):
def __init__(self, columns: Mapping[str, AbstractColumn], block: A... |
3265053 | import torch.nn as nn
import torch
class Discriminator(nn.Module):
def __init__(self, shared_dim: int, exclusive_dim: int):
"""Dense discriminator
Args:
shared_dim (int): [Dimension of the shared representation]
exclusive_dim (int): [Dimension of the exclusive representati... |
3265063 | from apprentice.explain.explanation import Explanation
from apprentice.working_memory import ExpertaWorkingMemory
from kill_engine import KillEngine, KillEngineEmpty
from experta import Fact, KnowledgeEngine
def test_explain():
cf = KillEngine()
cf.reset()
cf.run(10)
kill_fact = cf.facts[7]
new_w... |
3265073 | from openzwave.network import ZWaveNode
from openzwave.value import ZWaveValue
from Firefly import logging
from Firefly.components.zwave.zwave_device import ZwaveDevice
from Firefly.const import AUTHOR, DEVICE_TYPE_MOTION, WATER
from Firefly.helpers.device_types.water_sensor import WaterSensor
ALARM = 'alarm'
BATTERY... |
3265093 | from .create_act import get_act_layer
from .lowrank_bilinear_layers import LowRankBilinearLayer, LowRankBilinearAttention
from .scattention import SCAttention
from .tdconved_layers import TemporalDeformableLayer, ShiftedConvLayer, SoftAttention
from .base_attention import BaseAttention
__all__ = list(globals().k... |
3265098 | import argparse
import tflite_flops
def main():
parser = argparse.ArgumentParser()
parser.add_argument('input_model', help='Input TFLite model')
args = parser.parse_args()
tflite_flops.calc_flops(args.input_model)
if __name__ == '__main__':
main()
|
3265118 | import torch
import torch.nn as nn
import point_utils
class conv_2d(nn.Module):
def __init__(self, in_ch, out_ch, kernel, activation='relu'):
super(conv_2d, self).__init__()
if activation == 'relu':
self.conv = nn.Sequential(
nn.Conv2d(in_ch, out_ch, kernel_size=kernel)... |
3265226 | from django.contrib.auth.models import User
from django.utils.timezone import now
from .models import Paste
def recent_pastes(request):
pastes = Paste.objects.order_by('-created_at').filter(status=1, expire_time__gt=now())[:5]
return {'pastes': pastes}
def my_recent_pastes(request):
context = {}
if... |
3265263 | import statistics
from multimetric.cls.base_stats import MetricBaseStats
class MetricBaseStatsAverage(MetricBaseStats):
def __init__(self, args, **kwargs):
super().__init__(args, **kwargs)
def _getInputList(self, metrics, key):
res = []
for _, v in metrics.items():
if ke... |
3265317 | from threading import Thread
from time import sleep
user_input = [None, None]
def auth_handler():
"""
При двухфакторной аутентификации вызывается эта функция.
:return: key, remember_device
"""
num = user_input[0]
input_thread = Thread(target=get_auth_code, args=(user_input,))
input_thread... |
3265406 | from django.contrib import admin
from apps.routes.models import Route, RouteLeg
from .route import RouteAdmin
from .route_leg import RouteLegAdmin
admin.site.register(Route, RouteAdmin)
admin.site.register(RouteLeg, RouteLegAdmin)
|
3265423 | import logging
import math
import os
import numpy as np
import torch
from torch import nn
from torch.autograd import Variable as Var
from archive.genut import msk_list_to_mat
from archive.genut import Trainer
class LMTrainer(Trainer):
def __init__(self, opt, model, data):
super().__init__(opt, model, da... |
3265432 | import torch
import torch.nn as nn
import sentence_transformers as sent_trans
class DualEncoderModel(torch.nn.Module):
def __init__(self, label_encoder, instance_encoder, mode='ict'):
super(DualEncoderModel, self).__init__()
self.label_encoder = label_encoder
self.instance_encoder = instance_encoder
self.mode ... |
3265442 | import argparse
import os
import matplotlib
import numpy as np
import torch
from torch import optim
from torch.nn.utils import clip_grad_norm_
from torch.utils.data import DataLoader
import audio
import librosa
from data import MelDataset
from hparams import hparams, hparams_debug_string
from loss import compute_loss... |
3265456 | import logging
import math
import threading
import time
from concurrent.futures import ThreadPoolExecutor
from contextlib import suppress
from dataclasses import dataclass
from multiprocessing import Queue
from pathlib import Path
from random import choice
from threading import Thread
from time import perf_counter, sle... |
3265521 | import numpy as np
import pandas as pd
from sklearn.ensemble import RandomForestRegressor
# train is the training datat
# test is the test data
# y is the target variable
train = pd.DataFrame()
test = pd.DataFrame()
y = []
model = RandomForestRegressor()
bags = 10
seed = 1
# create array object to hold bagged predi... |
3265539 | from typing import Type, TypeVar
from ssz.hashable_container import HashableContainer
from .block_headers import SignedBeaconBlockHeader, default_signed_beacon_block_header
TProposerSlashing = TypeVar("TProposerSlashing", bound="ProposerSlashing")
class ProposerSlashing(HashableContainer):
fields = [
... |
3265544 | import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from matplotlib import cm
from demo import make_led
from ID3 import RandomizedID3Classifier, RandomizedID3Ensemble
n_trees = 3000
X, y = make_led()
fig, axs = plt.subplots(1, 2)
ax = axs[0]
clf = RandomizedID3Ensemble(n_estimators=n_trees,
... |
3265566 | import os
import stiefo
filenamebase = "praefix-test"
wlist = stiefo.wordlist()
#wlist.load("Wortlisten/wortliste-aufbauschrift-1.txt")
if os.path.isfile(filenamebase + '.wrd'):
wlist.load(filenamebase + '.wrd')
with open(filenamebase + '.txt', "r", encoding="utf-8") as f:
text = f.read()
s... |
3265578 | from typing import List
from algosdk import account, mnemonic
from algosdk.encoding import is_valid_address
from algosdk.account import address_from_private_key
from algosdk.future.transaction import AssetConfigTxn, AssetTransferTxn, AssetFreezeTxn, PaymentTxn
import base64
def validate_address(addr):
"""
Che... |
3265581 | from fbchat import GroupData, User
def test_group_from_graphql(session):
data = {
"name": "Group ABC",
"thread_key": {"thread_fbid": "11223344"},
"image": None,
"is_group_thread": True,
"all_participants": {
"nodes": [
{"messaging_actor": {"__typ... |
3265585 | import typing
lang = "Python"
typs_d = {typing.Any: "int", "List": "list"}
def linsert(l: typing.List[typing.Any], i: int, x: typing.Any) -> None:
pass
linsert_def = (linsert, 'list.insert', [0])
def lextend(l1: typing.List[typing.Any], l2: typing.List[typing.Any]) -> None:
pass
lextend_def = (lextend,... |
3265699 | from torch import nn
def to_cuda(network):
"""Calls model.cuda() and moves input(s) to the GPU before forward."""
network.cuda()
network._to_cuda_forward_cache = network.forward
def cuda_forward(x):
return network._to_cuda_forward_cache(x.cuda(non_blocking=True))
network.forward = cuda_... |
3265736 | import threading
from os import path
from .count import Counter
from .notification import Notification
from .watch import Watcher
class Schedule:
def __init__(self, counter_path):
self.watchers = {}
self.threads = {}
self.counter = Counter(counter_path)
self.notification = Notifica... |
3265739 | import os
this_directory = os.path.dirname(os.path.realpath(__file__))
parts_folder = os.path.join(this_directory, "parts")
import dnacauldron as dc
def test_combinatorial_type2s():
repository = dc.SequenceRepository()
repository.import_records(folder=parts_folder, use_file_names_as_ids=True)
parts_list ... |
3265804 | import h5py
import numpy as np
name_list = ['name1', 'name2']
image_names_array = np.asarray(name_list)
data_vectors = np.empty((2, 3000))
# write an hdf5 file
hf = h5py.File('data.hdf5', 'w')
hf.create_dataset('urls', data=image_names_array)
hf.create_dataset('vectors', data=data_vectors)
hf.close()
# read file
hf ... |
3265821 | from talon import Module, actions, app, ctrl
import os
app.register("ready", lambda: actions.user.mouse_show_cursor())
default_cursor = {
"AppStarting": r"%SystemRoot%\Cursors\aero_working.ani",
"Arrow": r"%SystemRoot%\Cursors\aero_arrow.cur",
"Hand": r"%SystemRoot%\Cursors\aero_link.cur",
"Help": r"... |
3265833 | from shinytest import ShinyTestCase
class TestSpawn(ShinyTestCase):
def setUp(self):
ShinyTestCase.setUp(self)
from shinymud.models.area import Area
self.area = Area.create({'name':'foo'})
self.room = self.area.new_room()
self.item = self.area.new_item()
self.npc = s... |
3265839 | from typing import Any
import sys
NEW_INSPECT = sys.version_info[:3] >= (3, 8, 0)
if NEW_INSPECT:
from typing import Protocol # since python3.8+
else:
from typing_extensions import Protocol # type: ignore
__all__ = ["PluginProto"]
class PluginProto(Protocol):
def init_app(self, app: Any) -> None:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.