id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
3294446 | from core.models import Project, Volume
from rest_framework import serializers
from api.v2.serializers.summaries import ProjectSummarySerializer
from .volume import VolumeSerializer
class ProjectRelatedField(serializers.PrimaryKeyRelatedField):
def get_queryset(self):
return Project.objects.all()
def... |
3294452 | import os
DIRNAME = os.path.dirname(__file__)
DEBUG = True
DATABASE_ENGINE = 'sqlite3'
DATABASE_NAME = os.path.join(DIRNAME, 'mptt.db')
#DATABASE_ENGINE = 'mysql'
#DATABASE_NAME = 'mptt_test'
#DATABASE_USER = 'root'
#DATABASE_PASSWORD = ''
#DATABASE_HOST = 'localhost'
#DATABASE_PORT = '3306'
#DATAB... |
3294489 | import os
import numpy as np
import matplotlib.animation as animation
import matplotlib.colors as colors
import matplotlib.patheffects as pe
import matplotlib.pyplot as plt
from matplotlib.animation import ArtistAnimation
from mpl_toolkits.mplot3d import Axes3D
from Quaternions import Quaternions
def animation_plot(... |
3294533 | from pathlib import Path
import random
import numpy
from pyrr import matrix44
import moderngl
import moderngl_window
from moderngl_window.opengl.vao import VAO
class Boids(moderngl_window.WindowConfig):
"""
An attempt to make something boid-list with GL3.3.
Not currently working as intended,... |
3294555 | import hashlib
from corehq.apps.integration.models import (
DialerSettings,
GaenOtpServerSettings,
HmacCalloutSettings,
)
def domain_uses_dialer(domain):
try:
settings = DialerSettings.objects.get(domain=domain)
return settings.is_enabled
except DialerSettings.DoesNotExist:
... |
3294557 | import tensorflow as tf
# ===============================================
# Previously was snippets.py of: 3_2_RNNs
# ===============================================
# i = input_gate, j = new_input, f = forget_gate, o = output_gate
# Get 4 copies of feeding [inputs, m_prev] through the "Sigma" diagram.
# Note that ea... |
3294595 | from typing import Optional, Sequence
from pydicom.dataset import Dataset
class CodingSchemeResourceItem(Dataset):
"""Class for items of the Coding Scheme Resource Sequence."""
def __init__(self, url: str, url_type: str) -> None:
"""
Parameters
----------
url: str
... |
3294610 | from datetime import timedelta
import arrow
from django.conf import settings
from django.contrib.auth import get_user_model
from django.core.files.base import ContentFile
from django.utils import timezone
from model_bakery import baker
from devilry.apps.core.deliverystore import MemoryDeliveryStore
from devilry.apps.... |
3294616 | import time
from agent import monitoring
from agent.modules import logger
logger_ = logger.get_logger(__name__)
SCRIPT_NAME = 'monitoring'
start = time.time()
if __name__ == '__main__':
try:
monitoring.run()
monitoring.set_scheduled_script_execution_time(SCRIPT_NAME, time.time() - start)
exc... |
3294627 | import numpy as np
import pytest
import xarray as xr
from esmtools.temporal import to_annual
@pytest.mark.parametrize(
"dataset",
(
pytest.lazy_fixture("gridded_da_datetime"),
pytest.lazy_fixture("gridded_da_cftime"),
),
)
def test_to_annual(dataset):
"""General checks that `to_annual... |
3294700 | import re
from bs4 import BeautifulSoup
from bs4.element import Comment
def visible_text_for(html):
def visible(element):
if element.parent.name in ['style', 'script', '[document]', 'head', 'title']:
return False
elif isinstance(element, Comment):
return False
# Hid... |
3294713 | import tensorflow as tf
import numpy as np
import math
%autoindent
try:
from tqdm import tqdm
except ImportError:
def tqdm(x, *args, **kwargs):
return x
# Set random seed
np.random.seed(0)
# Load data
data = np.load('data_with_labels.npz')
train = data['arr_0']/255.
labels = data['arr_1']
# Look at s... |
3294716 | import FWCore.ParameterSet.Config as cms
from DQMServices.Core.DQMEDAnalyzer import DQMEDAnalyzer
pixel_lumi_dqm = DQMEDAnalyzer('PixelLumiDQM',
pixelClusterLabel = cms.untracked.InputTag("siPixelClusters"),
includePixelClusterInfo = cms.untracked.bool... |
3294774 | from shufflenet_v2 import (
shufflenet_v2_x0_5,
shufflenet_v2_x1_0,
shufflenet_v2_x1_5,
shufflenet_v2_x2_0,
)
|
3294850 | from torch.utils import model_zoo
def load_pretrained(model, url):
state_dict = model_zoo.load_url(url)
state_dict = {k[7:]: v for k, v in state_dict.items() if 'module.' in k}
model.load_state_dict(state_dict, strict=False)
|
3294918 | import matplotlib
matplotlib.use('Agg')
import numpy as np
import scipy.stats
import matplotlib.pylab as plt
import os
import sys
from .context import vfe
from .context import config
import pdb
np.random.seed(42)
# We first define several utility functions
def kink_true(x):
fx = np.zeros(x.shape)
for t in ran... |
3294937 | from __future__ import division, print_function, absolute_import
import numpy as np
from numpy.testing import assert_array_equal, assert_equal
from scipy.optimize._constraints import (NonlinearConstraint, Bounds,
PreparedConstraint)
from scipy.optimize._trustregion_constr.canoni... |
3294978 | import torch
import torch.nn as nn
from torch.nn import functional as F
from .common import quantization
def normalization_on_weights(x, clip_value):
x = x / clip_value
x = torch.clamp(x, min=-1, max=1)
return x
def normalization_on_activations(x, clip_value):
x = x / clip_value
... |
3295002 | import lzma
import re
import sys
from tqdm import tqdm
typosre = re.compile(
r"((fix|correct)(|ed)\s+(|a\s+|the\s+)(typo|misprint)s?\s+.*(func|function|method|var|variable|cls|class|struct|identifier|attr|attribute|prop|property|name))|(^s/[^/]+/[^/]+)",
re.IGNORECASE)
typosblackre = re.compile(r"filename|fil... |
3295018 | from typing import Callable
import numpy as np
import pytest
from xarray.core.dataarray import DataArray
from xclim.core.calendar import percentile_doy
from xclim.indices import (
cold_spell_duration_index,
days_over_precip_thresh,
fraction_over_precip_thresh,
tg10p,
tg90p,
tn10p,
tn90p,
... |
3295043 | from os.path import join
from pprint import pformat
variants = ['classique', 'moderne', 'reforme1990', 'toutesvariantes']
header = '''"""
Ligature dictionary
"""
'''
class Word(object):
def __init__(self, wordline):
self._line = wordline # for debugging
if "/" in wordline:
self.wor... |
3295062 | import os
import pytest
import shutil, tempfile
nbdir = os.path.join('notebooks')
testdir = tempfile.mkdtemp()
def get_notebooks():
return [f for f in os.listdir(nbdir) if f.endswith('.ipynb')]
def get_jupyter_kernel():
try:
jklcmd = ('jupyter', 'kernelspec', 'list')
b = subprocess.Popen(jkl... |
3295112 | import os
from logging import getLogger
import numpy as np
import matplotlib.pyplot as plt
from matplotlib.animation import FuncAnimation
import matplotlib.animation as animation
logger = getLogger(__name__)
class Animator():
""" animation class
"""
def __init__(self, env, args=None):
"""
... |
3295142 | import mxnet as mx
import numpy as np
from operator_py.nms import py_nms_wrapper
def multiclass_nms(nms, cls_score, bbox_xyxy, min_det_score, max_det_per_image):
# remove background
cls_score = cls_score[:, 1:]
# TODO: the output shape of class_agnostic box is [n, 4], while class_aware box is [n, 4 * (1 +... |
3295143 | import ctypes
import os
import matplotlib.pyplot as plt
import nlopt
import numpy as np
from numba import njit
from numba import vectorize
from numba.extending import get_cython_function_address
from scipy import special
from tables import ComplexCol
from tables import Float64Col
from tables import IsDescription
from ... |
3295153 | import unittest
import torch
import numpy as np
import numpy.testing as npt
from torch_points_kernels import grouping_operation
class TestGroup(unittest.TestCase):
# input: points(b, c, n) idx(b, npoints, nsample)
# output: out(b, c, npoints, nsample)
def test_simple(self):
features = torch.tenso... |
3295174 | class User(object):
def __init__(self, name, pass):
self.name = name
self.pass = <PASSWORD>
class Permission(object):
def __init__(self, type):
self.type = type
|
3295177 | import json
from datetime import datetime
import pytest
from django.test import override_settings
from django.urls import resolve
from tests.testapp.models import BlogPage
from tests.utils import reload_urlconf
from wagtail_live.publishers.polling import LongPollingPublisher, PollingPublisherMixin
@pytest.fixture(s... |
3295196 | from .behavior import Behavior, BehaviorTemplate, BlackBoxBehavior
from .baseline import ConstantBehavior, DummyBehavior, RandomBehavior
from .hierarchical_behavior_template import HierarchicalBehaviorTemplate
from .linear import LinearBehavior
__all__ = [
"Behavior", "BehaviorTemplate", "BlackBoxBehavior", "Cons... |
3295217 | import pytest
from accounts.models import Account, AccountTier
from jobs.models import Queue, Zone
@pytest.mark.django_db
def test_queue_get_or_create():
AccountTier.objects.create()
acme = Account.objects.create(name="acme")
# Existing zone
north = Zone.objects.create(account=acme, name="north")
... |
3295237 | import itertools
import torch
import networkx as nx
from torch_geometric.utils import convert
from torch_geometric.data import Data
def check_edge_index_are_the_same(upper_index, edge_index):
"""Checks that two edge/cell indexes are the same."""
# These two tensors should have the same content but in differe... |
3295261 | try:
import commentjson as json
except ImportError:
import json
import argparse
def extractEventLists(solution):
divisions = solution["divisionResults"]
moves = solution["linkingResults"]
detections = solution["detectionResults"]
if divisions is None:
divisions = []
d... |
3295266 | EXPECTED = {'Foo': {'extensibility-implied': False,
'imports': {},
'object-classes': {},
'object-sets': {},
'types': {'Answer': {'members': [{'name': 'id', 'type': 'INTEGER'},
{'name': 'answer',
'typ... |
3295268 | from pepper.framework import *
from pepper.language import Utterance
from .responder import Responder, ResponderType
from pepper.knowledge import animations
from typing import Optional, Union, Tuple, Callable
from random import choice
import re
class GreetingResponder(Responder):
GREETINGS = [
"Yo",
... |
3295282 | from tinyspline import *
from tkinter import *
spline = BSpline(7)
ctrlp = spline.control_points
ctrlp[0] = 120 # x0
ctrlp[1] = 100 # y0
ctrlp[2] = 270 # x1
ctrlp[3] = 40 # y1
ctrlp[4] = 370 # x2
ctrlp[5] = 490 # y2
ctrlp[6] = 590 # x3
ctrlp[7] = 40 # y3
ctrlp[8] = 570 # x4
ctrlp[9] = 490 # y4
ctrlp[10] =... |
3295283 | import unittest
from unittest import mock
import copy
from tornado import gen
from tornado import testing
from jupyterhub_profiles import PrimeHubSpawner, OIDCAuthenticator
import jupyterhub
def mock_spawner():
return PrimeHubSpawner(_mock=True)
class AuthStateBuilder(object):
def __init__(self):
... |
3295299 | import os
import pandas as pd
train_dir = 'train_data'
def load_simple(data_dir=train_dir):
"""
returns a tuple with columns
timesteps: ndarray representing timesteps
prev_price: ndarray price right now you use for predictions
x1: ndarray representing a feature
x2: ndarray repre... |
3295392 | class Solution:
def totalHammingDistance(self, nums: List[int]) -> int:
res = 0
for pos in range(32):
bit_count = sum(((n >> pos) & 1) for n in nums)
res += bit_count * (len(nums) - bit_count)
return res
|
3295394 | def bubbleSort(arr):
n = len(arr)
ctr = 0
for i in range(n-1):
for j in range(0, n-i-1):
if arr[j] > arr[j + 1] :
arr[j], arr[j + 1] = arr[j + 1], arr[j]
ctr += 1
print(ctr)
lst = [1, 2, 3, 5, 4]
bubbleSort(lst)
# since lists are mutable
# the main list ... |
3295405 | import random
import time
import gevent
import grpc
from locust import User, events, task, constant
from locust.clients import HttpSession
from nacl.signing import SigningKey
# [transfer]
# 1) prepare (and sign) hsc transfer transaction to <TRANSFER>
# 2) prepare (and sign) hedera transaction
# 3) send hedera tra... |
3295421 | import abc
import asset_definitions
import django.core.exceptions
import django.forms
import django.template.loader
import django.utils.encoding
import django.utils.six
from typing import *
TemplateContext = Dict[str, Any]
__all__ = (
"PageComponent",
"TemplatePageComponent",
)
@django.utils.encoding.pyth... |
3295432 | from django.contrib import messages
from django.contrib.contenttypes.models import ContentType
from django.utils.translation import ugettext, ugettext_lazy as _
from utils.tokenizer import Token
from .models import Image
from .forms import ImageUploadForm
from . import signals
def get_gallery_context(request, contai... |
3295433 | from copy import deepcopy
import torch
from torch import nn
from torch.nn import functional as F
from torch.autograd import Variable
from torch import optim
import torch.utils.data
def var2device(t: torch.Tensor, use_cuda=True, **kwargs):
if torch.cuda.is_available() and use_cuda:
t = t.cuda()
return... |
3295464 | from ParadoxTrading.Engine import ExecutionAbstract, OrderEvent, FillEvent
from ParadoxTrading.Utils import DataStruct
class BarBacktestExecution(ExecutionAbstract):
"""
This is a simple and !!dangerous!! execution.
It only accept limit order with price.
And it will send fill event according to the or... |
3295504 | import os
import migrate.versioning.api as api
from migrate.exceptions import DatabaseAlreadyControlledError
from mlcomp import SA_CONNECTION_STRING
def migrate(connection_string: str = None):
folder = os.path.dirname(__file__)
connection_string = connection_string or SA_CONNECTION_STRING
try:
a... |
3295519 | import numpy as np
import geovista as gv
M, N = 45, 90
lats = np.linspace(-90, 90, M + 1)
lons = np.linspace(-180, 180, N + 1)
mlons, mlats = np.meshgrid(lons, lats, indexing="xy")
data = np.random.random((M + 1) * (N + 1))
mesh = gv.Transform.from_2d(mlons, mlats, data=data, name="synthetic")
plotter = gv.GeoPlott... |
3295552 | class Node:
""" A singly-linked node. """
def __init__(self, data=None):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__ (self):
self.tail = None
def append(self, data):
# Encapsulate the data in a Node
node = Node(data)
i... |
3295590 | import numpy
import math
import os
import gc
import cv2
import pandas
from tensorflow.keras.utils import Sequence
import girder_client
from sklearn.utils import shuffle
import random
class CNNSequence(Sequence):
def __init__(self,datacsv,indexes,batchSize,labelName,gClient = None,tempFileDir = None,shuffle=True,a... |
3295659 | import mock
import json
import cherrypy
from tests import base
from cumulus.constants import ClusterStatus
from girder.utility.model_importer import ModelImporter
AnsibleClusterAdapter = None
def setUpModule():
global AnsibleClusterAdapter
base.enabledPlugins.append('cumulus')
cherrypy.server.socket_por... |
3295726 | def test_empty_object(worksheet):
ws = worksheet
sheet_items = ws.sheet_items
assert sheet_items == []
def test_parse_csv_header(worksheet):
ws = worksheet
path = "tests/inventory.csv"
csv_file = open(path, "r", encoding="utf-8-sig")
ws.csv_to_dict(csv_file=csv_file, delimiter=";")
ws_... |
3295762 | import os
import subprocess
from avatar2 import *
filename = "a.out"
GDB_PORT = 1234
# This is a bare minimum elf-file, gracefully compiled from
# https://github.com/abraithwaite/teensy
tiny_elf = (
b"\x7f\x45\x4c\x46\x02\x01\x01\x00\xb3\x2a\x31\xc0\xff\xc0\xcd\x80"
b"\x02\x00\x3e\x00\x01\x00\x00\x00\x08\x00... |
3295796 | import json
import psycopg2
def lambda_handler(event, context):
# TODO implement
device_apn_token = event['queryStringParameters']['device_apn_token']
device_registration_token = event['queryStringParameters']['device_registration_token']
connection = psycopg2.connect(user = "<db_user>",
... |
3295817 | from __future__ import print_function
import contextlib
import numpy
import time
import math
from py import gosum
@contextlib.contextmanager
def time_print(task_name="", repititions=4):
t = time.time()
try:
yield
finally:
print(task_name, ":", time.time() - t, "s")
# Sin of NumPy array u... |
3295818 | import time
def func_timer(function):
@wraps(function)
def function_timer(*args, **kwargs):
print('[Function: {name} start...]'. \
format(name=function.__name__))
t0 = time.time()
result = function(*args, **kwargs)
t1 = time.time()
print('[Function: {name} finished, spent time... |
3295824 | def method1():
class PetrolPump:
def __init__(self, petrol, distance):
self.petrol = petrol
self.distance = distance
def printTour(arr):
n = len(arr)
start = 0
end = 1
curr_petrol = arr[start].petrol - arr[start].distance
while end != ... |
3295868 | from fs_data import FSData
if __name__=="__main__":
# RL
alhpa = 0.1
gamma = 0.99
epsilon = 0.01
# BSO
flip = 5
max_chance = 3
bees_number = 10
maxIterations = 10
locIterations = 10
# Test type
typeOfAlgo = 1
nbr_exec = 1
dataset = "Iris"
data_loc_path... |
3295871 | from __future__ import print_function
from crhelper import CfnResource
import logging
import boto3
import os
logger = logging.getLogger(__name__)
helper = CfnResource(json_logging=False, log_level='DEBUG', boto_level='CRITICAL')
client = boto3.client('cognito-idp')
try:
## Init code goes here
pass
except Exc... |
3295881 | from rlzoo.algorithms.pg.pg import PG
from rlzoo.common.policy_networks import *
import gym
""" load environment """
env = gym.make('CartPole-v0').unwrapped
# env = gym.make('Pendulum-v0').unwrapped
# env = DummyVecEnv([lambda: env]) # The algorithms require a vectorized/wrapped environment to run
obs_space =... |
3295882 | from datetime import timedelta
from pycroft import config
from pycroft.helpers.interval import closedopen
from pycroft.lib import user as UserHelper
from pycroft.model import session
from tests import FactoryWithConfigDataTestBase, factories
class UserWithNetworkAccessTestCase(FactoryWithConfigDataTestBase):
def... |
3295894 | from nose.tools import *
from pymacaroons import Macaroon, Verifier, MACAROON_V1, MACAROON_V2
from pymacaroons.serializers import JsonSerializer
class TestSerializationCompatibility(object):
def setup(self):
pass
def test_from_go_macaroon_json_v2(self):
# The following macaroon have been gen... |
3295903 | import functools
from prompt_toolkit.buffer import Buffer
open_file_in_editor = functools.partial(Buffer._open_file_in_editor, None)
|
3295950 | import torch
import torch.nn as nn
from torch.autograd import Variable
import torch.nn.functional as F
class Embedding(nn.Embedding):
def reset_parameters(self):
print("Use uniform to initialize the embedding")
self.weight.data.uniform_(-0.05, 0.05)
if self.padding_idx is not None:
... |
3295964 | import zmq
import json
import numpy as np
from base64 import standard_b64decode, standard_b64encode
from types import MethodType #dont delete this gets called in an exec
import warnings
import re
class PygellanBridge:
_DEFAULT_PORT = 4827
_EXPECTED_ZMQ_SERVER_VERSION = '2.3.0'
"""
Master class for co... |
3296027 | from rcwa.shorthand import *
from rcwa import Material
class Layer:
"""
Class for defining a single layer of a layer stack used in a simulation
:param er: Permittivity of the layer
:param ur: Permeability of the layer
:param L: Thickness of the layer
:param n: Refractive index of the layer
:param crystal: Crys... |
3296042 | from genty import genty, genty_dataset
import sys
from app.master.atomizer import Atomizer
from app.master.job_config import ConfigValidationError
from app.master.cluster_runner_config import ClusterRunnerConfig, ConfigParseError
from test.framework.base_unit_test_case import BaseUnitTestCase
@genty
class TestCluste... |
3296072 | import os
class Directory:
def __init__(self, absPath):
"""
Creates a Directory object.
Parameters
absPath: An absolute path to the directory this object operates over.
"""
self.absPath = absPath
def getDirList(self, extWhiteList=[]):
"""
Retu... |
3296105 | import opendbpy as odb
import os
current_dir = os.path.dirname(os.path.realpath(__file__))
tests_dir = os.path.abspath(os.path.join(current_dir, os.pardir))
opendb_dir = os.path.abspath(os.path.join(tests_dir, os.pardir))
data_dir = os.path.join(tests_dir, "data")
db = odb.dbDatabase.create()
lef = odb.read_lef(db, ... |
3296111 | import time
from .utils import make_graph, preprocess_features, run_pic
class PIC:
"""Class to perform Power Iteration Clustering on a graph of nearest neighbors.
Args:
args: for consistency with k-means init
sigma (float): bandwith of the Gaussian kernel (default 0.2)
... |
3296140 | import abc
import math
import numbers
import random
import numpy as np
class AllowMoveStrategy(abc.ABC):
def start_new_component(self, initial_labels, attr, objective_func, comp_idx):
"""
This method should be called whenever a new connected component is
clustered.
Parameters
... |
3296215 | import unittest
import ast
import pandas as pd
from blotter import blotter
from pandas.util.testing import assert_dict_equal
class TestBlotter(unittest.TestCase):
def setUp(self):
pass
def tearDown(self):
pass
def assertEventEqual(self, ev1, ev2):
self.assertEqual(ev1.type, ev2.... |
3296231 | import math
import torch
from torch.distributions import constraints
from torch.nn import Parameter
from .isotropic import Isotropy
from .kernel import Kernel
class Cosine(Isotropy):
r"""
Implementation of Cosine kernel:
:math:`k(x,z) = \sigma^2 \cos\left(\frac{|x-z|}{l}\right).`
:param torch.... |
3296240 | import boto3
s3 = boto3.resource('s3')
def lambda_handler(event, context):
num_of_file = int(event['num_of_file'])
bucket = event['input_bucket']
all_keys = []
for obj in s3.Bucket(bucket).objects.all():
all_keys.append(obj.key)
print("Number of File : " + str(len(all_keys)))
if... |
3296249 | import unittest
from quasimodo.statement_maker import StatementMaker
dataset = [
("why is", "is", ""),
("how is software piracy illegal in the first place?", "software", 'software piracy is illegal in the first place'),
("why are white monkeys superior to other races?", "white", 'white monkeys are superio... |
3296265 | class Solution:
def rob(self, root: TreeNode) -> int:
if not root:
return 0
self.res = 0
dic = {}
self.dfs(root, dic)
return self.res
def dfs(self, node, dic):
if not node:
return 0
if node in dic:
return dic[node]
... |
3296269 | from setuptools import setup
setup(name='cryptoscrap',
version='0.1',
description='CryptoCompare Web Scraper',
url='https://github.com/Max-Pol/cryptoscrap',
author='Max-Pol',
license='MIT',
packages=['cryptoscrap'],
install_requires=[
'requests',
'pandas',
... |
3296323 | import torch
from torch.utils.data import Dataset, DataLoader
from .util import load_file
import os.path as osp
import numpy as np
import nltk
import h5py
class VidQADataset(Dataset):
"""load the dataset in dataloader"""
def __init__(self, video_feature_path, video_feature_cache, sample_list_path, vocab, use_... |
3296375 | import scipy.signal
import scipy.fftpack as fftpack
import numpy as np
import pywt
import cv2
from . import array_operation as arr
def sin(f,fs,time,theta=0):
x = np.linspace(0, 2*np.pi*f*time, int(fs*time))
return np.sin(x+theta)
def downsample(signal,fs1=0,fs2=0,alpha=0,mod = 'just_down'):
if alpha == 0... |
3296410 | import logging
BACKEND = 'Mattermost'
BOT_ROOT_DIR = "/opt/errbot"
BOT_DATA_DIR = f"{BOT_ROOT_DIR}/data"
BOT_EXTRA_BACKEND_DIR = f"{BOT_ROOT_DIR}/backends/"
BOT_EXTRA_PLUGIN_DIR = f"{BOT_ROOT_DIR}/plugins/"
BOT_LOG_FILE = f"{BOT_ROOT_DIR}/log/err.log"
BOT_LOG_LEVEL = logging.DEBUG
BOT_LOG_SENTRY = False
SENTRY_DSN = ''... |
3296426 | import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
import os
adult_csv = "./scripts/plots_tables/csvs/adult.csv"
mnist_csv = "./scripts/plots_tables/csvs/mnist.csv"
out_plots_folder = './scripts/plots_tables/plots/corrheatmaps/'
if not os.path.exists(out_plots_folder):
os.makedirs(out_... |
3296439 | from scrapy.spider import BaseSpider
from scrapy.http import Request
from scrapy.selector import XmlXPathSelector
from openrecipes.spiders.thevintagemixer_spider import TheVintageMixerMixin
class TheVintageMixerFeedSpider(BaseSpider, TheVintageMixerMixin):
name = "thevintagemixer.feed"
allowed_domains = [
... |
3296493 | import os
import pytest
def on_travis():
return "TRAVIS" in os.environ and os.environ["TRAVIS"] == "true"
skip_on_travis = pytest.mark.skipif(on_travis(), reason="This test takes too long to run on Travis CI.")
|
3296513 | import onnx
from onnx import onnx_pb as onnx_proto
from ..quant_utils import QuantizedValue, QuantizedValueType
from .base_operator import QuantOperatorBase
"""
Quantize Gather
"""
class GatherQuant(QuantOperatorBase):
def __init__(self, onnx_quantizer, onnx_node):
super().__init__(onnx_quantizer, o... |
3296518 | from bitmovin_api_sdk.encoding.filters.rotate.rotate_api import RotateApi
from bitmovin_api_sdk.encoding.filters.rotate.customdata.customdata_api import CustomdataApi
from bitmovin_api_sdk.encoding.filters.rotate.rotate_filter_list_query_params import RotateFilterListQueryParams
|
3296522 | from setuptools import setup
setup(
name='patterns',
version='0.3',
author='<NAME>',
author_email='<EMAIL>',
description='Pattern matching for python',
long_description=open('README.rst').read().replace('|Build Status|', '', 1),
url='http://github.com/Suor/patterns',
license='BSD',
... |
3296532 | import os
import shutil
import sys
import tempfile
from unittest import TestCase, main
import lancet
class TestOutput(TestCase):
def setUp(self):
self.root = tempfile.mkdtemp()
self.output_dir = os.path.join(self.root, 'test')
def tearDown(self):
shutil.rmtree(self.root)
def tes... |
3296546 | import asyncio
import os
import uuid
import pandas as pd
import pytest
from storey import build_flow, CSVSource, CSVTarget, SyncEmitSource, Reduce, Map, FlatMap, AsyncEmitSource, ParquetTarget
from .integration_test_utils import _generate_table_name
has_azure_credentials = os.getenv("AZURE_ACCOUNT_NAME") and os.gete... |
3296602 | from doctr.file_utils import is_tf_available, is_torch_available
if not is_tf_available() and is_torch_available():
from .pytorch import * # type: ignore[misc]
|
3296610 | from yggdrasil.communication.transforms.TransformBase import TransformBase
class DirectTransform(TransformBase):
r"""Base class for message transforms."""
_transformtype = 'direct'
def evaluate_transform(self, x, no_copy=False):
r"""Call transform on the provided message.
Args:
... |
3296628 | from fiber import Process, SimpleQueue
def foo(q, a, b):
q.put(a + b)
if __name__ == '__main__':
q = SimpleQueue()
p = Process(target=foo, args=(q, 42, 21))
p.start()
print(q.get())
p.join()
|
3296640 | import pytest
import numpy as np
from persim.landscapes import PersLandscapeExact
from persim.landscapes import PersLandscapeApprox
from persim.landscapes import PersistenceLandscaper
from persim.landscapes import vectorize, snap_pl, lc_approx, average_approx
from persim.landscapes import death_vector
class TestPers... |
3296649 | from youtubedl import FileDownloader
from youtubedl import YoutubeIE
from youtubedl import MetacafeIE
from youtubedl import YoutubePlaylistIE
|
3296675 | from nltk.corpus import stopwords
# 英文停用词直接引用nltk包里的即可
def get_en_stopwords():
return set(stopwords.words('english'))
# 中文停用词自己实现
def get_zh_stopwords():
raise NotImplementedError
|
3296700 | import sys
from PySide2.QtCore import Qt, Signal, QRect, QSize
from PySide2.QtGui import QFont, QTextCursor, QTextOption, QColor, QPainter, QTextFormat
from PySide2.QtWidgets import (QApplication, QCompleter, QHBoxLayout,
QLineEdit, QPlainTextEdit, QWidget)
class QLineNumberArea(QWidget... |
3296743 | import os
from datetime import timedelta
BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
SECRET_KEY = os.environ.get('SECRET_KEY', os.urandom(24))
DEBUG = True
ALLOWED_HOSTS = ['*']
SITE_ID = 1
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'dja... |
3296753 | from marshmallow.fields import Field
from marshmallow.schema import Schema, SchemaMeta, SchemaOpts
import sqlalchemy as sa
from sqlalchemy.ext.declarative import DeclarativeMeta
from .convert import ModelConverter
from .exceptions import IncorrectSchemaTypeError
from .load_instance_mixin import LoadInstanceMixin
# T... |
3296781 | import time
import os
import random as rd
import numpy as np
from math import log
from ConfigSpace import ConfigurationSpace
from ConfigSpace.hyperparameters import UnParametrizedHyperparameter
from mindware.utils.logging_utils import get_logger
from mindware.components.utils.constants import IMG_CLS, TEXT_CLS, OBJECT... |
3296790 | from django.core.checks import Error, register
# the sole purpose of this warning is to prevent people who have
# django-autocomplete-light installed but not configured to start the app
@register()
def dal_check(app_configs, **kwargs):
from django.conf import settings
from todo.features import HAS_AUTOCOMPLETE... |
3296838 | import torch
import torch.nn as nn
import torch.optim as optim
import torch.nn.functional as F
import random
class Encoder(nn.Module):
def __init__(self, input_dim, emb_dim, enc_hid_dim, dec_hid_dim, dropout):
super().__init__()
self.embedding = nn.Embedding(input_dim, emb_dim)
self.rnn =... |
3296870 | import unittest
from nalaf.structures.data import Dataset, Document, Part, Token
from nalaf.features.simple import SimpleFeatureGenerator, SentenceMarkerFeatureGenerator
class TestSimpleFeatureGenerator(unittest.TestCase):
def setUp(self):
part = Part('Word1 word2 word3. Word4 word5 word6.')
part.... |
3296899 | import networkx as nx
import matplotlib.pyplot as plt
import numpy as np
class PlotsMixin:
"""Mixin for AssemblyMix"""
def plot_connections_graph(self, ax=None, figsize=(20, 20)):
"""Plot the mix's graph of connections between fragments."""
graph = self.uniquified_connection_graph
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.