id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
443101 | import numpy as np
import pandas as pd
import pytest
from numpy.testing import assert_array_equal
from cforest.tree import _compute_global_loss
from cforest.tree import _compute_valid_splitting_indices
from cforest.tree import _find_optimal_split
from cforest.tree import _find_optimal_split_inner_loop
from cforest.tre... |
443102 | import bisect
import datetime
import itertools
from gopro_overlay.entry import Entry
def pairwise(iterable): # Added in itertools v3.10
"s -> (s0,s1), (s1,s2), (s2, s3), ..."
a, b = itertools.tee(iterable)
next(b, None)
return zip(a, b)
class Timeseries:
def __init__(self, entries=None):
... |
443125 | from sp_api.api import ListingsRestrictions
def test_listing_restrictions():
res = ListingsRestrictions().get_listings_restrictions(sellerId='A3F26DF64ZIPJZ', asin='B07HRD6JKK')
assert res('restrictions') is not None
assert isinstance(res('restrictions'), list)
|
443151 | import json
from e2e.Classes.Merit.Merit import Merit
from e2e.Vectors.Generation.PrototypeChain import PrototypeBlock, PrototypeChain
proto: PrototypeChain = PrototypeChain(9, False)
merit: Merit = Merit.fromJSON(proto.finish().toJSON())
merit.add(PrototypeBlock(merit.blockchain.blocks[-1].header.time + 1200).finis... |
443202 | from __future__ import division
from __future__ import print_function
import argparse
import os
import pickle
import sys
# sys.path.append(".")
import numpy as np
from dss_vae.structs.dataset import Dataset
from dss_vae.structs.vocab import Vocab
from dss_vae.structs.vocab import VocabEntry
def data_details(train_... |
443207 | import cv2
import matplotlib.pyplot as plt
import numpy as np
def read_cv2_img(path):
'''
Read color images
Args:
path: Path to image
return:
Only returns color images
'''
img = cv2.imread(path, -1)
if img is not None:
if len(img.shape) != 3:
return... |
443208 | from typing import List, Optional
import numpy as np
from l5kit.data.filter import filter_agents_by_labels, filter_agents_by_track_id
from l5kit.geometry import rotation33_as_yaw
from l5kit.rasterization.render_context import RenderContext
from l5kit.rasterization.box_rasterizer import get_ego_as_agent, draw_boxes, B... |
443222 | import torch
from mmcls.models.classifiers import ImageClassifier
def test_repvgg():
g4_map = {l: 4 for l in [2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26]}
model_cfg = dict(backbone=dict(
type='RepVGG',
num_classes=1000,
num_blocks=[4, 6, 16, 1],
width_multiplier=[2.5, 2.5, ... |
443227 | import argparse
import wandb
from deepform.common import MODEL_DIR, WANDB_PROJECT
if __name__ == "__main__":
parser = argparse.ArgumentParser(description="download a model stored in W&B")
parser.add_argument(
"-v",
"--version",
dest="version",
help="model version to download",... |
443269 | from __future__ import division, print_function, absolute_import
import sys
import numpy as np
COLORS = dict(
black='0;30',
darkgray='1;30',
red='1;31',
green='1;32',
brown='0;33',
yellow='1;33',
blue='1;34',
purple='1;35',
cyan='1;36',
white='1;37',
reset='0'
)
COLORIZE =... |
443287 | import datetime
from dataclasses import dataclass
from .constant import *
@dataclass
class BarData:
"""
Candlestick bar data of a certain trading period.
"""
symbol: str
exchange: Exchange
datetime: datetime
interval: Interval = None
volume: float = 0
open_interest: float = 0
... |
443292 | from u2flib_server.utils import websafe_decode
from u2flib_server.model import (JSONDict, RegistrationData, SignatureData,
U2fRegisterRequest, U2fSignRequest)
from binascii import b2a_hex
import unittest
SAMPLE_REG_DATA = websafe_decode(
'BQRFJ5xApW6uBsuSJ_FgUcL-seKecha71q8evgqfQw... |
443296 | from azureml.core import Workspace
import os
import sys
subscription_id = os.environ.get("SUBSCRIPTION_ID", "<subscription_id>")
resource_group = os.environ.get("RESOURCE_GROUP", "tensorflow101")
workspace_name = os.environ.get("WORKSPACE_NAME", "tensorflow101-mlwrksp")
workspace_region = os.environ.get("WORKSPACE_REG... |
443331 | import csv
import json
from datetime import datetime
from decimal import Decimal
from pathlib import Path
from typing import Dict, List, Tuple, Union
from sqlalchemy.orm.session import Session
from reporter.database.model import Close, Price
class RICInfo:
def __init__(self,
description: str,
... |
443349 | import re
from drf_spectacular.openapi import AutoSchema
class PeeringManagerAutoSchema(AutoSchema):
"""
Subclass of Spectaclar's `AutoSchema` to support bulk operations.
"""
def get_operation_id(self):
tokenized_path = self._tokenize_path()
# replace dashes as they can be problemati... |
443434 | import unittest
import torch
from butterfly_factor import butterfly_factor_mult, butterfly_factor_mult_intermediate
from butterfly import Block2x2DiagProduct
from complex_utils import complex_mul
from factor_multiply import butterfly_multiply_intermediate, butterfly_multiply_intermediate_backward
def twiddle_list_... |
443484 | from compas.geometry import Circle
# These imports are used to check __repr__.
from compas.geometry import Plane # noqa: F401
from compas.geometry import Point # noqa: F401
from compas.geometry import Vector # noqa: F401
def test_circle():
point = [0, 0, 0]
vector = [1, 0, 0]
plane = (point, vector)
... |
443495 | import atexit
import signal
import sys
from threading import Timer
import pkg_resources
import sqlite3
from flask import Flask
from . import config
from . import utils
from .apputils import mx_request
def run_sql(filename):
conn = sqlite3.connect(config.db_name)
c = conn.cursor()
cmds = pkg_resources.re... |
443499 | from coverage.control import Coverage
from coveralls.report import CoverallsReporter
class coveralls(Coverage):
def coveralls(self, base_dir, ignore_errors=False, merge_file=None):
reporter = CoverallsReporter(self, self.config)
reporter.find_file_reporters(None)
return reporter.report(bas... |
443531 | from abc import ABC, abstractmethod
from pprint import pformat
from syndicate.core.resources.helper import filter_dict_by_shape
class AbstractExternalResource(ABC):
@abstractmethod
def define_resource_shape(self):
pass
@abstractmethod
def describe_meta(self, name):
pass
def comp... |
443573 | import unittest
from marqeta.errors import MarqetaError
from tests.lib.client import get_client
class TestUsersNotesSave(unittest.TestCase):
"""Tests for the users.notes.save endpoint."""
@classmethod
def setUpClass(cls):
"""Setup for all the tests in the class."""
cls.client = get_clien... |
443586 | import operator
from phidl.quickplotter import _get_layerprop
def write_lyp(filename, layerset):
""" Creates a KLayout .lyp Layer Properties file from a set of
PHIDL layers """
stipple_default = ['I2','I5','I9','I17','I19','I22','I33','I38']
stipple_count = 0
if filename[-4:] != '.lyp': filename =... |
443613 | import pytest
import six
from dbnd import dbnd_config, relative_path
from dbnd.testing.helpers import run_test_notebook
from dbnd.testing.helpers_pytest import assert_run_task
from dbnd_examples.data import data_repo, dbnd_examples_data_path
from dbnd_examples.orchestration.examples import wine_quality
from dbnd_examp... |
443633 | import unittest
import logging
from hearthstone.simulator.core import player
class BattleGroundsTestCase(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
logging.basicConfig(level=logging.DEBUG)
player.TEST_MODE = True |
443644 | from django.conf.urls import url
from .views import (
checkout_address_create_view,
checkout_address_reuse_view,
AddressListView,
AddressUpdateView,
AddressDeleteView,
AddressCreateView
)
urlpatterns = [
url(r'^checkout/create/$', checkout_address_create_view, ... |
443650 | def load_setting(key):
# Just some dummy values for demo
if key == 'key':
return '123123'
elif key == 'limit':
return 123123
elif key == 'dummylist':
return [1, 2, 3, 4, 5]
elif key == 'crap':
return {'good': "boy"}
def superlazy(key, default):
class T(type(defau... |
443674 | import logging
import xml.etree.ElementTree as ET
import base64
from remotepspy.psrp import PSRPParser
class SimpleCommandTracer:
"""A simple PowerShell tracer that attempts to print (and log, if enabled) commands and their output. Does not
support every possible use case fully, but attempts to cove... |
443699 | import pytest
import tempfile
import uuid
import os
import shutil
import responses
import click
from gigantumcli.server import ServerConfig
@pytest.fixture
def server_config():
"""Fixture to create a Build instance with a test image name that does not exist and cleanup after"""
unit_test_working_dir = os.pat... |
443704 | class Solution:
def maximumProduct(self, nums: List[int]) -> int:
min1 = min2 = inf
max1 = max2 = max3 = -inf
for n in nums:
if n < min1:
min2, min1 = min1, n
elif n < min2:
min2 = n
if n > max1:
max3, max2... |
443833 | from django.contrib import admin
from django.contrib.auth.models import User
from django.contrib.auth.admin import UserAdmin
from django.db import models
from systems.models import UserProfile
class UserProfileInline(admin.StackedInline):
model = UserProfile
class InvUserAdmin(UserAdmin):
filter_horizon... |
443836 | import urllib
import numpy as np
import torch
from archived.s3 import put_object
from archived.sync import merge_np_bytes
# lambda setting
tmp_bucket = "tmp-grads"
def handler(event, context):
bucket = event['Records'][0]['s3']['bucket']['name']
key = urllib.parse.unquote_plus(event['Records'][... |
443837 | from importlib import import_module
from django.urls import reverse
from django.shortcuts import _get_queryset
def import_model(path_or_callable):
if hasattr(path_or_callable, '__call__'):
return path_or_callable
else:
assert isinstance(path_or_callable, str)
package, attr = path_or_ca... |
443851 | PROG_NAME = "MTSv"
VERSION = "2.0.0"
DEFAULT_CFG_FNAME = "mtsv.cfg"
DEFAULT_LOG_FNAME = "mtsv_{COMMAND}_{TIMESTAMP}.log"
CONFIG_STRING = """
# NOTE: Changes to the config file in the middle of the pipeline
# may force previous steps to be rerun.
#
# ===============================================================
#
... |
443852 | from aws_cdk import (
core,
aws_ec2 as ec2,
aws_ecs as ecs,
aws_events as events,
aws_events_targets as events_targets,
aws_ecs_patterns as ecs_patterns,
aws_logs as logs,
aws_cloudformation as cloudformation,
aws_cloudwatch as cw,
aws_applicationautoscaling as aas,
)
class Cel... |
443868 | import fingerprint as fp
import db
import soundfile as sf
import taglib
import hashlib
import os
import glob
import sys
def convert_to_mono(sig):
if len(sig.shape) > 1:
return fp.np.mean(sig, axis=1)
return sig
def read_audiofile(filename):
# get tags
song = taglib.File(filename)
print(... |
443877 | from django.db import models
class Spammable(models.Model):
spam_flag = models.ManyToManyField("SpammyPosting")
class Meta:
abstract = True
|
443985 | from django.urls import include, path
from rest_framework import routers
from .views import Events, CMSDetail, CMSList, ChannelDeserializer
from .viewsets import ChannelViewset, ChatTypeViewset
router = routers.DefaultRouter()
router.register(r"channels", ChannelViewset, base_name="slackchat-channel")
router.register... |
444029 | import gym
import pandas as pd
import datetime
from recogym.agents import OrganicUserEventCounterAgent, organic_user_count_args
from recogym import build_agent_init
from recogym.agents import Agent
from recogym import Configuration
from recogym import (
gather_agent_stats,
AgentStats
)
from recogym import env_1... |
444056 | def test_i8():
i: i8
i = 5
print(i)
def test_i16():
i: i16
i = 4
print(i)
def test_i32():
i: i32
i = 3
print(i)
def test_i64():
i: i64
i = 2
print(i)
|
444059 | import numpy as np
import pygsti.algorithms.fiducialselection as fs
import pygsti.circuits as pc
from . import fixtures
from ..util import BaseCase
class FiducialSelectionUtilTester(BaseCase):
def test_build_bitvec_mx(self):
mx = fs.build_bitvec_mx(3, 1)
# TODO assert correctness
class Fiducial... |
444214 | import os
import time
import argparse
import threading
import grpc
import tensorflow as tf
from tensorflow_serving.apis import predict_pb2
from tensorflow_serving.apis import prediction_service_pb2_grpc
class Benchmark(object):
"""
num_requests: Number of requests.
max_concurrent: Maximum number of concurr... |
444217 | from pathlib import Path
import cdms2
datapath = (
"/p/user_pub/e3sm/zhang40/analysis_data_e3sm_diags/TRMM/climatology_diurnal_cycle/"
)
for path in Path(datapath).rglob("*.nc"):
print(path.name)
print(path)
filename = path.name.split("/")[-1]
print(filename)
# filename ='TRMM-3B43v-7_3hr_ANN... |
444250 | import numpy as np
import scipy.signal
def reclassify(array, class_dict):
"""Reclassifies values in a ndarray according to the rules provided in class_dict.
:param array: Array that holds categorical class values. (ndarray).
:param class_dict: Dictionary that maps input class values to output class value... |
444295 | import socket
from multiprocessing.pool import ThreadPool
from time import sleep
import six
from kombu import Connection, Consumer, Queue
from kombu.exceptions import MessageStateError
from kombu.utils import nested
from microservices.helpers.logs import InstanceLogger
from microservices.utils import get_logger
_log... |
444344 | from OpenNero import *
from random import seed
# add the key and mouse bindings
from inputConfig import *
# add network utils
from common import *
from module import getMod, delMod
### called from gui elements ############################
def toggle_ai_callback(pauseButton):
""" pause and resume all AI age... |
444444 | import json
from datetime import timedelta
from django.core import mail
from django.test import TestCase
from django.utils import timezone
from mock import Mock
from job_runner.apps.job_runner.management.commands.health_check import Command
from job_runner.apps.job_runner.models import Run, Worker
class CommandTest... |
444447 | import unittest
from api.app import app
import json
class TestAPI(unittest.TestCase):
def test_vincinv(self):
query = {
'lat1': -37.57037203,
'lon1': 144.25295244,
'lat2': -37.39101561,
'lon2': 143.5535383,
'from_angle_type': 'dms',
'... |
444497 | import csv
class Parser:
def __init__(self, ):
self.clusters = {}
def read_expression_clusters(self, network_file, cluster_file):
"""
Reads hrr and hcca file from the original PlaNet pipeline
ids are based on line number starting with 0 !
:param network_file: path to... |
444527 | import terrascript
import terrascript.provider
import terrascript.resource
config = terrascript.Terrascript()
# AWS provider
config += terrascript.provider.aws(region="us-east-1")
# Define Variable and add to config
v = terrascript.Variable("image_id", type="string")
config += v
# Define AWS EC2 instance and add to... |
444529 | from gbvision.utils.net import AsyncStreamReceiver
from .udp_stream_receiver import UDPStreamReceiver
class AsyncUDPStreamReceiver(AsyncStreamReceiver, UDPStreamReceiver):
def __init__(self, port, *args, **kwargs):
UDPStreamReceiver.__init__(self, port, *args, **kwargs)
AsyncStreamReceiver.__init... |
444533 | from torch import nn
import torch.nn.functional as F
class mini_xception(nn.Module):
def __init__(self):
super(mini_xception,self).__init__()
self.num_channels=1
self.image_size=48
self.num_labels=7
self.conv2d_1 =nn.Conv2d(in_channels=46,out_channels=8,kernel_size=3,stride=... |
444583 | import random
START = 0
STOP = 9999
max_num = 100
comparisons = 0
swaps = 0
def bubble_sort(numbers):
global comparisons
global swaps
n = len(numbers)
for i in range(n):
for j in range(0, n-i-1):
if numbers[j] > numbers[j+1] :
numbers[j], numbers[j+1] = numbers[j+1], numbers[j]
swaps += 1
co... |
444661 | from collections import Counter
from unittest import TestCase
from mab_ranking.bandits.bandits import BetaThompsonSampling
from mab_ranking.bandits.rank_bandits import IndependentBandits
class IndependentBanditsTest(TestCase):
def test_choose(self):
num_ranks = 3
rank_bandit = IndependentBandits(... |
444670 | import abc
class ExtraDataAbstractMixin(object, metaclass=abc.ABCMeta):
"""
Ensure that backends define these methods. Used in pipeline to save extra data on the user model.
"""
@abc.abstractmethod
def save_extra_data(response, user):
return
@abc.abstractmethod
def get_profile_im... |
444688 | import unittest
from numpy import hstack, max, abs, ones, zeros, sum, sqrt
from cantera import Solution, one_atm, gas_constant
import numpy as np
from spitfire import ChemicalMechanismSpec
from os.path import join, abspath
from subprocess import getoutput
test_mech_directory = abspath(join('tests', 'test_mechanisms', ... |
444721 | from .common import ImageSeriesTest, make_array, make_array_ims
class TestProperties(ImageSeriesTest):
def setUp(self):
self._a = make_array()
self._is_a = make_array_ims()
def test_prop_nframes(self):
self.assertEqual(self._a.shape[0], len(self._is_a))
def test_prop_shape(self):
... |
444730 | from rest_framework.pagination import LimitOffsetPagination
class MaxLimitPagination(LimitOffsetPagination):
max_limit = 8
|
444757 | import asyncio
from functools import partial
def mark_done(future, result):
print(f'Set to: {result}')
future.set_result(result)
async def b1():
loop = asyncio.get_event_loop()
fut = asyncio.Future()
loop.call_soon(mark_done, fut, 'the result')
loop.call_soon(partial(print, 'Hello', flush=Tr... |
444762 | import torch.nn as nn
from .heads.smpl_head_prediction import SMPLHeadPrediction
from .transformers import RelationTransformerModel
from yacs.config import CfgNode as CN
class Pose_transformer(nn.Module):
def __init__(self, opt):
super(Pose_transformer, self).__init__()
config = "uti... |
444819 | import requests
import logging
from server import config
logger = logging.getLogger(__name__)
def predict(story_text):
if story_text is None: # maybe we didn't parse any text out?
return {}
url = "{}/predict.json".format(config.get('NYT_THEME_LABELLER_URL'))
try:
r = requests.post(url, ... |
444837 | import os
import re
import subprocess
from time import sleep
from typing import Any, Dict, List, Optional
from semantic_version import Version
import src.cli.console as console
from src import settings
from src.local.providers.abstract_provider import AbstractK8sProvider
from src.local.providers.k3d.storage import K3... |
444920 | import torch.nn as nn
import torch.nn.functional as F
class res_mlp_block(nn.Module):
def __init__(self,num_channel,use_2d=False):
super().__init__()
if use_2d==False:
self.mlp1=nn.Conv1d(num_channel,num_channel,kernel_size=1)
self.mlp2=nn.Conv1d(num_channel,num_channel,kern... |
444938 | from jwt.exceptions import MissingRequiredClaimError
def test_missing_required_claim_error_has_proper_str():
exc = MissingRequiredClaimError('abc')
assert str(exc) == 'Token is missing the "abc" claim'
|
444949 | from typing import Generic, TypeVar
from .types import Realm, WellKnown, SecurityConsole, Client, Credential, ClientRegistration, \
OpenRedirect, NoneSign, FormPostXSS, Username, Password
from keycloak_scanner.utils import to_camel_case
SimpleType = TypeVar('SimpleType')
V = TypeVar('V')
class BadWrappedTypeEx... |
445040 | import sys
sys.path.append('../../')
from spear.labeling import preprocessor
@preprocessor()
def convert_to_lower(x):
return x.lower().strip() |
445041 | from django.urls import path
from sql import views
app_name = "sql"
urlpatterns = [
path('sql.html', views.SqlDdl.as_view(), name='sql_ddl'),
path('sql-<str:pk>.html', views.SqlDdlQuery.as_view(), name='sql_query'),
]
|
445068 | from typing import Hashable, Iterable, Optional, Union
import pandas_flavor as pf
import pandas as pd
from janitor.utils import deprecated_alias
@pf.register_dataframe_method
@deprecated_alias(columns="column_names")
def get_dupes(
df: pd.DataFrame,
column_names: Optional[Union[str, Iterable[str], Hashable]]... |
445102 | import json
import os
from typing import Any
from typing import Dict
from typing import Optional
from boto3.session import Session
from botocore.exceptions import ClientError
class TokenProvider:
def __init__(self):
pass
def get_token(self) -> Optional[str]:
pass
class EnvironmentVariableT... |
445107 | import math
from typing import Dict, Tuple, List
from OpenGL.GL import *
from OpenGL.GL.shaders import compileProgram, compileShader
from opengl_helper.shader import BaseShader
from opengl_helper.texture import Texture
class ComputeShader(BaseShader):
def __init__(self, shader_src: str):
BaseShader.__in... |
445148 | from gopro_overlay.models import KineticEnergyModel
from gopro_overlay.units import units
def test_kinetic():
speed = units.Quantity(15, units.mps)
mass = units.Quantity(10, units.kg)
model = KineticEnergyModel(mass)
result = model.evaluate(speed)
assert result == units.Quantity(1125, units.jou... |
445161 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import time
from scipy import misc
import tensorflow as tf
import numpy as np
import sys
import os
import argparse
import align.detect_face
import glob
from pdb import set_trace as bp
from six.moves import xran... |
445179 | from itertools import product
import math
import torch
import torch.nn.functional as F
def im2toepidx(c, i, j, h, w):
return c*h*w + i*w + j
def get_toeplitz_idxs(fshape, dshape, f_stride=(1,1), s_pad=(0,0)):
assert fshape[1] == dshape[0], "data channels must match filters channels"
fh, fw = fshape[-2:]
... |
445239 | import unittest
import pytest
from grapl_analyzerlib.comparators import (
Distance,
Not,
Has,
Eq,
)
PREDICATE: str = "pred"
VALUE: str = "value"
class TestComparators(unittest.TestCase):
def test_distance(self) -> None:
comparator = Distance(
predicate=PREDICATE,
v... |
445278 | from google.appengine.ext import ndb
from endpoints_proto_datastore.ndb import EndpointsModel
from endpoints_proto_datastore.ndb import EndpointsAliasProperty
from protorpc import messages
class AccountGeoCode(EndpointsModel):
lat = ndb.FloatProperty()
lng = ndb.FloatProperty()
class Account(EndpointsModel)... |
445304 | import pytest
import torch
from module import Embedding
class Config(object):
vocab_size = 10
word_dim = 10
pos_size = 12 # 2 * pos_limit + 2
pos_dim = 5
dim_strategy = 'cat' # [cat, sum]
config = Config()
x = torch.tensor([[1, 2, 3, 4, 5], [6, 7, 3, 5, 0], [8, 4, 3, 0, 0]])
x_pos = torch.ten... |
445316 | from .address_data import *
from .address_queries import *
from .address_summary import *
from .address_transactions import *
from .address_resolution import *
from .proxy_utils import *
|
445345 | import ckan.plugins as plugins
import ckan.plugins.toolkit as toolkit
import ckanext.validate_links.cli as cli
import ckanext.validate_links.views as views
def admin_only(context, data_dict=None):
return {'success': False, 'msg': 'Access restricted to system administrators'}
class Validate_LinksPlugin(plugins.S... |
445349 | import scrapy
from ..items import EconomycrawlerItem
from news.models import EHeadline
from economycrawler.spiders import economy_spider
from economycrawler import pipelines
class EconomySpider(scrapy.Spider):
name = "economy"
start_urls = [
'https://economictimes.indiatimes.com/markets/stocks/news'
]
def parse... |
445440 | import sys
sys.path.insert(0, "../")
from opetopy.UnnamedOpetope import address, ProofTree
p = ProofTree({
address([], 2): {
address([], 1): {
address('*'): {} # {} represents the point
},
address(['*']): {
address('*'): {}
}
},
address([['*']]): {
... |
445447 | import pandas as pd
import os
import os.path as osp
def load_csv(working_dir,csv_path):
cache_folder_name = "cache/"
cache_folder_path = osp.join(working_dir,cache_folder_name)
os.makedirs(cache_folder_path,exist_ok=True)
pickle_file_name = os.path.basename(csv_path) + ".pkl"
csv_folder = os.p... |
445469 | from torch2trt_dynamic.torch2trt_dynamic import (get_arg, tensorrt_converter,
trt_)
@tensorrt_converter('torch.take')
def convert_take(ctx):
input = ctx.method_args[0]
index = get_arg(ctx, 'index', pos=1, default=None)
input_trt = trt_(ctx.network, input)
... |
445490 | import cv2
import numpy as np
import matplotlib.pyplot as plt
import imutils
def img_equal_clahe_yuv(img):
"""Apply equalize, clahe into image with YUV channels.
Args:
img (image) : Image
Returns:
img_eq (image): Image with equalize applied
img_clahe (image): Image with clahe app... |
445510 | import getopt
import os
import sys
import matplotlib
import matplotlib.pyplot as plt
import numpy as np
import pylab
from matplotlib.font_manager import FontProperties
from matplotlib.ticker import LinearLocator, LogLocator, MaxNLocator
from numpy import double
OPT_FONT_NAME = 'Helvetica'
TICK_FONT_SIZE = 24
LABEL_FO... |
445513 | import pprint
points = []
xs = []
ys = []
for i in range(2):
xs.append(int(input("Enter an x value: ")))
for i in range(2):
ys.append(int(input("Enter an y value: ")))
points.append([xs[0], ys[0]])
points.append([xs[1], ys[0]])
points.append([xs[1], ys[1]])
points.append([xs[0], ys[1]])
pprint.pprint(points... |
445560 | from . import api
from flask import jsonify
def bad_request_error(message):
response = jsonify({'error': 'bad request', 'message': message})
response.status_code = 400
return response
def unauthorized_error(message):
response = jsonify({'error': 'unauthorized', 'message': message})
response.sta... |
445569 | from pythonforandroid.recipe import CompiledComponentsPythonRecipe
class PymunkRecipe(CompiledComponentsPythonRecipe):
name = "pymunk"
version = "6.0.0"
url = "https://pypi.python.org/packages/source/p/pymunk/pymunk-{version}.zip"
depends = ["cffi", "setuptools"]
call_hostpython_via_targetpython =... |
445576 | import os
import sys
sys.path.append(os.path.join(os.path.dirname(__file__), "../../../"))
import unittest
import pandas as pd
from karura.core.insights.categorical_to_dummy_insight import CategoricalToDummyInsight
from karura.core.dataframe_extension import DataFrameExtension
class TestCategoricalToDummyInsight(unit... |
445627 | import sys
import os
import subprocess
from shutil import copyfile, rmtree
def find_and_split_inputs(input_env_data, output_dir, number_of_inputs):
## Generate the environment file (by splitting inputs)
## Find the input file name
input_env_lines = input_env_data.split('\n')
input_vars = [line.split('... |
445640 | import numpy as np
import torch
import time
import torch.nn as nn
import torch.nn.functional as F
from torch.optim import Adam
import matplotlib.pyplot as plt
import config.HyperConfig as Config
import Attention_LSTM as Model
import loss_function as LossFunc
import data
# from sklearn.model_selection import train_test_... |
445668 | import os.path
from keras.optimizers import Adam
from rl.agents.dqn import DQNAgent
from rl.callbacks import ModelIntervalCheckpoint
from rl.core import Agent
from models import KickoffModes, AbstractConfiguration
def kickoff(configuration):
# type: (AbstractConfiguration) -> ()
dqn = DQNAgent(
mode... |
445679 | import ray
import time
# A regular Python function.
def normal_function():
return 1
# By adding the `@ray.remote` decorator, a regular Python function
# becomes a Ray remote function.
@ray.remote
def my_function():
return 1
# To invoke this remote function, use the `remote` method.
# This will immediately... |
445703 | import pytorch_lightning as pl
import torch
import torch.nn as nn
class OutputLayer(pl.LightningModule):
"""
Output Layer of the LegoFormer
Maps Transformer's output vector to decomposition factors.
"""
def __init__(self, dim_model, output_resolution=32):
"""
:param dim_m... |
445732 | import logging
import re
from qark.issue import Severity, Issue
from qark.scanner.plugin import ManifestPlugin
log = logging.getLogger(__name__)
API_KEY_REGEX = re.compile(r'(?=.{20,})(?=.+\d)(?=.+[a-z])(?=.+[A-Z])')
SPECIAL_CHARACTER_REGEX = re.compile(r'(?=.+[!$%^~])')
HARDCODED_API_KEY_REGEX = re.compile(r'api_ke... |
445746 | from .dash import Dash, no_update # noqa: F401
from .views import BaseDashView # noqa: F401
from . import dependencies # noqa: F401
from . import development # noqa: F401
from . import exceptions # noqa: F401
from . import resources # noqa: F401
from .version import __version__ # noqa: F401
# from ._callback_con... |
445754 | from .inference_models.hierarchical_model import infer_labels
from .utils.dataset import GogglesDataset
from .affinity_matrix_construction.construct import construct_image_affinity_matrices
__version__ = '0.1' |
445760 | from .base import BaseAPI, BaseEndpoint # noqa
from .client import api_client_factory # noqa
__all__ = ['BaseAPI', 'BaseEndpoint', 'api_client_factory']
|
445845 | import datetime
import html
from typing import List
from urllib.parse import quote_plus
from .source import Source
from ...models import Chapter, Novel
class NovelPub(Source):
base_urls = ("https://www.novelpub.com",)
last_updated = datetime.date(2021, 10, 29)
search_viable = True
search_url_templat... |
445850 | from itertools import product
from quantlib.instruments.option import EuropeanExercise
from quantlib.instruments.payoffs import PlainVanillaPayoff
from quantlib.instruments.option import Put, Call
from quantlib.instruments.asian_options import (
ContinuousAveragingAsianOption, DiscreteAveragingAsianOption, Geome... |
445858 | import torch
from torch.nn import Softplus, Module
from torch.distributions.normal import Normal
from .mixture_gaussian import GaussianDiagonalMixture
def transform_to_distribution_params(params, distr_dim=1, eps=1e-6):
"""Apply nonlinearities to unconstrained model outputs so
they can be represented as para... |
445864 | from Network.activity_net.video_hdf5_generator import process_video_dir
from Network.activity_net.API import ActivityNet_Dataloader, ActivityNet_Model
'''
You have to pre process videos before you training.
It will cost huge disk space and huge memmory space.
'''
process_video_dir(r"videos/folder/path", r"pre-process/... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.