id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
198084 | import os
import numpy as np
import cv2
import albumentations
from PIL import Image
from torch.utils.data import Dataset
class SegmentationBase(Dataset):
def __init__(self,
data_csv, data_root, segmentation_root,
size=None, random_crop=False, interpolation="bicubic",
... |
198085 | from sparcur.utils import want_prefixes
import rdflib
import requests
mis = rdflib.Graph().parse(data=requests.get('https://cassava.ucsd.edu/sparc/exports/curation-export.ttl').content, format='turtle')
graph = mis
def reformat(ot):
return [ot.label if hasattr(ot, 'label') and ot.label else '', ot.curie]
objects ... |
198097 | from django.contrib import admin
from nonrelated_inlines.admin import NonrelatedStackedInline
from .models import Customer, Invoice
class CustomerInvoiceStackedInline(NonrelatedStackedInline):
model = Invoice
fields = [
'id',
'amount'
]
def get_form_queryset(self, obj):
retu... |
198120 | from __future__ import absolute_import
from maya import cmds
import logging
from . import maya
class Importer(maya.Importer):
display_name = 'Arnold'
plugin_name = 'mtoa.mll'
def __init__(self):
super(Importer, self).__init__()
@property
def attributes(self):
'''
materia... |
198124 | import time
from django.core.validators import MinValueValidator
from django.db import models
from django.urls import reverse
from django.utils.timezone import now
from django.utils.translation import ugettext_lazy as _
from jsonfield import JSONField
from model_utils.models import SoftDeletableModel
from jobboard.hel... |
198145 | import os
import numpy
from chainer_chemistry.dataset.preprocessors import preprocess_method_dict
from chainer_chemistry import datasets as D
from chainer_chemistry.datasets.numpy_tuple_dataset import NumpyTupleDataset
from rdkit import Chem
from tqdm import tqdm
import utils
class _CacheNamePolicy(object):
tr... |
198150 | import stripe.checkout
import anvil.server
import anvil.google.auth, anvil.google.drive
from anvil.google.drive import app_files
import anvil.tables as tables
import anvil.tables.query as q
from anvil.tables import app_tables
import anvil.users
__measurements = []
__user = None
__my_ave = None
def my_measurements():
... |
198192 | import asyncio
import tempfile
import unittest
from electrum_zcash import constants
from electrum_zcash.simple_config import SimpleConfig
from electrum_zcash import blockchain
from electrum_zcash.interface import Interface, ServerAddr
from electrum_zcash.crypto import sha256
from electrum_zcash.util import bh2u
from ... |
198233 | from tensorflow.keras.layers import Layer
# from keras.layers import Layer
import tensorflow as tf
from util_graphs import trim_padding_boxes, normalize_boxes, shrink_and_project_boxes
from losses import focal, iou
class MetaSelectInput(Layer):
def __init__(self, strides=(8, 16, 32, 64, 128), pool_size=7, **kwarg... |
198314 | from mock import MagicMock
import pytest
from six import string_types
from sqlalchemy.exc import OperationalError
from chainerui.database import db
from tests.helpers import assert_json_api
@pytest.fixture(autouse=True, scope='function')
def setup_mock_db():
# not setup database
db._initialized = True
m... |
198322 | class Solution:
def findSmallestSetOfVertices(self, n: int, edges: List[List[int]]) -> List[int]:
degree = [0] * n
for u, v in edges:
degree[v] = 1
return [i for i, d in enumerate(degree) if d == 0]
|
198358 | from pathlib import Path
import click
from lhotse.bin.modes.cli_base import cli
from lhotse.utils import Pathlike
@cli.command(name="validate")
@click.argument("manifest", type=click.Path(exists=True, dir_okay=False))
@click.option(
"--read-data/--dont-read-data",
default=False,
help="Should the audio/f... |
198366 | import tensorflow as tf
import tensorflow.contrib.layers as layers
from tensorflow.contrib.rnn import LSTMStateTuple
class LSTMCell(tf.contrib.rnn.BasicRNNCell):
def __call__(self, x, state, scope="LSTM"):
with tf.variable_scope(scope):
s_old, h_old = state
gates = layers.fully_con... |
198382 | import requests
url = "https://h5api.m.taobao.com/h5/mtop.alimama.union.sem.landing.pc.items/1.0/?jsv=2.4.0&appKey=12574478&t=1582716745850&sign=1b91fff529136fed287df8f0056cecd6&api=mtop.alimama.union.sem.landing.pc.items&v=1.0&AntiCreep=true&dataType=jsonp&type=jsonp&ecode=0&callback=mtopjsonp2&data=%7B%22keyword%22%... |
198417 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
import numpy as np
import math
import tqdm
from .temporal_transformer_windowed import tcn_unit_attention_block
from .temporal_transformer import tcn_unit_attention
from .gcn_attention import gcn_unit_attention
from .... |
198419 | import numpy as np
import sys
import os
sys.path.append(os.path.expanduser('~/darts/cnn'))
#from train_class import Train
OPS = ['max_pool_3x3',
'avg_pool_3x3',
'skip_connect',
'sep_conv_3x3',
'sep_conv_5x5',
'dil_conv_3x3',
'dil_conv_5x5'
]
NUM_VERTICES = 4
INP... |
198443 | import copy
import json
import unittest
from metagrok.pkmn.engine import core
update_with_request = core._update_with_request
get_side = core._get_side
postproc = core._postprocess_engine_state
class UpdateWithRequestTest(unittest.TestCase):
def test_begin(self):
state = copy.deepcopy(state_begin)
postproc... |
198457 | from isitfit.utils import logger
import click
from isitfit.cli.click_descendents import IsitfitCliError
import pandas as pd
class MigMan:
"""
Class that manages a local sqlite database to keep track of migrations that were already run
https://www.pythoncentral.io/introduction-to-sqlite-in-python/
"""
def ... |
198465 | from . import app
from . import command
from . import config
from . import models
from . import operations
__version__ = app.__version__
|
198469 | import numpy as np
import torch
import torch.nn.functional as F
from torch.autograd import Variable
def cross_entropy_2d(predict, target):
"""
Args:
predict:(n, c, h, w)
target:(n, h, w)
"""
assert not target.requires_grad
assert predict.dim() == 4
assert target.dim() == 3
... |
198481 | class ITypeHintingFactory(object):
def make_param_provider(self):
"""
:rtype: rope.base.oi.type_hinting.providers.interfaces.IParamProvider
"""
raise NotImplementedError
def make_return_provider(self):
"""
:rtype: rope.base.oi.type_hinting.providers.interfaces.I... |
198593 | from bson import json_util
from flask.json import JSONEncoder
from mongoengine.base import BaseDocument
from mongoengine.queryset import QuerySet
def _make_encoder(superclass):
class MongoEngineJSONEncoder(superclass):
"""
A JSONEncoder which provides serialization of MongoEngine
documents... |
198599 | from collections import Counter
from hippybot.decorators import botcmd
class Plugin(object):
"""HippyBot plugin to make the bot complete a wave if 3 people in a
row do the action "\o/".
"""
global_commands = ['\o/', 'wave']
command_aliases = {'\o/': 'wave'}
counts = Counter()
def __init__(... |
198603 | import pytest
import rasa.shared.nlu.training_data.lookup_tables_parser as lookup_tables_parser
def test_add_item_to_lookup_tables():
lookup_item_title = "additional_currencies"
lookup_examples = ["Peso", "Euro", "Dollar"]
lookup_tables = []
for example in lookup_examples:
lookup_tables_par... |
198610 | from pathlib import Path
from typing import Union
import os
import shutil
import requests
from fastprogress.fastprogress import progress_bar
import zipfile
PathOrStr = Union[Path,str]
LOCAL_PATH = Path.cwd()
DATA_PATH = Path.home()/'tmp'
UCR_LINK = 'http://www.timeseriesclassification.com/Downloads/Archives/Univariat... |
198621 | import setuptools
# Makes it easy for contributors to install user-facing dependencies.
reqs = []
with open('requirements.txt') as f:
for line in f:
if not line.strip().startswith('#'):
line = line.rstrip('\n')
reqs.append(line)
with open("README.md", "r") as fh:
long_descripti... |
198653 | from snips_nlu.dataset.dataset import Dataset
from snips_nlu.dataset.entity import Entity
from snips_nlu.dataset.intent import Intent
from snips_nlu.dataset.utils import (
extract_intent_entities, extract_utterance_entities,
get_dataset_gazetteer_entities, get_text_from_chunks)
from snips_nlu.dataset.validation... |
198664 | from typing import Iterable
class InfiniteIterator:
"""Infinitely repeat the iterable."""
def __init__(self, iterable: Iterable):
self._iterable = iterable
self.iterator = iter(self._iterable)
def __iter__(self):
return self
def __next__(self):
for _ in range(2):
... |
198667 | from celery import (
group,
signature,
)
from django.core.management.base import BaseCommand
from pontoon.base.models import Translation
from pontoon.checks import DB_FORMATS
from pontoon.checks.tasks import check_translations
class Command(BaseCommand):
help = "Run checks on all translations"
def ... |
198693 | from ixnetwork_restpy.base import Base
from ixnetwork_restpy.files import Files
class Dhcpv6Relay(Base):
__slots__ = ()
_SDM_NAME = 'dhcpv6Relay'
_SDM_ATT_MAP = {
'HeaderMessageType': 'dhcpv6Relay.header.messageType-1',
'HeaderHopCount': 'dhcpv6Relay.header.hopCount-2',
'HeaderLink... |
198713 | from datetime import date
from django.conf import settings
from django.contrib.auth.models import User
from django.test import TestCase
from django.utils.formats import localize
from django.utils.translation import activate
class SitemapTests(TestCase):
urls = 'django.contrib.sitemaps.tests.urls'
def setUp(s... |
198739 | import sys
from loguru import logger
from flexget import options
from flexget.event import event
from flexget.plugin import plugins
from flexget.terminal import console
logger = logger.bind(name='doc')
def trim(docstring):
if not docstring:
return ''
# Convert tabs to spaces (following the normal P... |
198804 | from django import forms
from django.core.exceptions import ValidationError
from django.core import validators
class BasicForm(forms.Form):
title = forms.CharField(validators=[
validators.MinLengthValidator(2, "Please enter 2 or more characters")
])
mileage = forms.IntegerField()
purchase_date ... |
198805 | from django import forms
from django.conf import settings
from crits.campaigns.campaign import Campaign
from crits.core.forms import (
add_bucketlist_to_form,
add_ticket_to_form,
SourceInForm)
from crits.core import form_consts
from crits.core.widgets import CalWidget
from crits.core.handlers import get_ite... |
198814 | r"""
Use this script to visualize the output of a trained speech-model.
Usage: python visualize.py /path/to/audio /path/to/training/json.json \
/path/to/model
"""
from __future__ import absolute_import, division, print_function
import argparse
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplo... |
198851 | from pathlib import Path
from PyFlow.Core.Common import *
from PyFlow.Core.NodeBase import NodePinsSuggestionsHelper
from common import DeviceNode
class PedestrianDetectionAdas2Node(DeviceNode):
def __init__(self, name):
super(PedestrianDetectionAdas2Node, self).__init__(name)
self.frame = self.c... |
198863 | import json
import requests
octopus_server_uri = 'https://your.octopus.app/api'
octopus_api_key = 'API-YOURAPIKEY'
headers = {'X-Octopus-ApiKey': octopus_api_key}
def get_octopus_resource(uri):
response = requests.get(uri, headers=headers)
response.raise_for_status()
return json.loads(response.content.de... |
198876 | import json
import boto3
from datetime import datetime, timedelta
from botocore.exceptions import ClientError
import os
import time
def get_message_for_slack(event_details, event_type, affected_accounts, affected_entities, slack_webhook):
message = ""
summary = ""
if slack_webhook == "webhook":
if... |
198900 | from django.core.paginator import EmptyPage, PageNotAnInteger, Paginator
from django.template.response import TemplateResponse
from wagtail.contrib.routable_page.models import RoutablePageMixin, route
from flags.state import flag_enabled
from v1.documents import FilterablePagesDocumentSearch
from v1.feeds import Fil... |
198931 | from pprint import pprint
from copy import deepcopy
import torch
import json
from tqdm import tqdm
# from nltk.tokenize import sent_tokenize
from collections import Counter, defaultdict
from .data import SlotFeatures
def sent_tokenize(text, start_pos):
"""TODO"""
import spacy
nlp = spacy.load("en_cor... |
198940 | import os
import sys
import numpy as np
import multiprocessing
# Import flags specifying dataset parameters
from flags import getFlags
def preprocess_data(start_index, data_count, data_dir, mesh_dir, soln_dir, RESCALE=True):
RESCALE = False
LORES = True
HIRES = False
for i in range(start_index, start... |
198947 | import os
import sys
import subprocess
from joblib import Parallel, delayed
import numpy as np
import imageio
imageio.plugins.freeimage.download()
from imageio.plugins import freeimage
import h5py
from lz4.block import decompress
import scipy.misc
import cv2
from path import Path
path = os.path.join(os.path.dirname(... |
198951 | import tensorflow as tf
from tensorflow.contrib.layers import fully_connected as fc
from tensorflow.examples.tutorials.mnist import input_data
from tensorflow.python.client import timeline
from tensorflow.python.profiler import model_analyzer
from tensorflow.python.profiler import option_builder
# 每次训练 1000 张
batch_si... |
198962 | from django.contrib.auth.models import Group, User
from django.db import models
from django.utils.translation import gettext_lazy as _l
# this import has to be here so that the signal handlers get registered
from qatrack.notifications.faults import handlers as faults_handlers # noqa: F401
from qatrack.notifications.f... |
198972 | import FWCore.ParameterSet.Config as cms
from Configuration.Eras.Era_$ERA_cff import *
process = cms.Process('CTPPSTest', $ERA)
# load config
import Validation.CTPPS.simu_config.year_$CONFIG_cff as config
process.load("Validation.CTPPS.simu_config.year_$CONFIG_cff")
# minimal logger settings
process.MessageLogger = ... |
199021 | import os
import unittest
from twined import Twine, exceptions
from .base import BaseTestCase
class TestTwine(BaseTestCase):
"""Testing operation of the Twine class"""
def test_init_twine_with_filename(self):
"""Ensures that the twine class can be instantiated with a file"""
Twine(source=os.... |
199042 | import asyncio
import bs4
import collections
import datetime
import discord
import time
import os
import subprocess
import win_unicode_console
from datetime import timedelta
from itertools import islice
from music.musicstate import MusicState
from music.playlist import Playlist
from utils.votes import ActionVotes
win... |
199063 | import os
from base64 import b64encode
from rdflib import *
import json
from io import StringIO
from whyis import nanopub
from whyis import autonomic
from whyis.test.agent_unit_test_case import AgentUnitTestCase
import unittest
class OntologyImportAgentTestCase(AgentUnitTestCase):
def test_foaf_import(self):
... |
199095 | from CyberSource import *
import os
import json
from importlib.machinery import SourceFileLoader
config_file = os.path.join(os.getcwd(), "data", "Configuration.py")
configuration = SourceFileLoader("module.name", config_file).load_module()
# To delete None values in Input Request Json body
def del_none(d):
for ke... |
199145 | from prompt_toolkit.styles import style_from_dict
from pygments.token import Token
TABLE_JOB_MODEL = [['Spider', 'Started Time', 'Items', 'Tags', 'State', 'Close Reason', 'Errors', 'Version']]
TABLE_JOBS_MODEL = [['Id', 'Spider', 'Started Time', 'Items', 'Tags', 'State', 'Close Reason', 'Errors', 'Version']]
HC_TABL... |
199156 | import sys, os, tempfile, shutil
from PIL import Image
import util
import subprocess
'''
TOOL_PATH = os.path.join( os.path.dirname( __file__ ), "../../../../../../tools/bin" )
TEXTURE_CONVERTER = os.path.abspath( os.path.join( TOOL_PATH, "TextureConverter.exe" ) )
def Convert( src_filenames, dest_filename, t... |
199176 | from alpa.collective.collective import (
nccl_available, gloo_available, is_group_initialized, init_collective_group,
destroy_collective_group, create_collective_group, get_rank,
get_collective_group_size, allreduce, allreduce_multigpu, barrier, reduce,
reduce_multigpu, broadcast, broadcast_partialgpu, ... |
199180 | import inspect
from pathlib import Path
from unittest.mock import Mock
import parso
from test_pkg import functions
import pytest
from ploomber.util import dotted_path
from ploomber.exceptions import SpecValidationError
from ploomber.sources.inspect import getfile
@pytest.mark.parametrize('spec', [
'test_pkg.fun... |
199259 | from operator import itemgetter
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import matplotlib
from openreview_matcher.evals import base_evaluator
from openreview_matcher import utils
matplotlib.style.use('ggplot')
class Evaluator(base_evaluator.Evaluator):
"""
An Evaluator instan... |
199290 | import unittest
import io
from svgelements import *
class TestElementShape(unittest.TestCase):
def test_rect_dict(self):
values = {
'tag': 'rect',
'rx': "4",
'ry': "2",
'x': "50",
'y': "51",
'width': "20",
... |
199313 | from itertools import groupby
import django
from django import template
register = template.Library()
class DynamicRegroupNode(template.Node):
"""
Extends Django's regroup tag to accept a variable instead of a string literal
for the property you want to regroup on
"""
def __init__... |
199317 | import uuid
try:
from django_mongoengine import Document
except ImportError:
from mongoengine import Document
from mongoengine import StringField, UUIDField, BooleanField
from mongoengine import EmbeddedDocument
from django.conf import settings
from crits.core.crits_mongoengine import CritsBaseAttributes
from crit... |
199408 | import oe.path
from oeqa.selftest.case import OESelftestTestCase
from oeqa.utils.commands import bitbake
from oeqa.core.decorator.oeid import OETestID
class Fetch(OESelftestTestCase):
@OETestID(1058)
def test_git_mirrors(self):
"""
Verify that the git fetcher will fall back to the HTTP mirrors.... |
199430 | import rpy2_R6.r6b as r6b
import rpy2_arrow.pyarrow_rarrow as pyr
import rpy2.rinterface as rinterface
import rpy2.robjects
import rpy2.robjects.conversion
# Python proxies for the R6 class factories
array_factory = r6b.R6DynamicClassGenerator(pyr.rarrow.Array)
recordbatch_factory = r6b.R6DynamicClassGenerator(pyr.rar... |
199460 | import sys
def main():
cnt = 0
f_cnt = 0
input_file = sys.argv[1]
output_prefix = sys.argv[2]
chunk_size = int(sys.argv[3])
f_ov = open(f'{output_prefix}.valid.txt', 'w', encoding='utf-8')
f_ot = None
with open(input_file, 'r', encoding='utf-8') as f_in:
for line in f_in:
... |
199513 | from analizer.abstract import instruction
from analizer.typechecker.Metadata import File
from analizer.typechecker.Metadata import Struct
from analizer.reports.Nodo import Nodo
class AlterIndex(instruction.Instruction):
def __init__(self, name, exists, newName, row, column, idOrNumber=None):
instruction.In... |
199514 | import ee
import geemap
# Create a map centered at (lat, lon).
Map = geemap.Map(center=[40, -100], zoom=4)
dataset = ee.ImageCollection('JRC/GSW1_1/YearlyHistory') \
.filter(ee.Filter.date('2015-01-01', '2015-12-31'))
waterClass = dataset.select('waterClass')
waterClassVis = {
'min': 0.0,
'max'... |
199658 | import unittest
from unittest.mock import MagicMock, patch
from conjur import Client
from conjur.errors import MissingRequiredParameterException
from conjur.controller.host_controller import HostController
from conjur.data_object.host_resource_data import HostResourceData
from conjur.resource import Resource
class H... |
199664 | from flask import request, jsonify, make_response, current_app
import base64
import os
import redis
import uuid
# Find the stack on which we want to store the database connection.
# Starting with Flask 0.9, the _app_ctx_stack is the correct one,
# before that we need to use the _request_ctx_stack.
try:
from flask ... |
199682 | import re
from collections import deque
from contextlib import closing
from cStringIO import StringIO
from flanker.mime.message.headers.parsing import parse_stream
from flanker.mime.message.headers import MimeHeaders
def detect(message):
headers = collect(message)
return Result(
score=len(headers) / f... |
199715 | def fib(n):
'''
uses generater to return fibonacci sequence
up to given # n dynamically
'''
a,b = 1,1
for _ in range(0,n):
yield a
a,b = b,a+b
return a
|
199740 | from enum import IntEnum
import attr
import pytest
from cattr import Converter, GenConverter, UnstructureStrategy
class E(IntEnum):
ONE = 1
TWO = 2
@attr.define
class C:
a: int
b: float
c: str
d: bytes
e: E
f: int
g: float
h: str
i: bytes
j: E
k: int
l: floa... |
199779 | from azure.iot.device.aio import IoTHubDeviceClient, ProvisioningDeviceClient
from azure.iot.device import MethodResponse, Message
import smbus2, bme280, os, asyncio, json, time
from grove.grove_moisture_sensor import GroveMoistureSensor
from dotenv import load_dotenv
from grove.grove_light_sensor_v1_2 import GroveLigh... |
199818 | from gmusicapi._version import __version__
from gmusicapi.clients import Webclient, Musicmanager, Mobileclient
from gmusicapi.exceptions import CallFailure
__copyright__ = 'Copyright 2018 <NAME>'
__license__ = 'BSD 3-Clause'
__title__ = 'gmusicapi'
# appease flake8: the imports are purposeful
(__version__, Webclient,... |
199829 | import time
import torch.backends.cudnn as cudnn
import torch.optim
import torch.utils.data
from nets.deepdsod_model import DSOD
from loss import MultiBoxLoss
from datasets.dsod_dataset import mydateset
from os.path import exists
from utils import *
# {'car': 1, 'person': 2, 'truck': 3, 'bus': 4, 'rider': 5, 'rear': 6,... |
199875 | import copy
from matplotlib import cm
import matplotlib.colors
import numpy as np
import hexrd.ui.constants
from hexrd.ui.brightness_contrast_editor import BrightnessContrastEditor
from hexrd.ui.hexrd_config import HexrdConfig
from hexrd.ui.ui_loader import UiLoader
from hexrd.ui.utils import block_signals
class C... |
199886 | from .build_features_matrix import build_matrix, load_dataset, load_matrix
from .clustering_algo import ClusteringAlgo, ClusteringAlgoSparse
from .eval import general_statistics, cluster_event_match, mcminn_eval |
199921 | import datetime
from google.appengine.ext import ndb
class ExportTask(ndb.Model):
blob_key = ndb.BlobKeyProperty()
total_posts = ndb.IntegerProperty(default=0)
total_photos = ndb.IntegerProperty(default=0)
exported_posts = ndb.IntegerProperty(default=0)
exported_photos = ndb.IntegerProperty(default=0)
created =... |
199934 | from typing import Dict
import pandas as pd
from abm1559.config import rng
from abm1559.utils import (
get_basefee_bounds,
)
from abm1559.txs import (
Tx1559,
TxFloatingEsc
)
class User:
"""
Users submit transactions. They have a (randomly chosen) value per Gwei :math:`v`, (we choose per Gwei s... |
199954 | from pebl.test import testfile
from pebl import data, result
from pebl.learner import simanneal
class TestGreedyLearner:
def setUp(self):
self.data = data.fromfile(testfile('testdata5.txt'))
self.data.discretize()
def test_default_params(self):
s = simanneal.SimulatedAnnealingLearner(s... |
199956 | from orbit.models.ktrlite import KTRLite
import pandas as pd
import numpy as np
import math
from scipy.stats import nct
from enum import Enum
import torch
import matplotlib.pyplot as plt
from copy import deepcopy
from ..constants.constants import (
KTRTimePointPriorKeys,
PredictMethod,
TrainingMetaKeys,
... |
1600051 | import logging
from logging import (
Logger,
)
from dependency_injector.wiring import (
Provide,
)
from src.queries.models import (
Cart,
)
from src.queries.repository import (
CartQueryRepository,
)
from minos.aggregate import (
Event,
)
from minos.cqrs import (
QueryService,
)
from minos.net... |
1600057 | def co_code_findloadednames(co):
"""Find in the code of a code object, all loaded names.
(by LOAD_NAME, LOAD_GLOBAL or LOAD_FAST) """
import dis
from opcode import HAVE_ARGUMENT, opmap
hasloadname = (opmap['LOAD_NAME'],
opmap['LOAD_GLOBAL'], opmap['LOAD_FAST'])
insns = dis.ge... |
1600065 | from typing import Optional
from aiogrpcclient import BaseGrpcClient
from idm.api.proto.chat_manager_service_pb2 import Chat as ChatPb
from nexus.hub.proto.delivery_service_pb2 import \
StartDeliveryRequest as StartDeliveryRequestPb
from nexus.hub.proto.delivery_service_pb2 import \
StartDeliveryResponse as St... |
1600096 | from .utils import *
from .cat import build_model
from .dataset import build_loader
from .config import get_config
from .optimizer import build_optimizer
from .lr_scheduler import build_scheduler
from .logger import create_logger
|
1600124 | from __future__ import absolute_import, division, print_function
import os
import re
import pickle
import warnings
import numpy as np
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from rlssm import plotting
from .utils import list_individual_variables
from .stan_utility import check_all_diag... |
1600165 | from rtamt.node.node import Node
class UnaryNode(Node):
def __init__(self, child):
"""Constructor for Node"""
super(Node, self).__init__()
self.add_child(child)
|
1600180 | from peewee import (
IntegerField,
BooleanField,
FloatField,
CharField,
Model
)
# This table exists because we fetch _all_ shot_chart_detail records,
# even if the game doesn't exist in the game table. So, we stage all
# records in this temporary table, then insert into the main table
# filtering b... |
1600192 | from selenium import webdriver
from selenium.webdriver.common.by import By
from utilities.handy_wrappers import HandyWrappers
import time
class DynamicXPathFormat():
def test(self):
baseUrl = "https://letskodeit.teachable.com"
driver = webdriver.Firefox()
driver.maximize_window()
... |
1600204 | import sys
import os
def check_acc(file_gt, file_pred):
def parse_line(line):
line_split = line.split()
flag = True
parse_dict = {}
if 'SELECT' in line_split and \
line_split.index('SELECT') != 0:
flag = False
if 'SELECT' in line_split:
pos = None
if 'WHERE' in line_split:
pos = line_s... |
1600216 | from openstatesapi.jurisdiction import make_jurisdiction
J = make_jurisdiction('nj')
J.url = 'http://state.nj.us'
|
1600222 | from datetime import timedelta
BROKER_HOST = "localhost"
BROKER_PORT = 5672
BROKER_USER = "myuser"
BROKER_PASSWORD = "<PASSWORD>"
BROKER_VHOST = "myvhost"
CELERY_RESULT_BACKEND = "amqp"
CELERY_AMQP_TASK_RESULT_EXPIRES = 300
CELERY_IMPORTS = ("testapp.tasks", )
CELERY_ROUTES = ("testapp.process_router.ProcessRouter",)
... |
1600249 | df14 = h2o.H2OFrame.from_python(
{'D': ['18OCT2015:11:00:00',
'19OCT2015:12:00:00',
'20OCT2015:13:00:00']},
column_types=['time'])
df14.types
# {u'D': u'time'} |
1600255 | import torch
import torch.nn as nn
import torch.nn.functional as F
class BlurPool2d(nn.Sequential):
"""Blur Pooling Layer (MaxPool2d replacement)
See: https://richzhang.github.io/antialiased-cnns/
Paper: https://arxiv.org/abs/1904.11486
"""
__constants__ = ["in_features"]
_blur_kernel = torch... |
1600269 | import Core
info = {
"friendly_name": "Recent Changes List",
"example_template": "changecount",
"summary": "Inserts a description of recent Wiki activity.",
"details": """
<p>If 'changecount' is omitted, all changes recorded since the
current server was started are printed; otherwise, the list... |
1600274 | from django.db import models
# Create your models here.
class Category(models.Model):
name = models.CharField(max_length=255)
parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True)
last_modified = models.DateTimeField(auto_now=True)
def __str__(self):
if self.par... |
1600282 | import math
import random
import csv
import numpy as np
""""Functions used by build_l4.py"""
def lerp(v0, v1, t):
return v0 * (1.0 - t) + v1 * t
def distance_weight(delta_p, w_min, w_max, r_max):
r = np.linalg.norm(delta_p)
if r >= r_max:
return 0.0
else:
return lerp(w_max, w_min, r... |
1600322 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from .resnet_embedding import ResNet50
from .resnet_embedding import ResNet101
from .resnet_embedding import ResNet152
from .resnext_vd_embedding import ResNeXt50_vd_32x4d
from .resnext_vd_embedding import ResNe... |
1600358 | class Solution:
def longestBeautifulSubstring(self, word: str) -> int:
cnt = 1
start = res = 0
for i, (prev, cur) in enumerate(zip(word, word[1:]), 1):
if cur < prev:
cnt = 1
start = i
elif cur > prev:
cnt += 1
... |
1600409 | from django.core.exceptions import ObjectDoesNotExist
from mozdns.views import MozdnsCreateView
from mozdns.views import MozdnsDeleteView
from mozdns.views import MozdnsDetailView
from mozdns.views import MozdnsListView
from mozdns.views import MozdnsUpdateView
from mozdns.ptr.forms import PTRForm
from mozdns.ptr.mode... |
1600436 | import os
import dash_html_components as html
import dash_core_components as dcc
from dash.dependencies import Input, Output
import dash_bio
import pandas as pd
import numpy as np
import math
import plotly.graph_objects as go
from layout_helper import run_standalone_app
text_style = {"color": "#506784", "font-family"... |
1600459 | from django.contrib.auth import get_user_model
from django.contrib.sites.models import Site
from django_dynamic_fixture import G
from django_webtest import WebTest
from fluent_pages.models import PageLayout
from fluent_pages.pagetypes.fluentpage.models import FluentPage
from . import descriptors
from icekit.utils impo... |
1600472 | import collections
import copy
import six
import chainer
from chainer import configuration
from chainer.dataset import convert
from chainer.dataset import iterator as iterator_module
from chainer import function
from chainer import link
from chainer import reporter as reporter_module
from chainer.training import exte... |
1600474 | import os
import tempfile
import unittest
import logging
from pyidf import ValidationLevel
import pyidf
from pyidf.idf import IDF
from pyidf.controllers import ControllerWaterCoil
log = logging.getLogger(__name__)
class TestControllerWaterCoil(unittest.TestCase):
def setUp(self):
self.fd, self.path = tem... |
1600488 | from os import system
import time
import conexion as conn
db = conn.DB()
system("clear")
def create():
name = str(input("INGRESA SU NOMBRE: "))
email = str(input("INGRESA SU EMAIL: "))
if(len(name) > 0 and len(email) > 0):
sql = "INSERT INTO sistema(name,email) VALUES(?,?)"
parametros = (na... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.