id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
438475 | import scanpy as sc
import numpy as np
import scib
def test_scale():
adata = sc.datasets.blobs()
scib.pp.scale_batch(adata, 'blobs')
split = scib.utils.split_batches(adata, 'blobs')
for i in split:
assert np.allclose(i.X.mean(0), np.zeros((0,adata.n_vars)))
|
438498 | import json
from typing import Tuple, List, Optional, Callable
from copy import deepcopy
from mdstudio.api.sort_mode import SortMode
from mdstudio.collection import merge_dicts
from mdstudio.deferred.chainable import chainable
from mdstudio.deferred.return_value import return_value
@chainable
def paginate_cursor(fi... |
438545 | import os
from collections import OrderedDict
import pytest
import torch
from padl import transforms as pd, transform, Identity, batch, unbatch, group
from padl.transforms import Batchify, Unbatchify, TorchModuleTransform, RequirementNotFound
from padl.dumptools.serialize import value
import padl
from collections impor... |
438568 | from .model import GLAM
__all__ = ['GLAM']
# from .simulation import *
# from .utils import *
# from .components import *
# from .fit import * |
438592 | import apps.common.func.InitDjango
from apps.common.func.CommonFunc import *
from all_models.models import TbBusinessLine
class BusinessService(object):
@staticmethod
def getBusiness():
return dbModelListToListDict(TbBusinessLine.objects.all())
@staticmethod
def getInterfaceListBusinessId(inte... |
438596 | import os
import torch
import torch.nn as nn
import torch.nn.functional as F
import torchaudio
import torchaudio.functional as AF
import librosa
import math
import sys
import numpy as np
import time
from conf.feature import *
from conf.inference import *
def align(a, b, dim):
return a.transpose(0, dim)[:b.shape[d... |
438604 | import torch
import json
import numpy as np
from transformers import (BertForMaskedLM, BertTokenizer)
modelpath = 'bert-large-uncased-whole-word-masking/'
tokenizer = BertTokenizer.from_pretrained(modelpath)
model = BertForMaskedLM.from_pretrained(modelpath)
model.eval()
id_of_mask = 103
def get_embeddings(sentence... |
438613 | from __future__ import absolute_import
import functools
import logging
from pprint import pformat
from urllib import urlencode
import flask
from flask import request, current_app
from flask_login import current_user
import werkzeug as wz
from flask_acl.core import iter_object_acl, get_object_context, check
from flas... |
438618 | import urllib
def PHPMemcached():
print "\033[01m" + "\nThis is usable when you know Class and Variable name used by user\n"+ "\033[0m"
code = raw_input("\033[96m" +"Give serialization payload\nexample: O:5:\"Hello\":0:{} : "+ "\033[0m")
if(not code):
print "\033[93m" + "Plz give payload" + "\0... |
438654 | import io, sys, os, csv
from Bio import SeqIO
from selftarget.oligo import loadPamLookup, loadOligosByBarcode, getFileForOligoIdx
def closeFiles(fhandles):
for id in fhandles:
fhandles[id].close()
def writeBatchToFile(read_by_file, output_dir):
for (filedir, filename) in read_by_file:
if not ... |
438666 | from __future__ import print_function
from ._version import version as __version__
from time import strftime, localtime
try:
from time import monotonic
except ImportError:
from monotonic import monotonic
from IPython.core.magics.execution import _format_time as format_delta
def format_timestamp(struct_tim... |
438667 | from django.conf import settings
from django.db import migrations
from corehq.sql_db.config import plproxy_standby_config
from corehq.sql_db.management.commands.configure_pl_proxy_cluster import (
get_drop_server_sql,
get_sql_to_create_pl_proxy_cluster,
)
from corehq.sql_db.operations import RawSQLMigration
fr... |
438740 | from django.apps import AppConfig
class AppConfig(AppConfig):
pass
class CustomAppConfig(AppConfig):
"""
This class may be use to setup configuration for scalable components
and tools
"""
name = 'custom'
|
438752 | import argparse
from pathlib import Path
from typing import Dict
import pandas as pd
import torch
import torch.distributed as dist
import torch.nn.parallel
import torch.utils.data
import torch.utils.data.distributed
import yaml
from albumentations.core.serialization import from_dict
from iglovikov_helper_functions.con... |
438762 | import operator
import itertools
import copy
from math import *
from ROOT import std
from ROOT import TLorentzVector, TVector3, TVectorD
from PhysicsTools.Heppy.analyzers.core.Analyzer import Analyzer
from PhysicsTools.HeppyCore.framework.event import Event
from PhysicsTools.HeppyCore.statistics.counter import Coun... |
438769 | from .resnet import ResidualNet, ConvResidualNet
from .unet import UNet
from .attention import ConvAttentionNet
from .mlp import MLP
from .conv import SylvesterFlowConvEncoderNet, SylvesterFlowConvDecoderNet,infoGAN_decoder, infoGAN_encoder, ConvEncoder, simple_decoder, ConvDecoder, Conv2dSameSize, ModifiedConvEncoder
|
438786 | import os
import sys
import glob
import tqdm
import warnings
import argparse
import copy
import numpy as np
import pandas as pd
from itertools import product
from functools import partial
from math import sqrt, exp, pi, gamma, log
from multiprocessing import Pool, cpu_count
pdir = os.path.abspath(os.path.dirname(os.... |
438789 | from ipywidgets import Box
from hdijupyterutils.ipythondisplay import IpythonDisplay
from hdijupyterutils.ipywidgetfactory import IpyWidgetFactory
class AbstractMenuWidget(Box):
def __init__(self, spark_controller, ipywidget_factory=None, ipython_display=None,
nested_widget_mode=False, testing=F... |
438815 | import json
from datetime import datetime, timedelta
from django.test import override_settings
from django.utils import timezone
from model_mommy import mommy
from rest_framework import status
from rest_framework.test import APITestCase
from ratechecker.models import Adjustment, Product, Rate, Region
from ratechecke... |
438827 | import os, sys, stat
import CalcDigest
def fileSize( f ) : return os.stat(f)[stat.ST_SIZE]
def execRemote( cmd ) :
return os.popen( 'plink ks@172.16.17.32 %s' % cmd ).read()
def main() :
updateBuildNumber = int(file('CSpaceUpdate-BuildNumber.txt').read().strip())
updateFile = 'CSpaceUpdate%d.ex... |
438846 | from celery import shared_task
from django.conf import settings
from courses.bridge import import_courses as bridge_import_courses
@shared_task
def import_courses(force=False, all=False, catalog=True):
bridge_import_courses(force=force, all=all, catalog=catalog)
|
438870 | from .common import h
from .objects import CIM_TYPE_SIZES
def dump_definition(cd, cl):
"""
:type cd: ClassDefinition
:type cl: ClassLayout
"""
# TODO: migrate to templating?
ret = []
ret.append("classname: %s" % cd.class_name)
ret.append("super: %s" % cd.super_class_name)
ret.appe... |
438877 | from simpleeval import simple_eval, NameNotDefined
from datetime import datetime
import uuid
import copy
import pylabnet.utils.pulseblock.pulse as po
import pylabnet.utils.pulseblock.pulse_block as pb
from pylabnet.utils.iq_upconversion.iq_calibration import IQ_Calibration
from pylabnet.utils.pulseblock.placeholder im... |
438893 | from torch.autograd import Variable
import torch
import torch.optim
import copy
import numpy as np
from .helpers import *
from .decoder import *
from .fit import *
from .wavelet import *
def rep_error_deep_decoder(img_np,k=128,convert2ycbcr=False):
'''
mse obtained by representing img_np with the deep decoder... |
438920 | from .unittest_tools import unittest
from quantlib.quotes import SimpleQuote
class SimpleQuoteTestCase(unittest.TestCase):
def test_round_trip(self):
value = 72.03
quote = SimpleQuote(value)
self.assertAlmostEqual(value, quote.value)
def test_empty_constructor(self):
quote ... |
438969 | from ray.rllib.utils.annotations import override
from marltoolbox.algos.amTFT import base_policy, policy_using_rollouts
class InversedAmTFTRolloutsTorchPolicy(
policy_using_rollouts.AmTFTRolloutsTorchPolicy):
"""
Instead of simulating the opponent, simulate our own policy and act as
if it was the opp... |
438980 | import os.path
import sys
import traceback
from gamescript import start
main_dir = os.path.split(os.path.abspath(__file__))[0]
if __name__ == "__main__":
try: # for printing error log when error exception happen
runmenu = start.Mainmenu(main_dir)
runmenu.run()
except Exception: # Save error... |
439019 | from pwn import *
r = remote("ch41l3ng3s.codegate.kr", 3333)
def add(name, profile):
r.sendline(name)
print r.recvuntil("profile")
r.sendline(profile)
print r.recvuntil(">> ")
def sell(idx):
r.sendline("S")
print r.recvuntil("(number)")
r.sendline(str(idx))
print r.recvuntil("?")
r.sendline("S")
print r.re... |
439020 | from django.core.management.base import BaseCommand
from kong.models import Test
from kong.models import Site, Type
from optparse import OptionParser, make_option
class Command(BaseCommand):
option_list = BaseCommand.option_list + (
make_option("-t", "--test", dest="test"),
make_option("-s", "--s... |
439030 | from typing import List, Optional, TypeVar
import strawberry
from strawberry.annotation import StrawberryAnnotation
from strawberry.type import StrawberryList, StrawberryOptional, StrawberryTypeVar
def test_basic_string():
annotation = StrawberryAnnotation("str")
resolved = annotation.resolve()
assert r... |
439035 | base_product_page_url = 'https://www.amazon.com/gp/product/'
base_amazon_url = 'https://www.amazon.com/'
base_questions_url = 'https://www.amazon.com/ask/questions/asin/' |
439049 | import sys
import numpy as np
import pytest
from baal.utils.plot_utils import make_animation_from_data
@pytest.mark.skipif(sys.platform == "darwin", reason="Does not work on Mac.")
def test_make_animation_from_data():
x = np.random.rand(4, 2)
y = np.random.rand(4)
labelled_at = np.random.randint(0, 4, si... |
439075 | import sys
import re
import os
import subprocess
import collections
import json
import binascii
import base64
from capstone import *
from capstone.x86_const import *
from capstone.arm_const import *
ARCH = CS_ARCH_ARM
#MODE = CS_MODE_64
if ARCH == CS_ARCH_X86:
md = Cs(CS_ARCH_X86,MODE)
elif ARCH == CS_ARCH_ARM:
... |
439082 | from functools import reduce
import pandas as pd
from scipy import stats
def tabulate_predecessor_fitness(predecessor_df):
# root id 0 is the control competitors (i.e., the predecessors)
predecessor_df = predecessor_df[
predecessor_df['Root ID'] == 1
].reset_index()
predecessor_df['Series'] = ... |
439086 | from .ext import Admin
from .ui.decorators import admin_required
from .api.decorators import admin_required_api
from . import cli
__all__ = ["Admin", "admin_required", "admin_required_api", "cli"]
|
439090 | import FWCore.ParameterSet.Config as cms
process = cms.Process("reader")
process.maxEvents = cms.untracked.PSet( input = cms.untracked.int32(-1) )
process.load("FWCore.MessageLogger.MessageLogger_cfi")
process.MessageLogger.cout.placeholder = cms.untracked.bool(False)
process.MessageLogger.cout.threshold = cms.untra... |
439093 | import feedparser
import alkali
from alkali import fields
class RssLoader(alkali.Storage):
def __init__(self, url):
self.filename = url
def read(self, model_class):
feed = feedparser.parse(self.filename)
for item in feed['items']:
yield item
class Episode(alkali.Model):
... |
439111 | import numpy as np
from .dc_motor import DcMotor
class DcShuntMotor(DcMotor):
"""The DcShuntMotor is a DC motor with parallel armature and exciting circuit connected to one input voltage.
===================== ========== ============= ===========================================
Motor Parameter ... |
439116 | import tensorflow as tf
mat1 = tf.constant([[4, 5, 6],[3,2,1]])
mat2 = tf.constant([[7, 8, 9],[10, 11, 12]])
# hadamard product (element wise)
mult = tf.multiply(mat1, mat2)
# dot product (no. of rows = no. of columns)
dotprod = tf.matmul(mat1, tf.transpose(mat2))
with tf.Session() as sess:
print(sess.run(mult)... |
439128 | import datetime
from django.conf import settings
from django.core.management.base import BaseCommand
from django.template.loader import get_template
from periods import models as period_models, email_sender, helpers
class Command(BaseCommand):
help = 'Notify users of upcoming periods'
def _format_date(self... |
439142 | import sqlalchemy as sa
from mealie.db.models.model_base import SqlAlchemyBase
class Note(SqlAlchemyBase):
__tablename__ = "notes"
id = sa.Column(sa.Integer, primary_key=True)
parent_id = sa.Column(sa.Integer, sa.ForeignKey("recipes.id"))
title = sa.Column(sa.String)
text = sa.Column(sa.String)
... |
439187 | import unittest
from loa.unit import Unit
from loa.team import Team
from loa.team import TeamExaminer
def get_team():
return MyTeam("👑")
class Pawn(Unit):
HP = 20.0001 # Hit Points (health points)
ATT = 10 # Attack
ARM = 0 # Armor
EVS = 0 # Evasion
def __init__(self, team... |
439191 | from ....Common.DyStockCommon import *
from ....Common.Ui.Basic.DyStockTableWidget import *
class DyStockDataFocusInfoPoolWidget(DyStockTableWidget):
""" focus info pool widget """
header = ['热点', # 若一只股票有多个热点,只取强度最大的作为其热点
'热点强度', # 此热点在市场中的强度
'热点涨幅(%)', # 被此热点追踪到的股票的平均涨幅
... |
439210 | from __future__ import print_function
import copy
import os
import re
import time
import warnings
from collections import OrderedDict
from contextlib import contextmanager
from logging import getLogger
import six
import tensorflow as tf
from tfsnippet.dataflows import DataFlow
from tfsnippet.utils import (Statistics... |
439247 | from pathlib import Path
from setuptools import setup
long_description = (Path(__file__).parent / "README.md").read_text('utf-8').split('# Installation')[0]
setup(
name="manga-ocr",
version='0.1.7',
description="OCR for Japanese manga",
long_description=long_description,
long_description_content_t... |
439291 | from mau.visitors.html_visitor import HTMLVisitor
from mau.parsers import nodes
from mau.parsers.main_parser import MainParser
from tests.helpers import (
dedent,
remove_indentation,
init_parser_factory,
visitlist_factory,
)
init_parser = init_parser_factory(MainParser)
visitlist = visitlist_factory(H... |
439459 | import sys
import subprocess
import argparse
import os
import signal
from pathlib import Path
parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)
parser.add_argument("arch", type=str, help="architecture (dgx1|dgx2)")
parser.add_argument("--dir", type=str, help="output directory", d... |
439500 | from math import floor, log2
from typing import (
Any,
Collection,
Dict,
Iterator,
Optional,
Sequence,
Set,
Tuple,
Union,
)
from pystiche import ComplexObject, loss
from pystiche.misc import zip_equal
from .level import PyramidLevel
from .storage import ImageStorage
__all__ = ["Im... |
439514 | from itertools import permutations
from cons import cons
from pytest import raises
from unification import reify, unify, var
from unification.core import _reify, stream_eval
from kanren import conde, eq, run
from kanren.constraints import (
ConstrainedState,
ConstrainedVar,
DisequalityStore,
isinstanc... |
439561 | from deap import base
from deap import creator
from deap import tools
import random
import numpy
import matplotlib.pyplot as plt
import seaborn as sns
import elitism
from static_pipelay import static_pipe_lay
# thetaPT = 0...5 # Angle of inclination of firing line from horizontal, [deg]
# LFL = 80...150 # Length... |
439605 | import os
from model.MCFT import MCFT
from model.SiameseStyle import SiameseStyle
from model.VGGishEmbedding import VGGishEmbedding
from data.TestDataset import TestDataset
from data.OtoMobile import OtoMobile
from log import get_logger
logger = get_logger('factory')
def model_factory(model_name, model_filepath):
... |
439619 | class Solution:
def maxSubArray(self, nums):
sm, mn, mx = 0, 0, -float("inf")
for num in nums:
sm += num
mx, mn = max(mx, sm - mn), min(mn, sm)
return mx |
439634 | import numpy as np
from scipy.interpolate import splev
import matplotlib
matplotlib.rcParams = matplotlib.rc_params_from_file('../../matplotlibrc')
from matplotlib import pyplot as plt
def basis_plot(n, k, res=401):
""" Plots some b-spline basis functions.
Uses same knot vector as the circle interpolation prob... |
439730 | from .gfpn import GFPN
from .bricks import build_brick, build_bricks
from .builder import build_decoder
|
439785 | from prompt_toolkit.styles import Style
from prompt_toolkit.utils import is_windows
def load_style():
"""
Return a dict mapping {ui_style_name -> style_dict}.
"""
if is_windows():
return Style.from_dict(win32_code_style)
else:
return Style.from_dict(default_ui_style)
default_ui_s... |
439787 | import numpy as np
import lcc.stars_processing.deciders.supervised_deciders as dec
from lcc.stars_processing.deciders.neuron_decider import NeuronDecider
def set_up():
deciders = [dec.AdaBoostDec(), dec.ExtraTreesDec(), dec.GaussianNBDec(), dec.LDADec(), dec.QDADec(),
dec.RandomForestDec... |
439809 | from kaldo.forceconstants import ForceConstants
from kaldo.phonons import Phonons
from kaldo.conductivity import Conductivity
import matplotlib.pyplot as plt
import ase.io
"""
Unit and regression test for the kaldo package.
"""
# Import package, test suite, and other packages as needed
from kaldo.forceconstants import... |
439843 | import logging
from logging import NullHandler
from .exceptions import InvalidSWAGDataException
logging.getLogger(__name__).addHandler(NullHandler())
|
439850 | import matplotlib.pyplot as plt
from wbml.plot import tweak
from stheno import B, Measure, GP, EQ
# Define points to predict at.
x = B.linspace(0, 10, 100)
with Measure() as prior:
f1 = GP(3, EQ())
f2 = GP(3, EQ())
# Compute the approximate product.
f_prod = f1 * f2
# Sample two functions.
s1, s2 =... |
439862 | import json
from datetime import datetime
import requests
from django.test import TestCase
from rest_framework import status
class TestDataReadWrite(TestCase):
def setUp(self):
self.writeUrl = "https://zuri.chat/data/write"
self.plugin_id = "123"
self.org_id = "123"
self.playlist... |
439873 | from textwrap import dedent
from rest_framework.schemas.openapi import AutoSchema
boilerplate = dedent("""\
Allows for logging into Tator as an anonymous user.
""")
class AnonymousGatewaySchema(AutoSchema):
def get_operation(self, path, method):
operation = super().get_operation(path, method)
if ... |
439874 | from util import next_software_num
def test_next_software_num_for_non_existing_user_1():
expected = 1
actual = next_software_num(vm_id='does-not-exist-1')
assert expected == actual
def test_next_software_num_for_non_existing_user_2():
expected = 1
actual = next_software_num(vm_id='does-not-exist-2... |
439884 | from datetime import datetime
from typing import Optional
from pydantic import ConstrainedStr, HttpUrl
from pydantic.types import NonNegativeInt
from app.schemas.addresses import AddressResponse
from app.schemas.base import BaseModel
from app.schemas.organizations import OrganizationResponse
class PostalCode(Constr... |
439890 | from typing import Optional
from confluent_kafka.cimpl import TIMESTAMP_NOT_AVAILABLE
from confluent_kafka.cimpl import Message as ConfluentKafkaMessage
from kafkian.serde.deserialization import Deserializer
class Message:
"""
Message is an object (log record) consumed from Kafka.
It provides read-only... |
439914 | def test_configuration_session(eos_conn):
eos_conn.register_configuration_session(session_name="scrapli_test_session1")
result = eos_conn.send_configs(
configs=["interface ethernet 1", "show configuration sessions"],
privilege_level="scrapli_test_session1",
)
eos_conn.close()
# pop t... |
439925 | from django.core.management import BaseCommand
from django.db.models import Q
from django.utils import timezone
from data.constants import RACE_UNKNOWN_STRINGS
from data.models import Victim, Complainant, Involvement, Officer
class Command(BaseCommand):
def handle(self, *args, **kwargs):
now = timezone.n... |
439930 | from ursinanetworking import *
Server = UrsinaNetworkingServer("localhost", 25565)
@Server.event
def changeName(client, new_name):
client.name = new_name
Server.broadcast("messageReceveid", f"{client.name} joined the chat !")
@Server.event
def onClientDisconnected(client):
Server.broadcast("messageReceve... |
439968 | import argparse
import os
import csv
import re
import sys
# default to importing from CorpusTools repo
base = os.path.dirname(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))
sys.path.insert(0,base)
from corpustools.corpus.io import load_binary
from corpustools.corpus.classes.lexicon import EnvironmentFi... |
440044 | from src.base_sample.core import Core
from multiprocessing import freeze_support, cpu_count
import argparse
import logging
if __name__ == '__main__':
freeze_support()
parser = argparse.ArgumentParser()
parser.add_argument("-m", "--mic_amount", type=int,
help="microphone amount")
... |
440048 | import torchvision
from torchvision import transforms
from uvcgan.torch.select import extract_name_kwargs
TRANSFORM_DICT = {
'center-crop' : transforms.CenterCrop,
'color-jitter' : transforms.ColorJitter,
'random-crop' : transforms.RandomCrop,
'random-flip-vertical' :... |
440051 | from time import time
from rdfframes.knowledge_graph import KnowledgeGraph
from rdfframes.client.http_client import HttpClientDataFormat, HttpClient
from rdfframes.client.sparql_endpoint_client import SPARQLEndpointClient
from rdfframes.utils.constants import JoinType
__author__ = "Ghadeer"
endpoint = 'http://10.161.... |
440055 | from SDLInterface import SDLInterface
import xml.etree.ElementTree as ElementTree
class InterfaceParser:
begin_tag = "<SDL_interface>"
end_tag = "</SDL_interface>"
def __init__(self, raw_string):
self.interface = None
begin_index = raw_string.find(InterfaceParser.begin_tag)
end_index = raw_string.rfind(... |
440078 | import os
os.environ['TF_CPP_MIN_LOG_LEVEL']='2'
# Create your first MLP in Keras
from keras.models import Sequential
from keras.layers import Dense
from keras.models import model_from_json
from keras.models import model_from_yaml
from sklearn.model_selection import train_test_split
from sklearn import metrics
impo... |
440081 | from ocd_backend.transformers import BaseTransformer
from ocd_backend.models import *
class MotionItem(BaseTransformer):
def transform(self):
source_defaults = {
'source': 'partijgedrag',
'supplier': 'gegevensmagazijn',
'collection': 'motion',
}
motion ... |
440100 | import copy
import numpy as np
import torch
from agent import CustomAgent
from generic import to_pt
class EnsembleAgent(CustomAgent):
def get_ranks_greedy(self, obs, infos, input_quest, input_quest_mask, quest_id_list, previous_commands, previous_dynamics, previous_belief):
with torch.no_grad():
... |
440112 | import os, sys, time, ipdb, argparse, cv2, scipy, skimage, glob
import torch
import torch.optim
from torch.autograd import Variable
import torch.nn as nn
from torchvision import models
import torch.nn.functional as F
import torchvision.transforms as transforms
# from torch.utils.data import Dataset, TensorDataset
fro... |
440148 | import torch
import os
import sys
import pickle
sys.path.append(os.path.abspath('../'))
import network_utils as networkUtils
import unittest
import nets as models
from constants import *
import copy
MODEL_ARCH = 'mobilenet'
INPUT_DATA_SHAPE = (3, 224, 224)
LOOKUP_TABLE_PATH = os.path.join('../models', MODEL_ARCH, 'lu... |
440152 | from flask import Flask
from flask_compress import Compress
from serverpanel.ext.serverinfo import ServerInfo
server_info = ServerInfo()
compress = Compress()
def create_app(config):
app = Flask(__name__)
app.config.from_object(config)
server_info.init_app(app)
compress.init_app(app)
from ser... |
440179 | import os
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import torch
import torchvision
import torchvision.transforms as transforms
import torch.nn as nn
import torch.nn.functional as F
import copy
import random
# https://github.com/facebookresearch/higher imported on Dec 2020
import higher
impor... |
440232 | import sys,os
def get_parent_path(level=1):
bundle_dir=os.path.abspath(__file__)
for i in range(1,level):
bundle_dir=os.path.dirname(bundle_dir)
return bundle_dir
|
440269 | from django.contrib import admin
from django.db.models import Model
from django.template.defaultfilters import pluralize
from djedi.admin import cms
def register(admin_class):
name = admin_class.verbose_name
name_plural = getattr(admin_class, 'verbose_name_plural', pluralize(name))
model = type(name, (Mo... |
440278 | def subplots(nrows=1, ncols=1, sharex=False, sharey=False, squeeze=True,
subplot_kw=None, hemisphere='lower', projection='equal_area',
**fig_kw):
"""
Identical to matplotlib.pyplot.subplots, except that this will default to
producing equal-area stereonet axes.
This prevents cons... |
440303 | import unittest
from unittest.mock import patch
from collections import OrderedDict
import datetime
import os
import multicorn
from google.cloud import bigquery
from ..bqclient import BqClient
from ..fdw import ConstantForeignDataWrapper
class Test(unittest.TestCase):
def setUp(self):
# Set options
... |
440330 | import theano
import theano.tensor as T
from scipy.io import loadmat
import numpy as np
from theano.tensor.slinalg import eigvalsh
def mcca_loss(N):
'''
N - number of modalities (>2)
D - dimension of each modality
main loss is wrapped into this function
'''
def inner_mcca_objective(y_true, y_pred):
D = y_pred.... |
440333 | import json
from pathlib import Path
from fastapi import FastAPI, Request
from fastapi.middleware.cors import CORSMiddleware
from fastapi.responses import RedirectResponse
app = FastAPI()
app.add_middleware(
CORSMiddleware,
allow_origins=["*"],
allow_methods=["*"],
allow_headers=["*"],
)
@app.get("/"... |
440374 | import torch
import torch.nn as nn
from Sublayers import FeedForward, MultiHeadAttention, Norm
import numpy as np
class EncoderLayer(nn.Module):
def __init__(self, d_model, heads, dropout=0.1):
super().__init__()
self.norm_1 = Norm(d_model)
self.norm_2 = Norm(d_model)
self.attn = M... |
440401 | import streamlit as st
IMAGE_URL = "https://images.unsplash.com/photo-1548407260-da850faa41e3?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&auto=format&fit=crop&w=1487&q=80"
st.image(IMAGE_URL, caption="Sunrise by the mountains")
st.write(
"""
#### Image credit:
Creator: User _<NAME> (@neil_ingham)_ from _Un... |
440402 | import torch.nn as nn
class Model_FS(nn.Module):
def __init__(self, basic_net):
super(Model_FS, self).__init__()
self.basic_net = basic_net
self.basic_net.eval()
def forward(self, inputs):
outputs, _ = self.basic_net(inputs)
return outputs |
440438 | from enum import Enum
class ParameterLocation(str, Enum):
"""The places Parameters can be put when calling an Endpoint"""
QUERY = "query"
PATH = "path"
HEADER = "header"
COOKIE = "cookie"
|
440441 | import sklearn
from sklearn.feature_selection import RFE
from sklearn.feature_selection import VarianceThreshold
from sklearn.svm import SVR
import textwrap
import argparse
import multiprocessing
import pandas as pd
import numpy as np
import h5py
import os,tqdm,pdb
from itertools import product
#from feature_selector i... |
440455 | import os
import numpy as np
from keras import metrics
from keras import backend as K
from keras.models import Model
from keras.layers import Input, Dense, Concatenate
from keras.callbacks import CSVLogger, ModelCheckpoint
from keras.utils import plot_model
from src.model.autoencoder import AutoEncoder
class AutoEnco... |
440459 | from distutils.core import setup
from setuptools import find_packages
setup(
name='Amipy',
version='1.0.0',
url='https://github.com/01ly/Amipy',
description='A micro asynchronous Python website crawler framework',
# long_description=open('README.md').read(),
author='linkin',
maintainer='li... |
440496 | import os
import numpy as np
import data_utils
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
class PartDatasetPCN:
def __init__(self, root, npoints=400, class_choice='Chair', split='train'):
self.npoints = npoints
self.cache = {} # caching the loaded parts
cat, meta = data_utils... |
440512 | from starlette.requests import Request
from streams_explorer.core.services.dataflow_graph import DataFlowGraph
def get_dataflow_graph(request: Request) -> DataFlowGraph:
return request.app.state.dataflow_graph
|
440517 | from setuptools import setup
setup(
name='spoofbuz',
version='1.0',
description='A library for spoofing the Qobuz web player',
author='DashLt',
packages=['spoofbuz'],
classifiers=['Programming Language :: Python :: 3',
]
)
|
440530 | from primehub import Helpful, cmd, Module
class Me(Helpful, Module):
@cmd(name='me', description='Get user information', return_required=True)
def me(self) -> dict:
"""
Get account information
:rtype: dict
:returns: account information
"""
query = """
... |
440577 | import boto3
import json
from datetime import datetime
from decimal import Decimal
HEADERS = {'Content-Type': 'application/json'}
dynamodb = boto3.resource('dynamodb')
table = dynamodb.Table('moodtracker_events')
def handler(event, context):
user_id = event['requestContext']['authorizer']['claims']['sub']
try:
... |
440604 | from torchtext.data import BucketIterator
import torch
def build(dataset, device, batch_size, is_train):
device = None if device is None else torch.device(device)
iterator = BucketIterator(
dataset=dataset,
batch_size=batch_size,
repeat=False,
sort_key=dataset.sort_key,
... |
440606 | def seq_search(lst, element):
pos = 0
found = False
while pos < len(lst) and not found:
if lst[pos] == element:
found = True
else:
pos += 1
return found
arr = [1,2,3,4,5,56]
print(seq_search(arr,3))
print(seq_search(arr,56))
print(seq_search(arr,1))
print(se... |
440620 | from typing import Any, Collection, List, Tuple, Union, Optional
from ..models.heap_object import HeapObject, RenderOptions
from ..models.options import Options
from ..models.unique_identifier import UniqueIdentifier
from .base_heap_object_factory import HeapObjectFactory
class SequenceHeapObjectFactory(HeapObjectFa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.