id stringlengths 3 8 | content stringlengths 100 981k |
|---|---|
4827184 | class ParserGenerationException(Exception):
""" Raised when something goes wrong during parser generation """
pass
class ParserException(Exception):
""" Raised during a failure in the parsing process """
pass
|
4827191 | from __future__ import absolute_import
# Copyright (c) 2010-2015 openpyxl
from openpyxl.descriptors import Float, Set, Sequence, Alias, NoneSet
from openpyxl.compat import safe_string
from .colors import ColorDescriptor, Color
from .hashable import HashableObject
from openpyxl.xml.functions import Element, localname... |
4827200 | import torch
from model.base import BaseModule
from model.interpolation import InterpolationBlock
from model.layers import Conv1dWithInitialization
class ConvolutionBlock(BaseModule):
def __init__(self, in_channels, out_channels, dilation):
super(ConvolutionBlock, self).__init__()
self.leaky_relu... |
4827221 | import os
import sys
import matplotlib
matplotlib.use('cairo')
from matplotlib import pyplot as plt
from matplotlib.colors import LinearSegmentedColormap
import numpy
from scipy.cluster.hierarchy import linkage, leaves_list
import xmltodict
if __name__ == "__main__":
with open(sys.argv[1], 'r', encoding="utf-8") ... |
4827263 | from config import config_from_dict, config_from_python
import sys
import os
DICT = {
"a1.B1.c1": 1,
"a1.b1.C2": 2,
"A1.b1.c3": 3,
"a1.b2.c1": "a",
"a1.b2.c2": True,
"a1.b2.c3": 1.1,
"a2.b1.c1": "f",
"a2.b1.c2": False,
"a2.b1.c3": None,
"a2.b2.c1": 10,
"a2.b2.c2": "YWJjZGVm... |
4827274 | from typing import Tuple
import torch
from torch import nn
from torch.nn import functional as F
class PoolingError(Exception): pass
class UNet3dLite(nn.Module):
"""(WIP) Re-implementation of the unet3d_lite model from ELEKTRONN2
See https://github.com/ELEKTRONN/ELEKTRONN2/blob/master/examples/unet3d_lite.... |
4827317 | from bsym import Configuration, SymmetryOperation
import numpy as np
class ColourOperation( SymmetryOperation ):
"""
This class subclasses `SymmetryOperation`.
It defines a class of object for performing a compound operation on a
configuration.
First, a matrix transform applied to the configuratio... |
4827327 | import numpy as onp
import jax.numpy as np
from jax import jit
from tfc import utfc
from tfc.utils import MakePlot, step
# Constants:
N = 101
m = 8
nC = -1
nMC = 100
# Create the TFC class:
myTfc = utfc(N,nC,m,x0=-2.,xf=2.,basis='LeP')
x = np.linspace(0.,2.,N)
ind = np.argmin(np.abs(x-1.))
H = myTfc.H
m = H(x).sh... |
4827375 | import pytest
from pyscipopt.scip import Model, is_memory_freed
from util import is_optimized_mode
def test_not_freed():
if is_optimized_mode():
pytest.skip()
m = Model()
assert not is_memory_freed()
def test_freed():
if is_optimized_mode():
pytest.skip()
m = Model()
del m
as... |
4827468 | def user(first_name: str, last_name: str, **kwargs: str) -> None:
"""
get the name and last name and other information of the user
Args:
first_name (str): name of the user
last_name (str): last name of the user
*kwargs (str): keyword arguments
Return: None
"""
print(fir... |
4827473 | import argparse
import os
import torch
import torchvision.models as models
from torch.autograd import Variable
from torch.utils.serialization import load_lua
"""
Read a .t7 file created by caffemodel_to_t7.lua and a .pth file created by
t7_to_state_dict.py and make sure the converted PyTorch model computes the same
in... |
4827547 | from ..utils import _CurrentSiteCommand, SiteManager
class LogsCommand(_CurrentSiteCommand):
"""
Get the logs of the running site
"""
def run(self, **kwargs):
SiteManager().logs()
|
4827582 | import os
import pytest
from app import app
from app.models import db as _db
TEST_DB = 'test_project.db'
TEST_DB_PATH = "/opt/project/data/{}".format(TEST_DB)
TEST_DATABASE_URI = 'sqlite:///' + TEST_DB_PATH
@pytest.fixture(scope='session')
def app():
"""Session-wide test `Flask` application."""
app.config... |
4827600 | import numpy as np
import cv2 as cv
cap = cv.VideoCapture(cv.samples.findFile("vtest.avi"))
ret, frame1 = cap.read()
prvs = cv.cvtColor(frame1,cv.COLOR_BGR2GRAY)
hsv = np.zeros_like(frame1)
hsv[...,1] = 255
while(1):
ret, frame2 = cap.read()
next = cv.cvtColor(frame2,cv.COLOR_BGR2GRAY)
flow = cv.calcOptical... |
4827648 | import modutil
mod, __getattr__ = modutil.lazy_import(__name__, {'..A'})
def trigger_A():
return mod.A
|
4827650 | class CredentialProvider:
"""CredentialProvider.
This class allows Bots to provide their own implemention
of what is, and what is not, a valid appId and password.
This is useful in the case of multi-tenant bots, where the bot
may need to call out to a service to determine if a particular
appid/p... |
4827683 | import tensorflow as tf
import numpy as np
import scipy.stats as stats
import logging
class CRBM():
'''
CRBM based on a paper 'Unsupervised feature learning for audio classification using convolutional
deep belief networks' by <NAME>, <NAME>, <NAME>, and <NAME>.
'''
def __init__(self, filter_shape,... |
4827706 | from redis import connection
from redis.exceptions import (ResponseError)
from exceptions import (AskError, MovedError)
import logging
logging.basicConfig()
CUSTOM_EXCEPTION_CLASSES = {
'ASK': AskError,
'MOVED': MovedError,
}
def parse_error(self, response):
"Parse an error response"
error_code = r... |
4827768 | from bottle import local, post, request
from codalab.common import UsageError, precondition
from codalab.lib.bundle_action import BundleAction
from codalab.objects.permission import check_bundles_have_all_permission
from codalab.rest.schemas import BundleActionSchema
from codalab.server.authenticated_plugin import Aut... |
4827778 | from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals
import cv2
import numpy as np
import os
import math
from caffe2.python import core
from caffe2.python import workspace
from detectron.core.config import cfg
from detect... |
4827840 | from logger import get_logger
import os
import datetime
import utils.utils as utils
import utils.tags as tags
PARTITION_COL = os.environ.get('PARTITION_COL', 'study_date')
log = get_logger(__name__)
class dcmfile():
def __init__(self, source_s3_bucket=None, source_s3_bucket_region=None, source_s3_key=None, sour... |
4827890 | import sys
import time
import socket
import threading
import random
import datetime
from MainWin import HeartbeatPort, NotifyPort
from Utils import readDelimitedData
from AutoDetect import GetDefaultHost
DEFAULT_HOST = GetDefaultHost()
from xml.dom.minidom import parseString
CmdPort = 53161
testTags = '''e200101886... |
4827926 | import numpy as np
def i2t(sims, npts=None, return_ranks=False):
"""
Images->Text (Image Annotation)
sims: (N, 5N) matrix of similarity im-cap
"""
npts = sims.shape[0]
ranks = np.zeros(npts)
top1 = np.zeros(npts)
for index in range(npts):
inds = np.argsort(sims[index])[::-1]
... |
4827958 | from tensorflow.keras.layers import Input,GRU,Dense,Bidirectional
from tensorflow.keras.models import Model
class TEXT_BI_GRU:
def __init__(self, embedding_layer, class_len, max_sequence_len):
self.embedding_layer = embedding_layer
self.class_len = class_len
self.max_sequence_len = max_seque... |
4827981 | from pykrx import stock
df = stock.get_market_ohlcv_by_date("20190501", "20190531", "005930")
print(df) |
4827996 | import json
class RGBMixin():
def set_color(self, topic, command, level, color):
cmd = command.upper()
if cmd == 'ON' or cmd == 'OFF':
return {
'topic': topic,
'payload': json.dumps({
"state": command
})
}
... |
4828008 | from apscheduler.events import JobExecutionEvent, EVENT_ALL
from apscheduler.jobstores.redis import RedisJobStore
from apscheduler.schedulers.asyncio import AsyncIOScheduler
from loguru import logger
from pytz import utc
from sentry_sdk import capture_exception
from telegram_bot.settings import redis_config
jobstores... |
4828014 | from lib.base import QualysBaseAction
__all__ = [
'LaunchScanAction'
]
class LaunchScanAction(QualysBaseAction):
def run(self, title, option_title, iscanner_name,
asset_groups=None, ip=None):
scan = self.connection.launchScan(title, option_title,
... |
4828045 | import torch
import torch.distributed as dist
from torch import Tensor
from typing import Any, Tuple, Optional
from torch.distributed import ProcessGroup
COL_MOE_KERNEL_FLAG = False
try:
import colossal_moe_cuda
COL_MOE_KERNEL_FLAG = True
except ImportError:
print("If you want to activate cuda... |
4828055 | from django.contrib.auth import REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import login_required, user_passes_test
from django.shortcuts import redirect
from . import app_settings
def anonymous_required(function=None, redirect_url=app_settings.LOGIN_REDIRECT_URL):
"""Decorator to check if a user is ... |
4828059 | import numpy as np
from fastai.dataloader import DataLoader
class DialogueDataLoader(DataLoader):
def pad2d(self, x, max_cl, max_sl):
paddings = [(max_cl - x.shape[0], 0), (max_sl - x.shape[1], 0)] if self.pre_pad else [(0, max_cl - x.shape[0]),
... |
4828069 | import os
import errno
import sys
from pip._vendor import six
def _makedirs_31(path, exist_ok=False):
try:
os.makedirs(path)
except OSError as exc:
if not exist_ok or exc.errno != errno.EEXIST:
raise
# rely on compatibility behavior until mode considerations
# a... |
4828121 | import asynctest
import pytest
from jsondaora import dataclasses
@pytest.mark.asyncio
async def test_should_set_already_not_found_error_when_get_many_with_fields(
repository, mocker
):
fake_entity = 'fake'
repository.memory_data_source.hmget = asynctest.CoroutineMock(
return_value=[None, None, Non... |
4828171 | from .batch_td import BatchTD
from .fqi import FQI
from .double_fqi import DoubleFQI
from .boosted_fqi import BoostedFQI
from .lspi import LSPI
__all__ = ['FQI', 'DoubleFQI', 'BoostedFQI', 'LSPI']
|
4828192 | from dataclasses import dataclass
from .types import (
InfoLevel,
DebugLevel,
WarnLevel,
ErrorLevel,
ShowException,
NoFile
)
# Keeping log messages for testing separate since they are used for debugging.
# Reuse the existing messages when adding logs to tests.
@dataclass
class IntegrationTest... |
4828202 | import tensorflow as tf
def to_ints(value):
""" Converts a list to an int64 feature.
Args:
value: The list to convert.
Returns:
The corresponding feature. """
return tf.train.Feature(int64_list=tf.train.Int64List(value=value))
def to_bytes(value):
""" Converts a list to a uint8 feature.
Args:
value:... |
4828206 | from __future__ import absolute_import
import sys
import pytest
@pytest.fixture
def no_numpy_pyq(monkeypatch):
monkeypatch.setitem(sys.modules, 'numpy', None)
pyq_modules = [m for m in sys.modules
if m is not None and (m == 'pyq' or m.startswith('pyq.'))]
for m in pyq_modules:
m... |
4828218 | from itertools import product
from tekore.model import RecommendationAttribute
prefixes = {'min', 'max', 'target'}
attributes = set(str(a) for a in RecommendationAttribute)
valid = set('_'.join(i) for i in product(prefixes, attributes))
def validate_attributes(candidates: dict) -> None:
"""
Validate recommen... |
4828231 | from os import path
from notifypy import Notify
def notify(content, title="Orange Share"):
"""
Shows a notification.
:param content: The content
:param title: The titel (default: Orange Share)
:return:
"""
notification = Notify()
notification.title = title
notification.message = c... |
4828248 | import file_io
train_file_dir = "../data/toJeff/Train/"
test_file_dir = "../data/toJeff/Test/"
def get_list_file(file_dir):
#train_feature_list = file_io.get_listfile(file_dir + "Resized_images/","resnet_hypercolumn")
train_feature_list = file_io.get_listfile(file_dir + "Resized_images/","jpg")
train_lab... |
4828254 | r"""Functions for Higgs production.
Most of the numerical coefficients have been obtained with MadGraph_aMC@NLO v2.6.5
along with SMEFTsim v2 in the alpha scheme.
"""
import flavio
def ggF(C):
r"""Higgs production from gluon fusion normalized to the SM"""
# obtained from an analytical one-loop calculation
... |
4828319 | import sys
import os
import string
import time
from stat import *
if len(sys.argv) < 5:
print "<generated_scene_folder> <output_folder> <start frame> <end frame> <ray-tracing binary>"
sys.exit()
for i in range(string.atoi(sys.argv[3]), string.atoi(sys.argv[4])):
checkfile = sys.argv[2] + "render.%(#)05d.... |
4828355 | import os
import unittest
import yaml
from io import StringIO
from unittest import mock
from .. import *
from mike import mkdocs_utils
class Stream(StringIO):
def __init__(self, name, data=''):
super().__init__(data)
self.name = name
def close(self):
pass
def mock_open_files(files)... |
4828375 | from typing import List
from django.conf import settings
from django.http import Http404
from django.views.generic import TemplateView
class PageView(TemplateView):
"""Handles event pages showing."""
def get_template_names(self) -> List[str]:
"""Get specific template names."""
path: str = se... |
4828377 | from ray import tune
import numpy as np
from collections import OrderedDict
timesteps_total = 20_000
num_seeds = 10
var_env_configs = OrderedDict(
{
"state_space_size": [8], # , 10, 12, 14] # [2**i for i in range(1,6)]
"action_space_size": [8], # 2, 4, 8, 16] # [2**i for i in range(1,6)]
... |
4828407 | from uuid import uuid4
from moto.core import BaseBackend, BaseModel
from moto.wafv2 import utils
from .utils import make_arn_for_wacl, pascal_to_underscores_dict
from .exceptions import WAFV2DuplicateItemException
from moto.core.utils import iso_8601_datetime_with_milliseconds, BackendDict
import datetime
from collect... |
4828472 | d = dict()
d[True] = "true"
d[1] = "one"
d[0] = "zero"
d[False] = "false"
d[1.0] = "floatone"
print sorted(d.items())
d = dict()
d[True] = True
print 1 in d
print True in d
print 1.0 in d
print 1L in d
print 0 in d
print False in d
print "foo" in d
print "1" in d
|
4828488 | from django.utils.translation import ugettext_lazy as _
from event_log import registry
registry.register(
name='labour.signup.created',
message=_('{entry.person} signed up for volunteer work in {entry.event}'),
email_body_template='labour_signup_created.eml',
)
registry.register(
name='labour.signu... |
4828522 | from libweasyl.cache import region
from libweasyl.models.media import MediaItem, SubmissionMediaLink, UserMediaLink
@SubmissionMediaLink.register_cache
@region.cache_multi_on_arguments()
def get_multi_submission_media(*submitids):
return SubmissionMediaLink.bucket_links(submitids)
@UserMediaLink.register_cache
... |
4828556 | import copy
import unittest
import numpy as np
import torch
import torch.nn.functional as F
from pytorch_adapt.adapters import Aligner
from pytorch_adapt.containers import Models, Optimizers
from pytorch_adapt.hooks import AlignerPlusCHook, JointAlignerHook, validate_hook
from pytorch_adapt.layers import CORALLoss, M... |
4828580 | from typing import List
from sqlalchemy import Column, String
from sqlalchemy.orm import relationship
from IocManager import IocManager
from models.base.connection.ConnectionTypeBase import ConnectionTypeBase
from models.dao.connection.Connection import Connection
from models.dao.connection.ConnectorType import Connec... |
4828688 | import re
from random import randint
from typing import List
from typing import Match
from typing import Optional
from retrying import retry
import apysc as ap
from apysc._display.stage import get_stage_variable_name
from apysc._expression import expression_data_util
from tests._display.test_graphics_expre... |
4828701 | import os
import parser
import unittest
import pathlib
import numpy as np
class TestParser(unittest.TestCase):
def test_membros_ativos(self):
self.maxDiff = None
expected = {
'reg': '02003042' ,
'name': '<NAME>',
'role': 'PROCURADOR DE JUSTICA',
'ty... |
4828703 | import pytest
import mygrad as mg
from mygrad._dtype_mirrors import __all__ as all_mirrored_dtyped
@pytest.mark.parametrize("dtype_str", all_mirrored_dtyped)
def test_mirrored_dtype_is_valid(dtype_str):
mg.tensor(1, dtype=getattr(mg, dtype_str))
|
4828724 | import pytest
codeastro_mode = False
def pytest_addoption(parser):
parser.addoption(
"--mode",
action="store",
metavar="NAME",
help="different test modes NAME.",
)
def pytest_runtest_setup(item):
global codeastro_mode
envnames = [mark.args[0] for mark in item.iter_mark... |
4828738 | from bokeh.events import ButtonClick
from bokeh.io import curdoc
from bokeh.layouts import column, row, widgetbox
from bokeh.models import Button, ColumnDataSource, Div, Slider
from bokeh.plotting import figure
import numpy as np
doc = curdoc()
x = np.linspace(0, 2, 1000)
y = 1 - (x-1)**2
source = ColumnDataSource(... |
4828751 | import pyblish.api
import nuke
import os
import openpype
import clique
class NukeRenderLocal(openpype.api.Extractor):
# TODO: rewrite docstring to nuke
"""Render the current Fusion composition locally.
Extract the result of savers by starting a comp render
This will run the local render of Fusion.
... |
4828797 | import os
import logging
def printlog(self,data):
for dat in data:
logging.critical(dat) |
4828802 | import warnings
warnings.warn("BeautifulSoup 3.x (as of 3.1) is not fully compatible with html5lib and support will be removed in the future", DeprecationWarning)
from BeautifulSoup import BeautifulSoup, Tag, NavigableString, Comment, Declaration
import _base
from html5lib.constants import namespaces, DataLossWarnin... |
4828818 | from __future__ import absolute_import
import uuid
from job_progress import states
from job_progress.utils import classproperty
def _generate_id():
"""Return job unique id."""
return str(uuid.uuid4())
class JobProgress(object):
"""
JobProgress
:param int amount: amount of work to do.
:par... |
4828848 | class Solution:
def strangePrinter(self, s):
memo = {}
def dp(i, j):
if i > j: return 0
if (i, j) not in memo:
ans = dp(i+1, j) + 1
for k in range(i+1, j+1):
if s[k] == s[i]:
ans = min(ans, dp(i, k-1)... |
4828853 | from conans import ConanFile, tools
import os
class ReaderWriterQueue(ConanFile):
name = "readerwriterqueue"
url = "https://github.com/conan-io/conan-center-index"
homepage = "https://github.com/cameron314/readerwriterqueue"
description = "A fast single-producer, single-consumer lock-free queue for C+... |
4828860 | import numpy as np
import pandas as pd
import os
import matplotlib.pyplot as plt
def compute_challenge_metric_for_opt(labels, outputs):
classes=['10370003','111975006','164889003','164890007','164909002','164917005','164934002','164947007','17338001',
'251146004','270492004','284470004','39732003','426177001','... |
4828911 | import struct
import string
s_lookup = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
name = raw_input('Ingrese el nombre: ')
serial = ''
name = name.upper() + 'PERUCRACKERS'
for i in range(0,len(name)):
char_name = name[i]
pos_char_lut = s_lookup.index(char_name)
aux_1 = pos_char_lut + len(name)
if aux_1 < len... |
4828927 | import torch
from torch.utils import model_zoo
def to_array(feature_map):
if feature_map.shape[0] == 1:
feature_map = feature_map.squeeze(0).permute(1, 2, 0).detach().cpu().numpy()
else:
feature_map = feature_map.permute(0, 2, 3, 1).detach().cpu().numpy()
return feature_map
def t... |
4828962 | import os
import sys
import logging
import sys
import mrcfile
from IsoNet.preprocessing.cubes import create_cube_seeds,crop_cubes,DataCubes
from IsoNet.preprocessing.img_processing import normalize
from IsoNet.preprocessing.simulate import apply_wedge1 as apply_wedge
from multiprocessing import Pool
import numpy as n... |
4828965 | from __future__ import absolute_import
from django.core.exceptions import ImproperlyConfigured
from django.db.models.loading import get_app
from django.test import TestCase
from django.test.utils import override_settings
from django.utils import six
from .models import Empty
class EmptyModelTests(TestCase):
def... |
4829005 | import hashlib
import logging
import struct
import time
from binascii import hexlify, unhexlify
from collections import OrderedDict
from datetime import datetime
import ecdsa
from .account import PrivateKey, PublicKey
from .chains import known_chains
from .operations import Operation, GrapheneObject, isArgsThisClass
... |
4829009 | from flask import Flask
from flask import request
import json
import requests
import hashlib as hasher
import datetime as date
node = Flask(__name__)
# Define what a Snakecoin block is
class Block:
def __init__(self, index, timestamp, data, previous_hash):
self.index = index
self.timestamp = timestamp
se... |
4829033 | n = int(input())
for i in range(n):
k,x = input().split()
k,x = [int(k),int(x)]
print(((k-1)*9)+x) |
4829053 | import glob
import numpy
import pylab
import random
import copy
targets = glob.glob('povme/*')
#print targets
normalize = True
allAsSubplots = True
comparePovmeTo = 'dpocket'
#comparePovmeTo = 'mdpocket'
if comparePovmeTo == 'mdpocket':
targets = [i.split('/')[1] for i in targets if (not ('.' in i) and not('rot' ... |
4829086 | from machine import Pin, SPI
from splitflap import SplitFlap, luts
from time import sleep
OUT = Pin.OUT
IN = Pin.IN
NUM_COL = 16
NUM_ROW = 1
char_lut = luts.char_lut
words = [
"HELLO",
"WORLD",
":D XD ;3",
"/(ØWØ)/",
]
def vals_to_mat(vals, lut, w, h, default):
mat = [[default for a in range(h)... |
4829119 | from cwltool.main import main
from .util import get_data
def test_missing_cwl_version() -> None:
"""No cwlVersion in the workflow."""
assert main([get_data("tests/wf/missing_cwlVersion.cwl")]) == 1
def test_incorrect_cwl_version() -> None:
"""Using cwlVersion: v0.1 in the workflow."""
assert main([... |
4829138 | import torch
from src.resnet_cppn.config import get_config
from src.resnet_cppn.trainer import Trainer
from src.resnet_cppn.tester import Tester
def main():
config = get_config()
print(config)
device = 'cuda:0' if torch.cuda.is_available() else 'cpu'
config.device = device
print(f'd... |
4829144 | from pytorch_pretrained_bert.tokenization_transfo_xl import TransfoXLTokenizer
from pytorch_pretrained_bert.modeling_transfo_xl import (
TransfoXLModel,
TransfoXLLMHeadModel
)
# A lot of models share the same param doc. Use a decorator
# to save typing
transformer_xl_docstring = """
Transformer XL use a re... |
4829241 | from collections import defaultdict
from typing import Type, Callable, Any, Tuple, List, Dict
class Router:
"""
Direct router implementation.
Note:
"""
SubscriptionID = Tuple[Type, Callable]
def __init__(self):
self._handlers = defaultdict(list) # type: Dict[Type, List[Callable]]
... |
4829256 | try:
from unittest2 import TestCase
from mock import patch
except ImportError:
from unittest import TestCase
from mock import patch
import base64
from cfn_sphere.aws.kms import KMS
class KMSTests(TestCase):
@patch('cfn_sphere.aws.kms.boto3.client')
def test_decrypt_value(self, boto_mock):
... |
4829289 | import logging
from .log_adapter import adapt_log
LOGGER = logging.getLogger(__name__)
class FuncRunner(object):
""" Func Runner class """
log = adapt_log(LOGGER, 'FuncRunner')
def __init__(self, func, *args, **kwargs):
""" FuncRunner Initializer
Args:
func (reference): fun... |
4829304 | from .accountant import PickleAccountant # noqa: F401
from .decoder import PickleFinanceDecoder # noqa: F401
from .main import PickleFinance # noqa: F401
|
4829305 | from .EmbConstant import *
from .WriteHelper import write_int_8, write_int_16le, write_int_32le
FULL_JUMP = False
ROUND = True
MAX_JUMP_DISTANCE = 124 # 0xFCFF/2 16 bit signed, FD,FE,FF reserved.
MAX_STITCH_DISTANCE = 124
def write_xxx_header_b(pattern, f):
stitches = pattern.stitches
for i in ra... |
4829307 | from evdev import ecodes
scan_to_hid = {
# Reserved: 0
# ErrorRollOver: 1
# POSTFail: 2
# ErrorUndefined: 3
ecodes.KEY_A: 0x04,
ecodes.KEY_B: 0x05,
ecodes.KEY_C: 0x06,
ecodes.KEY_D: 0x07,
ecodes.KEY_E: 0x08,
ecodes.KEY_F: 0x09,
ecodes.KEY_G: 0x0a,
ecodes.KEY_H: 0x0b,
ecodes.KEY_I: 0x0c,
ec... |
4829327 | from .builder import build_decoder_layer, build_encoder_layer # noqa 401
from .decoder import TransformerDecoderLayer1D # noqa 401
from .encoder import TransformerEncoderLayer1D, TransformerEncoderLayer2D # noqa 401
|
4829355 | import pytest
from mockito import mock, expect
from app.clients.github_client import GithubClient
from app.enums.event_types import EventType
from app.hook_details.release_hook_details import ReleaseHookDetails
from app.mongo.registration_cursor import RegistrationCursor
from tests.async_mockito import async_value
py... |
4829372 | from django import template
register = template.Library()
@register.filter(name='file_name')
def file_name(dict):
return dict['file_name'] |
4829383 | from mango.relations import base
from mango.relations.constants import CASCADE
__all__ = [
"OneToOneRel",
"OneToManyRel",
"ManyToOneRel",
"ManyToManyRel",
]
class OneToOneRel(base.Relation):
def __init__(
self,
cls=None,
name=None,
rev_name=None,
... |
4829385 | import re
from typing import (
Optional,
Tuple,
Iterator
)
# operators
# (
# )
# :
# ,
REGEX_SPECIAL_CHARS = re.compile(r'[\\=<>/]+|[():,\r\n]', re.A)
STR_CARRIAGE_RETURN = '\n'
STR_COLON = ':'
STR_COMMA = ','
STR_PARAN_L = '('
STR_PARAN_R = ')'
REGEX_NOT_WHITESPACE = re.compile(r'[^\s]', re.A)
Loc = Tu... |
4829400 | from kivy.lang.builder import Builder
from kivymd.uix.screen import MDScreen
Builder.load_string(
"""
<MyAKBadgeLayout@AKBadgeLayout>
pos_hint: {"center_x": .5, "center_y": .5}
badgeitem_padding: dp(5)
bold: True
<BadgeLayout>
MDBoxLayout:
orientation: "vertical"
MyToolbar:
... |
4829426 | class Smell(object):
def __init__(self):
self.id = None
self.name = ""
self.description = ""
self.aka = []
self.aka_obj_list = []
self.reference = ""
self.category = ""
self.category_obj = None
self.ref_obj = None
self.tool_list = [] #i... |
4829502 | import re
from collections import namedtuple
component = r"""
(?:/\*\*((?:\*(?!/)|[^*])*)\*/\s+)?
(
(?:<cf)?
component\b
)
([^>{]*)
"""
component = re.compile(component, re.I | re.X | re.S)
Component = namedtuple('Component', 'script docblock attributes')
script_function = r"""
(?:/\*\*((?:\*(?!/)|[^*])*)\*... |
4829590 | from django.utils.translation import ugettext_lazy as _
from oscar.apps.basket import signals
from oscar.core.loading import get_model, get_class
from rest_framework import status, generics, exceptions
from rest_framework.response import Response
from rest_framework.views import APIView
from oscarapi import permissi... |
4829657 | class Data:
pass
d = Data()
d.id = 10
print(d.id)
setattr(d, 'id', 20)
print(d.id)
# setattr with dynamic programming
d = Data()
attr_name = input('Enter the attribute name:\n')
attr_value = input('Enter the attribute value:\n')
setattr(d, attr_name, attr_value)
print('Data attribute =', attr_name, 'and its... |
4829662 | from setuptools import setup
from codecs import open
from os import path
here = path.abspath(path.dirname(__file__))
with open(path.join(here, 'README.rst'), encoding='utf-8') as f:
long_description = f.read()
setup(
name='meteocalc',
version='1.1.0',
description='Functions for calculation of meteor... |
4829702 | from django.db import models
# Create your models here.
# class YTS(models.Model):
# movie_id = models.IntegerField()
# imdb_code = models.CharField(max_length=15)
# title = models.TextField()
# title_english = models.TextField()
# year = models.IntegerField()
# rating = models.FloatField()
# runtim... |
4829720 | import numpy as np
np.random.seed(1234)
# 1. Data Preprocess and declare
x = np.array([
[1,0,0],
[1,1,0],
[1,1,1]
])
y = np.array([
[1],
[2],
[3]
])
# 1.3 Starting Weights - however -
# the best set of weights would be wx = 1 and wrec = 1
wx = [0.2]
wrec = [1.5]
# Hyper Par
number_or_epoc... |
4829737 | import pytest
# No need for cleanup
@pytest.mark.admin
def test_001_i_want_to_force_unsupported_operation_towards_admin_interface(h2ac_admin):
requestBody = { "foo":"bar" }
responseBodyRef = { "result":"false", "response":"unsupported operation" }
# Send POST
response = h2ac_admin.postDict("/admin/v1/foo"... |
4829788 | import os
from tempfile import TemporaryDirectory
import numpy as np
import pytest
from starfish import ImageStack
from starfish.core.intensity_table.test import factories
from ..intensity_table import IntensityTable
def test_to_mermaid_dataframe():
"""
Creates a basic IntensityTable from an ImageStack and ... |
4829821 | from saasu_client import settings
API_URL = 'https://secure.saasu.com/webservices/rest/r1/'
DEFAULT_GET_URL = '%s%s?wsaccesskey=%s&fileuid=%s' % (API_URL, '%s', settings.SAASU_WSACCESS_KEY, settings.SAASU_FILE_UID)
DEFAULT_POST_URL = '%s%s?wsaccesskey=%s&fileuid=%s' % (API_URL, '%s', settings.SAASU_WSACCESS_KEY, sett... |
4829846 | import os
import pickle
import types
from .ifp_object import IFPObject
from .exceptions import DeserializationError, Unserializable
##############################################################
# SERIALIZER.PY - the save/load system for IntFicPy
# Defines the SaveState class, with methods for saving and loading game... |
4829886 | from mirage.libs.zigbee_utils.rzusbstick import *
from mirage.libs.zigbee_utils.hackrf import *
from mirage.libs.zigbee_utils.packets import *
from mirage.libs.zigbee_utils.helpers import *
from mirage.libs.zigbee_utils.pcap import *
from mirage.libs.zigbee_utils.scapy_xbee_layers import *
from mirage.libs import wirel... |
4829923 | from PyQt5.QtCore import QObject, pyqtSlot
class SignalHandler(QObject):
@pyqtSlot(int, int)
def sum(self, arg1, arg2):
print("Adding two numbers")
@pyqtSlot(str)
def info(self, arg1):
print("STR " + arg1) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.