content
stringlengths
5
1.05M
import vapoursynth as vs def nnedi3_rpow2(clip, rfactor=2, width=None, height=None, correct_shift=True, kernel="spline36", nsize=0, nns=3, qual=None, etype=None, pscrn=None, opt=True, fapprox=None): """nnedi3_rpow2 is for enlarging images by powers of 2. Args: rfacto...
from plugins.nornir_addon import playbook_dir from plugins.push_config import push_config import logging import re from plugins.junos_get import junos_get from nornir.core.task import Result, Task logger = logging.getLogger(__name__) output_template = ''' ================================================================...
"""This module handles displaying information on how to connect and query.""" from typing import Any, Dict from jinja2 import Environment, PackageLoader, select_autoescape from ..utils import display_html LOADER = PackageLoader("dataprep", "connector/assets") ENV_LOADER = Environment(loader=LOADER, autoescape=select_a...
""" Harvester for the Scholars Portal dataverse. More information here: https://github.com/CenterForOpenScience/SHARE/blob/master/providers/info.scholarsportal.dataverse.md """ from __future__ import unicode_literals from scrapi.base import OAIHarvester class SPDataverse(OAIHarvester): short_name = 'spdataver...
import socket found_nodes = [] for x in range(1, 100): try: found_nodes.append(socket.gethostbyname(f"redis{x}")) except socket.error: continue found_nodes.sort() addrs = ":6379 ".join(found_nodes) print(f"docker exec -it redis1 redis-cli --cluster create {addrs}:6379 --cluster-replicas 1"...
from .utils import ActionCaller, Mixable idfunc = lambda func: func class TestWM(Mixable): def on_key(self, key): assert isinstance(key, str), 'First argument to on_key must be string' return ActionCaller(self, idfunc) def on_timer(self, period, start=True): return ActionCaller(self,...
from utils import DEFAULT_NUMBERS from thread2 import CustomThread, SiteCrawler import queue import time if __name__ == "__main__": q = queue.Queue() for num in DEFAULT_NUMBERS: q.put(num) print('create c1') c1 = CustomThread(25, q) print('create c2') c2 = CustomThread(25, q) print(...
"""Option for setting the current date of the picker.""" from datetime import date from pollbot.poll.update import try_update_reference from pollbot.decorators import poll_required from pollbot.display.creation import get_datepicker_text from pollbot.enums import ExpectedInput, ReferenceType from pollbot.helper.stats ...
from flask import Blueprint, request, make_response, jsonify from flask.views import MethodView from project.server import bcrypt, db from project.server.models import User display_blueprint = Blueprint('display', __name__) class displayAPI(MethodView): """ User Display Resource """ def get(self): ...
import numpy as np import pp from scipy.constants import c as SPEED_OF_LIGHT from simphony.elements import Model from simphony.tools import freq2wl, interpolate, wl2freq def load(component, **kwargs): """ load Sparameters for a component Args: component: component factory or instance **kwargs...
# Copyright (C) 2020. Huawei Technologies Co., Ltd. All rights reserved. # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to us...
from math import floor NUMBER_OF_DICE = 4 import random class Character: def __init__(self): self.strength = dice_throw() self.dexterity = dice_throw() self.constitution = dice_throw() self.intelligence = dice_throw() self.wisdom = dice_throw() self.charisma = dice_throw...
import json from django.urls import reverse from djmoney.money import Money from mock import patch from rest_framework import status from bluebottle.funding.tests.factories import FundingFactory, DonorFactory, PlainPayoutAccountFactory from bluebottle.funding_flutterwave.tests.factories import FlutterwavePaymentProvi...
from flask import Flask, request import json import classla app = Flask(__name__) pipelineCache = dict() @app.route('/', methods=['POST']) def annotate(): global pipelineCache properties = request.args.get('properties', '') lang = request.args.get('pipelineLanguage', '') text = list(request.form.keys...
import uuid import dramatiq from fief.tasks.base import TaskBase class OnAfterRegisterTask(TaskBase): __name__ = "on_after_register" async def run(self, user_id: str, workspace_id: str): workspace = await self._get_workspace(uuid.UUID(workspace_id)) user = await self._get_user(uuid.UUID(use...
from collections import defaultdict from dataclasses import dataclass from typing import Optional from execute_config import ExecuteConfig from problem_info import ProblemInfo @dataclass class RunConfig(ExecuteConfig): problem_info: ProblemInfo = None
import ahocorasick class ACAutomaton(): def __init__(self, patterns: list): self.ac = ahocorasick.Automaton() for pattern in set(patterns): self.ac.add_word(pattern, pattern) self.ac.make_automaton() def query(self, queries: list): ''' `queries`: the `list` of `str` to query return values: `lis...
"""Miscellaneous utilities which operate on image data.""" import warnings from typing import Tuple, Union import numpy as np from PIL import Image from tiatoolbox.utils.misc import conv_out_size from tiatoolbox.utils.transforms import ( bounds2locsize, bounds2slices, imresize, locsize2bounds, pad...
"""Fuse U-net predictions with an LSTM network Requires predictions from the U-nets Requires the trained LSTM model Produces a results pickle file to be used by the postprocessing """ # + import sys # Root folder of main library sys.path.insert(0, 'library') # Root folder of EDF files EDF_ROOT = '/esat/biomeddata/Ne...
from datetime import datetime import numpy as np from hdmf.backends.hdf5 import H5DataIO from hdmf.build import ObjectMapper from hdmf.data_utils import DataChunkIterator from hdmf.spec import DatasetSpec, RefSpec, DtypeSpec from hdmf.testing import TestCase class TestConvertDtype(TestCase): def test_value_none...
#!/usr/bin/env python # count the number of common SNPs in two files import sys import operator import argparse def calcHamm(args): mHamm = {} x=0 int1= open("input1.txt",'w') with open(args.input1, 'r') as f: for l in f: l = l.strip() r = l.split() s="" k="" if(len(r[2])>1): k=r[2...
from mcts import mcts from typing import List, Dict from monopoly_deal.actions import Action from monopoly_deal.agents import Agent, RandomAgent from monopoly_deal.cards import Card from monopoly_deal.game import Game, Player from monopoly_deal.play import step class State: def __init__(self, ai_player: Player, ...
from pathlib import Path from setuptools import setup, Extension import Cython.Build # read the contents of your README file this_directory = Path(__file__).parent long_description = (this_directory / "README.md").read_text() version = '0.0.4' ext = Extension(name="UltraDict", sources=["UltraDict.py"]) setup( n...
import requests import six.moves.urllib.parse as urlparse import json import os import logging logger = logging.getLogger(__name__) logger.setLevel(logging.INFO) class Client(object): """ Gym client to interface with gym_http_server """ def __init__(self, remote_base): self.remote_base = remot...
import cv2 cap = cv2.VideoCapture('video.avi') # XML File cars.xml contains classifiers for cars which can be detected. car_cascade = cv2.CascadeClassifier('cars.xml') while True: ret, frames = cap.read() # Convert to gray gray = cv2.cvtColor(frames, cv2.COLOR_BGR2GRAY) # Detect Cars of different siz...
from jabberbot import JabberBot, botcmd import commands import logging logger = logging.getLogger(__name__) class PiRobotJabberBot(JabberBot): @botcmd def serverinfo( self, mess, args): """Displays information about the server""" version = open('/proc/version').read().strip() loadavg =...
from typing import List, Dict from dataclasses import dataclass, field from collections import defaultdict from copy import deepcopy from metrics import hotpotqa_eval, BaseMetric @dataclass class LabelPredictionInstance: label_answer: str = None probe_predicted_answers: List[str] = field(default_factory=lam...
""" Salem package """ from __future__ import division from os import path from os import makedirs import sys from functools import wraps import pyproj try: from .version import version as __version__ except ImportError: # pragma: no cover raise ImportError('Salem is not properly installed. If you are runnin...
import json import os import pytest import responses from cryptojwt.key_jar import init_key_jar from idpyoidc.client.defaults import DEFAULT_OAUTH2_SERVICES from idpyoidc.client.oauth2 import Client _dirname = os.path.dirname(os.path.abspath(__file__)) ISS = "https://example.com" KEYSPEC = [ {"type": "RSA", "u...
# Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. """Groups of optimizers for use in benchmarks """ import typing as tp import numpy as np import nevergrad as ng from never...
""" auth.py author: @mbiokyle29 / @boydgreenfield - Adapted from v0 auth.py """ from __future__ import print_function import datetime import json import logging import os import sys import click from onecodex.utils import collapse_user from onecodex.version import __version__ from onecodex.lib.auth import check_versi...
from time import localtime from backtester import query_table, backtest_data import sm_util from sm_util import ArgumentError, historical_database sm_util.credentials_file = 'credentials/trader_bot0' def lambda_handler(event, context = None): params = event['params']['querystring'] function = params['function...
from ecdsa import SigningKey, NIST256p sk = SigningKey.generate(curve = NIST256p) sk_name = 'signing_key.pem' print('Signing key for signing device firmware: '+sk_name) open(sk_name,'wb+').write(sk.to_pem()) vk = sk.get_verifying_key() print('Public key in various formats:') print() print([c for c in vk.to_string()...
n = 1000-int(input()) money = [500,100,50,10,5,1] coin = 0 for i in money: coin += n//i n %= i print(coin)
import os import platform def ubuntu_req_fix(): os_version = platform.version() if '18.' in os_version: os.system('sudo apt install ffmpeg') else: os.system('sudo add-apt-repository ppa:jonathonf/ffmpeg-4') os.system('sudo apt update') os.system('sudo apt remove ffmpeg && s...
from fabric import task CODE_DIR = '~/django-projects/test-osale/foodbank-campaign/src' # for FreeBSD compatibility SHELL = '/bin/sh -c' @task def deploy(c): c.shell = SHELL with c.cd(CODE_DIR): pull_changes(c) with c.prefix('. ../venv/bin/activate'): update_dependencies(c) ...
# Copyright 2021 IBM Corp. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agre...
import pandas as pd import settings import auth from random import choice import string engine = settings.engine cur = engine.connect() #=====================Senha==================== def definirsenha(): tamanho = 8 valores = string.ascii_lowercase + string.digits senha = '' for i in range(tamanho): ...
# -*- coding: utf-8 -*- """QGIS Unit tests for QgsServer. .. note:: This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. """ __autho...
from typing import NamedTuple class Coordinates(NamedTuple): latitude: float longitude: float
import discord from discord.ext import commands from discord.ext.commands import cooldown,BucketType from cogs.usefullTools.dbIntegration import * class HelpCog(commands.Cog): def __init__(self, bot): self.bot = bot # Help console @commands.command() @cooldown(1, 3, BucketType.channel) async def help(self...
# MIT License # # Copyright (c) 2017 Javier Romero # # Permission is hereby granted, free of charge, to any person obtaining a copy # of this software and associated documentation files (the "Software"), to deal # in the Software without restriction, including without limitation the rights # to use, copy, modify, mer...
from django.contrib import admin from unitology.forms import UnitsFieldFormMixin from .models import Person class PersonChangeForm(UnitsFieldFormMixin): class Meta: model = Person fields = ['name', 'units', 'weight', 'height'] class PersonAdmin(admin.ModelAdmin): form = PersonChangeForm ...
from datetime import datetime from Components.scp_connect import ScpConnect from Components.status_bar import StatusBar class TextSync: def __init__(self, tab, combo, text): self.refresh_enable = False self.pause = False self.server = "" self.port = "" self.user = "" ...
from __future__ import absolute_import import itertools import math import mjolnir.sampling import numpy as np from pyspark.sql import functions as F import string def test_sampling_selects_all_if_less_than_samples_per_wiki(spark_context): # Generate a sample dataframe with only 10 queries, then ask for 10000 ...
from __future__ import absolute_import import os from sfepy.base.base import output, dict_to_struct, Struct from sfepy.base.conf import ProblemConf, get_standard_keywords import sfepy.base.ioutils as io from sfepy.discrete import Problem from sfepy.discrete.fem.meshio import MeshIO from .application import Application...
from ocsmesh.mesh.mesh import Mesh # type: ignore[attr-defined] __all__ = ["Mesh"]
class TrackStructure(object): def __init__(self, track, user): self.track = track self.user = user self.votes = 0 class Tracklist(object): """ Tracklist works as following: Track with the most votes goes first. After that the track with one vote less. """ def __init__(s...
# -*- coding: utf-8 -*- """ Skyperious main program entrance: launches GUI application or executes command line interface, handles logging and status calls. ------------------------------------------------------------------------------ This file is part of Skyperious - a Skype database viewer and merger. Releas...
import traceback from binaryninja import Architecture, BinaryView, SegmentFlag, log_error, FileMetadata is_enabled = False class LiveView(BinaryView): """ A custom binary view that allows arbitrary data to be written to it, without requiring that any segments created must exist in the actual file. This can b...
from ..abstract import SequentialProcessor from .. import processors as pr class AugmentImage(SequentialProcessor): """Augments an RGB image by randomly changing contrast, brightness saturation and hue. """ def __init__(self): super(AugmentImage, self).__init__() self.add(pr.Random...
# sliderControl.py # # It creates a simple slider control surface. from gui import * class SliderControl: def __init__(self, title="Slider", updateFunction=None, minValue=10, maxValue=1000, startValue=None, x=0, y=0): """Initializes a SliderControl object.""" self.title = title # holds the title o...
def closure_test_suite(name, data): browsers = { "firefox": ("ff", "//java/client/src/org/openqa/selenium/firefox"), "chrome": ("chrome", "//java/client/src/org/openqa/selenium/chrome"), "ie": ("ie", "//java/client/src/org/openqa/selenium/ie"), "safari": ("safari", "//java/client/src...
def eval_tbike(tbike): if tbike.status != 'finished': return 0 S = 0 Sp = 0 bikes = [tbike.init_bikes_count for _ in range(len(tbike.locations))] bike_returns = [[] for _ in range(len(tbike.bikes_requests))] for t, reqs in enumerate(tbike.bikes_requests): rets = bike_returns[t...
import taichi as ti from Rope import Rope if __name__ == "__main__": ti.init(arch=ti.cuda) # control paused = False rest_length = 0.1 num = 20 mode = 3 delta_t = 0.1 rope = Rope(start = [0.2,0.8], end = [0.8,0.8],num_nodes = num, node_mass = 1, ela_coeff = 10, rest_length =...
from unittest import TestCase import plotly.graph_objs as go from plotly.tests.utils import strip_dict_params class TestAssignmentPrimitive(TestCase): def setUp(self): # Construct initial scatter object self.scatter = go.Scatter(name='scatter A') # Assert initial state d1, d2 = ...
# -*- coding: utf-8 -*- import os import shutil import csv import json from dataclasses import dataclass from .baseparser import ParseError @dataclass class Output: name: str value: str DIR_SCRIPT = 'code/' DIR_LOG = 'boba_logs/' LOG_EXT = '.txt' def get_universe_name(universe_id): """ Get the name of ...
# Copyright (c) 2021, NVIDIA CORPORATION & AFFILIATES. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless requ...
from flask import Flask, Response, jsonify, request import copy import json import nltk import numpy as np import os import re import requests import string from nltk.corpus import stopwords from nltk.tokenize import word_tokenize from sklearn.metrics.pairwise import cosine_similarity from sklearn.feature_extraction.t...
# desafio 023: Faça um programa que leia um número de 0 a 9999 e mostre na tela cada um dos # dígitos separados. numero = input('Digite um numero entre 0 e 9999: ') uni = numero[3] dez = numero[2] cen = numero[1] mil = numero[0] print('Está é a \n unidade: {}\n dezena: {}\n centena: {}\n milhar: {}'.format(uni,dez,cen...
import numpy as np from random import random, seed import pandas as pd from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler import sklearn.linear_model as sk #import SGDRegressor, Lasso, LinearRegression, Ridge from dataset import train_test_rescale from misc import MS...
# Generated by Django 3.1.1 on 2020-09-08 01:44 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Classes', fields=[ ('id', models.AutoField(...
"""Prepare MS COCO datasets""" import os import shutil import argparse import zipfile from encoding.utils import download, mkdir _TARGET_DIR = os.path.expanduser('~/.encoding/data') def parse_args(): parser = argparse.ArgumentParser( description='Initialize MS COCO dataset.', epilog='Example: pyth...
import numpy as np import torch from torch.optim import Adam import gym from gym.spaces import Box, Discrete import time import spinup.algos.pytorch.ppo.core as core from spinup.utils.logx import EpochLogger from spinup.utils.mpi_pytorch import setup_pytorch_for_mpi, sync_params, mpi_avg_grads from spinup.utils.mpi_too...
import socket socket.socket._bind = socket.socket.bind def my_socket_bind(self, *args, **kwargs): self.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1) return socket.socket._bind(self, *args, **kwargs) socket.socket.bind = my_socket_bind
# (C) British Crown Copyright 2013 - 2018, Met Office # # This file is part of cartopy. # # cartopy is free software: you can redistribute it and/or modify it under # the terms of the GNU Lesser General Public License as published by the # Free Software Foundation, either version 3 of the License, or # (at your option)...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from ... import _utilities fro...
# -*- coding: utf-8 -*- # USAGE: # PYTHONPATH=".." python test_transcribe.py from eng_to_ipa import transcribe import transcribe_fixtures import copy, sys words = { 'teacher':'', 'aardvark':'', 'pangram': "The beige hue on the waters of the loch impressed all, including the French queen, before she heard th...
from pathlib import Path import sys import shutil dir_path = Path(sys.argv[1]) for item_path in dir_path.iterdir(): if item_path.suffix.lower() in ['.jpg', '.png']: target_path = Path(item_path.parent, 'image') shutil.move(str(item_path), str(target_path)) print("hello world!")
#!/usr/bin/env python # # This code defines an object which is really only for a single use. # Can you rewrite it so that it only uses a functions? from threading import Thread from queue import Queue class Processor(object): """Prepare to process something on a callback of some sort.""" def __init__(self, d...
from typing import Optional, TYPE_CHECKING from cached_property import cached_property import astroid.nodes from .. import astroidutils if TYPE_CHECKING: import pydocspec class DataClassesDataMixin: @cached_property def is_dataclass_field(self: 'pydocspec.Data') -> bool: #type:ignore[misc] """ ...
import pytest import json from datetime import date from model_mommy import mommy from rest_framework import status from django.core.management import call_command from django.db.models import Q from usaspending_api.awards.models import Transaction, TransactionContract, TransactionAssistance from usaspending_api.awar...
from rest_framework import status from rest_framework.views import APIView from rest_framework.response import Response from ..models import * from ..serializers import * from ..permissions import * class LeaveView(APIView, LeaveHelpers): def get(self, request): team_id = request.query_params['team_id']...
def __residuumSign(self): if self.outcome == 0: return -1 else: return 1
from util import stream from config import Struct def parse(npk_file, offset, size): npk_file.seek(offset + 24) index_size = stream.read_struct(npk_file, Struct['INT']) index_num = stream.read_struct(npk_file, Struct['INT']) textures = [] for i in range(index_num): texture = {} te...
n = int(input()) for i in range(n): for digit in [i for i in range(1, i + 2)]: print(digit, end='') print()
# Librairies print("Load Libraries") import os import hashlib import numpy as np import pandas as pd import tensorflow.keras.preprocessing.image as kpi import tensorflow.keras.models as km from tensorflow.python.client import device_lib MODE = "GPU" if "GPU" in [k.device_type for k in device_lib.list_local_devices(...
import numpy as np from matplotlib import pyplot as plt from random import gauss def get_data(mean, sigma, classification): x = [] y = [] for i in range(60): dat_x, dat_y = gauss(mean, sigma), gauss(mean, sigma) x.append([1, dat_x, dat_y]) y.append([classification]) x = np.arra...
# Name: Michael Stroet # Student number: 11293284 import os def open_txt(input_txt): ''' Reads a text file and returns the lines as lists of strings ''' with open(input_txt, "r") as file: file_content = file.read() file_lines = file_content.split() return file_lines def convert_t...
''' Simple Python based installer of PDL Tools. In time this will involve to become more complex but perhaps not quite as complex as madpack :-) Note: Most of this script has been copied from madpack.py. We've removed irrelevant portions from madpack to build pdlpack. Srivatsan Ramanujam <sramanujam@pivotal.io> 28 Jan ...
# -*- cpy-indent-level: 4; indent-tabs-mode: nil -*- # ex: set expandtab softtabstop=4 shiftwidth=4: # # Copyright (C) 2008,2009,2010,2012,2013,2014,2017,2018 Contributor # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obt...
from distutils.version import LooseVersion import torch _TORCH_LOWER_1_4 = LooseVersion(torch.__version__) < LooseVersion("1.4.0") _TORCH_LOWER_1_5 = LooseVersion(torch.__version__) < LooseVersion("1.5.0") _TORCH_LOWER_1_6 = LooseVersion(torch.__version__) < LooseVersion("1.6.0")
"""A load class.""" class Load: """Load class containing location, force, and moment vectors.""" def __init__(self, xyz=[0, 0, 0], force=[0, 0, 0], moment=[0, 0, 0]): """Initialize a Load instance.""" self.xyz = xyz self.force = force...
cardStack = [] print(','.join(cardStack)) cardStack.append('5 of diamonds') print(','.join(cardStack)) cardStack.append('3 of clubs') print(','.join(cardStack)) cardStack.append('ace of hearts') print(','.join(cardStack)) cardStack.pop() print(','.join(cardStack))
# coding=utf-8 # -------------------------------------------------------------------------- # Code generated by Microsoft (R) AutoRest Code Generator. # Changes may cause incorrect behavior and will be lost if the code is # regenerated. # -------------------------------------------------------------------------- from ...
# Copyright 2013 IBM Corp. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed t...
# must be within Tests folder to run # Complete/Tests $ pytest -v import sys sys.path.append('..') from Pages.page_form import FormPage from globals import FormyGlobals from selenium import webdriver import pytest class TestFormSuccessChrome(): @pytest.fixture() def test_setup(self): global driver ...
import pytest from descarteslabs.common.proto.formats import formats_pb2 from .. import mimetype_to_proto def test_mimetype_to_proto(): proto = mimetype_to_proto("application/vnd.pyarrow; compression=LZ4") assert isinstance(proto, formats_pb2.Format) assert proto.has_pyarrow and not proto.has_geotiff ...
# uncompyle6 version 3.2.4 # Python bytecode 2.7 (62211) # Decompiled from: Python 2.7.15 (v2.7.15:ca079a3ea3, Apr 30 2018, 16:30:26) [MSC v.1500 64 bit (AMD64)] # Embedded file name: lib.coginvasion.minigame.FinalScoreGUI from panda3d.core import TextNode from direct.directnotify.DirectNotifyGlobal import directNotify...
import os import datetime import requests class RescueAPI: def __init__(self, ): self.API_KEY = os.environ['RESCUETIME_API_KEY'] self.payload = {"key": self.API_KEY} def endpoint(self, endpoint): base_url = "https://www.rescuetime.com/anapi" endpoint = base_url + endpoint ...
from flytekit.sdk.tasks import inputs, outputs, python_task from flytekit.sdk.types import Types from flytekit.sdk.workflow import workflow_class, Input, Output import json @inputs(custom=Types.Generic) @outputs(counts=Types.Generic, replicated=Types.List(Types.Generic)) @python_task def generic_type_task(wf_params, ...
# @Eamil : iamfuture_x@outlook.com # @Author : Mr-NB import logging, pathlib import aiohttp_autoreload, aioredis, jinja2, aiohttp_jinja2 import aiohttp from aiohttp import web from tortoise.contrib.aiohttp import register_tortoise from app.config import * from aiohttp.log import web_logger TEMPLATES_ROOT = pathl...
import requests from urllib.parse import quote as _uriquote from datetime import datetime from .exceptions import * from .session import ClientSession class Client: def __init__(self, ratelimit=0, bot=None, hide_token=False): self._session = None self._ratelimit = ratelimit self._last_use =...
def nb_pytest_parameters(f): try: # new pytest return len(f.pytestmark) except AttributeError: # old pytest return len(f.parametrize.args) / 2 def get_pytest_param(f, i): try: # new pytest return f.pytestmark[i].args except AttributeError: # old ...
# # Data pipelines for Edge Computing # # Inspired by Google Media pipelines # # # Dataflow can be within a "process" and then hook in locally # But can also be via a "bus" or other communication mechanism # class Calculator: def __init__(self, name, streams, options=None): self.name = name # inpu...
#!/usr/bin/env python """ Copyright 2018 Johns Hopkins University (Author: Jesus Villalba) Apache 2.0 (http://www.apache.org/licenses/LICENSE-2.0) """ """ Trains x-vectors with attention """ from __future__ import absolute_import from __future__ import print_function from __future__ import division from six.moves i...
import numpy as np from tensorflow import keras import pickle import os import random class ReplayBuffer(): def __init__(self, max_size, input_dims, fname="dqn_replay_buffer.pickle"): self.mem_size = max_size self.mem_cntr = 0 self.state_memory = np.zeros((self.mem_size, *input_dims), dtype...
from collections import Counter import random, torch import numpy as np import hashlib class Instance: def __init__(self, events, src_blk, tag, type, confidence=None, tag_logit=None): self.src_events = events self.src_words = [] for event in self.src_events: self.src_words....
# _*_coding : UTF_8 _*_ # Author : Xueshan Zhang # Date : 2022/1/22 2:59 PM # File : Status.py # Tool : PyCharm # Reference : __repr__ << Thread << threading.py import threading import time, os def Subthread(n): for i in range(n): print('is going to sleep', i, 's.') time.sleep(i)...
import ftfy with open("data/small_text.json") as fp: for line in fp: print(ftfy.fix_encoding(line), end='')