id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
402437 | import torch.nn as nn
class WNConv2d(nn.Module):
"""Weight-normalized 2d convolution.
Args:
in_channels (int): Number of channels in the input.
out_channels (int): Number of channels in the output.
kernel_size (int): Side length of each convolutional kernel.
padding (int): Padd... |
402447 | import pytest
from django.core.exceptions import ValidationError
from django.urls import path
from rest_batteries.errors_formatter import ErrorsFormatter
from rest_batteries.views import APIView
from rest_framework import serializers
from rest_framework.views import exception_handler as drf_exception_handler
from .mod... |
402536 | import bpy
from bpy_extras.io_utils import ExportHelper, ImportHelper
import math
from . import data
from . import calc
from . import create
from . import delete
from . import io
from . import update
from . test_camera_generator import test_main
from typing import Any, List, Dict, Tuple
# ---------------------------... |
402540 | from Crypto.Util.number import *
import random
def nextPrime(prim):
if isPrime(prim):
return prim
else:
return nextPrime(prim+1)
p = getPrime(512)
q = nextPrime(p+1)
while p%4 != 3 or q%4 !=3:
p = getPrime(512)
q = nextPrime(p+1)
n = p*q
m = open('secret.txt').read()
m = bytes_to_long... |
402552 | import re
import numpy as np
from utensor_cgen.backend.utensor.snippets._base import Snippet, SnippetBase
from utensor_cgen.backend.utensor.snippets._types import (NP_TYPES_MAP,
UTENSOR_TYPES_MAP)
__all__ = [
"OpConstructSnippet",
"DeclareRomTensorSnippet... |
402567 | import os
import pytest
import numpy as np
from datetime import datetime
import ezomero
from ezomero import rois
from omero.cli import CLI
from omero.gateway import BlitzGateway
from omero.gateway import ScreenWrapper, PlateWrapper
from omero.model import ScreenI, PlateI, WellI, WellSampleI, ImageI
from omero.model imp... |
402568 | from django.conf.urls import patterns, url
urlpatterns = patterns('webshell.views',
url(r'^execute/$', 'execute_python', name='execute-python'),
url(r'^execute-shell/$', 'execute_shell', name='execute-shell'),
) |
402587 | from collections import OrderedDict
import importlib
import inspect
import six
import warnings
calculators = OrderedDict() # active calculators
# all the calculators including those cannot be activated
# (not disclosed to outside, but used by make_details_md.py)
all_calculators = OrderedDict()
def check_signatu... |
402598 | import filecmp
import os
import pathlib
import shutil
import yaml
import numpy as np
import mc2client as mc2
import pytest
from envyaml import EnvYAML
# Note: to run this test, you'll need to start a gRPC orchestrator and an enclave running Secure XGBoost
# Follow the demo here to do so: https://secure-xgboost.readt... |
402614 | from pandac.PandaModules import *
MainCameraBitmask = BitMask32.bit(0)
ReflectionCameraBitmask = BitMask32.bit(1)
ShadowCameraBitmask = BitMask32.bit(2)
SkyReflectionCameraBitmask = BitMask32.bit(3)
GlowCameraBitmask = BitMask32.bit(4)
EnviroCameraBitmask = BitMask32.bit(5)
def setCameraBitmask(default, node_path, cam... |
402624 | from sphinx_gallery.sorting import ExampleTitleSortKey
class CustomSortKey(ExampleTitleSortKey):
def __call__(self, filename):
return ("" if filename == "basic.py" # goes first
else super().__call__(filename))
|
402639 | import pyaudio
import numpy
import wave
from reader import BaseReader
class MicrophoneReader(BaseReader):
default_chunksize = 8192
default_format = pyaudio.paInt16
default_channels = 2
default_rate = 44100
default_seconds = 0
# set default
def __init__(self, a):
super(MicrophoneReader, self).__init_... |
402687 | from mango.fields.base import *
from mango.fields.generic import *
from mango.fields.arrays import *
from mango.fields.compounds import *
from mango.fields.geometry import *
|
402691 | import os
from django.shortcuts import render
from django.urls import reverse
from django.http import HttpResponse, JsonResponse, Http404, HttpResponseRedirect
from django.views.decorators.csrf import csrf_exempt
from django.contrib.auth import authenticate, login
from django.contrib.auth.decorators import login_requi... |
402715 | import datetime
import pytest
import responses
from parameterized import parameterized
from tests.utils import CensysTestCase
from censys.search import SearchClient
VIEW_HOST_JSON = {
"code": 200,
"status": "OK",
"result": {
"services": [
{
"transport_protocol": "UDP"... |
402716 | from time import sleep, time
from unittest import TestCase
from mock import Mock, call
from tools import funcutils
class Testget_rate_limited_function(TestCase):
def setUp(self):
self.mock_func, self.mock_limit = Mock(name='func'), Mock(name='limit')
self.rate_limited_func = funcutils.get_rate_l... |
402730 | import logging
import sys
from textwrap import TextWrapper
import datasets
import huggingface_hub
import matplotlib.font_manager as font_manager
import matplotlib.pyplot as plt
import torch
import transformers
from IPython.display import set_matplotlib_formats
# TODO: Consider adding SageMaker StudioLab
is_colab = "g... |
402765 | import torch.nn as nn
import torch
from simple_nmt.encoder import Encoder
from simple_nmt.decoder import Decoder
from simple_nmt.attention import Attention
from simple_nmt.generator import Generator
from simple_nmt.search import SingleBeamSearchSpace
import data_loader
class Seq2Seq(nn.Module):
def __init__(self,... |
402770 | from django.urls import reverse
from faker import Faker
from openbook_common.tests.models import OpenbookAPITestCase
from rest_framework import status
import logging
import json
from openbook_common.tests.helpers import make_user, make_authentication_headers_for_user, \
make_community, make_fake_post_text, make_p... |
402775 | from torchvision import transforms
class ResizeImage(object):
''' Resize image transformation class.
It resizes an image and transforms it to a PyTorch tensor.
Args:
img_size (int or tuple): resized image size
'''
def __init__(self, img_size):
if img_size is None or img_size < 1:... |
402804 | import time
#start time recording
start = time.time()
import datetime
import mpmath
import math
from math import sqrt,sin,cos,tan
import mathutils
from itertools import chain
import bpy, bmesh
import numpy as np
import sympy
from sympy import symbols,I,latex,pi,diff,idiff #"I" is sympy's imaginary numbe... |
402816 | from collections import UserDict, defaultdict
class TypeConversionDict(UserDict):
def get(self, key, default=None, type=None):
try:
rv = self[key]
except KeyError:
return default
if type is not None:
try:
rv = type(rv)
except... |
402835 | from __future__ import unicode_literals
import pytest
from ... import load as load_spacy
def test_issue957(en_tokenizer):
'''Test that spaCy doesn't hang on many periods.'''
string = '0'
for i in range(1, 100):
string += '.%d' % i
doc = en_tokenizer(string)
# Don't want tests to fail if they... |
402855 | import contextlib
import os
import sys
import textwrap
import re
import unittest
import numpy as np
from sys import platform
from shutil import copytree
from subprocess import Popen, PIPE
from opensauce.__main__ import CLI
from opensauce.snack import sformant_names
from test.support import TestCase, data_file_path, ... |
402869 | from contextlib import suppress
from .adaptive import Adaptive
from .cluster import Cluster
from .local import LocalCluster
from .spec import ProcessInterface, SpecCluster
from .ssh import SSHCluster
with suppress(ImportError):
from .ssh import SSHCluster
|
402919 | import matplotlib.pyplot as plt
import numpy as np
def Marchenko_Pastur(N, nu):
X = nu* np.random.randn(int(2 ** (N / 2)), int(2 ** (N / 2)))
Y = X @ np.transpose(X)
Y /= np.trace(Y)
return np.log(np.sort(np.linalg.eigvals(Y))[::-1])
for i in [0.1, 0.5, 1.0, 2, 5, 10]:
plt.plot(Marchenko_Pastur(16... |
402927 | from typing import List
class Solution:
def minArray(self, numbers: List[int]) -> int:
left, right, mid = 0, len(numbers) - 1, 0
while numbers[left] >= numbers[right]:
if right - left == 1:
mid = right
break
mid = (left + right) // 2
if numbers[left] == numbers[mid] and numb... |
402944 | import asyncio
import numpy as np
from bokeh.plotting import Figure
from entropylab.graph_experiment import (
Graph,
PyNode,
pynode,
GraphExecutionType,
SubGraphNode,
)
async def a():
rest = 0.001
print(f"Node a resting for {rest}")
await asyncio.sleep(rest)
print(f"Node a finish... |
402966 | from direct.showbase.PythonUtil import getBase as get_base
class Connection:
def __set__(self, instance, value):
super().__set__(instance, value)
# TODO: This possibly should register when set then deregister when
# set to None.
if value is not None:
get_base().scene.... |
402980 | import re
import sublime
from ..emmet import expand as expand_abbreviation, extract, Config
from ..emmet.html_matcher import match, balanced_inward, balanced_outward
from ..emmet.css_matcher import balanced_inward as css_balanced_inward, \
balanced_outward as css_balanced_outward
from ..emmet.action_utils import se... |
403026 | from flask import Blueprint
import ckan.model as model
import ckan.plugins.toolkit as tk
from ckan.common import g
import ckan.logic as logic
import ckanext.hdx_package.helpers.analytics as analytics
import ckanext.hdx_package.helpers.custom_pages as cp_h
from ckanext.hdx_search.controller_logic.search_logic import ... |
403032 | from PuzzleLib.Backend import gpuarray
from PuzzleLib.Modules.Module import ModuleError, Module
class Pool1D(Module):
def __init__(self, size=2, stride=2, pad=0, name=None):
super().__init__(name)
self.gradUsesOutData = True
self.size = (1, size)
self.stride = (1, stride)
self.pad = (0, pad)
self.works... |
403040 | import logging
import time
from concurrent import futures
import grpc
from prometheus_client import start_http_server
import tests.integration.hello_world.hello_world_pb2 as hello_world_pb2
import tests.integration.hello_world.hello_world_pb2_grpc as hello_world_grpc
from py_grpc_prometheus.prometheus_server_intercep... |
403096 | import string
import random
helloWorld = ''
while (helloWorld != "Hello World!"):
helloWorld = ''
for i in range(11):
if i == 5:
helloWorld += ' '
else:
helloWorld += random.choice(string.ascii_letters)
helloWorld += '!'
print(helloWorld)
|
403124 | import numpy as np
from sklearn import preprocessing
from sklearn.ensemble import RandomForestClassifier
import matplotlib.pyplot as plt
input_file = 'car.data.txt'
# Reading the data
X = []
y = []
count = 0
with open(input_file, 'r') as f:
for line in f.readlines():
data = line[:-1].split(',')
X.... |
403132 | import logging
import requests
from protect_archiver.errors import Errors
class LegacyClient:
def __init__(
self,
protocol: str,
address: str,
port: int,
username: str,
password: str,
verify_ssl: bool,
):
self.protocol = protocol
self.a... |
403136 | import numpy
import numpy as np
n,m = map(int,input().split())
arr = np.array([input().split() for i in range(n)], int)
x=np.sum(arr,axis=0)
print(np.prod(x))
|
403145 | from typing import Any, Union
from boa3.builtin import NeoMetadata, metadata, public
from boa3.builtin.contract import Nep17TransferEvent, abort
from boa3.builtin.interop.blockchain import get_contract
from boa3.builtin.interop.contract import GAS, NEO, call_contract
from boa3.builtin.interop.runtime import calling_sc... |
403169 | import xml.etree.ElementTree as ET
import os
import sys
PATH_EVDEV = '/usr/share/X11/xkb/rules/evdev.xml'
PATH_SYMBOLS = '/usr/share/X11/xkb/symbols/us'
dir_path = os.path.dirname(os.path.realpath(__file__))
# Append the symbols file
with open(os.path.join(dir_path, 'intlde'), 'r') as intde_file:
with open(PATH_S... |
403203 | import networkx as nx
from utils import files,statistics
import json
# 将线的label数据进行处理,最后得到{'label':数值}
def get_data_from_label_edge(network):
# source target 其他label
labels = files.get_labels_from_db(network, False)
G = files.read_network_with_type(network)
edges = G.edges()
data = []
temp =... |
403207 | from typing import *
class PlotAccessor:
@overload
def area(self, /):
"""
usage.hvplot: 2
usage.koalas: 1
"""
...
@overload
def area(self, /, y: Literal["sales"]):
"""
usage.koalas: 1
"""
...
def area(self, /, y: Literal["sa... |
403219 | from flask_sqlalchemy import SQLAlchemy
from flask_bcrypt import Bcrypt
from sqlalchemy.ext.hybrid import hybrid_property
from sqlalchemy.sql.expression import func
from itsdangerous import (TimedJSONWebSignatureSerializer as Serializer, BadSignature, SignatureExpired)
db = SQLAlchemy()
bcrypt = Bcrypt()
# This is t... |
403268 | import FWCore.ParameterSet.Config as cms
muonPFNoPileUpIsolation = cms.EDProducer(
"CITKPFIsolationSumProducer",
srcToIsolate = cms.InputTag("muons"),
srcForIsolationCone = cms.InputTag('pfNoPileUpCandidates'),
isolationConeDefinitions = cms.VPSet(
cms.PSet( isolationAlgo = cms.string('MuonPFIs... |
403272 | from rubicon_ml import domain
from rubicon_ml.client import Experiment
def test_properties(project_client):
project = project_client
domain_experiment = domain.Experiment(
project_name=project.name,
description="some description",
name="exp-1",
model_name="ModelOne model",
... |
403284 | from imgaug import augmenters as iaa
augmenter = iaa.Sequential(
[
iaa.Fliplr(0.5),
],
random_order=True,
)
|
403318 | from math import pi
def circle_area(r):
if r < 0:
raise ValueError("value is negative")
if type(r) not in [int, float]:
raise TypeError("not integer or type")
return pi * r ** 2 |
403334 | import FWCore.ParameterSet.Config as cms
from Validation.HGCalValidation.hgcalRecHitStudyEE_cfi import *
hfnoseRecHitStudy = hgcalRecHitStudyEE.clone(
detectorName = cms.string("HGCalHFNoseSensitive"),
source = cms.InputTag("HGCalRecHit", "HGCHFNoseRecHits"),
ifNose = cms.untracked.bool(True),
rMi... |
403362 | import fabric
from .hostinfo import HostInfo, HostInfoList
from multiprocessing import Pipe, Process
from multiprocessing import connection as mp_connection
import click
def run_on_host(hostinfo: HostInfo, workdir: str, recv_conn: mp_connection.Connection,
send_conn: mp_connection.Connection, env: dic... |
403381 | import locale
def hebrew_strftime(dt, fmt=u'%A %d %B %Y %H:%M'):
locale.setlocale(locale.LC_ALL, 'he_IL.utf8')
return dt.strftime(fmt).decode('utf8')
|
403429 | from distutils.version import StrictVersion
from rest_framework import VERSION as REST_FRAMEWORK_VERSION
REST_FRAMEWORK_V3 = StrictVersion(REST_FRAMEWORK_VERSION) > StrictVersion('3.0.0')
|
403441 | class Solution(object):
# def singleNumber(self, nums):
# """
# :type nums: List[int]
# :rtype: int
# """
# # hash
# dic = {}
# for num in nums:
# try:
# dic[num] += 1
# except KeyError:
# dic[num] = 1
... |
403460 | from sklearn.svm import LinearSVC
from sklearn.datasets import load_iris
from gama.postprocessing.ensemble import fit_and_weight
def test_fit_and_weight():
x, y = load_iris(return_X_y=True)
good_estimator = LinearSVC()
bad_estimator = LinearSVC(
penalty="l1"
) # Not supported with default squ... |
403479 | import pytest
from tests.examples import TestExample as base_class
@pytest.mark.suite('mpi')
class TestExampleRPC3b(base_class):
r"""Test the rpc_lesson3b example."""
@pytest.fixture(scope="class")
def example_name(self):
r"""str: Name of example being tested."""
return "rpc_lesson3b"... |
403486 | import torch
import torch.nn as nn
import torch.nn.functional as F
from torchsummary import summary
import sys
import ipdb
import itertools
import warnings
import shutil
import pickle
from pprint import pprint
from types import SimpleNamespace
from math import floor,ceil
from pathlib import Path
import... |
403491 | import os
import shutil
import six
import pytest
import numpy as np
from pyshac.config import hyperparameters as hp, data
# compatible with both Python 2 and 3
try:
FileNotFoundError
except NameError:
FileNotFoundError = IOError
def deterministic_test(func):
@six.wraps(func)
def wrapper(*args, **kw... |
403507 | import asyncio
from aiohttp.web import Application
from aioqiwi.kassa import QiwiKassa, Notification
from aioqiwi.wallet import Wallet, WebHook, types, enums
from aioqiwi.core.currencies import Currency
loop = asyncio.get_event_loop()
qiwi = Wallet("api_hash from qiwi.com/api", loop=loop) #
kassa = QiwiKassa("secr... |
403522 | import unittest
from tests.lib.client import get_client
from tests.lib.utilities import Utilities
from tests.lib.user_verifications import verify_user_card_holder_response
class TestUsersCreate(unittest.TestCase):
"""Tests for the users.create endpoint."""
def setUp(self):
"""Setup for each test."""... |
403539 | import os
import torch
from collections import OrderedDict
from pathlib import Path
from tqdm import tqdm
import sys
from matplotlib import pyplot as plt
import cv2
pix2pixhd_dir = Path('../src/pix2pixHD/')
sys.path.append(str(pix2pixhd_dir))
from data.data_loader import CreateDataLoader
from models.models import crea... |
403541 | class Solution(object):
def isValid(self, s):
"""
:type s: str
:rtype: bool
"""
if len(s) == 0:
return True
if len(s) == 1:
return False
left = []
right = []
for i in range(len(s)):
c = s[i]
if c ... |
403695 | import importlib
import os.path as osp
def get_config(config_file):
assert config_file.startswith(
'configs/'), 'config file setting must start with configs/'
temp_config_name = osp.basename(config_file)
temp_module_name = osp.splitext(temp_config_name)[0]
config = importlib.import_module("con... |
403710 | import sys
from pretty_midi.utilities import program_to_instrument_class
sys.path.append('./models')
sys.path.append('../accomontage code/models')
from model import DisentangleVAE
from ptvae import PtvaeDecoder
from EC2model import VAE
sys.path.append('./util_tools')
from format_converter import melody_matrix2data, ... |
403719 | from __future__ import print_function, absolute_import, division
from future.builtins import *
from future import standard_library
standard_library.install_aliases()
# Copyright 2017 Autodesk Inc.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with t... |
403751 | import re
import time
import codecs
import os, shutil
import random
def prep_str(text):
text = text.lower()
text = re.sub("([^a-zA-Z])", " ", text)
text = re.sub(" +", " ", text)
tokens = text.split()
return tokens
def counter(word_dict, tokens):
count = len(word_dict)
for word in tokens:
count +=1
if ... |
403754 | import json
import iam_floyd as statement
def get_policy():
# doc-start
policy = {
'Version': '2012-10-17',
'Statement': [
# allow all CFN actions
statement.Cloudformation() \
.allow() \
.all_actions() \
... |
403778 | from ExamplePage import ExamplePage
class CustomError:
"""Custom classic class not based on Exception (for testing)."""
def __init__(self, msg):
self.msg = msg
def __str__(self):
return self.msg
class Error(ExamplePage):
def title(self):
return 'Error raising Example'
... |
403792 | import torch
import torch.utils.data as torch_data
import os
class dataset(torch_data.Dataset):
def __init__(self, src1, src2,src3, tgt, tgtv,tgtpv):#raw_src1, raw_src2, raw_src3, raw_tgt):
self.src1 = src1
self.src2 = src2
self.src3 = src3
self.tgt = tgt
self.tgtv = tgtv
... |
403801 | import configparser
import os
BASEDIR = os.path.normpath(os.path.join(os.path.dirname(__file__), os.pardir))
_config = configparser.ConfigParser()
_config.read(os.path.join(BASEDIR, 'config.ini'))
config = _config['FILE']
def save(key, value):
with open(config['KEYSTORE'], "a") as keystore:
keystore.wri... |
403804 | import random
import string
from nose.plugins.skip import SkipTest
from galaxy_test.base.populators import DatasetPopulator, skip_if_toolshed_down
from galaxy_test.driver import integration_util
from .uses_shed import CONDA_AUTO_INSTALL_JOB_TIMEOUT, UsesShed
FETCH_TOOL_ID = 'toolshed.g2.bx.psu.edu/repos/devteam/data... |
403809 | from __future__ import (absolute_import, division,
print_function, unicode_literals)
from ast import literal_eval
from builtins import *
from future.utils import iteritems
import os
import json
import logging
from brave.palettes import *
from brave.notebook_display import *
ipython = try_imp... |
403813 | from config import RESULT_PATH, DATABASE_PATH
from utils import load_splitdata, balancer_block, save_to_pickle, \
load_from_pickle, check_loadsave, training_series, evaluating_series, \
load_30xonly, load_50xonly
from utils import mutypes, pcodes
from os import path, makedirs
from sys import argv
import num... |
403872 | import pytest
import json
import aleph.chains
from aleph.chains.substrate import verify_signature
TEST_MESSAGE = '{"chain": "DOT", "channel": "TEST", "sender": "<KEY>", "type": "AGGREGATE", "time": 1601913525.231501, "item_content": "{\\"key\\":\\"test\\",\\"address\\":\\"5CGNMKCscqN2QNcT7Jtuz23ab7JUxh8wTEtXhECZLJn5v... |
403889 | class Handler:
"""
The handler is responsible for running special events based on an instance.
Typical use-cases: Feed updates, email and push notifications.
Implement the handle_{action} function in order to execute code.
Default actions: create, update, delete
"""
model = None
def ... |
403945 | from amuse.test import amusetest
from amuse.datamodel.incode_storage import *
import numpy
import time
from amuse.units import units
from amuse.units import constants
from amuse.units import nbody_system
class TestParticles(amusetest.TestCase):
def test1(self):
class Code(object):
def __... |
403968 | import unittest
from zoonado import exc
class ExceptionTests(unittest.TestCase):
def test_connect_error_string(self):
e = exc.ConnectError("broker01", 9091, server_id=8)
self.assertEqual(str(e), "Error connecting to broker01:9091")
def test_response_error_string(self):
e = exc.Data... |
403982 | import matplotlib.pyplot as plt
import pandas as pd
from sklearn.datasets import load_boston
if __name__ == "__main__":
dataset = load_boston()
x = dataset.data
y = dataset.target
df = pd.DataFrame(x, columns=dataset.feature_names)
df["y"] = y
print(df.head(n=10))
print(df.info())
pr... |
403985 | import ujson as json
from sift.corpora import wikicorpus
from sift.dataset import ModelBuilder, Model, Redirects, Documents
from sift import logging
log = logging.getLogger()
class WikipediaCorpus(ModelBuilder, Model):
def build(self, sc, path):
PAGE_DELIMITER = "\n </page>\n"
PAGE_START = '<pag... |
403989 | import thumb_shift_immediate_add_subtract_move_and_compare
import thumb_data_processing
import thumb_special_data_instructions_and_branch_and_exchange
from ldr_literal_t1 import LdrLiteralT1
import thumb_load_store_single_data_item
from adr_t1 import AdrT1
from add_sp_plus_immediate_t1 import AddSpPlusImmediateT1
impor... |
404018 | import os
import numpy as np
from PIL import Image
from torch import nn
from lib.syncbn import SynchronizedBatchNorm1d, SynchronizedBatchNorm2d, SynchronizedBatchNorm3d
import torch.nn.init as initer
class AverageMeter(object):
"""Computes and stores the average and current value"""
def __init__(self):
... |
404029 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
import argparse
from functools import partial
from multiprocessing import Pool
import os
import re
import cropper
import numpy as np
import tqdm
# ============================================================... |
404035 | from __future__ import annotations
import math
from copy import copy
from typing import TYPE_CHECKING
from objects import Vector3, Routine
from utils import cap, defaultPD, defaultThrottle, sign, backsolve, shot_valid
if TYPE_CHECKING:
from hive import MyHivemind
from objects import CarObject, BoostObject
g... |
404041 | import unittest
from surlex import surlex_to_regex as surl, match, register_macro, parsed_surlex_object, Surlex, MacroRegistry
from surlex import grammar
from surlex.exceptions import MalformedSurlex, MacroDoesNotExist
import re
class TestGrammer(unittest.TestCase):
def test_parser_simple(self):
parser = g... |
404056 | from os import getenv as env
import logging
from utils import setup_logging, GSheet
GSHEETS_DOC_ID = env("GSHEETS_DOC_ID")
GSHEETS_SHEET_NAMES = env("GSHEETS_SHEET_NAMES")
logger = logging.getLogger()
@setup_logging
def handler(event, context):
"""
Load google sheet, parse, and import into dynamoDB.
""... |
404057 | import time
from dgim.utils import generate_random_stream
from dgim import Dgim
def profile_dgim(dgim, stream):
for elt in stream:
dgim.update(elt)
def main():
N = 1000000
error_rate = 0.5
length = 2 * N
dgim = Dgim(N=N, error_rate=error_rate)
stream = generate_random_stream(length=l... |
404061 | import argparse # polyaxon parameters
from typing import List
def get_parameters():
"""
Gets the parser with its arguments and returns a dictionary of those args
"""
parser = add_args()
args = parser.parse_known_args()
parameters = args[0].__dict__
return parameters
def add_args():
... |
404137 | import argparse
import numpy as np
import pandas as pd
import torch
import torch.nn as nn
from sklearn.model_selection import train_test_split
from joblib import load
from EEGGraphDataset import EEGGraphDataset
from dgl.dataloading import GraphDataLoader
from torch.utils.data import WeightedRandomSampler
from sklearn.m... |
404161 | import functools
import numpy as np
from scipy.ndimage import map_coordinates
def uv_meshgrid(w, h):
uv = np.stack(np.meshgrid(range(w), range(h)), axis=-1)
uv = uv.astype(np.float64)
uv[..., 0] = ((uv[..., 0] + 0.5) / w - 0.5) * 2 * np.pi
uv[..., 1] = ((uv[..., 1] + 0.5) / h - 0.5) * np.pi
return... |
404174 | from django.db import models, migrations
def rename(apps, _schema_editor):
GradeDocument = apps.get_model('grades', 'GradeDocument')
for grade_document in GradeDocument.objects.all():
if grade_document.type == 'PRE':
grade_document.type = 'MID'
grade_document.save()
class Mig... |
404210 | import torch
import torch.nn as nn
import torchvision.models
import torch.nn.functional as F
from sklearn.cluster import KMeans
from sklearn.metrics.pairwise import cosine_similarity
from models.backbones import *
from models.senet import *
from models.activation import *
from models.layers import *
'''
Modified bac... |
404214 | import setuptools
with open("README.md", "r") as fh:
long_description = fh.read()
setuptools.setup(
name="kcrawler",
version="1.1",
author="ken",
author_email="<EMAIL>",
description="A python crawler authored by Ken.",
long_description=long_description,
long_description_content_type="t... |
404244 | import FWCore.ParameterSet.Config as cms
# Energy scale correction for Fixed Matrix Endcap SuperClusters
correctedFixedMatrixSuperClustersWithPreshower = cms.EDProducer("EgammaSCCorrectionMaker",
corectedSuperClusterCollection = cms.string(''),
sigmaElectronicNoise = cms.double(0.15),
superClusterAlgo = cm... |
404252 | import json
from django.conf import settings
from django.core.management.base import BaseCommand
# package might not be installed
try:
import environ
except ImportError:
environ = None
class SettingsEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, set):
return list(... |
404265 | import os
app_dir = os.path.abspath(os.path.dirname(__file__))
class BaseConfig:
DEBUG = True
POSTGRES_URL="migrate-app-to-azure-database.postgres.database.azure.com" #TODO: Update value
POSTGRES_USER="manish@migrate-app-to-azure-database" #TODO: Update value
POSTGRES_PW="<PASSWORD>" #TODO: Update... |
404268 | from openprocurement.auction.core import compoenents
class TestDispatch(object):
def test_predicate(self):
pass
def test_plugin_load(self):
pass
def test_adapters(self):
pass
|
404270 | from setuptools import setup, find_packages
import glob
import os
# Find C++ files by obtaining the module path and trimming the absolute path
# of the resulting files.
d500_path = os.path.dirname(os.path.abspath(__file__)) + '/deep500/'
cpp_files = [
f[len(d500_path):]
for f in glob.glob(d500_path + 'framewor... |
404278 | import unittest
from pathlib import Path
from unittest.mock import MagicMock
from dockerized.adapters.dockercompose import DockerCompose
from dockerized.adapters.environment import Environment
from dockerized.core.commands.shell import ShellCommand
class TestShellCommand(unittest.TestCase):
def test_runs_docker_... |
404284 | import json
import os
import requests
from hassbrainapi.settings import *
import hassbrainapi.util as hb_util
from io import BytesIO
# FIELDS
SCORE = "score"
PREDICTED_ACTIVITY = "predicted_state"
RT_NODE = "rt_node"
def get(url, user_name, password):
auth=(user_name, password)
url = url + URL_DEVICE_PRED
... |
404307 | from django.db import models
class Recommend(models.Model):
TYPE_CHOICES = (
('N', 'New'),
('A', 'Added'),
('L', 'Not Good Enough'),
('I', 'Ignore'),
('O', 'Others'),
)
email = models.CharField(max_length=100, unique=True, blank=True)
category = models.CharField(max... |
404314 | import json
import logging
import datetime
import hmac
import pytz
import hashlib
from typing import List, Any
from cryptoxlib.WebsocketMgr import Subscription, WebsocketMgr, WebsocketMessage, Websocket, CallbacksType, \
ClientWebsocketHandle, WebsocketOutboundMessage
from cryptoxlib.Pair import Pair
from cryptoxl... |
404317 | from modules.base import BaseModule, registerModule
import os,subprocess
from sources.base import BaseSource, SourceSelector, CommonSource
from sources import *
from utils import formats
from utils.command import OptionParser
@registerModule
class M3U8(BaseModule):
name = "M3U8"
selector = SourceSelector(bili... |
404385 | import typing
import logging
import contextlib
import asyncio
from concurrent.futures import Future as ThreadFuture
from .sentry import sentry_scope
from .actor import Actor
from .message import ActorMessage
from .client import AsyncActorClient, ActorClient
from .registery import ActorRegistery
from .queue import Acto... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.