id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
9880527 | import os
import numpy as np
import torch
from nlp import load_dataset
from rdkit import Chem
from rdkit.ML.Descriptors.MoleculeDescriptors import MolecularDescriptorCalculator
from torch.utils.data import Dataset
class RawTextDataset(Dataset):
"""
Custom Torch Dataset for tokenizing large (up to 100,000,000... |
9880568 | from sparknlp.base import *
class Doc_2_Chunk:
@staticmethod
def get_default_model():
return Doc2Chunk() \
.setInputCols("sentence") \
.setOutputCol("entities")
|
9880577 | from django.test import TestCase
from django_logic.state import State
from tests.models import Invoice
class StateTestCase(TestCase):
def setUp(self) -> None:
self.state = State(Invoice.objects.create(status='draft'), 'status')
def test_hash_remains_the_same(self):
self.assertEqual(self.stat... |
9880578 | from django.conf.urls import url
from .views import staff_view
urlpatterns = (
url(r'^$', staff_view, name='staff'),
)
|
9880595 | from planets import earth
from vis import sphere, curve, color # vPython tools
from raphson import orbit # orbital calculator
def planet_ini(planetdata, n, scale_up): # retrieves data from planet dictionary and creates a planet
a = planetdata['a'] # semi-major axis
tilt = planetdata['tilt']
timescale... |
9880611 | from benderopt.stats import sample_generators
from benderopt.stats import probability_density_function
import numpy as np
np.random.seed(0)
def test_lognormal_generator():
"""Test to reassure."""
search_space = {
"weights": [0.25, 0.75],
"parameters": [
{"category": "uniform", "se... |
9880625 | from a10sdk.common.A10BaseClass import A10BaseClass
class Monitor(A10BaseClass):
""" :param data_cpu: {"description": "Monitor data CPU threshold (Threshold value in percentage, default 90)", "format": "number", "default": 90, "optional": true, "maximum": 100, "minimum": 1, "type": "number"}
:param co... |
9880640 | from tool.runners.python import SubmissionPy
class EvqnaSubmission(SubmissionPy):
def is_valid(self, password_entry):
policy, c, pwd = password_entry.split()
c = c[0]
c_min, c_max = map(int, policy.split('-'))
pwd_set = ''.join(sorted(pwd))
return c * c_min in pwd_set and ... |
9880642 | from elegantrl.train.run_tutorial import *
from elegantrl.train.config import Arguments
from elegantrl.agents.AgentSAC import AgentModSAC
# demo for MuJoCo environment, using 1 GPU
args = Arguments(env=build_env('AntBulletEnv-v0', if_print=True), agent=AgentModSAC())
GPU_ID = 0
args.learner_gpus = (GPU_ID, )
args.age... |
9880647 | import numpy as np
import tensorflow as tf
from .Dataset import Dataset
class IMDb(Dataset):
pass
def load_imdb(one_hot=True,
num_words=None,
start_char=1,
oov_char=2,
index_from=3,
train_test_split=True):
train, valid = \
tf.kera... |
9880664 | memo = {}
class Solution:
def countArrangement(self, N, arr = None):
if not arr: arr = tuple(range(1, N + 1))
if (N, arr) in memo or N == 1: return N == 1 and 1 or memo[(N, arr)]
memo[(N, arr)] = sum([self.countArrangement(N-1, arr[:j]+arr[j + 1:]) for j in range(len(arr)) if arr[j]%N==0 or ... |
9880683 | from __future__ import print_function
import matplotlib.cm as cm
import matplotlib.pyplot as plt
import numpy as np
from sklearn.datasets import load_wine
from sklearn.model_selection import train_test_split
from sklearn.linear_model import LogisticRegression
from sklearn.metrics import confusion_matrix
# For repr... |
9880701 | import sys
import argparse
import logging
import time
def pase_info(seq):
info = {'SVLEN': 0, 'END': 0, "SVTYPE": '', "RE": 0, "CHR2": ''}
for i in seq.split(';'):
if i.split('=')[0] in ["SVLEN", "END", "RE"]:
try:
info[i.split('=')[0]] = abs(int(float(i.split('=')[1])))
except:
pass
i... |
9880738 | from __future__ import print_function
import Pyro4
import bouncer
# you could set a comm timeout to avoid the deadlock situation...:
# Pyro4.config.COMMTIMEOUT = 2
with Pyro4.Daemon() as daemon:
uri = daemon.register(bouncer.Bouncer("Server"))
Pyro4.locateNS().register("example.deadlock", uri)
print("Th... |
9880770 | import numpy as np
import torch
import os
import json
from sklearn.metrics import precision_recall_fscore_support
import argparse
import copy
from collections import deque
def compute_accuracy(y_pred, y_true):
size_pred = np.shape(y_pred)
size_true = np.shape(y_true)
if len(size_pred) == 1:
n ... |
9880832 | from glob import glob
import argparse
import os
import sys
def parse_args():
parser = argparse.ArgumentParser()
parser.add_argument('wdir', help='directory with the grounding eval files')
args = parser.parse_args()
return args
if __name__ == '__main__':
args = parse_args()
files = glob(os.p... |
9880876 | import pytest
from pytest import raises
from m3d.exceptions.m3d_exceptions import M3DIllegalArgumentException
from m3d.hadoop.core.spark_parameters import SparkParameters
from test.core.unit_test_base import UnitTestBase
class TestSparkParameters(UnitTestBase):
driver_memory = "5G"
new_driver_memory = "6G"
... |
9880922 | from __future__ import absolute_import
import torch
import torch.nn as nn
import numpy as np
import scipy.misc
from .misc import *
def im_to_numpy(img):
img = to_numpy(img)
img = np.transpose(img, (1, 2, 0)) # H*W*C
return img
def im_to_torch(img):
img = np.transpose(img, (2, 0, 1)) # C*H*W
img ... |
9880932 | from sqlalchemy.orm import scoped_session
from tests.scoring_engine.unit_test import UnitTest
class TestDB(UnitTest):
def test_session_type(self):
assert isinstance(self.session, scoped_session)
|
9880956 | from __future__ import absolute_import
import json
from six.moves.urllib.parse import quote
from createsend.createsend import CreateSendBase
from createsend.utils import json_to_py
class List(CreateSendBase):
"""Represents a subscriber list and associated functionality."""
def __init__(self, auth=None, lis... |
9880997 | import re
class CannotGetMiroShard(Exception):
pass
def choose_miro_shard(miro_id):
"""
Decides the shards that a Miro ID belongs to.
We group the Miro IDs into per-thousand "shards". This is an organisational
scheme inherited from the way Miro assets were laid out from disk in the old
Mir... |
9881008 | import torch
import torch.nn as nn
import torch.nn.functional as F
from dropblock import DropBlock2D, LinearScheduler
from modelR.layers.convolutions import Convolutional, Deformable_Convolutional
from modelR.layers.shuffle_blocks import Shuffle_new, Shuffle_Cond_RFA, Shuffle_new_s
import config.cfg_lodet as cfg
class... |
9881029 | import argparse
import matplotlib.pyplot as plt
import numpy as np
import os
import pandas as pd
import scipy.interpolate
import time
from .utils import _init_modes, _init_precs
class EpochTimer:
def __init__(self):
self.reset()
def reset(self):
self._timing = {
'epoch': [],
'epoch_star... |
9881042 | from tir import Webapp
import unittest
import time
class WMSA332(unittest.TestCase):
@classmethod
def setUpClass(inst):
inst.oHelper = Webapp()
inst.oHelper.Setup("SIGAWMS", "10/12/2020", "T1", "M SP 01", "42")
inst.oHelper.Program("WMSA332")
def test_WMSA332_CT001(self):
self.oHelper.SetValue('Serviço ... |
9881072 | from marktex.texrender import MarkTex
doc = MarkTex.convert_file(
r".\test_in_md\01-Faster RCNN代码解析第一弹.md", r".\test_out_pdf")
doc.generate_tex()
|
9881078 | from caracal.execution.node import (
Event,
ExternalEvent,
Message,
Handler,
handler,
Node,
Property,
)
from caracal.execution.session import Session
|
9881173 | import numpy as np
from spyne import Tensor, Constant
def basis_vectors(x):
for idxs in np.ndindex(*x.shape):
vect = np.zeros(x.shape)
vect[idxs] = 1
yield vect
def _is_tensor(node):
return issubclass(node.__class__, Tensor) or issubclass(node.__class__, Constant) |
9881175 | import importlib
import os.path
from collections import defaultdict
import click
import yaml
# TODO: tests
@click.group(name="openscm-ar6-wg1-data-compilation")
def cli():
"""
Command-line interface
"""
pass
@cli.command(context_settings={"help_option_names": ["-h", "--help"]})
@click.argument("co... |
9881209 | from utils import sample
import numpy as np
class TabularQ:
def __init__(self, model, alpha, gamma):
self.model = model
self.a = alpha
self.g = gamma
self.Q = {}
self.reset_q()
def rand_sam_one_step_pla(self, n_updates=1, decay=False):
decay_rate = (1 - 1 / n_updates) if decay else None
... |
9881221 | from fence.errors import AuthError
class OIDCError(AuthError):
"""
Base class for errors specified by OIDC.
"""
status_code = 400
error_code = "oidc_error"
def __init__(self, message=""):
super(OIDCError, self).__init__(message)
self.message = message
def __str__(self):
... |
9881245 | import cv2
import numpy as np
from common.device.c_android import AndroidDevice
from azurelane.scenes.enemy_search import EnemySearch
from common.logutil import logger
screen_path = 'temp/screen.png'
def main():
device = AndroidDevice()
screen = np.asarray(device.screen_capture_as_image()) # 实时截取并加载图片
#... |
9881253 | import sys
from copy import copy
try:
from functools import lru_cache
except ImportError:
from functools32 import lru_cache
from makefun import with_signature
from six import with_metaclass
try: # python 3.5+
# noinspection PyUnresolvedReferences
from typing import Callable, Any, List, Union
try... |
9881275 | from common.message import Message
from common.hostmask import Hostmask
class Command(Message):
"""
An IRC command sent by a client.
"""
NICK = "NICK"
USER = "USER"
JOIN = "JOIN"
PRIVMSG = "PRIVMSG"
PART = "PART"
QUIT = "QUIT"
def __init__(self, raw):
"""
Create a command representation ... |
9881277 | def TheAnswerToLifeTheUniverseAndEverything():
"""
Provides the Answer to the Ultimate Question of Life, the Universe, and Everything.
Returns
-------
answer : integer
See https://en.wikipedia.org/wiki/42_(number)#Popular_culture.
"""
return 42
|
9881346 | import random
import math
import numpy as np
import mxnet as mx
from mxnet import gluon, nd
from mxnet.gluon import nn
import gluonnlp as nlp
class DotProductAttention(nn.Block):
def __init__(self, dropout, **kwargs):
super(DotProductAttention, self).__init__(**kwargs)
self.dropout = nn.Dropout(d... |
9881366 | def split_by(string: str, symbol: str) -> list[str]:
return list(filter(None, map(str.strip, string.split(symbol))))
class WrongRulesException(Exception):
def __init__(self, message):
self.message = message
def parse_rules(rules_str: str, lambda_symbol: str) -> dict[str, list[str]]:
dictionary =... |
9881394 | from django.conf.urls import url
from django.views.generic.base import RedirectView
from rest_framework.documentation import include_docs_urls
from api import views
urlpatterns = [
url(r'^rates/$', views.GetRates.as_view()),
url(r'^rates/csv/$', views.GetRatesCSV.as_view()),
url(r'^search/$', views.GetAut... |
9881396 | import numpy as np
import pytest
from robogym.envs.rearrange.common.utils import PlacementArea
@pytest.mark.parametrize(
"used_table_portion,expected_placement_area",
[
(
1.0,
PlacementArea(
offset=(0.3038, 0.38275, 0.06648), size=(0.6075, 0.58178, 0.26)
... |
9881401 | import os, sys, inspect
sys.path.insert(1, os.path.join(sys.path[0], '..'))
from conformal import *
from utils import *
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.patches as mpatches
from scipy.special import softmax
import torch
import torchvision
import torchvision.transforms as tf
import r... |
9881404 | from django.contrib import admin
from app.myblog.models import *
# Register your models here.
admin.site.register(Article)
admin.site.register(Classification)
admin.site.register(Tag)
admin.site.register(Comment)
admin.site.register(CommentReply)
admin.site.register(Env)
admin.site.register(Knowledge) |
9881411 | from .bow_encoder import BOWEncoder
from .label_indexer import LabelIndexer
from .sentence_indexer import SentenceIndexer
from .sentence_one_hot_encoder import SentenceOneHotEncoder
from .sentence_tokenizer import SentenceTokenizer
from .word_decoder import WordDecoder
__all__ = [
'BOWEncoder',
'LabelIndexer',... |
9881436 | from __future__ import absolute_import
from . import backend as K
from .utils.generic_utils import get_from_module
class Constraint(object):
def __call__(self, p):
return p
def get_config(self):
return {'name': self.__class__.__name__}
class MaxNorm(Constraint):
"""MaxNorm weight const... |
9881461 | import torch
import numpy as np
import scipy.io as sio
import os
import skimage.io
from .utils import rotate_pt, pc_normalize, knn
class PascalPFCategory:
def __init__(self, data_path, cpair, label, random_rotate=False):
self.data_path = data_path
self.cpair = cpair
self.label = label
... |
9881463 | import FWCore.ParameterSet.Config as cms
from RecoEgamma.EgammaIsolationAlgos.electronTrackIsolations_cfi import trkIsol03CfgV2,trkIsol04CfgV2
heepIDVarValueMaps = cms.EDProducer("ElectronHEEPIDValueMapProducer",
beamSpot=cms.InputTag("offlineBeamSpot"),
... |
9881467 | import asyncio
import socket
import os
import re
import sys
import logging
from time import strftime
from functools import partial
from chaperone.cutil.logging import info, warn, debug, set_custom_handler
from chaperone.cutil.misc import lazydict, maybe_remove, remove_for_recreate
from chaperone.cutil.servers import ... |
9881482 | listt = [100-28, 100+1, 100+8, 100+8, 100+11, 100-13, 100+11, 100+14, 100+8, 100, 100-67]
for i in listt:
print(chr(i), end="")
print()
|
9881522 | import torch
import apex
model = apex.parallel.SyncBatchNorm(4).cuda()
model.weight.data.uniform_()
model.bias.data.uniform_()
data = torch.rand((8,4)).cuda()
model_ref = torch.nn.BatchNorm1d(4).cuda()
model_ref.load_state_dict(model.state_dict())
data_ref = data.clone()
output = model(data)
output_ref = model_ref(d... |
9881540 | import os
import sys
import re
l = []
for a in sys.argv:
f = open(a)
for line in f:
l.append(line)
f.close()
l.sort()
for line in l:
print line,
|
9881614 | import sublime
import sublime_plugin
from api.inspect import highlighting
class ToggleHighlightCommand(sublime_plugin.TextCommand):
def run(self, edit):
highlighting.toggle(self.view)
def is_checked(self):
return highlighting.is_enabled()
|
9881644 | import time
import sys
import os
import numpy as np
import logging
import pandas as pd
print(sys.path)
from h2o4gpu.util.testing_utils import find_file, run_glm
import h2o4gpu
from scipy.sparse import csr_matrix
logging.basicConfig(level=logging.DEBUG)
# Function to check fall back to sklearn
def test_fit_simple_b... |
9881655 | import os
from .sac import SAC
from discor.network import GaussianPolicy
from discor.utils import disable_gradients
class EvalAlgorithm(SAC):
def __init__(self, state_dim, action_dim, device,
policy_hidden_units):
self._state_dim = state_dim
self._action_dim = action_dim
... |
9881706 | import pandas as pd
import numpy as np
from .base import register_verb, register_type_methods_as_verbs
from .column_spec import parse_column_specification, series_and_strings_to_names
# register all pandas.DataFrame functions and properties.
DataFrameGroupBy = pd.core.groupby.DataFrameGroupBy
SeriesGroupBy = pd.core.g... |
9881725 | import unittest
from unittest.mock import patch
from loguru import logger
from novelsave.client.cli.helpers import get_source_gateway
from novelsave.exceptions import SourceNotFoundException
class TestSourceHelper(unittest.TestCase):
@classmethod
def setUpClass(cls) -> None:
logger.remove()
@pa... |
9881748 | from distutils.core import setup
with open("requirements.txt", 'r') as f:
requirements = [l.strip() for l in f.readlines() if l.find("=")>0]
setup(
name='decorators4DS',
packages=['decorators4DS'],
install_requires=requirements,
version='1.2',
python_requires='>=3.4',
description='Useful de... |
9881767 | from .template import Template
class Policy(Template):
KEYS = {
'permitted_idps': list,
'authentication_timeout': int
}
def __init__(self, **kw):
super(Policy, self).__init__(Policy.KEYS, kw)
|
9881799 | from abc import ABC
from enum import Enum
from pathlib import Path
from typing import Any, Dict, Generic, Sequence, TypeVar, Union
from torch.utils.data import DataLoader
Data = TypeVar("Data")
LightingDataLoaders = Union[
DataLoader[Any],
Sequence[DataLoader[Any]],
Sequence[Sequence[DataLoader[Any]]],
... |
9881822 | from typing import List
import torch
import torch.nn as nn
from models import ResNetBlock
class ResNetDecoder(nn.Module):
def __init__(self, num_output_channels: int, num_features: List = None, verbose: bool = False) -> None:
super().__init__()
if num_features is None:
num_features ... |
9881857 | from datetime import datetime, timedelta
from fastapi import APIRouter, Depends, HTTPException
from fastapi.security import OAuth2PasswordBearer, OAuth2PasswordRequestForm
from sqlalchemy.orm import Session
from starlette.status import HTTP_200_OK, HTTP_401_UNAUTHORIZED, HTTP_201_CREATED, HTTP_409_CONFLICT
from app.d... |
9881921 | import os, sys
from optparse import make_option
from uliweb.core.commands import Command, get_answer
class ClearCommand(Command):
name = 'clear'
help = 'Clear all records of recorder.'
def handle(self, options, global_options, *args):
from uliweb import functions
from uliweb.orm import Com... |
9881927 | import numpy as np
import pandas as pd
from scipy.stats import norm
import unittest
from context import grama as gr
from context import data
##==============================================================================
## grouping test functions
##===================================================================... |
9881961 | import time
import numpy as np
import vpi
import cv2
from threading import Thread
from PIL import Image
from jetvision.elements import Camera
MAX_DISP = 64
WINDOW_SIZE = 10
def get_calibration() -> tuple:
fs = cv2.FileStorage(
"calibration/rectify_map_imx219_160deg_1080p.yaml", cv2.FILE_STORAGE_READ
... |
9881985 | import torch
# Used util code from open-nmt code: https://github.com/OpenNMT/OpenNMT-py/blob/master/onmt/Utils.py
def sequence_mask(lengths, max_len=None):
"""
Creates a boolean mask from sequence lengths.
"""
if type(lengths) == torch.autograd.Variable:
lengths_ = lengths.data
else:
... |
9881993 | from itertools import cycle
from nurses import ScreenManager, colors
from nurses.widgets import Textbox
from nurses.widgets.behaviors import Bouncing
class BouncingTextbox(Bouncing, Textbox):
def __init__(self, *args, **kwargs):
super().__init__(*args, border_style="curved", **kwargs)
def refresh(se... |
9882001 | from turf.distance import distance
from turf.utils.error_codes import error_code_messages
from turf.utils.exceptions import InvalidInput
def square(bbox):
"""
Takes a bounding box and calculates the minimum square bounding box that
would contain the input.
:param bbox: bounding box extent in [minX, ... |
9882006 | from setuptools import find_packages, setup
from src.wagtail_live import __version__
with open("README.md", "r") as fh:
long_description = fh.read()
install_requires = [
"wagtail>=2.12",
]
docs_requires = [
"mkdocs>=1.2,<1.3",
"mkdocs-material>=7.2,<7.3",
"mkdocstrings>=0.15.2,<0.16",
]
test_re... |
9882010 | import rain.lexer as L
import rain.token as K
import pytest
def test_factory():
assert L.factory('return') == K.keyword_token('return')
assert L.factory('this') == K.name_token('this')
assert L.factory('Multi_Word') == K.name_token('multiword')
def test_keywords():
stream = L.stream(' '.join(L.KEYWORDS))
fo... |
9882018 | import argparse
if __name__ == '__main__':
parser = argparse.ArgumentParser()
parser.add_argument('--supernet', type=str)
parser.add_argument('--gpu', type=int)
args = parser.parse_args()
print(args.supernet)
cnt = 0
with open(f'logs/sfsuper/eval_subnet_noise_x2_opt2_ratiorand_'
... |
9882024 | from PySide2.QtWidgets import QWidget, QApplication, QLabel, QPushButton, QVBoxLayout
from PySide2.QtCore import Qt, QThread, Signal
import sys
from time import sleep
class LongProcessThread(QThread):
transaction = Signal()
def __init__(self, parent=None):
super(LongProcessThread, self).__init__(par... |
9882094 | from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIcon, QPixmap
from PyQt5.QtSql import QSqlTableModel, QSqlDatabase
from PyQt5.QtCore import pyqtSlot, pyqtSignal, QObject, QTimer, Qt, QModelIndex, qInstallMessageHandler
class view_case_ui(QMainWindow):
problem_path = ''
text_box = ''
line_endings_shown = 0
... |
9882116 | from office365.entity import Entity
class Extension(Entity):
"""An abstract type to support the OData v4 open type openTypeExtension."""
pass
|
9882154 | import numpy as np
def jacobi(A, b, eps, maxIterations):
size = len(A)
x = np.zeros(size)
D = np.diag(A)
Dm = np.diagflat(D)
Dneg = np.diagflat([1 / n for n in D])
R = A - Dm
w, v = np.linalg.eig(np.dot(Dneg, R))
if max(abs(w)) > 1:
print("Spectral radius of matrix is less than 1, aborting calcul... |
9882185 | from __future__ import division
from builtins import object
import pytest
try:
from mpi4py import MPI
except:
pytest.skip("mpi4py not installed", allow_module_level=True)
import numpy as np
from sporco import mpiutil
def fn(prm):
x = prm[0]
return (x - 0.1)**2
def fnnan(prm):
x = prm[0]
if... |
9882229 | class Solution:
def countBits(self, num):
r = [0]
for i in range(1, num + 1):
r.append(r[i / 2] + i % 2)
return r
|
9882232 | class Rot:
def _decrypt(message, key=None):
ans = ""
key = 26 - key
# traverse message
for i in range(len(message)):
char = message[i]
if char.isalpha():
ans += chr((ord(char) + key - 97) % 26 + 97)
else:
ans += cha... |
9882241 | import torch
eps = 1
def dice_round(preds, trues, is_average=True):
preds = torch.round(preds)
return dice(preds, trues, is_average=is_average)
def dice(preds, trues, weight=None, is_average=True):
num = preds.size(0)
preds = preds.view(num, -1)
trues = trues.view(num, -1)
if weig... |
9882277 | import argparse
import os
import cv2
import numpy as np
import torch
from torch.utils.data import DataLoader
from tqdm import tqdm
from pynif3d.common.verification import check_path_exists
from pynif3d.datasets import DTUMVSIDR
from pynif3d.pipeline import IDR
from pynif3d.utils.transforms import radians, rotation_ma... |
9882287 | from collections import namedtuple
from typing import List, Tuple, Iterable, Optional
from . import vala
def find_prefix(items: List[str]) -> str:
pos = len(items[0])
while pos > 0:
prefix = items[0][0:pos]
for item in items:
if not item.startswith(prefix):
break
... |
9882353 | import collections
class Customer(collections.namedtuple('Customer', 'name address')):
def greeting(self):
return "Hello %s!" % self.name
print(Customer('Dave', '123 Main').greeting())
|
9882363 | import cv2
import numpy as np
import os
def resize_pad_to_fit(img, size, pad_value=np.array([0,0,0]), interp=cv2.INTER_LINEAR): # size: [rows, cols], to uniform size
if len(size) != 2:
raise Exception("Error: len(size) should be 2")
rows = img.shape[0]
cols = img.shape[1]
two_axis = False
... |
9882390 | from RFEM.initModel import Model, clearAtributes, ConvertToDlString
from RFEM.enums import ReinforcementDirectionType
from math import pi
class ConcreteReinforcementDirection():
def __init__(self,
no: int = 1,
name: str = "RD 1",
surfaces = "1",
reinf... |
9882403 | from itertools import groupby
from docutils import nodes
from packaging.version import parse as parse_version
from sphinx.addnodes import versionmodified
from sphinx.util import logging
__version__ = "1.0.1"
logger = logging.getLogger(__name__)
def setup(app):
app.add_config_value("log_cabinet_collapse_all", Fa... |
9882411 | import numpy as np
import matplotlib.pyplot as plt
import torch
import random
import numpy as np
import os
from segmentation_models_pytorch import Unet, FPN
import sys
from collections import OrderedDict
sys.path.append("..")
from configs.train_params import *
# https://www.kaggle.com/paulorzp/rle-functions-run-leng... |
9882467 | from typing import Any
from aat.common import _in_cpp
try:
from ...binding import InstrumentCpp # type: ignore
_CPP = _in_cpp()
except ImportError:
InstrumentCpp = object
_CPP = False
def _make_cpp_instrument(*args: Any, **kwargs: Any) -> InstrumentCpp:
return InstrumentCpp(*args, **kwargs)
|
9882482 | from abc import ABCMeta
import numpy as np
from deslib.base import BaseDS
from deslib.util.aggregation import (aggregate_proba_ensemble_weighted,
sum_votes_per_class,
get_weighted_votes)
class BaseDES(BaseDS):
"""Base class for a Dynamic ... |
9882499 | from execution.executeSentence import executeSentence
from execution.AST.sentence import *
from execution.AST.expression import *
from execution.executeInstruction import createFunction, deleteFunction
from console import print_error, print_success, print_warning, print_text
from goto import with_goto
import math
@wi... |
9882524 | import sys
import linecache
import copy
option = sys.argv
ifinfo = []
value_name_key = ['set', 'policy', 'id', 'policy_id', 'name', 'value_name', 'from', 'src_zone', 'to',
'dst_zone', 'src_ip', 'dst_ip', 'protocol', 'nat', 'src', 'dst', 'ip', 'dst_nat_ip', 'expect', 'log']
value_name_keyex = ['set'... |
9882555 | from floppy.graph import Graph
from floppy.floppyUi import Painter2D, MainWindow
import sys
from PyQt5.QtWidgets import QApplication
import argparse
import logging
logger = logging.getLogger('Floppy')
logger.setLevel(logging.DEBUG)
fh = logging.FileHandler('floppy.log')
fh.setLevel(logging.DEBUG)
formatter = logging.F... |
9882605 | import mrms_inventory
import datetime
import re
import os.path
import pytz
def test_one_day():
inv = mrms_inventory.inventory(0, datetime.date(2021, 8, 21))
assert inv.shape[0] == 24
assert inv.shape[1] == 4
d = inv["date"][0]
print(f"{d} {type(d)} {d == datetime.date(2021, 8, 21)}")
verify_da... |
9882608 | import decimal
import sys
from enum import Enum
from typing import Any, Callable, Dict, List, Union
if sys.version_info >= (3, 8):
from typing import TypedDict
else:
from typing_extensions import TypedDict
Timeout = Union[float, int]
Numeric = Union[float, int, decimal.Decimal]
Item = Dict[str, Any]
DynamoIt... |
9882615 | from __future__ import print_function
import demisto_client.demisto_api
from demisto_client.demisto_api.rest import ApiException
from pprint import pprint
api_key = None # set to your 'YOUR_API_KEY' or set environment variable: DEMISTO_API_KEY
base_url = None # set to your 'http://DEMISTO_HOST' or set environment va... |
9882701 | from django.utils.translation import gettext_lazy as _
from rest_framework.exceptions import AuthenticationFailed
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer
class APITokenObtainPairSerializer(TokenObtainPairSerializer):
@classmethod
def get_token(cls, user):
if user.is_... |
9882716 | import glob
import json
import pandas as pd
from asreviewcontrib.statistics import DataStatistics
metadata_files = glob.glob("datasets/*/*.json")
metadata = {}
for dataset_fp in metadata_files:
with open(dataset_fp, "r", encoding="utf-8") as f:
res = json.load(f)
# new variables
res["ty... |
9882719 | from django.contrib import admin
from django.contrib.auth import get_user_model
from .models import GennotesEditor, GenomeReport
User = get_user_model()
admin.site.register(GennotesEditor)
admin.site.register(GenomeReport)
|
9882758 | from elasticsearch import Elasticsearch
import editdistance
es = Elasticsearch(['http://node1.research.tib.eu:9200/'])
docType = "doc"
def entitySearch(query):
indexName = "wikidataentityindex"
results=[]
###################################################
elasticResults=es.search(index=indexName, ... |
9882799 | from corehq.project_limits.rate_limiter import RateDefinition
STANDARD_RATIO = RateDefinition(
per_week=115,
per_day=23,
per_hour=3,
per_minute=0.07,
per_second=0.005,
).times(1 / 23)
def get_standard_ratio_rate_definition(events_per_day):
return STANDARD_RATIO.times(events_per_day)
|
9882803 | from abc import ABC, abstractmethod
class User:
def __init__(self, **kargs):
self.name = kargs.get("name", "")
self.access_level = kargs.get("access_level", 1)
class ISystemAuth(ABC):
@abstractmethod
def level_1_tasks(self):
pass
@abstractmethod
def level_2_tasks(self):
pass
@abstractmethod
def level... |
9882804 | import numpy as np
import tensorflow as tf
from models.layers import CustomDense, GraphConvolution, InnerProductDecoder, get_layer_uid
from utils.preprocess import normalize_graph_gcn, sparse_to_tuple
flags = tf.compat.v1.flags
FLAGS = flags.FLAGS
class GraphAE(object):
"""Base GraphAE class. Defines basic API ... |
9882811 | import unittest
import zen
class FlowTestCase(unittest.TestCase):
def test_min_cut(self):
#sample graph
G = zen.DiGraph()
G.add_node('a')
G.add_node('b')
G.add_node('c')
G.add_node('d')
G.add_node('e')
G.add_node('f')
G.add_node('g')
G.add_node('h')
G.add_edge('a','b',weight=10)
G.add_edge('... |
9882840 | def extractPrinceRevolution(item):
"""
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol) or 'preview' in item['title'].lower():
return None
tagmap = [
('Romance RPG', 'Romance RPG', 'translated'),
('The Legend of Sun Kn... |
9882892 | from django.db import models
class Animal(models.Model):
""" Base model of other animals"""
name = models.CharField(max_length=256)
def says(self):
"""implemented by different animal.
"""
raise NotImplementedError("I don't know what to say")
class Meta:
abstract = ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.