id
stringlengths
3
8
content
stringlengths
100
981k
132827
import torch import torch.nn as nn from ltprg.model.seq import sort_seq_tensors, unsort_seq_tensors, SequenceModel from torch.autograd import Variable class ObservationModel(nn.Module): def __init__(self): super(ObservationModel, self).__init__() def forward(self, observation): """...
132902
import numpy as np import pandas as pd from sklearn.decomposition import PCA from numpy.linalg import norm import matplotlib.pyplot as plt from sklearn import preprocessing import seaborn as sns; sns.set_theme() seed = 0 np.random.seed(seed) """We test without normalization""" def normalize(data, shift = 'z-score'):...
132904
from meta_policy_search.utils import logger import numpy as np import tensorflow as tf from collections import OrderedDict from meta_policy_search.optimizers.base import Optimizer class FiniteDifferenceHvp(Optimizer): def __init__(self, base_eps=1e-5, symmetric=True, grad_clip=None): self.base_eps = np.ca...
132905
t = int(input()) ans = [] for testcase in range(t): n, m = [int(i) for i in input().split()] if (n == 2) and (m == 2): folds = [] for i in range(n): folds += [int(i) for i in input().split()] for i in range(n - 1): folds += [int(i) for i in input().split()] ...
132937
import argparse import logging import json import sys sys.path.insert(0, '.') from tools.constants import JSON_FORMAT_KWARGS from tools.utils import get_json_files def reserialize(file_): """Reformat json file""" with open(file_) as fp: try: data = json.load(fp) except ValueError...
132939
from bot.bot import Friendo from discord import errors from discord.ext.commands import Cog, Context, group from bot.settings import AOC_JOIN_CODE, AOC_LEADERBOARD_LINK, AOC_SESSION_COOKIE class AdventOfCode(Cog): """Cog for AOC 2021 for small features.""" def __init__(self, bot: Friendo): self.bot =...
132951
import os import sys import random import itertools import colorsys import numpy as np from skimage.measure import find_contours import matplotlib.pyplot as plt from matplotlib import patches, lines from matplotlib.patches import Polygon # import IPython.display def random_colors(N, bright=True): ''' Generat...
133021
import argparse import numpy as np from tqdm import tqdm from os.path import join, isfile from data import Labels from joblib import Parallel, delayed labels = Labels() def job(text_path, numpy_path): with open(text_path, 'r', encoding='utf8') as file: text = file.read() if not labels.is_accepted(t...
133043
import requests import urllib3 from datetime import datetime, timedelta from requests.auth import HTTPDigestAuth import voluptuous as vol from homeassistant.components.sensor import PLATFORM_SCHEMA, ENTITY_ID_FORMAT from homeassistant.const import CONF_ID, CONF_NAME import homeassistant.helpers.config_validation as c...
133105
import torch from vedacore.misc import registry from vedadet.bridge import build_converter, build_meshgrid from vedadet.misc.bbox import bbox2result, multiclass_nms from .base_engine import BaseEngine @registry.register_module('engine') class InferEngine(BaseEngine): def __init__(self, model, meshgrid, converte...
133107
from datetime import datetime import unittest from pypushwoosh import constants from pypushwoosh.exceptions import PushwooshFilterInvalidOperatorException, PushwooshFilterInvalidOperandException from pypushwoosh.filter import ApplicationFilter, ApplicationGroupFilter, IntegerTagFilter, StringTagFilter, \ ListTagFil...
133145
import numpy from .eval_splines import eval_cubic ## the functions in this file provide backward compatibility calls ## ## they can optionnally allocate memory for the result ## they work for any dimension, except the functions which compute the gradient ####################### # Compatibility calls # ##############...
133261
import itertools from runtests.mpi import MPITest import pybnb from .common import mpi_available def left_child(i): return 2 * i + 1 def right_child(i): return 2 * i + 2 def log2floor(n): assert n > 0 return n.bit_length() - 1 def height(size): return log2floor(size) def set_none(heap, ...
133310
import FWCore.ParameterSet.Config as cms tccFlatToDigi = cms.EDProducer("EcalFEtoDigi", FileEventOffset = cms.untracked.int32(0), UseIdentityLUT = cms.untracked.bool(False), SuperModuleId = cms.untracked.int32(-1), debugPrintFlag = cms.untracked.bool(False), FlatBaseName = cms.untracked.string('eca...
133366
from django.conf.urls import url from apps.myadmin.views import login, user, team, role, teamUserRelation, userRole, adminUser, businessLine, \ interfaceModule, interfacePermission, moduleManage, source, changeLog, businessLineModule, configService, \ jiraModule, modulePlatform, jiraBusinessLine, jiraBusiness...
133392
import logging import requests import yaml from bot.listeners import TelegramListener, AlertListener from bot.protocol import SendExpedition from ogame.game.const import Ship, CoordsType, Resource from ogame.game.model import Coordinates from ogame.util import find_unique def parse_bot_config(config): """ @retu...
133397
from pandas_datareader import data start_date = '2014-01-01' end_date = '2018-01-01' goog_data = data.DataReader('GOOG', 'yahoo', start_date, end_date) import numpy as np import pandas as pd goog_data_signal = pd.DataFrame(index=goog_data.index) goog_data_signal['price'] = goog_data['Adj Close'] goog_data_signal['da...
133401
import sys import numpy as np from starfish import ImageStack from starfish.spots import FindSpots from starfish.types import Axes def test_lmpf_uniform_peak(): data_array = np.zeros(shape=(1, 1, 1, 100, 100), dtype=np.float32) data_array[0, 0, 0, 45:55, 45:55] = 1 imagestack = ImageStack.from_numpy(dat...
133437
import pytest # Code that uses this is commented-out below. # from ..types import TrackingItem pytestmark = [pytest.mark.setone, pytest.mark.working, pytest.mark.schema] @pytest.fixture def tracking_item(): return {"tracking_type": "other", "other_tracking": {"extra_field": "extra_value"}} def test_insert_an...
133454
import numpy as np import pandas as pd import statsmodels.api as sm from statsmodels.imputation.bayes_mi import BayesGaussMI, MI from numpy.testing import assert_allclose def test_pat(): x = np.asarray([[1, np.nan, 3], [np.nan, 2, np.nan], [3, np.nan, 0], [np.nan, 1, np.nan], [3, 2, 1]]) ...
133498
import transformers as trans import torch import pytorch_lightning as pl from torch.nn import CrossEntropyLoss, MSELoss from transformers.models.auto.configuration_auto import AutoConfig from transformers import AutoTokenizer from openue.data.utils import get_labels_ner, get_labels_seq, OutputExample from typing import...
133507
from pathlib import Path from setuptools import setup VERSION = "0.1.6" def get_long_description(): readme_path = Path(__file__).parent / "README.md" with open(readme_path.absolute(), mode="r", encoding="utf8") as fp: return fp.read() setup( name="datasette-dashboards", description="Datase...
133512
import datetime import io import lzma import pickle from mongoengine import signals def now(): return datetime.datetime.now() def to_pickle(obj): buff = pickle.dumps(obj, protocol=pickle.HIGHEST_PROTOCOL) cbuff = lzma.compress(buff, format=lzma.FORMAT_XZ) return io.BytesIO(cbuff) def from_pickle(...
133565
import torch.nn as nn class MaskL1Loss(nn.Module): """ Loss from paper <Pose Guided Person Image Generation> Sec3.1 pose mask loss """ def __init__(self, ratio=1): super(MaskL1Loss, self).__init__() self.criterion = nn.L1Loss() self.ratio = ratio def forward(self, generat...
133576
import re from ..exceptions import RouteConfigurationError class PatternParser: PARAM_REGEX = re.compile(b'<.*?>') DYNAMIC_CHARS = bytearray(b'*?.[]()') CAST = { str: lambda x: x.decode('utf-8'), int: lambda x: int(x), float: lambda x: float(x) } @classmethod def val...
133595
import math import torch from torch import nn from torch.nn import Parameter import torch.nn.functional as F from .encdec_attention_func import encdec_attn_func import onmt class EncdecMultiheadAttn(nn.Module): """Multi-headed encoder-decoder attention. See "Attention Is All You Need" for more details. ""...
133603
from .nlp.JsonFromFiles import JsonFromFilesDataset dataset_list = { "JsonFromFiles": JsonFromFilesDataset }
133607
import logging from django.conf import settings from django.contrib import auth from django.core.exceptions import PermissionDenied from django.http import HttpResponse, HttpResponseRedirect, HttpResponseServerError from django.views.decorators.cache import never_cache from django.views.decorators.csrf import csrf_exe...
133617
import torchvision from torchvision import models import torch class DeepLabV3Wrapper(torch.nn.Module): def __init__(self, model): super(DeepLabV3Wrapper, self).__init__() self.model = model def forward(self, input): output = self.model(input)['out'] return output def initiali...
133638
import pytest from .utils import template_test, resolve_param_values_and_ids def pytest_generate_tests(metafunc): param_values, param_ids = resolve_param_values_and_ids( schema_version='http://json-schema.org/draft-07/schema', suite_dir='JSON-Schema-Test-Suite/tests/draft7', ignored_suite...
133721
import pytest from reactivated import forms from sample.server.apps.samples import models @pytest.mark.django_db @pytest.mark.urls("tests.urls") def test_autocomplete(client): composer = models.Composer.objects.create(name="<NAME>") models.Composer.objects.create(name="<NAME>") assert client.get("/autoc...
133783
from ..meshio import form_mesh import numpy as np import logging def merge_meshes(input_meshes): """ Merge multiple meshes into a single mesh. Args: input_meshes (``list``): a list of input :class:`Mesh` objects. Returns: A :py:class:`Mesh` consists of all vertices, faces and...
133803
from collections.abc import MutableMapping import numpy as np _HIDDEN_ATTRS = frozenset( [ "REFERENCE_LIST", "CLASS", "DIMENSION_LIST", "NAME", "_Netcdf4Dimid", "_Netcdf4Coordinates", "_nc3_strict", "_NCProperties", ] ) class Attributes(Mutable...
133834
from manimlib.constants import * from manimlib.mobject.svg.tex_mobject import SingleStringTexMobject from manimlib.mobject.types.vectorized_mobject import VMobject class DecimalNumber(VMobject): CONFIG = { "num_decimal_places": 2, "include_sign": False, "group_with_commas": True, "...
133845
import FWCore.ParameterSet.Config as cms def customise(process): # add ECAL and HCAL specific Geant4 hits objects process.g4SimHits.Watchers = cms.VPSet(cms.PSet( instanceLabel = cms.untracked.string('EcalValidInfo'), type = cms.string('EcalSimHitsValidProducer'), verbose = cms.untracked....
133886
import argparse import json import time from pathlib import Path from sklearn import metrics from scipy import interpolate import torch.nn.functional as F from models import * from utils.utils import * from torchvision.transforms import transforms as T from utils.datasets import LoadImages, JointDataset, co...
133930
from functools import wraps from typing import Callable, List, Optional, Tuple from sanic.request import Request from sanic_jwt_extended.exceptions import ( AccessDeniedError, ConfigurationConflictError, CSRFError, FreshTokenRequiredError, InvalidHeaderError, NoAuthorizationError, RevokedT...
133966
import string import random def uuid(length=8, lower=True): """sebbe-approved UUID""" # risk of collision # mixed case: 8 characters -> 1 in 54 trillion # lower case: 8 characters -> 1 in 208 billion letters = string.ascii_letters if lower: letters = letters.lower() return ''.join...
133968
from functools import reduce from sherlock.codelib.analyzer.factory import ListManagerFactory class Function(object): def __init__(self, name, args_type, return_type, code_generator): self.name = name self.return_type = return_type self.args_type = args_type self.code_generator = c...
133979
import os, pickle, json from collections import deque import numpy as np import tensorflow as tf import torch import torch.nn.functional as F from guacamol.distribution_matching_generator import DistributionMatchingGenerator from rdkit import Chem from torch.utils.data import DataLoader, Dataset from tqdm import tqdm ...
134050
import logging logging.basicConfig(level=logging.DEBUG) from slack_bolt import App, BoltContext from slack_bolt.oauth import OAuthFlow from slack_sdk import WebClient app = App(oauth_flow=OAuthFlow.sqlite3(database="./slackapp.db")) @app.use def dump(context, next, logger): logger.info(context) next() @...
134108
from setuptools import setup, find_packages # read readme with open("README.md", "r") as f: readme = f.read() setup( name="bpreg", version="1.1.0", packages=find_packages(), url="https://github.com/MIC-DKFZ/BodyPartRegression", include_package_data=True, package_data={"bpreg": ["settings/b...
134109
number = int(input()) if any(number % int(i) for i in input().split()): print('not divisible by all') else: print('divisible by all')
134123
try: import unittest from copy import copy from numpy.testing import assert_allclose import numpy as np from spitfire.chemistry.mechanism import ChemicalMechanismSpec from spitfire.chemistry.library import Library, Dimension from spitfire.chemistry.flamelet import FlameletSpec from spi...
134261
import pprint import click import fitz # pip install pymupdf @click.command() @click.argument("filepath", type=click.Path(exists=True)) def entrypoint(filepath): pp = pprint.PrettyPrinter(indent=4) with fitz.open(filepath) as doc: pp.pprint(doc.metadata) print(f"Scanned pages: {get_scanned_p...
134272
from flask import Blueprint, session, redirect, url_for babel_blueprint = Blueprint( 'babel', __name__, url_prefix="/babel" ) @babel_blueprint.route('/<string:locale>') def index(locale): session['locale'] = locale return redirect(url_for('blog.home'))
134337
import pytest from django.db.models import Q from helper import TestMigrations class TestWithShackdataBase(TestMigrations): app = "bookkeeping" migrate_fixtures = ["tests/fixtures/test_shackspace_transactions.json"] migrate_from = "0012_auto_20180617_1926" @pytest.mark.xfail @pytest.mark.django_db class...
134406
from dataclasses import dataclass, field import xleapp.templating as templating from xleapp._authors import __authors__, __contributors__ from ..html import Contributor, HtmlPage, Template @dataclass class Index(HtmlPage): """Main index page for HTML report Attributes: authors (list): list of auth...
134425
import gc from functools import reduce from typing import Callable, Iterable, List, Optional, Tuple, TypeVar import numpy as np import pandas as pd from .graph import AttrMap, Graph from .trace import AddOp, TraceKey from .utils import filter_not_null from .utils.fs import IOAction from .utils.ray import ray_iter __...
134462
import os from mindware.components.feature_engineering.transformations.base_transformer import Transformer from mindware.components.utils.class_loader import find_components, ThirdPartyComponents """ Load the buildin classifiers. """ generator_directory = os.path.split(__file__)[0] _generator = find_components(__packa...
134471
import DOM class UIObject: def getElement(self): return self.element def setElement(self, element): self.element = element def setStyleName(self, style): DOM.setAttribute(self.element, "className", style) class Widget(UIObject): def setParent(self, parent): self.pa...
134486
from printer import Printer, PrinterError from unittest import TestCase class TestPrinter(TestCase): def setUp(self): self.printer = Printer(pages_per_s=2.0, capacity=300) def test_print_within_capacity(self): self.printer.print(25)
134489
from tests import run_main_and_assert FAST_LOCAL_TEST_ARGS = "--exp-name local_test --datasets mnist" \ " --network LeNet --num-tasks 3 --seed 1 --batch-size 32" \ " --nepochs 3" \ " --num-workers 0" \ " --approach mas" def t...
134524
from __future__ import absolute_import import sys import unittest from testutils import ADMIN_CLIENT, suppress_urllib3_warning from testutils import harbor_server from testutils import TEARDOWN import library.repository import library.cnab from library.project import Project from library.user import User from library...
134539
from time import sleep from pycrunch_trace.client.api import trace def alternative_ways_to_trace(): sleep(0.25) print('You can use Trace object to manually start and stop tracing') print(' Or by applying @trace decorator to the method') print(' See examples bellow') def example_without_decorators():...
134624
from __future__ import print_function from datetime import datetime import inspect import os import socket import sys import threading import uuid import gridengine from gridengine import schedulers # ---------------------------------------------------------------------------- # JOB DISPATCHER # ---------------------...
134639
from cryptoxlib.exceptions import CryptoXLibException class BiboxException(CryptoXLibException): pass
134671
import gdown import os from zipfile import ZipFile demos = { "Sawyer_chair_agne_0007_00XX.zip": "1-lVTCH4oPq22cLC4Mmia9AKqzDIIVDO0", 'Sawyer_table_dockstra_0279_00XX': '1QAchFmYpQGqa6zaZ2QeZH5ET-iuyerU0', "Sawyer_bench_bjursta_0210_00XX.zip": "12b8_j1mC8-pgotjARF1aTcqH2T7FNHNF", "Sawyer_table_bjorkudde...
134676
from socket import gethostbyname from random import randint # proxy: https://luminati.io/ def get_luminati_session(username, password): """Returns a new sticky Luminati Proxy Session.""" port = 22225 ip = gethostbyname("zproxy.lum-superproxy.io") session_id = randint(1000, 9999) return ( ...
134689
from typing import Iterable, Any from numpy.random import RandomState def shuffled_cycle(iterable: Iterable[Any], rng: RandomState, nb_loops: int = -1) -> Iterable[Any]: """ Yield each element of `iterable` one by one, then shuffle the elements and start yielding from the start. Stop after `nb_loops` loo...
134692
import file_helper import shutil import os import re import yaml import json # # The `specification` folder in the azure-rest-api-specs repo contains the folder hierarchy for the swagger specs # # specification # |-service1 (e.g. `cdn` or `compute`) # | |-common # | |-quickstart-tem...
134732
import toolz import toolz.curried from toolz.curried import (take, first, second, sorted, merge_with, reduce, merge, operator as cop) from collections import defaultdict from importlib import import_module from operator import add def test_take(): assert list(take(2)([1, 2, 3])) == [1, ...
134796
from cas.common.assets.models import ( Asset, AssetBuildContext, SerialDriver, PrecompileResult, ) from typing import List class CaptionDriver(SerialDriver): """ Driver that handles compiling closed captions """ def _tool_name(self): return "captioncompiler" def precompi...
134827
import inspect import re import sys import unicodedata import yaml # from reversion import revisions as reversion import reversion from django.conf import settings from django.contrib.auth.models import Group from django.db import models from django.db.models import Q from django.db.models.signals import m2m_changed, ...
134830
from typing import List import numpy as np import segmentation_models_pytorch as smp from segmentation_models_pytorch.base.modules import Activation import torch from torch import nn from torch.nn import functional as F from torchvision import datasets from torchvision.transforms import transforms from baal import Ac...
134862
from sacred import Experiment import os.path as osp import os import numpy as np import yaml import cv2 import torch from torch.utils.data import DataLoader from tracktor.config import get_output_dir, get_tb_dir from tracktor.solver import Solver from tracktor.datasets.factory import Datasets from tracktor.resnet imp...
134889
from pathlib import Path from typing import Any, Iterable, List, Tuple, Type from black import FileMode, format_str from click import secho from jinja2 import Environment, PackageLoader from reactant.exceptions import RenderFailed from reactant.main import PeeweeORM from reactant.orm.peewee import PeeweeCombustor, Pe...
134905
from unittest import mock from django.test import TestCase from django.test.utils import override_settings from cid.cursor import CidCursorWrapper class TestCidCursor(TestCase): def setUp(self): self.cursor = mock.Mock() self.cursor.execute = mock.Mock(return_value=None) self.cursor.exe...
134925
import cv2 import numpy as np from cv_viewer.utils import * import pyzed.sl as sl #---------------------------------------------------------------------- # 2D VIEW #---------------------------------------------------------------------- def cvt(pt, scale): ''' Function that scales point coordinates '...
134939
from acceptability.modules import LMGenerator if __name__ == '__main__': trainer = LMGenerator() trainer.load() trainer.generate()
134942
from __future__ import print_function import sys, os sys.path.insert(1, os.path.join("..","..","..")) import h2o from tests import pyunit_utils from h2o.estimators.word2vec import H2OWord2vecEstimator def word2vec_to_frame(): print("Test converting a word2vec model to a Frame") words = h2o.create_frame(rows=...
134969
from django.conf import settings from importlib import import_module from django.utils.module_loading import import_string try: from django.urls import URLPattern as RegexURLPattern from django.urls import URLResolver as RegexURLResolver except: from django.core.urlresolvers import RegexURLResolver, RegexUR...
134988
from django.conf.urls import url from blog.views import IndexView, PostView, CommentView, RepositoryView, RepositoryDetailView, TagListView, \ CategoryListView, AuthorPostListView, CommentDeleteView urlpatterns = [ url(r'^$', IndexView.as_view()), url(r'^post/(?P<pk>[0-9]+)$', PostView.as_view()), url...
134993
from datetime import timedelta # 3rd party imports from django.conf import settings from django.test import TestCase from django.test.utils import override_settings from django.urls import reverse from django.utils.timezone import now from libya_site.tests.factories import DEFAULT_USER_PASSWORD, UserFactory from regi...
134995
import os import sys import numpy as np from joblib import Parallel, delayed import joblib import argparse import importlib from itertools import product import collections from copy import deepcopy from mcpy.utils import filesafe from mcpy import plotting def _get(opts, key, default): return opts[key] if (key in...
135023
from .base import AuthenticationBase class RevokeToken(AuthenticationBase): """Revoke Refresh Token endpoint Args: domain (str): Your auth0 domain (e.g: username.auth0.com) """ def revoke_refresh_token(self, client_id, token, client_secret=None): """Revokes a Refresh Token if it has ...
135046
import random from datetime import datetime random.seed(datetime.now()) class SoS(object): def __init__(self, CSs, environment): self.CSs = CSs self.environment = environment pass def run(self, tick): logs = [] random.shuffle(self.CSs) for CS in self.CSs: ...
135051
import torch import torch.nn as nn import torch.nn.functional as F import pickle import numpy as np class RMTPP(nn.Module): def __init__(self, cfg, args): super(RMTPP, self).__init__() self.cfg = cfg self.args = args if self.cfg.EMB_DIM != 0: self.embedding = nn.Embeddi...
135060
import sys import os from os import path import shutil """ Look at a "rendered" folder, move the rendered to the output path Keep the empty folders in place (don't delete since it might still be rendered right) Also copy the corresponding yaml in there """ input_path = sys.argv[1] output_path = sys.argv[2] yaml_path ...
135154
from sklearn import tree def train(X, y): clf = tree.DecisionTreeClassifier(max_depth=10, random_state=0) clf = clf.fit(X, y) return clf
135202
joystick = runtime.createAndStart("joystick","Joystick") sleep(4) a = 0 rb = 0 def buttonA(): global a a = msg_joystick_button1.data[0] print a check() def buttonRB(): global rb rb = msg_joystick_button6.data[0] print rb check() def check(): if ((a == 1) and (rb == 1)): ...
135215
import os import openai from secrets import API_Token from prompt import en_ru translate_input = input("What to Translate: ") openai.api_key = API_Token response = openai.Completion.create( engine="davinci", prompt=en_ru + translate_input + "\nRussian: ", temperature=0.5, max_tokens=100, top_p=1, frequency_...
135217
import sys import os import errno from fontTools.ttLib import TTFont from os.path import dirname, abspath, join as pjoin PYVER = sys.version_info[0] BASEDIR = abspath(pjoin(dirname(__file__), os.pardir, os.pardir)) _enc_kwargs = {} if PYVER >= 3: _enc_kwargs = {'encoding': 'utf-8'} def readTextFile(filename): w...
135220
import logging import json import os import torch import pickle from cnn import CNN import numpy as np import gzip from io import BytesIO, StringIO OUTPUT_CONTENT_TYPE = 'text/csv' INPUT_CONTENT_TYPE = 'application/x-npy' logger = logging.getLogger(__name__) image_names = [] def model_fn(model_dir): model_i...
135226
from googlemaps.timezone import timezone as _timezone async def timezone(client, location, timestamp=None, language=None): return await _timezone(client, location, timestamp=timestamp, language=language)
135275
import os import pytest from molecule import config from molecule.verifier import ansible @pytest.fixture def _patched_ansible_verify(mocker): m = mocker.patch("molecule.provisioner.ansible.Ansible.verify") m.return_value = "patched-ansible-verify-stdout" return m @pytest.fixture def _verifier_sectio...
135290
import logging import os import posixpath from django.conf import settings from django.utils import timezone from celery import shared_task, current_task from .exporter import get_export_models, get_resource_for_model logger = logging.getLogger(__name__) @shared_task def export(exporter_class, format='xlsx', **kwa...
135300
import tensorflow as tf def attention(inputs): # Trainable parameters hidden_size = inputs.shape[2].value u_omega = tf.get_variable("u_omega", [hidden_size], initializer=tf.keras.initializers.glorot_normal()) with tf.name_scope('v'): v = tf.tanh(inputs) # For each of the timestamps its v...
135327
import unittest class TestMisc(unittest.TestCase): def test_pypi_api(self): from dl_coursera.lib.misc import get_latest_app_version ver = get_latest_app_version() self.assertRegex(ver, r'\d+\.\d+\.\d+')
135339
from __future__ import absolute_import import argparse import collections import gc import json import os from datetime import datetime import numpy as np from catalyst.dl import SupervisedRunner, OptimizerCallback, SchedulerCallback from catalyst.utils import load_checkpoint, unpack_checkpoint from pytorch_toolbelt....
135357
from .. import mq class MQ(mq.MQ): """Redis Message Broker """ def __init__(self, backend, store): super().__init__(backend, store) self._client = store.client() async def get_message(self, *queues): '''Asynchronously retrieve a :class:`Task` from queues :return: a :c...
135376
import logging import os from logging.handlers import RotatingFileHandler LOGGER_NAME = "connexion_example" def create_log(): if not os.path.exists("./logs"): os.makedirs("./logs") logger = logging.getLogger(LOGGER_NAME) logger.setLevel(logging.DEBUG) handler_local = RotatingFileHandler( ...
135378
import os, sys import argparse import numpy as np import cv2 from skimage import filters from linefiller.thinning import thinning from linefiller.trappedball_fill import trapped_ball_fill_multi, flood_fill_multi, mark_fill, build_fill_map, merge_fill, \ show_fill_map, my_merge_fill def dline_of(x, low_thr=1, h...
135420
import base64 import json import logging from typing import ( Union, ) import uuid import attr from botocore.exceptions import ( ClientError, ) from azul.service import ( AbstractService, ) from azul.service.step_function_helper import ( StateMachineError, StepFunctionHelper, ) from azul.types imp...
135443
from ctypes import * import unittest import os import ctypes import _ctypes_test class BITS(Structure): _fields_ = [("A", c_int, 1), ("B", c_int, 2), ("C", c_int, 3), ("D", c_int, 4), ("E", c_int, 5), ("F", c_int, 6), ...
135455
import setuptools with open("README.md", "r") as fh: long_description = fh.read() import versioneer setuptools.setup( name="removestar", version=versioneer.get_version(), cmdclass=versioneer.get_cmdclass(), author="<NAME>", author_email="<EMAIL>", description="A tool to automatically repl...
135471
def assert_raises(excClass, callableObj, *args, **kwargs): """ Like unittest.TestCase.assertRaises, but returns the exception. """ try: callableObj(*args, **kwargs) except excClass as e: return e else: if hasattr(excClass,'__name__'): excName = excClass.__name__ e...
135472
import numpy as np import pandas.compat as compat import pandas as pd class TablePlotter(object): """ Layout some DataFrames in vertical/horizontal layout for explanation. Used in merging.rst """ def __init__(self, cell_width=0.37, cell_height=0.25, font_size=7.5): self.cell_width = cel...
135492
import io from django.contrib import messages from django.template.defaultfilters import linebreaksbr from django.utils.translation import ugettext as _ import ghdiff from CommcareTranslationChecker import validate_workbook from CommcareTranslationChecker.exceptions import FatalError from corehq.apps.app_manager.exc...
135517
import enum from typing import Dict, Any, Optional from .types import * class DeviceException(Exception): # pylint: disable=too-few-public-methods exc: Dict[int, Any] = { 0x6A86: WrongP1P2Error, 0x6A87: WrongDataLengthError, 0x6D00: InsNotSupportedError, 0x6E00: ClaNotSupportedEr...