id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
11483930 | import requests
url = "http://localhost:8501/v1/models/simple_model:predict"
payload = {'instances': [1.0]}
response = requests.post(url, json=payload)
print(response.text)
print(response.status_code, response.reason)
|
11483977 | import conftest
from qemu import QemuVm
def run_ioctl_test(command: str, vm: QemuVm) -> None:
conftest.Helpers.run_vmsh_command(
[command, str(vm.pid)], cargo_executable="examples/test_ioctls"
)
def spawn_ioctl_test(command: str, vm: QemuVm) -> conftest.VmshPopen:
return conftest.Helpers.spawn_v... |
11483992 | import numpy as np
from periodicity.core import TSeries
from periodicity.data import SustainedPlusGappedPureTones
from periodicity.decomposition import CEEMDAN
def test_two_tones_two_imfs():
# Test if nothing but the two tones are recovered by CEEMDAN
x = TSeries(values=SustainedPlusGappedPureTones())
im... |
11484084 | import enum
#I might be doing something wrong, but I saw an "02" value come through
#which doesn't seem to be in any of the documentation I saw... it registered
#as low on the interface, so I'll just assume there's two codes
@enum.unique
class ErdRinseAgentRaw(enum.Enum):
RINSE_AGENT_GOOD = "00"
RINSE_AGENT_LO... |
11484088 | from flask import Blueprint
from api.controllers.logscontroller import logs_controller
logs_blueprint = Blueprint("logs", __name__)
logs_blueprint.add_url_rule(
'/logs/<int:project_id>',
view_func=logs_controller['fetch_project_logs'],
methods=['GET'],
)
logs_blueprint.add_url_rule(
'/logs/<int:pro... |
11484094 | import os
import numpy as np
import pandas as pd
from pyuplift.utils import download_file
def download_hillstrom_email_marketing(
data_home=None,
url='http://www.minethatdata.com/Kevin_Hillstrom_MineThatData_E-MailAnalytics_DataMiningChallenge_2008.03.20.csv'
):
"""Downloading the Hillstrom Email Marketin... |
11484121 | import aiotfm
import pytest
from aiotfm.utils import Date, get_keys, shakikoo
from aiotfm.utils import Locale
def test_date():
date = Date(2020, 6, 25)
assert date == Date.fromtimestamp(date.timestamp())
async def test_keys():
with pytest.raises(aiotfm.errors.EndpointError):
await get_keys('', '')
def test_... |
11484164 | import types
def get_as_num(value):
"""Return the JS numeric equivalent for a value."""
if hasattr(value, 'get_literal_value'):
value = value.get_literal_value()
if value is None:
return 0
try:
if isinstance(value, types.StringTypes):
if value.startswith("0x"):
... |
11484179 | import torch
from torch.utils.data import DataLoader
from poutyne.framework import Model
from torch_enhance.datasets import BSDS300, Set14, Set5
from torch_enhance.models import SRCNN
from torch_enhance import metrics
scale_factor = 2
train_dataset = BSDS300(scale_factor=scale_factor)
val_dataset = Set14(scale_fact... |
11484216 | from .GenericProduct import (open_product,
get_hdf5_file_product_type,
GenericProduct)
|
11484261 | import json
import os
import requests
from config import *
from common import sdkIPAddress
headers = {
"Content-Type": "application/json",
"Accept": "application/json",
}
if oltest == "1":
url_fullnode = "http://{}/jsonrpc".format(sdkIPAddress(fullnode_dev))
else:
url_fullnode = "http://{}/jsonrpc".... |
11484301 | import torch
import torch.nn as nn
from Model.Classifier import Classifier
from Model.Cross_TE_Module import Cross_TE_Module
class TE_Cross_Connector(nn.Module):
def __init__(self, _num_stages=3, _use_avg_on_conv3=True,
indim=256, transform_classes=6,num_class=10,
nchannels=256*8*8... |
11484303 | from a10sdk.common.A10BaseClass import A10BaseClass
class StaticDestMapping(A10BaseClass):
"""Class Description::
Stateless NAT46 mapping (IPv4 <-> IPv6).
Class static-dest-mapping supports CRUD Operations and inherits from `common/A10BaseClass`.
This class is the `"PARENT"` class for this modul... |
11484325 | from setuptools import setup, find_packages
DISTNAME = "octopy"
VERSION = "1.0.0"
DESCRIPTION = """Octopy is a companion Python library for octosport.io. The library offers tools for football (soccer) analytics."""
LONG_DESCRIPTION = """Octopy is a companion Python library for octosport.io. The library offers tools fo... |
11484336 | import logging
import pytest
from kazoo.client import KazooClient
from kazoo.handlers.threading import SequentialThreadingHandler
from kazoo.retry import KazooRetry
from kazoo.security import ACL, ANYONE_ID_UNSAFE, Permissions
@pytest.fixture(scope="session")
def zk_conn():
conn_retry_policy = KazooRetry(max_tri... |
11484338 | import numpy as np
from fireworks import Workflow
from mpmorph.fireworks import powerups
from mpmorph.fireworks.core import StaticFW, MDFW, OptimizeFW
from mpmorph.util import recursive_update
__author__ = '<NAME> and <NAME>'
__maintainer__ = '<NAME>'
__email__ = '<EMAIL>'
def get_quench_wf(structures, priority=None... |
11484394 | from SPARQLWrapper import SPARQLWrapper, CSV, JSON, POST
import json
from tqdm import tqdm
import time
import numpy as np
import pandas as pd
import io
from tabulate import tabulate
import os
import numpy as np
import bs4 as bs
import datetime
import uuid
from datetime import timezone
data = pd.read_excel('data... |
11484397 | import sys
sys.path.append('../py')
from iroha import *
from iroha.iroha import *
d = IDesign()
mod = IModule(d, "M_top")
tab = ITable(mod)
st1 = IState(tab)
st2 = IState(tab)
st3 = IState(tab)
tab.states.append(st1)
tab.states.append(st2)
tab.states.append(st3)
design_tool.AddNextState(st1, st2)
design_tool.AddNext... |
11484400 | from .sbml import load_cbmodel
class ModelCache:
def __init__(self, ids, paths, load_args=None, post_processing=None):
self.paths = dict(zip(ids, paths))
self.cache = dict()
self.load_args = load_args if load_args is not None else {}
self.post_processing = post_processing
de... |
11484405 | import gitlab
import logging
from typing import Dict, List
from hypermodel.platform.gcp.config import GooglePlatformConfig
from hypermodel.platform.gcp.data_lake import DataLake
from hypermodel.platform.gcp.data_warehouse import DataWarehouse
from hypermodel.platform.gitlab.git_host import GitLabHost
from hypermodel.pl... |
11484414 | from brownie import interface
from rich.console import Console
from helpers.utils import snapBalancesMatchForToken
from .StrategyCoreResolver import StrategyCoreResolver
console = Console()
class StrategyDiggLpMetaFarmResolver(StrategyCoreResolver):
def confirm_rebase(self, before, after, value):
"""
... |
11484420 | from django.urls import path
from . import views
app_name = 'books'
urlpatterns = [
path('',
views.HomeView.as_view(),
name='home'),
path('publishers/',
views.PublisherListView.as_view(),
name='publisher_list'),
path('publishers/<int:pk>/',
views.PublisherDetai... |
11484449 | import os.path as op
import cooler
import cooltools.coverage
from numpy import testing
import numpy as np
def test_coverage_symmetric_upper(request):
# perform test:
clr = cooler.Cooler(op.join(request.fspath.dirname, "data/CN.mm9.1000kb.cool"))
cov = cooltools.coverage.get_coverage(clr, ignore_diags=2, c... |
11484458 | from authzed.api.v1 import Client, ReadSchemaRequest
from grpcutil import bearer_token_credentials
client = Client(
"grpc.authzed.com:443",
bearer_token_credentials("<PASSWORD>"),
)
resp = client.ReadSchema(ReadSchemaRequest())
print(resp.schema_text)
|
11484460 | bl_info = {
"name": "Dagon Asset Export",
"author": "<NAME>",
"version": (1, 0),
"blender": (2, 7, 0),
"location": "File > Export > Dagon Asset (.asset)",
"description": "Export Dagon engine asset file",
"warning": "",
"wiki_url": "",
"tracker_url": "",
"category": "Imp... |
11484499 | import isce3
def file_to_rdr_grid(ref_grid_path: str) -> isce3.product.RadarGridParameters:
'''read parameters from text file needed to create radar grid object'''
with open(ref_grid_path, 'r') as f_rdr_grid:
sensing_start = float(f_rdr_grid.readline())
wavelength = float(f_rdr_grid.readline()... |
11484503 | import logging
from functools import lru_cache
from typing import Collection, Union, Set, Callable, Tuple
from talkgenerator.datastructures.image_data import ImageData
logger = logging.getLogger("talkgenerator")
class PeakedWeight(object):
def __init__(
self, peak_values: Tuple[int, ...], weight: float... |
11484506 | import asyncio
from asyncio import AbstractEventLoop
from concurrent.futures import ThreadPoolExecutor
from typing import TypeVar, Callable, Any, Awaitable, Optional
import logging
logger = logging.getLogger(__name__)
T = TypeVar("T")
executor = ThreadPoolExecutor(max_workers=2)
def _loop() -> AbstractEventLoop:
... |
11484529 | import argparse
import numpy as np
import os
import torch
import torch.nn as nn
from trixi.util import Config, GridSearch
class ConvModule(nn.Module):
"""Utility Module for more convenient weight initialization"""
conv_types = (nn.Conv1d,
nn.Conv2d,
nn.Conv3d,
... |
11484530 | import unittest
from synthetic.stats import create_stat, StatType, DistanceType
from synthetic.tests.graphs import *
class TestStats(unittest.TestCase):
def test_degrees_undir(self):
g = full_graph(directed=False)
s = create_stat(g, StatType.DEGREES, bins=10)
self.assertListEqual(list(s.da... |
11484550 | import argparse, sys
parser = argparse.ArgumentParser()
parser.add_argument('file', nargs='?',
type=argparse.FileType('r'), default=sys.stdin,
help="input file to be sorted")
parser.add_argument('-u', '--unique', action='store_true',
help="sort uniquely")
arg... |
11484642 | from __future__ import absolute_import
import warnings
from functools import wraps
__all__ = ('Undef', 'UndefType', 'is_list', 'is_allowed_attr', 'opt_checker', 'same', 'warn', )
class UndefType(object):
def __repr__(self):
return "Undef"
def __reduce__(self):
return "Undef"
Undef = Undef... |
11484670 | from instauto.api.client import ApiClient
from instauto.helpers.friendships import follow_user
client = ApiClient.initiate_from_file('.instauto.save')
follow_user(client, user_id="user_id")
# or
follow_user(client, username="instagram")
|
11484688 | import logging
import unittest
from unittest import TestCase
from supplychainpy._helpers import _data_cleansing
from supplychainpy.model_demand import holts_trend_corrected_exponential_smoothing_forecast, \
simple_exponential_smoothing_forecast
from supplychainpy.model_demand import holts_trend_corrected_exponenti... |
11484715 | import pandas as pd
import numpy as np
import operator
import xgboost as xgb
import lightgbm as lgb
from catboost import CatBoostClassifier, cv, Pool
import seaborn as sns
import matplotlib.pyplot as plt
import math
color = sns.color_palette()
class BesXGboost:
"""
XGBoost model. https://github.com/dmlc/xgbo... |
11484784 | import logging
import os
import sys
from skyline.initialization import (
check_skyline_preconditions,
initialize_skyline,
)
from skyline.error_printing import print_analysis_error
logger = logging.getLogger(__name__)
def register_command(subparsers):
parser = subparsers.add_parser(
"time",
... |
11484821 | import os
import logging
try:
import jsonlogger
except ImportError:
# python-json-logger version 0.1.0 has changed the import structure
from pythonjsonlogger import jsonlogger
class TaskAdapter(logging.LoggerAdapter):
""" Enhance any log messages with extra information about the
current context o... |
11484847 | import cv2 as cv
import numpy as np
from matplotlib import pyplot as plt
def hough():
'''
The Hough Transform is a Popular technique
to detect any shape, if you can represent
that shape in a mathematical form, It can
detect the shape even if it is broken or
distorted a little bit.
# Θ Th... |
11484885 | from databases import Database
from sqlalchemy import MetaData
from sqlalchemy import event
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.pool import Pool
from feeder import settings
@event.listens_for(Pool, "checkout")
def _fk_pragma_on_connect(dbapi_con, con_record, con_proxy):
dbapi_... |
11484911 | import numpy as np
import matplotlib
import matplotlib.pyplot as plt
class BenchmarkSoftsortBackwardsResultsParser:
r'''
Parses an individual results (i.e. log) file and stores the results.
'''
def __init__(self):
self.epochs = None
self.loss = None
self.spearmanr = None
... |
11484933 | import subprocess
from __future__ import print_function
infile = open("alignment_export_2018_12_07.1.xml","rt")
xmllines = infile.readlines()
infile.close()
#tree = ET.parse(infilename)
#root = tree.getroot()
outfile =open("test.xml","wt")
iov = 0
firstline = xmllines.pop(0)
secondline = xmllines.pop(0)
lastline = ... |
11484960 | from server.crud.base import CRUDBase
from server.db.models import ProductTypesTable
from server.schemas.product_type import ProductTypeCreate, ProductTypeUpdate
class CRUDProductType(CRUDBase[ProductTypesTable, ProductTypeCreate, ProductTypeUpdate]):
pass
product_type_crud = CRUDProductType(ProductTypesTable)
|
11484978 | import datetime
import pandas as pd
from pkg_resources import resource_filename
sample = resource_filename(__name__, 'sample_data/survey_ibema_faxinal_Cartesian.csv')
from .coordinates import (
CartesianCoordinate,
CoordinateSystem,
)
from .geometry import (
Line2D,
Triangle,
TriangularMesh,
Tr... |
11485012 | from geotrek.common.forms import CommonForm
from .models import Report
class ReportForm(CommonForm):
geomfields = ["geom"]
class Meta:
fields = [
"geom",
"email",
"comment",
"activity",
"category",
"problem_magnitude",
... |
11485014 | import warnings
from eventlet import Timeout # noqa
from eventlet import event
from eventlet import greenthread
from eventlet import queue
from greenlet import GreenletExit
from kombu import syn
blocking = syn.blocking
spawn = greenthread.spawn
Queue = queue.LightQueue
Event = event.Event
class Entry(object):
... |
11485028 | import sys
import jax
import torch
import numpy as np
import torch.nn as nn
import jax.numpy as jnp
sys.path.append('..')
from train_tools import to_string
def jax2tor(array, tor2jax=False):
"""Convert between JAX arrays and Pytorch tensors"""
if tor2jax:
return jnp.array(array.numpy())
else:
... |
11485073 | import cv2
import numpy as np
img_arr = np.arange(0, 640000, 1, np.uint8)
img_arr = np.reshape(img_arr, (800, 800))
height, width = img_arr.shape
for i in range(height):
for j in range(width):
if ((i//(width/8))%2+(j//(width/8))%2)%2==0:
img_arr[i][j]=255
else:
... |
11485110 | import sqlite3, sys
from PyQt5.QtWidgets import QDialog, QApplication
from sqlite3 import Error
from demoDeleteUser import *
class MyForm(QDialog):
def __init__(self):
super().__init__()
self.ui = Ui_Dialog()
self.ui.setupUi(self)
self.ui.pushButtonDelete.clicked.connect(self.Dele... |
11485111 | from abc import ABC, abstractmethod
from typing import Dict, Optional
from great_expectations.core.expectation_configuration import ExpectationConfiguration
from great_expectations.rule_based_profiler.domain_builder import Domain
from great_expectations.rule_based_profiler.parameter_builder import ParameterContainer
... |
11485186 | def aliquot_sum(input_num: int) -> int:
"""
Menemukan jumlah alikuot dari bilangan bulat input, di mana
alikuot jumlah suatu bilangan n
sebagai jumlah semua
bilangan asli kurang dari n
yang membagi n secara merata. Untuk
contoh, jumlah alikuot dari 15 adalah 1 + 3 + 5 = 9. Ini adalah
im... |
11485190 | import unittest, json
from backend.kubernetes.k8sclient import KubeClient
class KubeClientTestCase(unittest.TestCase):
def setUp(self):
self.client = KubeClient("http://192.168.0.10:8080/api/v1/")
def tearDown(self):
self.client = None
def test_add_slash(self):
url = "http://192... |
11485195 | import os
import numpy as np
from agent import BaseAgent
try:
import tensorflow as tf
except ImportError:
tf = None
from keras.backend import tensorflow_backend, image_data_format
from keras.optimizers import Adam
from rl.callbacks import ModelIntervalCheckpoint
from rl.core import Processor
from rl.memory i... |
11485209 | from __future__ import absolute_import
# flake8: noqa
# import apis into api package
from proton_api.api.annuities_api import AnnuitiesApi
from proton_api.api.business_financial_management_api import BusinessFinancialManagementApi
from proton_api.api.cards_api import CardsApi
from proton_api.api.financial_health_api ... |
11485217 | import torch
import torch.nn.functional as F
import math
def softmax_focalloss(y_pred, y_true, ignore_index=255, gamma=2.0, normalize=False):
"""
Args:
y_pred: [N, #class, H, W]
y_true: [N, H, W] from 0 to #class
gamma: scalar
Returns:
"""
losses = F.cross_entropy(y_pred... |
11485239 | import math
def get_chunks(xs, chunk_count=3):
"""
Helper function to split a list into roughly equally sized chunks.
"""
chunk_width = math.ceil(len(xs) / chunk_count)
ranges = range(0, len(xs), chunk_width)
return [xs[x:x + chunk_width] for x in ranges]
|
11485242 | import os
import datetime
from flask import Flask
app = Flask(__name__)
@app.route('/')
def current_time():
ct = datetime.datetime.now()
return 'The current time is : {}!\n'.format(ct)
if __name__ == "__main__":
app.run(debug=True,host='0.0.0.0')
|
11485306 | import unittest
import numpy as np
from pysprint.core._preprocess import *
class TestEdit(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def test_savgol(self):
x, y, v, w = np.loadtxt("test_arms.txt", delimiter=",", unpack=True)
a, b = savgol(x, y, v,... |
11485312 | from stepist.flow.steps.step import StepData
import ujson
def get_connection(sqs_engine):
queues = sqs_engine._queues.keys()
return SQSConnection(sqs_engine.session,
queues,
sqs_engine.message_retention_period,
sqs_engine.visibility_t... |
11485337 | from django.db import models
from dictionary.views import get_def_for_tooltip
import json
from search.models import TableNames
import settings
from opus_support import (display_result_unit,
get_default_unit,
get_unit_display_name,
parse_f... |
11485438 | import torch
import torch.nn as nn
import torchvision
from python_developer_tools.cv.bases.channels.channels import ChannelShuffle
def Conv3x3BNReLU(in_channels,out_channels,stride,groups):
return nn.Sequential(
nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=3, stride=strid... |
11485449 | import time
import numpy as np
from lcc.entities.star import Star
from lcc.stars_processing.deciders import LDADec, QDADec, GradBoostDec
from lcc.stars_processing.descriptors import AbbeValueDescr
from lcc.stars_processing.stars_filter import StarsFilter
from lcc.stars_processing.systematic_search.stars_searcher impo... |
11485477 | from tincan.documents.document import Document
from tincan.documents.state_document import StateDocument
from tincan.documents.activity_profile_document import ActivityProfileDocument
from tincan.documents.agent_profile_document import AgentProfileDocument
|
11485488 | import networkx as nx
from utils.graph import ExceptionDataNode, Graph
from utils.pageRank import PRIterator
from utils.pcalg import construct_service_dependency_diagram
class DiagnosisFaultService:
@staticmethod
def get_servcie_fault_causes(serviceNode,data):
"""
对某一故障服务进行细粒度诊断
:para... |
11485509 | import os
import sys
import tempfile
from pathlib import Path
from shutil import rmtree
import pytest
try:
from h5pyd._apps.hstouch import main as hstouch
from hsds.hsds_app import HsdsApp
with_reqd_pkgs = True
except ImportError:
with_reqd_pkgs = False
def set_hsds_root():
"""Make required HSD... |
11485516 | import click
from .tools.es import es_cli, purge as purge_es
from .tools.s3 import s3_cli, reset as reset_s3
from .tools.pg import pg_cli, reset as reset_pg
from .tools.neo import neo4j_cli, purge as purge_neo4j
from .config import Config
from pathlib import Path
import shutil
@click.group()
def cli():
"""Pipelin... |
11485546 | import os
class Note:
def __init__(self, path: str):
self.path = path
@classmethod
def from_file(cls, path: str):
if os.path.exists:
return cls(path) |
11485564 | import docker
import hashlib
import os
import os.path as op
import slugid
import sys
CONTAINER_PREFIX = "higlass-manage-container"
NETWORK_PREFIX = "higlass-manage-network"
REDIS_PREFIX = "higlass-manage-redis"
REDIS_CONF = "/usr/local/etc/redis/redis.conf"
SQLITEDB = "db.sqlite3"
def md5(fname):
hash_md5 = hash... |
11485575 | import asyncio
import json
import os
import re
import zipfile
from os import path, walk
from aioconsole import aprint
from rich.progress import Progress
from fz_manager.factorio_zone_api import FZClient, ServerStatus
from fz_manager.menu import ActionMenu, SelectMenu, CheckboxMenu, MenuEntry, PathMenu, AlertMenu, Inp... |
11485583 | import os
from ament_index_python.packages import get_package_share_directory
from launch import LaunchDescription
from launch.actions import IncludeLaunchDescription, DeclareLaunchArgument
from launch.launch_description_sources import PythonLaunchDescriptionSource
from launch.substitutions import LaunchConfiguration,... |
11485615 | from ceph_medic import metadata
from ceph_medic.checks import mons
class TestGetSecret(object):
def setup(self):
self.data = {
'paths': {
'/var/lib/ceph': {
'files': {
'/var/lib/ceph/mon/ceph-mon-0/keyring': {
... |
11485622 | import os
import matplotlib as mpl
import torch
import torchvision
from data_management import Permute, load_ct_data
from networks import RadonNet
# ----- load configuration -----
import config # isort:skip
# ----- global configuration -----
mpl.use("agg")
device = torch.device("cuda:0")
torch.cuda.set_device(0)
... |
11485633 | import tensorflow as tf
import numpy as np
import math
class Detector:
def __init__(self,sess,state_dim,obj_num,fea_size,state_input,postfix):
self.sess = sess;
self.state_dim = state_dim;
self.fea_size=fea_size;
self.obj_num=obj_num;
... |
11485667 | import torch
import sys
MOCO_WEIGHTS_PATH = sys.argv[1]
CONVERTED_WEIGHTS_OUT_PATH = sys.argv[2]
moco_weights = torch.load(MOCO_WEIGHTS_PATH, map_location='cpu')
moco_weights = {
k.replace("module.encoder_q.", "model."): v
for k, v in moco_weights['state_dict'].items()
if "module.encoder_q." in k
}
torch... |
11485686 | import jsonobject
import requests
from requests import HTTPError, RequestException
from dimagi.utils.logging import notify_exception
from corehq.apps.formplayer_api import const
from corehq.apps.formplayer_api.exceptions import (
FormplayerAPIException,
FormplayerRequestException,
)
from corehq.apps.formplaye... |
11485709 | from ..model import ik,types,config
from ..math import vectorops
from ..robotsim import IKSolver,IKObjective
from ..io import loader
import time
import random
from ..math import optimize,symbolic,symbolic_klampt,so3,se3
import numpy as np
class KlamptVariable:
"""
Attributes:
name (str): the Klamp't it... |
11485733 | import argparse
import os.path
from transformers import ViTFeatureExtractor, ViTForImageClassification
from hugsvision.inference.VisionClassifierInference import VisionClassifierInference
parser = argparse.ArgumentParser(description='Image classifier')
parser.add_argument('--path', type=str, default="./out/M... |
11485743 | import os
import dgl
import tqdm
import torch
import json
import os.path
import numpy as np
import scipy.sparse
from dgl import DGLGraph
from dgl.data import citegrh
from itertools import compress
from torchvision.datasets import VisionDataset
from sklearn.preprocessing import StandardScaler, MinMaxScaler
class Cont... |
11485792 | import torch.nn as nn
import torchquantum as tq
from abc import ABCMeta
__all__ = [
'QuantumModule',
'QuantumModuleList',
'QuantumModuleDict',
]
class QuantumModule(nn.Module):
def __init__(self) -> None:
super().__init__()
self.static_mode = False
self.graph = None
s... |
11485793 | import torch
from ezflow.modules import MODULE_REGISTRY
def test_ConvGRU():
inp_x = torch.rand(2, 8, 32, 32)
inp_h = torch.rand(2, 8, 32, 32)
module = MODULE_REGISTRY.get("ConvGRU")(hidden_dim=8, input_dim=8)
_ = module(inp_h, inp_x)
def test_BasicBlock():
inp = torch.randn(2, 3, 256, 256)
... |
11485817 | import requests
import asyncio
import json
import urllib3
from walkoff_app_sdk.app_base import AppBase
class Crowdstrike_Falcon(AppBase):
__version__ = "1.0"
app_name = "Crowdstrike_Falcon"
def __init__(self, redis, logger, console_logger=None):
self.verify = False
urllib3.disable_warni... |
11485825 | import numpy as np
import pandas as pd
from filter import movingaverage
import math
from trendy import segtrends
#!pip install mlboost
from mlboost.core.pphisto import SortHistogram
# little hack to make in working inside heroku twp submodule
import os, sys
sys.path.append(os.path.join(os.path.dirname(os.path.abspath... |
11485838 | from __future__ import absolute_import
import six
import unittest
from mock import Mock, patch
import urllib
class TestUrllibPatch(unittest.TestCase):
@unittest.skipIf(six.PY2, "urllib not compatible with python2")
def test_request_fn_injects_headers_and_returns(self):
from beeline.patch.urllib impor... |
11485845 | from datetime import date
from ..core import WesternCalendar, MON, TUE, WED, THU, FRI, SAT
from ..astronomy import solar_term
from ..registry_tools import iso_register
# https://www.feriados.cl
# http://www.feriadoschilenos.cl
@iso_register('CL')
class Chile(WesternCalendar):
"Chile"
FIXED_HOLIDAYS = Wester... |
11485862 | from __future__ import division, print_function, absolute_import
import numpy as np
from ipsolver._constraints import (BoxConstraint,
LinearConstraint,
NonlinearConstraint,
_check_kind,
... |
11485900 | import numpy as np
import torch
"""
Generate mm-spaces an their euclidean metric
"""
def euclid_dist(x, y):
return np.linalg.norm(x[:, None, :] - y[None, :, :], axis=2)
def dist_matrix(x_i, y_j, p=2):
if p == 1:
return (x_i[:, :, None, :] - y_j[:, None, :, :]).norm(p=2, dim=3)
elif p == 2:
... |
11485916 | import demistomock as demisto
from CommonServerPython import *
from CommonServerUserPython import *
from functools import reduce
def get_by_incident_id(incident_id, get_key, set_key=""):
set_key = get_key if not set_key else set_key
keys = get_key.split('.')
try:
context = demisto.executeCommand(... |
11485936 | from typing import Literal, Optional, Union
import torch
from torch import nn
from buglab.models.layers.relational_multihead_attention import RelationalMultiheadAttention
def _get_activation_fn(activation):
if activation == "relu":
return nn.functional.relu
elif activation == "gelu":
return ... |
11485945 | from gevent import monkey
monkey.patch_all()
from typing import Optional
from apis.scaffold import mining, install
class Scaffold:
@staticmethod
def install(cdn: Optional[bool] = None):
"""
下载项目运行所需的配置。
## Basic Usage
Usage: python main.py install
__________________... |
11485981 | from aws_cdk import (
aws_ecs as ecs,
aws_iam as iam,
aws_logs,
NestedStack,
Resource,
RemovalPolicy,
)
from constructs import Construct
from stacks.vpc_stack import VpcStack
class EcsStack(NestedStack):
def __init__(self, scope: Construct, id: str, vpc: VpcStack, **kwargs) -> None:
... |
11486007 | from __future__ import absolute_import
import os
try:
# for Python2
import ConfigParser as cp
except ImportError:
# for Python3
import configparser as cp
import utils2to3
class EDRUserConfig(object):
def __init__(self, config_file='config/user_config.ini'):
self.config = cp.ConfigParser(... |
11486008 | from __future__ import division
from OpenGL.GL import *
from OpenGL.GLUT import *
from OpenGL.GLU import *
from model_helpers import *
from data_3d import *
# ----------------------------------------------
def render_polyface( polyface ):
if len(polyface) == 3:
_draw_polyface(... |
11486012 | from office365.runtime.client_value import ClientValue
class Video(ClientValue):
"""The Video resource groups video-related data items into a single structure."""
pass
|
11486063 | import hashlib
import logging
print_warning = False
logger = logging.getLogger(__name__)
try:
from bcrypt import hashpw, gensalt
except ImportError:
print_warning = True
def hashpw(password, *args, **kwargs):
return hashlib.sha512(password).hexdigest().encode('utf8')
def gensalt(*args, **k... |
11486077 | from django.conf.urls import url
from django.contrib import admin
from django_graph_api.views import GraphQLView
from test_app.schema import schema
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^graphql$', GraphQLView.as_view(schema=schema)),
]
|
11486091 | import math
import time
import torch
from nitorch import io
from nitorch import spatial
from nitorch.core import utils, py
from nitorch.core.optionals import try_import
from .volumes import show_orthogonal_slices
# from .menu import Menu, MenuItem
# optional imports
plt = try_import('matplotlib.pyplot', _as=True)
grid... |
11486123 | import os
root_dir = 'data/waymo2kitti/training/'
seg_list = sorted(os.listdir(root_dir))
interval = 3
f = open('train_org.txt', 'w')
for seg in seg_list:
if 'segment' in seg:
image_list = os.listdir(root_dir + seg+'/label_0')
img_list = sorted(image_list, key=lambda c: int(c.split('.')[0]))
# ... |
11486197 | import time
import calendar
import unittest
from .. import cron
class TestCron(unittest.TestCase):
def test_init_coercion(self):
self.assertEqual(cron.Cron({
"weekday": cron.value("sunday")
}), cron.Cron({
"weekday": "sunday"
}))
self.assertEqual(cron.Cron... |
11486224 | import os, re, sys
class Blob:
def append(self, *_):
pass
def finish(self, *_):
pass
class Formula(Blob):
def __init__(self):
self.lines = []
def append(self, line):
self.lines.append(line)
def finish(self, *_):
for i, line in enumerate(self.lines):
... |
11486245 | import argparse
from curses import wrapper
import logging
import sys
import pprint
from _version import __version__, name
try:
from .core import bluelyze, term, get_logo, wifilyze, allyze
except:
from core import bluelyze, term, get_logo, wifilyze, allyze
def main(args):
"""
Executes logic from p... |
11486248 | def test_issue_455(data: list[i32]) -> f64:
sum: f64
sum = 0.0
i: i32
for i in range(len(data)):
sum += data[i]
return sum
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.