id
stringlengths
3
8
content
stringlengths
100
981k
3378199
import torch from torch.nn import functional as F from torch.nn import Linear, Parameter, Conv1d class AttentionBase(torch.nn.Module): """Abstract attention class. Arguments: representation_dim -- size of the hidden representation query_dim -- size of the attention query input (probably d...
3378213
from sklearn.neighbors import KNeighborsClassifier from sklearn.ensemble import RandomForestClassifier from sklearn import preprocessing import sqlite3 as sql import numpy import sys import argparse import time parser = argparse.ArgumentParser(description="Classify input reads") parser.add_argument("taxonomer_input",...
3378249
for i in xrange(0,10): print '??'+str(i)+'>>'+str(i)+'??' for i in xrange(0,9): print str(i) + '??<>' + str(i+1) print '9??>>?0\n9?>>?0' for i in xrange(0,9): print str(i)+'?<>'+str(i+1) print '?<>1' for i in xrange(1,10): print str(i) + '>>' + str(i) + '??'
3378261
import pytest import torch import torch.nn as nn import pyro.distributions as dist from pyro.nn import PyroModule, PyroSample from pyro.nn.module import to_pyro_module_ import tyxe def as_pyro_module(module): to_pyro_module_(module, recurse=True) for m in module.modules(): for n, p in list(m.named...
3378264
import sys import signal import os import json from datetime import datetime import numpy as np import torch from six.moves import shlex_quote from mpi4py import MPI from logging import CRITICAL from config import argparser from config.motion_planner import add_arguments as mp_add_arguments from rl.trainer import Tra...
3378314
import logging from socket import gethostbyaddr, gethostbyname from django.conf import settings from django.core.cache import cache from django.shortcuts import redirect from ratelimit.utils import is_ratelimited from biostar.utils import helpers from . import util, auth logger = logging.getLogger("engine") def limi...
3378323
from rastervision.core.data.label_source import (LabelSourceConfig, ObjectDetectionLabelSource) from rastervision.core.data.vector_source import VectorSourceConfig from rastervision.pipeline.config import register_config @register_config('object_detection_label_source'...
3378357
import collections EPSILON = '<empty>' END_OF_INPUT = '<$>' class Production(object): """Represents a grammar production rule.""" def __init__(self, rule, func): items = rule.split(':', 1) self.lhs = items[0].strip() self.rhs = items[1].strip().split() or [EPSILON] self.func ...
3378361
reader = open('test01.csv', 'r') for line in reader: fields = line.split(',') print(fields) reader.close()
3378364
import inspect import logging import sys from typing import Callable, Optional, Type, TypeVar LOG = logging.getLogger("AutoClick") EMPTY = inspect.Signature.empty EMPTY_OR_NONE = {EMPTY, None} GLOBAL_CONFIG = {} T = TypeVar("T") def set_global(name: str, value: T) -> Optional[T]: """ Configure global AutoCl...
3378365
from model.segmentation import Segmentation from model.swin_transformer import build_model import torch import torch.nn as nn import transformers import torch.nn.functional as F from torch import Tensor from utils.util import load_pretrained_swin class LVAT(nn.Module): def __init__(self,config,logger): sup...
3378458
from ..factory import Type class jsonValueObject(Type): members = None # type: "vector<jsonObjectMember>"
3378474
import binascii import io from attr import dataclass from lark.lark import Lark from lark.visitors import Discard, Transformer def unhex(hexdump: str) -> bytes: """Unparses hexdump back to binary representation. In addition to basic parsing the following extra features are supported: * line comments st...
3378509
from flask import redirect from app.main import main @main.route('/.well-known/security.txt', methods=['GET']) @main.route('/security.txt', methods=['GET']) def security_policy(): # See GDS Way security policy which this implements # https://gds-way.cloudapps.digital/standards/vulnerability-disclosure.html#v...
3378525
from setuptools import setup, find_packages import os readme_file = os.path.join(os.path.dirname(os.path.abspath(__file__)), "README.md") with open(readme_file, "r") as f: readme = f.read() ISRELEASED = True MAJOR = 1 MINOR = 0 MICRO = 1 VERSION = f"{MAJOR}.{MINOR}.{MICRO}" setup_dir = os.path.abspath(os.path.d...
3378571
from typing import Dict, Optional, Tuple, Union import numpy as np from autotabular.pipeline.base import DATASET_PROPERTIES_TYPE, PIPELINE_DATA_DTYPE from autotabular.pipeline.components.base import AutotabularPreprocessingAlgorithm from autotabular.pipeline.constants import DENSE, INPUT, SPARSE, UNSIGNED_DATA from Co...
3378591
import unittest import json from unittest.mock import patch from collections import namedtuple from elasticsearch import helpers, Elasticsearch, TransportError from flask import current_app as app import numpy as np import redis from app.main import db from app.test.base import BaseTestCase from app.test.test_shared_m...
3378621
import json import requests from docopt import docopt def upload_softwares(file_json, url="http://127.0.0.1:3001/api/software", ): with open(file_json) as json_data: softwares = json.load(json_data) print(str(len(softwares)) + " softwares read from "+file_json ) tot_upload = 0 for...
3378637
from __future__ import absolute_import from __future__ import division from __future__ import print_function import os from bert import modeling import collections import tensorflow as tf flags = tf.flags FLAGS = flags.FLAGS ## Required parameters flags.DEFINE_string( "bert_config_file", None, "The config j...
3378732
import os import glob import xml.etree.ElementTree as ET import numpy import soundfile def main(): for f in glob.glob("*/**/*.xps"): t = ET.parse(f) r = t.getroot() d = recurse_tree(r) if not d: continue dirname = os.path.dirname(f) irname = d["IRFileNam...
3378735
import numpy as np import scipy.linalg as scla from ...utils import splogdet from pysal.spreg.utils import spdot def logp_rho_prec(state, val): """ This computes the logp of the spatial parameter using the precision, rather than the covariance. This results in fewer matrix operations in the case of a SE formul...
3378745
import certvalidator import pytest from kopf._kits.webhooks import WebhookServer def test_missing_oscrypto(no_oscrypto): with pytest.raises(ImportError) as err: WebhookServer.build_certificate(['...']) assert "pip install certbuilder" in str(err.value) def test_missing_certbuilder(no_certbuilder): ...
3378776
from .precheck_argus import * # noqa from .make_gzip_file import * # noqa from .tagutils import * # noqa
3378780
import json import type_checker class DTODescriptor: __slots__ = "_immutable", "_type", "_field", "_validator", "_dto_class_name", "_coerce" def __init__(self, dto_class_name: str, field: str, type_: type, immutable: bool = True, validator: callable = None, coerce: callable = None): ...
3378801
import numpy as np import chainer import os import glob from chainer import cuda, optimizers, serializers, Variable import cv2 from .datasets_base import datasets_base class mnist_train(datasets_base): def __init__(self, path=None, img_size=64): self.train, _ = chainer.datasets.get_mnist(withlabel=False, ...
3378866
from setuptools import setup, find_packages setup( name='oregami', version='1.0.0', packages=find_packages(), url='https://github.com/shemesh999/oregami', license='MIT', author='<NAME>', description='IDA plugins and scripts for analyzing register usage frame', install_requires=[ ...
3378885
import torch import torchvision import numpy as np import time def get_batch(bs=1): loader = torch.utils.data.DataLoader( torchvision.datasets.MNIST('./../data/MNIST/', train=False, download=True, transform=torchvision.transforms.ToTensor()), batch_size=bs, shuffle=Tru...
3378886
import unittest from katas.kyu_7.filter_unused_digits import unused_digits class UnusedDigitsTestCase(unittest.TestCase): def test_equals(self): self.assertEqual(unused_digits(12, 34, 56, 78), '09') def test_equals_2(self): self.assertEqual(unused_digits(2015, 8, 26), '3479') def test_e...
3378909
import tensorflow as tf import numpy as np import time def relu(inputs): return tf.nn.relu(inputs) class model(): def conv2d(self, inputs, name, out_channels, act=relu, ksize=3): with tf.variable_scope(name): in_channels = inputs.get_shape()[-1] filter = tf.get_variable('weig...
3378913
import unittest import numpy as np import tensorflow as tf from nose.tools import assert_true from sklearn.metrics import roc_curve, auc import deepchem as dc from deepchem.data import NumpyDataset from deepchem.data.datasets import Databag from deepchem.models.tensorgraph.layers import Dense, SoftMaxCrossEntropy, Re...
3378914
class NodeNotes(object): """ The class adds the support to the notes dynamic attribute. """ def __init__(self): pass def getNotes(self): pass def setNotes(self, string): pass __dict__ = None __weakref__ = None _...
3378921
from boa3.builtin.type import UInt160 class Policy: @classmethod def get_fee_per_byte(cls) -> int: """ Gets the network fee per transaction byte. :return: the network fee per transaction byte :rtype: int """ pass @classmethod def get_exec_fee_factor(cl...
3378931
import re def migrate(resource): return isced_to_object(resource) def isced_to_object(resource): for property in resource.keys(): if property in ["audience", "about"]: print "Migrating " + property + " for " + resource["@id"] objects = [] for string in resource[pro...
3378945
from __future__ import print_function import numpy as np import time import data_util weight_names = ["w_in", "b_in", "w_out", "b_out", "rnn/multi_rnn_cell/cell_0/basic_lstm_cell/weights", "rnn/multi_rnn_cell/cell_0/basic_lstm_cell/biases", "rnn/multi_rnn_cell/cell_1/bas...
3378967
from os import walk, path, unlink import pickle import datetime from drkns.context.get_unit_step_path import persistence_directory, extension from drkns.stepexecutionstatus.StepExecutionStatus import StepExecutionStatus def clean_persistence_files(): if not path.exists(persistence_directory): return ...
3378970
from django.conf.urls import include, url from . import views urlpatterns = [ url(r'^accounts/ClientLogin$', views.login, name='login'), url(r'^reader/api/0/', include('feedhq.reader.api_urls')), url(r'^reader/atom/(?P<content_id>.+)?$', views.stream_contents, {'output': 'atom'}, name='atom_conte...
3379016
import dicom from numpy import * import SimpleITK as sitk import os def read_ct_scan(path, verbose=False): # type: (object) -> object # Read the slices from the dicom file slices = [] if os.path.isfile(path): try: return sitk.ReadImage(path) except: if verbose: ...
3379037
import numpy as np from pyecsca.sca import Trace, match_pattern, match_part, pad from .utils import Plottable class MatchingTests(Plottable): def test_simple_match(self): pattern = Trace( np.array([1, 15, 12, -10, 0, 13, 17, -1, 0], dtype=np.dtype("i1")), None ) base = Trace( ...
3379110
import pathlib import shutil import pytest import uqbar.io @pytest.fixture def rm_dirs(app): for path in [pathlib.Path(app.doctreedir), pathlib.Path(app.outdir) / "_images"]: if path.exists(): shutil.rmtree(path) yield @pytest.mark.sphinx("html", testroot="book") def test_sphinx_book_ht...
3379112
import os import itertools import subprocess import argparse def parse_args(): parser = argparse.ArgumentParser() parser.add_argument('--act_class', type=str) parser.add_argument('--num_threads', type=int) return parser.parse_args() timeout = 60 * 60 * 24 * 3 args = parse_args() num_thread = args.nu...
3379142
import os import rospy import math import sys from glob import glob from sensor_msgs.msg import PointCloud2, PointField import std_msgs.msg import sensor_msgs.point_cloud2 as pcl2 import numpy as np import pickle from pathlib import Path import pykitti import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import ...
3379149
from setuptools import setup from setuptools import find_packages setup(name='estim2b', version='0.2', description='Unofficial Python API for E-stim 2B', author='<NAME>', author_email='<EMAIL>', url='https://github.com/fredhatt/estim2b', license='MIT', install_requires=['nump...
3379157
import torch import torch.nn as nn import torch.nn.functional as F from .basics import SpectralConv3d class FNN3d(nn.Module): def __init__(self, modes1, modes2, modes3, width=16, fc_dim=128, layers=None, in_dim=4, out_dim=1): ''' Args: modes1: list of int, first dimension maximal mode...
3379163
from test_junkie.decorators import Suite, test from tests.junkie_suites.TestListener import TestListener @Suite(listener=TestListener) class ErrorSuite3: @test(parameters={1, 2}) def test_1(self, parameter): pass
3379168
from mlapp.main import MLApp from mlapp.config import settings import pandas as pd if __name__ == "__main__": config = { 'handler_name': 'handler', 'files': [{ 'table_name': 'table', 'file_name': 'file_name.csv' }] } mlapp = MLApp({'env_file_path': 'path/to/...
3379172
import copy import sys import tornado.httputil from asgiref.sync import sync_to_async from furl import furl from onelogin.saml2.errors import OneLogin_Saml2_Error from onelogin.saml2.idp_metadata_parser import OneLogin_Saml2_IdPMetadataParser from consoleme.config import config from consoleme.config.config import dic...
3379197
import sys from functools import wraps from strange_case.registry import Registry def provides(conf): def decorator(function): @wraps(function) def wrapper(source_file, config): if conf not in config: return function(source_file, config) return config ...
3379210
from math import pow while True: h0, num_workers = list(map(int, input().split())) if h0 == num_workers == 0: break if h0 == num_workers: v1, v2 = 0, h0 else: N = -1 for k in range(1, 32): n = pow(num_workers, 1/k) N = int(n) if N**k == num_workers: if (N+1)*...
3379243
import os import threading import time import yarntf def cluster_spec_test(): """Assumes ClusterSpecGeneratorServer is running""" threads = [] os.environ['TENSORBOARD'] = 'true' for i in range(0, 3): os.environ['TB_DIR'] = 'tensorboard_' + str(i) thread = threading.Thread(target=yarntf.createCluster...
3379273
import pytest import pygamma_agreement as pa from pyannote.core import Segment def test_errors_continuum(): continuum = pa.Continuum() with pytest.raises(ValueError): cat_dissim = pa.LevenshteinCategoricalDissimilarity(continuum.categories) cat_dissim = pa.AbsoluteCategoricalDissimilarity() ...
3379332
from __future__ import (absolute_import, division, print_function, unicode_literals) from .scale import scale from copy import deepcopy import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap, rgb2hex, ColorConverter def colors_at_breaks(cmap, breaks=[0, 0.25, 0.5...
3379347
import numpy as np, tensorflow as tf, aolib.util as ut, aolib.img as ig, os import tensorflow.contrib.slim as slim import tensorflow.contrib.slim.nets as nets import vgg, h5py import sklearn.metrics pj = ut.pjoin class Params(ut.Struct): def __init__(self, **kwargs): self.__dict__.update(kwargs) @property ...
3379351
import random import mimetypes import urllib.request import json def uploadFile(url, path, post_field): boundary = '-----------------' + str(random.randint(1, 1000000000000000000)) parts = [] parts.append('--' + boundary) parts.append('Content-Disposition: form-data; name="{}"; filename="file.jpg"'.for...
3379420
import unittest import logging import numpy as np import pandas as pd import diffxpy.api as de class _TestSingleFullRank(unittest.TestCase): def _test_single_full_rank(self): """ Test if de.wald() generates a uniform p-value distribution if it is given data simulated based on the null mo...
3379421
import pytest import torch from espnet2.enh.loss.criterions.tf_domain import FrequencyDomainL1 from espnet2.enh.loss.wrappers.fixed_order import FixedOrderSolver @pytest.mark.parametrize("num_spk", [1, 2, 3]) def test_PITSolver_forward(num_spk): batch = 2 inf = [torch.rand(batch, 10, 100) for spk in range(n...
3379433
import sys CAFFE_ROOT = '../../../caffe/' sys.path.insert(0, CAFFE_ROOT + 'python') import caffe caffe.set_mode_gpu() NUM_DATA = {} NUM_DATA['TRAIN'] = 10000 NUM_DATA['VAL'] = 1000 NUM_DATA['TEST'] = 1000 RAND_SEED = {} RAND_SEED['TRAIN'] = 19654 RAND_SEED['VAL'] = 2353 RAND_SEED['TEST'] = 51235
3379463
from garnett.fields import TranslatedField def patch_compare(): from reversion_compare.compare import CompareObjects as COBase class CompareObjects(COBase): def __init__(self, field, field_name, obj, version1, version2, is_reversed): if isinstance(field, TranslatedField): ...
3379503
import sys import bayesnewton import objax from bayesnewton.cubature import Unscented import numpy as np import matplotlib.pyplot as plt import time from scipy.io import loadmat import pickle print('loading data ...') y = loadmat('speech_female')['y'] fs = 44100 # sampling rate (Hz) scale = 1000 # convert to millise...
3379505
from __future__ import annotations from typing import Callable, Generic, TypeVar T = TypeVar("T") U = TypeVar("U") class DoubleLinkedListNode(Generic[T, U]): """ Double Linked List Node built specifically for LRU Cache >>> DoubleLinkedListNode(1,1) Node: key: 1, val: 1, has next: False, has prev: F...
3379539
import bugsnag from django.shortcuts import render from django.http import HttpResponseRedirect, HttpResponse from django.views import generic from django.utils import timezone from django.urls import reverse from .models import Note class IndexView(generic.ListView): template_name = 'notes/index.html' cont...
3379554
import json import uuid import httpretty import pytest from mock import patch from lecli.log import api ID_WITH_VALID_LENGTH = str(uuid.uuid4()) MOCK_API_URL = 'http://mydummylink.com' LOG_RESPONSE = { "log" : { "id" : "XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX", "name" : "Test Log", "logsets...
3379586
from .chat import Chat from .chats import Chats from .friend import Friend from .group import Group from .groups import Groups from .member import Member from .mp import MP from .user import User
3379598
from tkinter import * from tkinter import messagebox import random import time unsorted_data = data = [] def draw_data(data, colors): """" Function that is used to draw the array of data Inputs: data => array of the data to be drawn colors => array carrying the corresponding color of each value ...
3379600
from lxml import etree from zipfile import ZipFile from string import lstrip from common import wSPar, NSM, NSW, Body, Document, wText, setx import ct _pd = dict() def xdoc(nd): setx(nd, Document, Document) ct.cnl(nd) def xdocument(nd): setx(nd, Body, Body) ct.cnl(nd) def save(name): zf = Z...
3379634
import csv import config import os as os # Read the metadata of LibriSpeech dataset # Put them in a dictionnary with the following structure # { # [speaker_key:{'sex':M/F, 'chapters':[(int), ...]}, ..., speaker_key:{..},] # } def read_metadata(subset_name=config.data_subset): metadata = {} path_speake...
3379679
from markupsafe import Markup import heroicons def heroicon_outline(name: str, *, size: int = 24, **kwargs: object) -> str: return _render_icon("outline", name, size, **kwargs) def heroicon_solid(name: str, *, size: int = 20, **kwargs: object) -> str: return _render_icon("solid", name, size, **kwargs) de...
3379730
from mojo.roboFont import CurrentFont from glyphConstructionController import GlyphBuilderController GlyphBuilderController(CurrentFont())
3379773
from __future__ import division, print_function import fileinput import re import itertools from collections import defaultdict pattern = re.compile("(\w+) can fly (\d+) km\/s for (\d+) seconds, but then must rest for (\d+) seconds.") runners = defaultdict(lambda: 0) runnerData = {} runnerPoints = defaultdict(lambda:...
3379774
import time import plot_confusion_matrix START_TIME = None STOPPED = False def start_measurement(): global START_TIME START_TIME = time.time() def stop_measurement(): global STOPPED, START_TIME if not STOPPED: elapsed_seconds = time.time() - START_TIME m, s = divmod(elapsed_seconds,...
3379795
import os import torch from collections import OrderedDict from PIL import Image import numpy as np from matplotlib import pyplot as plt import sys from torch.nn.functional import upsample this_dir = os.path.dirname(__file__) sys.path.insert(0, 'dextr') import networks.deeplab_resnet as resnet from dataloaders import h...
3379815
import torch import torch.nn as nn import torch.nn.functional as F from torch.autograd import Variable ''' This is the models of TSception and its variant To use the models, please manage the data into the dimension of(mini-batch, 1, EEG-channels,data point) before feed the data into forward() For more d...
3379872
from .fc import FC as FullyConnectedClassifier from .rnn import RNNClassifier from .bert_hf import BERT __all__ = ["FullyConnectedClassifier", "RNNClassifier", "BERT"]
3379905
from setuptools import setup exec (open('dash_resumable_upload/version.py').read()) setup( name='dash_resumable_upload', version=__version__, author='marrenr', packages=['dash_resumable_upload'], include_package_data=True, license='MIT', description='Dash Resumable Upload component for lar...
3379964
import os import shutil from nose.tools import assert_raises from paradrop.lib.utils import pdos, pdosq from paradrop.base import nexus, settings class TestingNexus(nexus.NexusBase): pass def setup(): settings.loadSettings(mode="unittest") def teardown(): pdos.remove(settings.CONFIG_HOME_DIR) #####...
3379990
import sys, time import time from collections import namedtuple import mxnet as mx import numpy as np def evaluate_model(cnn_model, batch_size, max_grad_norm, learning_rate, epoch, x_train, y_train, x_dev, y_dev): ''' Train the cnn_model using back pro...
3380002
import time import inspect from functools import update_wrapper from fixate.core.common import mode_builder, unit_scale from fixate.core.exceptions import ParameterError, InstrumentError from fixate.drivers.funcgen.helper import FuncGen MODES = { ":SINusoid": { " [{frequency}]": {",[{amplitude}]": {",[{off...
3380015
import torch.nn as nn import torch.nn.functional as F class TransformMatrix(nn.Module): def __init__(self, input_dim, output_dim): super(TransformMatrix, self).__init__() self.fc = nn.Linear(in_features=input_dim, out_features=output_dim, bias=False) # self.fc.apply(init_weights) def ...
3380063
import os import sys sys.path.insert(1, os.path.dirname(os.path.realpath(__file__)) + '/../') from common import utils import models from common.log import log, LogLevel from common.state import State from common import cuda from common import paths import common.torch import common.numpy from training import train_cla...
3380094
import requests from urllib.parse import urlparse class CFProxy: TOKEN_HEADER = 'Px-Token' TOKEN_VALUE = '<PASSWORD>' HOST_HEADER = 'Px-Host' IP_HEADER = 'Px-IP' def __init__(self, proxy_host, ua, fake_ip, proxy=None): self.session = requests.Session() self.session.proxies.update(...
3380126
import asyncio import json import logging import os import re import shutil import string from collections import Counter from dataclasses import dataclass, asdict, field from random import random from typing import List, Optional, Dict, Generator import aiofiles import github import time import github_util git_hub ...
3380136
import json as jsonlib from html import unescape from django import template from django.template import engines, TemplateSyntaxError from django.template.base import NodeList, token_kwargs from django.template.defaulttags import IfNode from django.template.loader import get_template from django.template.loader_tags i...
3380142
from __future__ import print_function from django.core.management.base import BaseCommand from django.utils.translation import ugettext_lazy from odk_logger.models import XForm class Command(BaseCommand): help = ugettext_lazy('Repair submission counts for all users') def handle(self, *args, **kwargs): ...
3380164
from datetime import datetime from recurrence import Recurrence, Rule import recurrence RULE = Rule( recurrence.DAILY ) PATTERN = Recurrence( rrules=[RULE] ) def test_between_without_dtend_and_dtstart(): occurrences = [ instance for instance in PATTERN.between( datetime(2014...
3380186
INSTALL_WINDOWS_AGENT = """ # download the cloud endure agent Invoke-WebRequest -Uri https://console.cloudendure.com/installer_win.exe -OutFile C:\installer_win.exe # install the agent, and configure it using your account's agent installation token. C:\installer_win.exe -t "{{ agent_installation_token }}" --no-prompt ...
3380271
data_dir_test = data_dir+'test/' N_test = len(os.listdir(data_dir_test+"/test")) test_datagen = kpi.ImageDataGenerator(rescale=1. / 255) test_generator = test_datagen.flow_from_directory( data_dir_test, #data_dir_sub+"/train/", target_size=(img_height, img_width), batch_size=batch_size, class_mode...
3380275
from core.agent.reinforce import REINFORCE from .utils import check_interact, check_save_load, check_sync_in_out def test_discrete_reinforce(MockEnv): state_size, action_size, action_type = 2, 3, "discrete" episode_len = 10 env = MockEnv(state_size, action_size, action_type, episode_len) hidden_size ...
3380304
import re PRIVILEGED_STATEMENT_RULES = { "\*:\*": "Full AWS Account Admin", "^[A-Za-z0-9]+:\*$": "Full {service} Admin" } FIND_SERVICE_REGEX = "^([A-Za-z0-9]+)(?=:)" RESOURCE_ARN_WITH_SERVICE_REGEX = "^arn:aws(-cn|):{service}:.+" class PoliciesPermissionsParser(object): def __init__(self, policies): ...
3380339
from kivy.properties import BooleanProperty from kivy.properties import ( NumericProperty, ) from kivymd.color_definitions import colors from kivymd.uix.behaviors.toggle_behavior import MDToggleButton from kivymd.uix.button import MDFloatingActionButton, \ MDRoundFlatIconButton, \ MDRectangleFlatButton fro...
3380362
import torch import numpy as np import itertools """ Qnt: Quantization Methods. this collection of methods, compute the quantization tables for RGB, and LAB color space. These methods are organized in a way that each bin is recognized by its central value. ES: RGB 0-255 2 levels of quantization for each channel ...
3380394
from taskutils import task import logging import math def TaskTest1(): def Go(): @task def Length(inp): logging.info("Post, Length: %s" % len(inp)) for exponent in range(3): length = int(math.pow(10, exponent + 5)) logging.info("Pre, Length: ...
3380411
def readposint(): while True: try: a = int(input("Please enter a positive integer: ")) if a <= 0: print("Non-positive integers are not allowed") else: break except ValueError as e: print(e) print("The positive integer ...
3380436
import unittest import functools import numpy as np import pandas as pd import scipy.signal from spatial_lda import featurization def make_grid_df(neighborhood_data, make_all_cells_anchors=False): n, m, k = neighborhood_data.shape xs, ys = np.meshgrid(range(n), range(n)) xs = xs.flatten() ys = ys.fla...
3380449
from core.advbase import * class Veronica(Adv): comment = "last destruction teambuff not considered" def prerun(self): if not self.nihilism: SingleActionBuff("last_destruction", 0.1, 1, "s").on() variants = {None: Veronica}
3380523
import os import shutil import pytest import unittest if os.name == "posix": TMPDIR = "/tmp/" else: TMPDIR = "%TMP%" if not os.environ.get("TRAVIS") == "true": from pyveg.src.download_modules import VegetationDownloader, WeatherDownloader @unittest.skipIf(os.environ.get("TRAVIS") == "true", "Skipping t...
3380545
from __future__ import annotations from dataclasses import InitVar, dataclass import re from typing import Callable, ClassVar, Dict, List, Optional, Union import ibis from ibis.expr.types import AnyColumn, AnyScalar, TableExpr, ValueExpr from lark import Tree from pandas import Series from sql_to_ibis.sql.column_uti...
3380556
from dataclasses import dataclass from .base import BasePosition from .types import Literal @dataclass class Namespace(BasePosition): type: Literal["namespace"] = "namespace"
3380565
import re from typing import cast def replace_colons(text: str, strip: bool = False) -> str: """Parses a string with colon encoded emoji and renders found emoji. Unknown emoji are left as is unless `strip` is set to `True` :param text: String of text to parse and replace :param strip: Whether to stri...
3380577
import torch import torch.nn as nn class MLP(torch.nn.Module): def __init__(self, out_features, in_features, hidden_layer_size, output_nonlinearity): super().__init__() self.fc1 = nn.Linear(in_features=in_features, out_features=hidden_layer_size) self.fc2 = nn.Linear(in_features=hidden_lay...
3380580
import unittest import mock from pyhive.presto import Cursor, Connection from pyhive.exc import DatabaseError from luigi.contrib.presto import PrestoTask, PrestoClient, PrestoTarget class WithPrestoClientTest(unittest.TestCase): def test_creates_client_with_expected_params(self): # arrange class...
3380617
workclass_map = {"Not in universe": "None", "Private": "Private", "Self-employed-not incorporated": "Self-emp-not-inc", "Local government": "Local-gov", "State government": "State-gov", "Self-employed-incorporated": "Self-emp-inc", ...