id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
420815 | from __future__ import print_function, division
from typing import Optional, List
import torch
import math
import torch.nn as nn
import torch.nn.functional as F
from ..backbone import build_backbone
from ..block import conv3d_norm_act
from ..utils import model_init
class FPN3D(nn.Module):
"""3D feature pyramid ... |
420825 | from django.apps import AppConfig
from django.utils.translation import ugettext_lazy as _
class MailsConfig(AppConfig):
name = 'apps.mails'
verbose_name = _('Mails')
|
420830 | import FWCore.ParameterSet.Config as cms
AnalyticalPropagator = cms.ESProducer("AnalyticalPropagatorESProducer",
MaxDPhi = cms.double(1.6),
ComponentName = cms.string('AnalyticalPropagator'),
PropagationDirection = cms.string('alongMomentum')
)
|
420842 | import twitter, os, json, time, tempfile, contextlib, sys, io, requests
from PIL import Image
from minio import Minio
from minio.error import ResponseError
@contextlib.contextmanager
def nostdout():
save_stdout = sys.stdout
sys.stdout = io.BytesIO()
yield
sys.stdout = save_stdout
minioClient = Minio(... |
420891 | import pytest
from MicroTokenizer.tokenizers.crf.tokenizer import CRFTokenizer
from MicroTokenizer.tokenizers.dag_tokenizer import DAGTokenizer
from MicroTokenizer.tokenizers.hmm_tokenizer import HMMTokenizer
from MicroTokenizer.tokenizers.max_match.backward import MaxMatchBackwardTokenizer
from MicroTokenizer.tokeniz... |
420899 | import argparse
parser = argparse.ArgumentParser("add_sample_name")
parser.add_argument("sample", type=str,
help="namd of sample to be extracted from vcf and kept in bed format")
parser.add_argument("-v", '--version', type=str,
help="indicate the version (old / new) of the vcf se... |
420921 | from django.db import models
from datetime import timedelta
from django.utils import timezone
import pytz
from django.conf import settings
from uuid import uuid4
utc = pytz.UTC
class Kiosk(models.Model):
id = models.AutoField(primary_key=True)
name = models.CharField("Name", max_length=30, unique=True)
k... |
420941 | from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save, post_init
from announce.tasks import update_mailchimp_subscription
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
mailing_list_signup = models.Boo... |
421071 | from flask import Flask
from flask import render_template, request ,abort
from flask_cors import CORS
app = Flask(__name__)
CORS(app, supports_credentials=True)
@app.route('/app' ,methods=['GET'])
def index():
try:
url1 = request.args.get("url1")
url2 = request.args.get("url2")
... |
421109 | import argparse
import os
import commentjson
from stable_baselines import PPO2, SAC
from gym_kuka_mujoco.envs import *
from stable_baselines.common.vec_env import DummyVecEnv
# Add the parent folder to the python path for imports.
import sys, os
sys.path.insert(0, os.path.abspath('..'))
from play_model import replay_m... |
421194 | import math
import genconfig as gc
import genutils as gu
import loggerdb as ldb
from storage import indicators as storage
# Misc Indicator Helpers
class Helpers:
def SMA(list1, period):
if len(list1) >= period:
SMA = math.fsum(list1[-period:]) / period
return SMA
def EMA(list1, list2, period1):... |
421385 | import torch
import sys, os, json
import warnings
warnings.filterwarnings("ignore")
import nltk
nltk.download('punkt')
sys.path.append("..")
from torch_geometric.utils import to_dense_adj
device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')
class Cache_GNN_Embeds():
def __init__(self, confi... |
421406 | import uuid
from flask_restplus import Resource
from flask import request, current_app
from sqlalchemy_filters import apply_pagination, apply_sort
from sqlalchemy import desc, func, or_
from marshmallow.exceptions import MarshmallowError
from werkzeug.exceptions import BadRequest
from app.extensions import api
from ap... |
421407 | from typing import Iterable
from unittest.mock import patch
from nose.tools import assert_equal, assert_in, assert_true
from pyecharts.charts import Bar, Line, Tab
from pyecharts.commons.utils import OrderedSet
from pyecharts.components import Table
from pyecharts.faker import Faker
def _create_bar() -> ... |
421520 | from app import db
from app.models.setting_model import Setting
def create_setting():
return Setting()
def save(setting):
db.session.add(setting)
db.session.commit()
return setting
def find_by_key(key):
return db.session.query(Setting).filter_by(key=key).first()
def delete_setting(setting):
... |
421535 | from __future__ import annotations
import typing
from ctc import evm
from ctc import spec
from . import uniswap_v2_events
from . import uniswap_v2_state
async def async_get_pool_log_deltas(
pool: spec.Address,
start_block: typing.Optional[spec.BlockNumberReference] = None,
end_block: typing.Optional[spe... |
421538 | def mean(interactions, _):
"""Computes the mean interaction of the user (if user_based == true) or the mean
interaction of the item (item user_based == false). It simply sums the interaction
values of the neighbours and divides by the total number of neighbours."""
count, interaction_sum = 0, 0
for... |
421556 | from click.testing import CliRunner
runner = CliRunner()
def test_mlcube_ssh():
from mlcube.tests.test_mlcommons_mlcube_cli import test_mlcube
test_mlcube()
|
421558 | import cPickle
from cython_bbox import bbox_overlaps
import numpy as np
def nms(boxes, score, trace, th = 0.3):
idx = score.argmax()
choice = boxes[idx]
target_trace = trace[idx]
del(trace[idx])
t = score[idx]
score = np.delete(score, idx)
del(boxes[idx])
sss = np.zeros((score.size))
for i in xrange(... |
421560 | from dearpygui.core import *
import time
from db_manage import *
def doodleTool(pad_name, lineColor, lineThickness):
time.sleep(0.1)
while True:
if is_mouse_button_released(mvMouseButton_Left):
# If mouse is clicked outside the Drawing Pad, exit the tool.
if get_active_window... |
421573 | import os.path as osp
from abc import ABCMeta, abstractmethod
import megengine as mge
import megengine.distributed as dist
from megengine.optimizer.optimizer import Optimizer
from megengine.module import Module
from edit.utils import mkdir_or_exist, build_from_cfg, get_root_logger
from ..hook import Hook, HOOKS, get_pr... |
421607 | from entityservice.cache.active_runs import is_run_active
from entityservice.database import DBConn, check_project_exists, check_run_exists
from entityservice.errors import DBResourceMissing, InactiveRun
def assert_valid_run(project_id, run_id, log):
if not is_run_active(run_id):
raise InactiveRun("Run is... |
421666 | from functools import wraps
from time import time
def timing(f):
@wraps(f)
def wrapper(*args, **kwargs):
start = time()
result = f(*args, **kwargs)
end = time()
print(f'Elapsed time: {(end - start):.3f}s')
return result
return wrapper
|
421668 | import mock
import unittest2
import urllib
import urllib2
from mlabns.util import constants
from mlabns.util import message
from mlabns.util import prometheus_status
class ParseSliverToolStatusTest(unittest2.TestCase):
def test_parse_sliver_tool_status_returns_successfully_parsed_tuple(self):
status = {... |
421730 | from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.forms import UserCreationForm
from django.utils.translation import gettext_lazy as _
from {{cookiecutter.project_slug}}.accounts.models import User
class CustomUserCreationForm(UserCreationForm):
"""
A f... |
421735 | import logging
logging.basicConfig(level=logging.DEBUG)
# ---------------------
# Flask App
# ---------------------
import os
# pip install flask
from flask import Flask, make_response, request
app = Flask(__name__)
logger = logging.getLogger(__name__)
@app.route("/slack/oauth/callback", methods=["GET"])
def end... |
421751 | import json
import os
import sys
from datetime import datetime
import csv
import pycountry
# Layer code, like parsing_lib, is added to the path by AWS.
# To test locally (e.g. via pytest), we have to modify sys.path.
# pylint: disable=import-error
try:
import parsing_lib
except ImportError:
sys.path.append(
... |
421782 | from math import exp
def mul(l1, l2):
return round(sum(a*b for a,b in zip(l1, l2)), 3)
def sgn(x):
return 1 if x > 0 else -1
def imul(x, a):
return [round(a*xi,3) for xi in x]
def add(l1, l2):
return [round(a+b,3) for a,b in zip(l1, l2)]
def func(net):
# bipolar continuous
return 2 / (1 + ... |
421791 | import operator
from typing import Dict, List
from confluent_kafka.admin import ConfigResource
from esque.resources.resource import KafkaResource
class Broker(KafkaResource):
def __init__(self, cluster, *, broker_id: int = None, host: str = None, port: int = None):
self.cluster = cluster
self.br... |
421797 | import numpy as np
import tensorflow as tf
tf.logging.set_verbosity(tf.logging.ERROR)
import gpflow as gp
def _sample_inducing_tensors(sequences, num_inducing, num_levels, increments):
Z = []
sequences_select = sequences[np.random.choice(sequences.shape[0], size=(num_inducing), replace=True)]
for m in rang... |
421809 | import unittest
from mock import Mock, patch
import torch.nn as nn
import torch.nn.functional as F
import torchbearer
from torchbearer.metrics import DefaultAccuracy
class TestDefaultAccuracy(unittest.TestCase):
def test_defaults(self):
state = {torchbearer.CRITERION: 'not a criterion'}
metric ... |
421826 | import numpy as np
from gradient_textures import get_radial_img_data
from gradient_textures import get_gradient_img_data
class FGTextureType:
PlainBin = "plainbin"
PlainGray = "plaingray"
GradientRadial = "gradientradial"
GradientLinear = "gradientlinear"
class Foreground(object):
def __init__(se... |
421831 | from django.db.models.manager import Manager
class PassThroughManager(Manager):
'''
Inherit from this Manager to enable you to call any methods from your
custom QuerySet class from your manager. Simply define your QuerySet
class, and return an instance of it from your manager's `get_query_set`
met... |
421854 | from django.utils.functional import cached_property
from waldur_core.structure.tests.fixtures import ProjectFixture
from . import factories
class AzureFixture(ProjectFixture):
@cached_property
def settings(self):
return factories.AzureServiceSettingsFactory(customer=self.customer)
@cached_prope... |
421895 | import os
from jinja2 import Environment, PackageLoader
from . import helpers
class Ansidoc():
"""Main ansidoc Object."""
def __init__(self, **kwargs):
"""initiate object with provided options."""
self.verbose = kwargs.get('verbose')
self.dry_run = kwargs.get('dry_run')
self.t... |
421941 | from omnihash.omnihash import main
import os
import sys
import unittest
import click
from click.testing import CliRunner
def safe_str(obj):
try:
s = str(obj)
except Exception as ex:
s = ex
return s
class TOmnihash(unittest.TestCase):
# Sanity
def test_hello_world(self):
... |
421954 | def get_arrangement_count(free_spaces):
if not free_spaces:
return 1
elif free_spaces < 2:
return 0
arrangements = 0
if free_spaces >= 3:
arrangements += (2 + get_arrangement_count(free_spaces - 3))
arrangements += (2 + get_arrangement_count(free_spaces - 2))
return arr... |
421968 | import torch
from torch import nn
from .memory import ContrastMemory
eps = 1e-7
class CRDLoss(nn.Module):
"""CRD Loss function
includes two symmetric parts:
(a) using teacher as anchor, choose positive and negatives over the student side
(b) using student as anchor, choose positive and negatives over... |
421974 | import numpy as np
import pyccl as ccl
import time
def test_timing():
ls = np.unique(np.geomspace(2, 2000, 128).astype(int)).astype(float)
nl = len(ls)
b_g = np.array([1.376695, 1.451179, 1.528404,
1.607983, 1.689579, 1.772899,
1.857700, 1.943754, 2.030887,
... |
422004 | from abc import ABC, abstractmethod
from typing import Union
import tensorflow as tf
from . import listify
class Score(ABC):
"""Abstract class for defining a score function.
"""
def __init__(self, name=None) -> None:
"""
Args:
name: Instance name. Defaults to None.
""... |
422031 | import logging
from pymongo import MongoClient
from tqdm import tqdm
from jsonschema import ValidationError
import fhirstore
import fhirpipe
_client = None
def get_mongo_client():
global _client
if _client is None:
_client = MongoClient(
host=fhirpipe.global_config["fhirstore"]["host"]... |
422101 | import os
import argparse
import numpy as np
from shutil import copy2
import torch
from torch.autograd import Variable
import torch.nn as nn
import eval_sent_embeddings_labels_in_expl
import streamtologger
GLOVE_PATH = '../dataset/GloVe/glove.840B.300d.txt'
parser = argparse.ArgumentParser(description='eval')
# p... |
422136 | import gc
import multiprocessing
from multiprocessing import Queue
from .dataset import *
from .base import *
class StageRunner(object):
def __init__(self, max_procs):
self.max_procs = max_procs
def launch_process(self, p_id, input_q, output_q):
raise NotImplementedError()
def run(self, ... |
422193 | import numpy as np
import torch
from ding.torch_utils import to_dtype, to_ndarray
def pack_birdview(data, packbit=False):
if isinstance(data, dict):
if 'obs' in data:
pack_birdview(data['obs'])
if 'next_obs' in data:
pack_birdview(data['next_obs'])
if 'birdview' in... |
422282 | from builtins import range
from functools import reduce
import numpy as np
""" Factor Graph classes forming structure for PGMs
Basic structure is port of MATLAB code by <NAME>
Central difference: nbrs stored as references, not ids
(makes message propagation easier)
Note to self: use %pdb and %load... |
422316 | from rest_framework.viewsets import GenericViewSet
from rest_framework import mixins
from rest_framework.exceptions import PermissionDenied
from django.db.models import Count, Avg
from rest_framework.response import Response
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework import serial... |
422331 | import datetime
import requests
import json
import time
from sqlite_utils.db import AlterError, ForeignKey
def save_items(items, db):
for item in items:
transform(item)
authors = item.pop("authors", None)
items_authors_to_save = []
if authors:
authors_to_save = []
... |
422333 | import torch
import torch.nn as nn
import torch.nn.functional as F
import numpy as np
import random
from typing import Any
from .utils import BasicBrain
class PERD3QNAgent(BasicBrain):
""" Prioritized Experience Replay Dueling Double Deep Q Network
Parameters:
-----------
input_dim : int, default 153... |
422334 | import torch
from torch import nn
from torch.nn import functional as F
class LWSLinear(nn.Linear):
__constants__ = ['bias', 'in_features', 'out_features']
def __init__(self, in_features, out_features, bias=True):
super(nn.Linear, self).__init__()
self.in_features = in_features
self.ou... |
422347 | import wx
import wx.grid as gridlib
import Utils
from HighPrecisionTimeEdit import HighPrecisionTimeEdit
class HighPrecisionTimeEditor(gridlib.GridCellEditor):
Empty = '00:00:00.000'
def __init__(self):
self._tc = None
self.startValue = self.Empty
super().__init__()
def Create( self, parent, id=wx.ID_ANY, ... |
422353 | import os
from pathlib import Path
output_dir = Path("outputs")
if not output_dir.exists():
print('output_dir does not exist.'.format(output_dir))
exit(-1)
eval_folder = output_dir.joinpath('eval')
if not eval_folder.exists():
eval_folder.mkdir(parents=True, exist_ok=True)
testlist = "./lists/dtu/test.tx... |
422395 | import json
from django.forms.widgets import Widget
from jarbas.dashboard.admin.subquotas import Subquotas
class ReceiptUrlWidget(Widget):
def render(self, name, value, attrs=None, renderer=None):
if not value:
return ''
url = '<div class="readonly"><a href="{}" target="_blank">{}<... |
422403 | from pwn import *
context.arch = 'amd64'
context.terminal = ['tmux', 'splitw', '-h']
p = process("./simplerop")
gdb.attach(p, '')
binary = ELF("./simplerop")
rop = ROP(binary)
binsh = 0x402008
system = 0x4011df
rop.call(system, [binsh])
print(rop.dump())
p.sendline(b'A' * 8 + rop.chain())
p.interactive()
|
422425 | import os
import subprocess
import sys
from detail.android_studio_build import android_studio_build
from detail.download_unzip import download_unzip
from detail.polly_build import polly_build
ci_type = os.getenv('TYPE')
ci_type_expected = 'Expected values:\n* polly\n* android-studio'
if ci_type == None:
sys.exit(... |
422470 | import os
from floyd.constants import DEFAULT_FLOYD_IGNORE_LIST
from floyd.log import logger as floyd_logger
class FloydIgnoreManager(object):
"""
Manages .floydignore file in the current directory
"""
CONFIG_FILE_PATH = os.path.join(os.getcwd() + "/.floydignore")
@classmethod
def init(cls)... |
422479 | from __future__ import absolute_import, print_function
from llvmlite import ir
from llvmlite.ir.transforms import Visitor, CallVisitor
class FastFloatBinOpVisitor(Visitor):
"""
A pass to add fastmath flag to float-binop instruction if they don't have
any flags.
"""
float_binops = frozenset(['fadd... |
422493 | import tensorflow as tf
import tensorflow.contrib.layers as layers
import numpy as np
import data_util
from model_components import task_specific_attention, bidirectional_rnn
class HANClassifierModel():
""" Implementation of document classification model described in
`Hierarchical Attention Networks for Docume... |
422494 | from snowflake.ingest import SimpleIngestManager
from snowflake.ingest import StagedFile
import time
import os
def test_simple_ingest(connection_ctx, test_util):
param = connection_ctx['param']
pipe_name = '{}.{}.TEST_SIMPLE_INGEST_PIPE'.format(
param['database'],
param['schema'])
privat... |
422498 | import pytest
from route_distances.validation import validate_dict
@pytest.mark.parametrize(
"route_index",
[0, 1, 2],
)
def test_validate_example_trees(load_reaction_tree, route_index):
validate_dict(load_reaction_tree("example_routes.json", route_index))
def test_validate_only_mols():
dict_ = {
... |
422507 | import ast
from .fat_tools import (OptimizerStep, ReplaceVariable, FindNodes, NodeTransformer,
compact_dump, copy_lineno, copy_node,
ITERABLE_TYPES)
import inline, copy, astunparse
CANNOT_UNROLL = (ast.Break, ast.Continue, ast.Raise)
#class UnrollStep(OptimizerStep, ast.NodeTr... |
422555 | import pandas as pd
import matplotlib.pylab as plt
df_calculated = pd.read_csv('../logs/output.log', sep=' ', names=['ts', 'x', 'y', 'r'])
df_benchmark = pd.read_csv('../logs/benchmarks.log', sep=' ', names=['x', 'y', 'ts', 'ori', 'subloc'])
plt.gca().set_aspect('equal')
plt.plot(df_calculated.x, df_calculated.y, '.-... |
422578 | from nose.tools import assert_equals, assert_false, assert_true
import json
import imp
imp.load_source("check_user","check_user_py3.py")
from check_user import User
def test_check_user_positive():
chkusr = User("root")
success, ret_msg = chkusr.check_if_user_exists()
assert_true(success)
assert_equals(... |
422618 | import kerastuner
import tensorflow as tf
from codecarbon import EmissionsTracker
class RandomSearchTuner(kerastuner.tuners.RandomSearch):
def run_trial(self, trial, *args, **kwargs):
# You can add additional HyperParameters for preprocessing and custom training loops
# via overriding `run_trial`... |
422628 | from .Source import Source
from inspect import ismethod
from types import FunctionType
from ..util.Math import interp1d
from ..util.SetDefaultParameterValues import SourceParameters
try:
# this runs with no issues in python 2 but raises error in python 3
basestring
except:
# this try/except allows for pytho... |
422671 | from __future__ import division
import sys
from statistics import mean
from sklearn.ensemble import BaggingClassifier
from sklearn.metrics import accuracy_score
from sklearn.model_selection import GridSearchCV
from sklearn.multiclass import OneVsRestClassifier
from sklearn.svm import SVC
from tools.classifier.evalua... |
422702 | import dataclasses
from typing import Any, Dict, Optional, Sequence, Union
from . import MemoryDataSource, RangeOutput
@dataclasses.dataclass
class DictMemoryDataSource(MemoryDataSource):
db: Dict[str, Any] = dataclasses.field(default_factory=dict)
async def set(self, key: str, data: str) -> None:
s... |
422740 | import random
import torch
import torch.nn as nn
import torch.nn.functional as F
# Helper function for returning deprocessing of decorrelated tensors
def get_decorrelation_layers(image_size=(224,224), input_mean=[1,1,1], device='cpu', decay_power=0.75, decorrelate=[True,None]):
mod_list = []
if decorrelate[0]... |
422750 | from selenium import webdriver
class FindByIdName():
def test(self):
baseUrl = "https://letskodeit.teachable.com/pages/practice"
driver = webdriver.Firefox()
driver.get(baseUrl)
elementById = driver.find_element_by_id("name")
if elementById is not None:
print("... |
422761 | from .base import Engine
from .finder import engine_finder
from .postgres import PostgresEngine
from .sqlite import SQLiteEngine
__all__ = ["Engine", "PostgresEngine", "SQLiteEngine", "engine_finder"]
|
422795 | import ast
import dataclasses
import inspect
import typing
from abc import ABC, abstractmethod
from ast import Set, Dict, Tuple
from collections import defaultdict
from contextlib import contextmanager
from dataclasses import dataclass
from functools import lru_cache, singledispatch
from inspect import getmembers
from ... |
422813 | expected_output = {
"interfaces": {
"GigabitEthernet1/0/1": {
"name": "foo bar",
"down_time": "00:00:00",
"up_time": "4d5h",
},
}
} |
422873 | from __future__ import absolute_import, division, print_function
import logging
import sys
logging.basicConfig(
stream=sys.stdout,
level=logging.DEBUG,
format='%(asctime)s %(name)s-%(levelname)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S')
import matplotlib as mpl
mpl.use('Agg') # TO DISABLE GUI. USE... |
422919 | from functools import partial
from typing import Optional
import numpy as np
import xarray as xr
from starfish.core.imagestack.imagestack import ImageStack
from starfish.core.types import Axes, Levels
from ._base import FilterAlgorithm
class LinearUnmixing(FilterAlgorithm):
"""
LinearUnmixing enables the us... |
422932 | from typing import Any
import torch
from torch import fx
class NodeProfiler(fx.Interpreter):
"""
This is basically a variant of shape prop in
https://github.com/pytorch/pytorch/blob/74849d9188de30d93f7c523d4eeceeef044147a9/torch/fx/passes/shape_prop.py#L65.
Instead of propagating just the shape, we r... |
422937 | from ethereum import utils
def mk_multisend_code(payments): # expects a dictionary, {address: wei}
kode = b''
for address, wei in payments.items():
kode += b'\x60\x00\x60\x00\x60\x00\x60\x00' # 0 0 0 0
encoded_wei = utils.encode_int(wei) or b'\x00'
kode += utils.ascii_chr(0x5f + len(enc... |
422952 | from __future__ import absolute_import
from __future__ import print_function
import veriloggen
import _iter
expected_verilog = """
module blinkled
(
input CLK,
input RST,
output reg [8-1:0] LED
);
reg [32-1:0] count;
always @(posedge CLK) begin
if(RST) begin
count <= 0;
end else begin
i... |
422977 | import sys
import os
nbits = int(sys.argv[1])
for block_size in range(1, nbits + 1):
if (block_size * 8) % nbits == 0:
break
def gen_pack_bytes(num_values):
code = []
nbytes = (num_values * nbits + 7) // 8
for i in range(num_values):
code.append('const unsigned char s{} = *src++;'.for... |
423062 | import pytest
from ithkuil.parser import parseWord
words_to_test = [
('poi', {
'type': 'personal adjunct',
'[tone]': None,
'[stress]': -2,
'C1': 'p',
'Vc': 'oi',
'Cz': None,
'Vz': None,
'VxC': None,
'Vc2': None,
'Vw': None,
'C... |
423064 | import numpy as np
import math
from sardem.dem import main as load_dem
from numba import jit, prange
from typing import Tuple, NamedTuple, Dict
import gdal
class RPCCoeffs(NamedTuple):
height_off: float
height_scale: float
lat_off: float
lat_scale: float
line_den_coeff: np.array
line_num_coeff... |
423075 | import sessions
import wx
from core.gui import SquareDialog
class CountdownDialog (SquareDialog):
def __init__(self, *args, **kwargs):
super(CountdownDialog, self).__init__(*args, **kwargs)
wx.StaticText(parent=self.pane, label=_("Name:"))
self.name = wx.TextCtrl(parent=self.pane)
wx.StaticText(par... |
423107 | import os
import glob
from fontTools.misc.loggingTools import LogMixin
from fontTools.designspaceLib import DesignSpaceDocument, AxisDescriptor, SourceDescriptor, RuleDescriptor, InstanceDescriptor
try:
import xml.etree.cElementTree as ET
except ImportError:
import xml.etree.ElementTree as ET
# Reader that p... |
423109 | from bunq.sdk.exception.api_exception import ApiException
class MethodNotAllowedException(ApiException):
pass
|
423135 | import numbers
def is_id(value):
"""
Return True, if the input value is a valid ID. False otherwise.
"""
if isinstance(value, numbers.Number):
try:
int(value)
return True
except ValueError:
return False
return False
|
423144 | import unittest
import pytest
from gitopscli.gitops_config import GitOpsConfig
from gitopscli.gitops_exception import GitOpsException
class GitOpsConfigV0Test(unittest.TestCase):
def setUp(self):
self.yaml = {
"deploymentConfig": {"applicationName": "my-app", "org": "my-org", "repository": "m... |
423181 | import pytest
from pg13 import sqparse2,pgmock
def test_parse_arraylit():
v=sqparse2.ArrayLit((sqparse2.Literal(1),sqparse2.Literal(2),sqparse2.Literal("three")))
assert v==sqparse2.parse("array[1,2,'three']")
assert v==sqparse2.parse("{1,2,'three'}")
def test_parse_select():
# this is also testing nesting an... |
423185 | symbology = 'code93'
cases = [
('001.png', 'CODE93', dict(includetext=True)),
('002.png', 'CODE93^SFT/A', dict(parsefnc=True, includecheck=True)),
]
|
423265 | import os
import contextlib
import hou
import sys
from collections import deque
import pyblish.api
import openpype.api
import openpype.hosts.houdini.api.usd as hou_usdlib
from openpype.hosts.houdini.api.lib import render_rop
class ExitStack(object):
"""Context manager for dynamic management of a stack of exit c... |
423277 | from spacy.tokens import Doc
from spacy.language import Language
import operator
@Language.factory("healthsea.aggregation.v1")
def create_clause_aggregation(nlp: Language, name: str):
return ClauseAggregation(nlp, name)
class ClauseAggregation:
"""Aggregate the predicted effects from the clausecat and apply... |
423326 | from __future__ import absolute_import, division, print_function
from builtins import bytes, range, int
import math
from itertools import combinations
try:
from itertools import zip_longest
except:
from itertools import izip_longest as zip_longest
from random import randint
from copy import deepcopy
from Cryp... |
423373 | import random
import os
import json
from interfaces.SentenceOperation import SentenceOperation
from tasks.TaskTypes import TaskType
def noun_compound_paraphraser(text, compounds):
L = [[text]]
for k in compounds.keys():
if k in L[0][0]:
new = []
for l in L:
f... |
423407 | from test_helper import exchange_updates
import y_py as Y
def test_set():
d1 = Y.YDoc()
x = d1.get_map('test')
value = d1.transact(lambda txn : x.get(txn, 'key'))
assert value == None
d1.transact(lambda txn : x.set(txn, 'key', 'value1'))
value = d1.transact(lambda txn : x.get(txn, 'key'))
... |
423408 | import requests
from unittest import TestCase
from test_arguments import test_print
from test_functions import compare_get_request, compare_post_request
class TestSubmit(TestCase):
def test_submit(self):
test_print("test_main_page starting")
headers = {'Accept':'text/plain'}
compare_get_re... |
423416 | from a_stanford_data_processor import AStanfordDataProcessor
from stanford_car_dataset_augmented import StanfordCarAugmentedDataset
from stanford_car_dataset_augmented import preprocess_data
from stanford_cars_data_augmentation import StanfordCarsDataAugmentation
class StanfordAugmentedDataProcessor(AStanfordDataProc... |
423447 | from graphilp.imports.ilpgraph import ILPGraph
def read(G):
""" Wrap a NetworkX graph class by an ILPGraph class
The wrapper class is used store the graph and the related variables of an optimisation problem
in a single entity.
:param G: a `NetworkX graph <https://networkx.org/documentation/stable/r... |
423503 | from pathlib import Path
from shutil import copyfile
import click
from autoalbument.cli.lib.migrations import migrate_v1_to_v2
from autoalbument.cli.lib.yaml import yaml
from autoalbument.utils.click import should_write_file
@click.command()
@click.option(
"--config-dir",
type=click.Path(),
required=Tru... |
423509 | import os
from glob import glob
from setuptools import find_packages
from setuptools import setup
package_name = 'crs_utils_py'
setup(
name=package_name,
version='0.0.0',
# Packages to export
packages=find_packages(),
# Files we want to install, specifically launch files
data_files=[
(... |
423512 | import tensorflow as tf
import tensorflow.contrib.slim as slim
from core.config import cfgs
DATA_FORMAT = "NHWC"
debug_dict = {}
BottleNeck_NUM_DICT = {
'resnet50_v1d': [3, 4, 6, 3],
'resnet101_v1d': [3, 4, 23, 3]
}
BASE_CHANNELS_DICT = {
'resnet50_v1d': [64, 128, 256, 512],
'resnet101_v1... |
423522 | from collections import Counter
def soma_quadrados(n):
pass
import unittest
class SomaQuadradosPerfeitosTestes(unittest.TestCase):
def teste_0(self):
self.assert_possui_mesmo_elementos([0], soma_quadrados(0))
def teste_1(self):
self.assert_possui_mesmo_elementos([1], soma_quadrados(1)... |
423530 | from .abstract_portfolio import AbstractPortfolio
from .components import PortfolioHistory
from .. import metrics
class SimulatedPortfolio(AbstractPortfolio):
"""Simulated Portfolio Class
The simulated portfolio is a implementation of the abstract portfolio class
specifically for historical backtesting p... |
423556 | import os
import shutil
import subprocess
import sparsechem as sc
import numpy as np
import string
import glob
import scipy.sparse
from urllib.request import urlretrieve
def download_chembl23(data_dir="test_chembl23", remove_previous=False):
if remove_previous and os.path.isdir(data_dir):
os.rmdir(data_dir... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.