content
stringlengths
5
1.05M
import os from flask import request, send_file, current_app from app.core import ApiResponse, ApiPagedResponse from . import api from ..import db from ..models import Deliverable, DeliverableFile, Permission from .decorators import permission_required from flask_jsonschema import validate from sqlalchemy import or_ d...
from pathlib import Path from unittest.mock import call, patch, mock_open import unittest from adk.exceptions import InvalidPathName, JsonFileNotFound, MalformedJsonFile from adk.utils import copy_files, get_dummy_application, get_py_dummy, read_json_file, reorder_data, write_json_file, \ write_file, validate_path...
# Generated by Django 2.2.8 on 2020-01-12 10:08 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('post', '0004_auto_20200112_0959'), ] operations = [ migrations.AddField( model_name='adminprofile', name='email', ...
from __future__ import annotations from ctc import binary from ctc import spec from . import function_parsing def get_event_hash(event_abi: spec.EventABI) -> str: """compute event hash from event's abi""" signature = get_event_signature(event_abi=event_abi) return binary.keccak_text(signature) def get_...
import unittest import time from pidevices.mcp23017 import MCP23017 from pidevices import Mcp23017GPIO from pidevices.exceptions import NotInputPin class TestMcp23017GPIO(unittest.TestCase): def test_add_pins(self): interface = Mcp23017GPIO(echo='A_1', trigger='B_2') self.assertEqual(interface.pi...
import cvxpy as cp import numpy as np import geopandas as gpd import matplotlib.pyplot as plt from matplotlib.collections import LineCollection from shapely.geometry import box, Point, LineString, Polygon, MultiPolygon from shapely.affinity import scale from scipy.spatial import distance_matrix from matplotlib.animatio...
# -*- coding: utf-8 -*- # Time : 2022/1/30 1:49 # Author : QIN2DIM # Github : https://github.com/QIN2DIM # Description: from services.bricklayer import Bricklayer from services.explorer import Explorer from services.settings import logger from services.utils import ( ToolBox ) SILENCE = True brickla...
import glob import logging import os import re from itertools import chain from django.core.management.base import BaseCommand from cms.models import CMSPlugin, Placeholder, StaticPlaceholder from djangocms_alias.models import Category, Alias, AliasContent from djangocms_alias.constants import DEFAULT_S...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('projects', '0008_auto_20160310_1222'), ] operations = [ migrations.AddField( model_name='projectvolume', ...
from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() firstname = forms.CharField(max_length=20) lastname = forms.CharField(max_length=20) class Meta: mod...
from objects.CSCG._3d.mesh.domain.regions.region.types_wrt_metric.base import TypeWr2MetricBase import numpy as np from root.config.main import cOmm, rAnk from objects.CSCG._3d.mesh.elements.element.types_wrt_metric.chaotic import ChaoticElement from objects.CSCG._3d.mesh.trace.elements.element.types_wrt_metric.chaot...
############################################################################## # Copyright 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved. # # # # Licensed under the Apache License, Version 2.0 (the "License"). # # Y...
import argparse import os from multiprocessing import Pool import logging import random import copy import tensorflow as tf from generic.data_provider.iterator import BasicIterator from generic.tf_utils.evaluator import Evaluator from generic.data_provider.image_loader import get_img_builder from guesswhat.models.or...
import torch # from pytorch_lightning.metrics import Metric class MatchPrecision(): def __init__(self, name = None): self.name = name def __call__(self, scores, gt_scores, match_thresh = 0.2): ''' scores: (n_batch, n_obs_kpt, n_model_kpt) gt_scores: (n_batch, n_obs_kpt, n_model...
"""Module with shell specific actions, each shell class should implement `from_shell`, `to_shell`, `app_alias` and `put_to_history` methods. """ from collections import defaultdict from subprocess import Popen, PIPE from time import time import os from psutil import Process from .utils import DEVNULL class Generic(o...
# Lab 1 # 12 October 2020 # Created by YongHua # Python version 3.8 import math def average(a, b): return (a + b) * 0.5 print(average(10, 20)) print(average(10, 4)) def distance(a, b): if a > b: return a - b else: return b - a print(distance(3, 4)) print(distance...
#!/usr/bin/env python # author: me@itzo.org # version: 2.2 # description: Get current data from Bittrex for market exchange rates and amounts in order book # Store the data in a sqlite database for future use import urllib import json import datetime import sys import getopt import sqlite3 a...
# dupFinder.py import os, sys import hashlib import stat from pytube import YouTube # duplicates file def findDup(parentFolder): # Dups in format {hash:[names]} testing_path = 'W:\Work\PythianTask\TestingDir\\1' # linking = gos.link(testing_path, 'tap') # os.chmod(testing_path, stat.S_IR...
#!/usr/bin/env python # -*- coding: utf-8 -*- """Tests for :mod:`~utilipy.decorators.func_io.dtype_decorator`.""" ############################################################################## # IMPORTS # THIRD PARTY import numpy as np import pytest # PROJECT-SPECIFIC from utilipy.decorators.func_io import dtypeDe...
# Escreva um programa que pergunte a quantidade de km percorridos # por um carro alugado e a quantidade de dias pelos quais ele foi alugado. # Calcule o preço a pagar, sabendo que o carro custa R$ 60 por dia e R$ 0.15 por km rodado. km = float(input('\nQuantos km rodados? ')) dias = int(input('Quantos dias alugados? ...
class Address: def __init__(self, address1 = '', address2 = '', city = '', state = '', zip = '', country = ''): self.address1 = address1 self.address2 = address2 self.city = city self.state = state self.zip = zip self.country = country def deserialize(address...
from setuptools import setup from setuptools import find_packages setup(name="layer_preview_proto", version="0.0.1", description="tf-layer-preview protobuffer definition library", url="https://github.com/recogni/tf-layer-preview", author="sabhiram", install_requires=[ ], packa...
from typing import Union import strawberry from strawberry.types import Info from reddit.comments.types import CommentType __all__ = ("comment_create",) @strawberry.input class CommentCreateInput: content: str subreddit_id: strawberry.ID post_id: strawberry.ID @strawberry.type class CommentCreateSuc...
from django.db import models from django.utils.text import slugify class Category(models.Model): category_name = models.CharField(max_length=50) def __str__(self): return self.category_name class Meta: verbose_name='Kateqoriya' class Post(models.Model): category=models.ManyToManyF...
import unittest from bc211 import dtos, exceptions from common.testhelpers.random_test_values import a_string, a_phone_number class TestOrganization(unittest.TestCase): def test_throws_on_missing_id(self): with self.assertRaises(exceptions.MissingRequiredFieldXmlParseException): dtos.Organizat...
import os import time import urllib.request, urllib.parse, urllib.error import sys import datetime from django.core.management.base import BaseCommand, CommandError from nadine.utils.backup import BackupManager class Command(BaseCommand): help = "Creates a backup containing an SQL dump and the media files." ...
from ..ext.database import db class Perfil(db.Model): __tablename__ = "Perfil" id_perfil = db.Column(db.Integer, primary_key=True) refresh_rate = db.Column(db.Integer) name = db.Column(db.String(30)) def __init__(self, name,refresh_rate): self.name = name self.refresh_rate ...
#!/usr/bin/env python # -*- coding: utf-8 -*- #* #* CreateID_pass.py #* #* Copyright (c) 2020 IWATA Daiki #* #* This software is released under the MIT License. #* see http://opensource.org/licenses/mit-license #* import sys import hashlib import sqlite3 userID = input("Input userID: ") passwd = input("Input pas...
import os import sys from game import Game from client import Client from botmanager import BotManager from constants import Constants as Cts from flask import Flask, render_template from flask_sockets import Sockets reload(sys) sys.setdefaultencoding('utf8') game = Game(Cts.LINES, Cts.COLUMNS, Cts.SLEEP_TIME) bot_m...
""" Components for adding syntax highlighting to a `markyp-html` webpage using Highlight.js. See https://www.npmjs.com/package/highlight.js. """ from typing import Optional, Tuple from markyp import PropertyValue from markyp_html import link, script from markyp_html.block import pre from markyp_html.inline import co...
import yaml import os import check def 练习(number): config=yaml.load(open(str(number)+'.yaml'),Loader=yaml.FullLoader) 科目=config['必需项']['科目'] 题目=config['必需项']['题目'] 答案=config['必需项']['答案'] 选项=config['非必需项']['选项'] 解析=config['非必需项']['解析'] 出题者=config['非必需项']['出题者'] os.system("clear") print("所属科目:\033[36m"+科目+"\033...
class LRUCache: # @param capacity, an integer def __init__(self, capacity): self.capacity = capacity self.cache = collections.OrderedDict() # @return an integer def get(self, key): if not key in self.cache: return -1 value = self.cache.pop(key) ...
### Import the ONNX model to Tensorflow ### import onnx from onnx_tf.backend import prepare import torch # Load the ONNX file model = onnx.load('DA2_FMNIST/output/mnist.onnx') # Import the ONNX model to Tensorflow tf_rep = prepare(model, strict=False) # Input nodes to the model print('inputs:', tf_rep.inputs) # Ou...
from django.conf.urls import url from .views import BaseView urlpatterns = [ url(r"^$", BaseView.as_view(), name="base-view-2"), ]
from django.db import models from django.urls import reverse class Message(models.Model): recipient = models.ForeignKey( "fuauth.User", related_name="messages", on_delete=models.CASCADE ) sender_name = models.CharField(max_length=35) message_text = models.TextField(max_length=125) created...
#Desafio 027 print("Desafio 027") nome=str(input("Digite seu nome completo:")).strip() nome1=nome.split() print("Seu primeiro nome é {}.".format(nome1[0])) print("Seu último nome é {}.".format(nome1[len(nome1)-1]))
import pathlib from setuptools import setup, find_packages import os # The directory containing this file HERE = pathlib.Path(__file__).parent # The text of the README file README = (HERE / "README.md").read_text() # Get the code version version = {} with open(os.path.join(HERE, "key_driver_analysis/version.py")) as...
#!/usr/bin/python3 # coding=utf-8 # pylint: disable=I0011,E0401 # Copyright 2021 getcarrier.io # # 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/license...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- # vim:fenc=utf-8 """ About: Configuration for Python built-in logging """ import logging logger = logging.getLogger('nc_coder') logger.propagate = False LEVELS = { 'debug': logging.DEBUG, 'DEBUG': logging.DEBUG, 'info': logging.INFO, 'INFO': logging.IN...
# -*- coding: utf-8 -*- # Copyright 2015 Mirantis, Inc. # # 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 requi...
import codecs file_path = 'test_files/EncodedFile.txt' data_enc = 'shift-jis' file_enc = 'euc-jp' ef = codecs.EncodedFile(file_path, data_enc, file_enc) #ef = codecs.EncodedFile(file_path, codecs.lookup(data_enc), codecs.lookup(file_enc))#TypeError: lookup() argument must be str, not CodecInfo print(type(ef)) data = ...
import time import uuid import logging import numpy as np import pandas as pd __all__ = [ "generateCombinations", "sortLinkages", "identifySubsetLinkages", "mergeLinkages", "removeDuplicateLinkages", "removeDuplicateObservations", "calcDeltas" ] logger = logging.getLogger(__name__) def ge...
import matplotlib import numpy as np import matplotlib.pyplot as plt import random as rnd import math def runRandomWalk(steps, not_backfire): x_vals = [] y_vals = [] x = 0 y = 0 indices = [] direction = math.floor(rnd.uniform(0, 4)) def intersectsSelf(): for i in range(len(x...
import random ''' Movie Generator ''' movie_genre = input('Enter a movie genre you currently prefer: ') # Here we make an intput for the user to choose a genre action =['The Matrix', 'Pirates of the Caribbean', 'The Terminator', 'Mr & Mrs Smith', 'Rush Hour', 'Pearl Harbor'] comedy = ['Johnny English', 'Cheape...
# Copyright 2019 Dragonchain, Inc. # Licensed under the Apache License, Version 2.0 (the "Apache License") # with the following modification; you may not use this file except in # compliance with the Apache License and the following modification to it: # Section 6. Trademarks. is deleted and replaced with: # 6. Tr...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Author: Tony <stayblank@gmail.com> # Time: 2019/5/31 00:34 import unittest from onion_decorator.override import override import test_somepackage class SuperClass(object): def some_method(self): """Super Class Docs""" return 'super' class SubClass...
# -*- coding: utf-8 -*- # Copyright (c) 2015, Frappe Technologies Pvt. Ltd. and contributors # For license information, please see license.txt from __future__ import unicode_literals import frappe from frappe import _ from frappe.utils import getdate from frappe.model.document import Document class Vehicle(Document):...
from random import randint def random_base(RNAflag = False): return ("UCAG" if RNAflag else "TCAG")[randint(0,3)] def random_codon(RNAflag = True): return random_base(RNAflag) + random_base(RNAflag) + random_base(RNAflag) print(random_codon())
# Copyright 2019 Arie Bregman # # 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 agree...
# -*- coding: utf-8 -*- #Ativa compatibilidade com ç ^ ~ ´ ` print("Olá mundo!") """ Comentario de Multiplas linhas """
import math #this is just becouse i used math down below exNum1 = -5 exNum2 = 5 print(abs(exNum1)) #absolute function if abs(exNum1) == exNum2: print('these are the same') exList = [1,2,3,4,5,6,7,8,9,10,11] print(max(exList)) print(min(exList)) intMe = '55' #take it as a string print(intMe) pri...
import sys from unittest.mock import patch from conda_diff import cli def test_parse_args(): mock_args = ["conda-diff", "env_a", "env_b"] with patch.object(sys, "argv", mock_args): args = cli.parse_args() assert args.environment_a == "env_a" assert args.environment_b == "env_b"
name = 'Michael' age = 43 # Create the string "Hi, I'm Michael and I'm 43 years old." # crash: print("Hi, I'm " + name + " and I'm " + age + " years old.") # works, but not pythonic print("Hi, I'm " + name + " and I'm " + str(age) + " years old.") # probably pythonic print("Hi, I'm %s and I'm %d years old." % (nam...
import os from flask import Flask, request, jsonify, g, url_for, abort from flask_httpauth import HTTPBasicAuth from models import db, PlantType, Plant, PlantData, User app = Flask(__name__) app.config.from_object(os.environ['APP_SETTINGS']) app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db.init_app(ap...
from datetime import datetime from decimal import Decimal from typing import List from pytest import raises, mark, approx from fastapi import HTTPException from santaka.stock.utils import ( YahooMarket, calculate_commission, calculate_sell_tax, get_active_markets, validate_stock_transaction, ) fro...
import abc, methodtools currentmodule = None class UnitsError(Exception): pass class Distance: def __new__(self, *args, **kwargs): return currentmodule.Distance(*args, **kwargs) def onepixel(pscale): return Distance(pixels=1, pscale=pscale) def onemicron(pscale): return Distance(microns=1, pscale=pscale) ...
import numpy as np import torch from torch import nn import torch.nn.functional as F class AverageMeter(object): def __init__(self): self.reset() def reset(self): self.val = 0 self.avg = 0 self.sum = 0 self.count = 0 def update(self, val, n=1): self.val =...
# -*- coding: utf-8 -*- import unittest import time import math from timer.timer import Timer from timer.timer_task_entry import TimerTaskEntry class TimerTest(unittest.TestCase): now = time.time() def _print(self, key): t = time.time() - self.now print('time: %s -- key: %s' % (round(t), ke...
# Copyright 2020 Google LLC # # 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, ...
from app.service.storage.collection_crud import CollectionCrud class Sources(list): # Persistence def bulk(self) -> CollectionCrud: return CollectionCrud("source", self)
from matplotlib import pyplot as plt import math # this program shows the side lengths of a right triangle, and the derivative of a side length in the falling ladder calculus problem constant = 5 # lenght of the hypotenuse dt = 0.0001 # unit of time. More accurate results with a smaller dt b_speed = -1 # per unit of ...
# coding: utf-8 # Team : uyplayer team # Author: uyplayer # Date :2019/11/20 下午4:22 # Tool :PyCharm ''' https://blog.csdn.net/c9Yv2cf9I06K2A9E/article/details/79739287 https://msd.misuland.com/pd/13340603045208861 ''' class AttnDecoderRNN(nn.Module): def __init__(self, hidden_size, output_size, dr...
"""Treadmill test skip windows. """ from __future__ import absolute_import from __future__ import division from __future__ import print_function from __future__ import unicode_literals import os import unittest if os.name == 'nt': raise unittest.SkipTest("Test not applicable to Windows.")
{ "targets": [ { "target_name": "manatee", "sources": [ "src/manatee.cc" ], "libraries": [ "-lBarcodeScanner" ] } ] }
import unittest class FixturesTest(unittest.TestCase): def setUp(self): print('In setUp()') r=1/0 self.fixture = range(1, 10) def tearDown(self): print('In tearDown()') r=1/0 del self.fixture def test_fixture1(self): print('in test1()') se...
""" BSD 3-Clause License Copyright (c) 2021, Netskope OSS All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of condi...
import os import io from google.cloud import vision from google.cloud.vision import types import cv2 def detect_cloth_image(path): with open(path, 'rb') as image_file: content = image_file.read() print("AAA", type(content)) image = vision.types.Image(content=content) objects = client.object_localiza...
# -*- coding: utf8 -*- """Autogenerated file - DO NOT EDIT If you spot a bug, please report it on the mailing list and/or change the generator.""" from nipype.interfaces.base import CommandLine, CommandLineInputSpec, SEMLikeCommandLine, TraitedSpec, File, Directory, traits, isdefined, InputMultiPath, OutputMultiPath i...
from django.core.management.base import BaseCommand from places.models import Place, Image import requests from django.core.files.base import ContentFile class Command(BaseCommand): help = 'Загружаем локации и картинки в БД' def add_arguments(self, parser): parser.add_argument('url', type=str) d...
import sys import numpy as np def preprocess(text): text = text.lower() text = text.replace('.', ' .') words = text.split(' ') word_to_id = {} id_to_word = {} for word in words: if word not in word_to_id: new_id = len(word_to_id) word_to_id[word] = new_id ...
from django.test import TestCase, Client from django.urls import reverse class TestViews(TestCase): def setUp(self): self.client = Client() self.register_url = reverse('register') def test_register_request(self): response = self.client.get(self.register_url) self.assertEqual...
'''OpenGL extension APPLE.texture_2D_limited_npot This module customises the behaviour of the OpenGL.raw.GLES1.APPLE.texture_2D_limited_npot to provide a more Python-friendly API Overview (from the spec) Conventional OpenGL ES 1.X texturing is limited to images with power-of-two (POT) dimensions. APPL...
from typing import Callable import pytest from web3 import Web3 from web3.contract import Contract from raiden_synapse_modules.presence_router.blockchain_support import ( read_initial_services_addresses, setup_contract_from_address, install_filters, ) from conftest import register_service @pytest.mark.p...
""" Copyright (C) 2019-2021, Monash University, Geoscience Australia Copyright (C) 2018, Stuart Walsh Bluecap is released under the Apache License, Version 2.0 (the "License"); you may not use this software except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licen...
import numpy as np import matplotlib.pyplot as plt from ODEmethods.methods import rk_methods from ODEmethods.rungekutta import RKMethod # Chemical reactions: Iodine clock - Persulfate variation def iodine_clock(t, y, par): y0 = - par[0]*y[0]*y[1] y1 = - par[0]*y[0]*y[1] - par[1]*y[1]*y[2] + par[2]*y[3]*y[5]...
import ast from kanren import var from tests.helpers import EvaloTestCase class TestStatements(EvaloTestCase): def test_expression_doesnt_change_env(self): ret, _ = self.run_stmt(ast_expr=ast.Expr(value=ast.Num(n=1)), value=var()) self.assertEqual(ret[0], []) def test_assignment_adds_variabl...
# import the GPIO module import RPi.GPIO as GPIO import time GPIO.setmode(GPIO.BCM) GPIO.setwarnings(False) def red_light_on(): # turn the light on GPIO.output(light_red, True) def red_light_off(): # turn the light off GPIO.output(light_red, False) def yellow_light_on(): # turn the light on G...
from types import FunctionType from unittest.mock import patch from django.test import TestCase from django.core.exceptions import ValidationError from vimage.core.validator_types import ValidationRuleDimensions from vimage.core.exceptions import InvalidValueError from .test_validation_rule_base import ValidatorTest...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sat Jul 20 12:58:27 2019 @author: TempestGuerra """ import numpy as np def computeTemperatureProfileOnGrid(PHYS, REFS, Z_in, T_in, isSmooth, isUniform): # Get REFS data z = REFS[1] ZTL = REFS[5] NC = len(ZTL[0,:]) ...
"""Test google directory service module functionality.""" from config import PATHS from mock import MagicMock from mock import patch import sys import unittest # Need to mock the call to get an XSRF token at function definition time, i.e. # when the module is loaded. http://stackoverflow.com/a/7667621/2830207 def Moc...
from __future__ import absolute_import from __future__ import print_function from __future__ import division from __future__ import unicode_literals import inspect from xml.etree import ElementTree as ET from ..extern import six # OrderedDict compat (Python 2.7+ and 3.1+) try: from collections import OrderedDict...
import os import errno class MakeDirectory: def __init__(self, prefix, suffix): self.prefix = prefix self.suffix = suffix self.folder_out = None def get_dir_name(self, print_dir): if type(self.suffix) == tuple and len(self.suffix) > 1: for i in rang...
# The MIT License (MIT) # # Copyright (c) 2016 Leon Jacobs # # 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, modif...
import torch from retriever import UnifiedRetriever from data_retriever import ZeshelDataset, transform_entities, load_data, \ get_all_entity_hiddens, get_hard_negative, \ Data from util import Logger import argparse import numpy as np import os import random import torch.nn as nn from transformers import BertT...
#!/usr/bin/env python3 import argparse import random import biotools as bt # setup parser = argparse.ArgumentParser( description='Generates random FASTA files.') # required arguments parser.add_argument('--count', required=True, type=int, metavar='<int>', help='number of sequences') parser.add_argument('--min', r...
""" @name: PyHouse/src/Modules/Computer/Web/_test/test_web_schedules.py @author: D. Brian Kimmel @contact: D.BrianKimmel@gmail.com @copyright: (c) 2016-2017 by D. Brian Kimmel @license: MIT License @note: Created on Nov 23, 2016 @summary: Test """ __updated__ = '2020-02-14' # Import system type st...
# rawmanifest.py # # Copyright 2013-2016 Facebook, Inc. # # This software may be used and distributed according to the terms of the # GNU General Public License version 2 or any later version. """Output (a subset of) the manifest as a bser serialisation Outputs raw manifest data The manifest can be updated with the c...
from __future__ import absolute_import from __future__ import unicode_literals from corehq.apps.reports.datatables import DataTablesHeader, DataTablesColumn from corehq.apps.reports.generic import GenericTabularReport from corehq.apps.reports.standard import CustomProjectReport, DatespanMixin from corehq.apps.reports.u...
from tqdm import tqdm import requests import time import click import re def download_video(url, index, filename): """ Downloads a video and saves it by its name plus index for easy sorting """ print("\n" + filename + "\n") maximum_retries = 5 with open(f"{index}-{filename}.mp4", 'wb') as...
from utils.search import BaiduEngine from utils.constant import we_load_dict, load_ap import csv import multiprocessing import time import redis import ujson key_set, company_suffix = we_load_dict() ap = load_ap() redis_host = '172.18.18.173' redis_db = 2 pool = redis.ConnectionPool(host=redis_host, port=6379, ...
from numpy import array, ndarray from datagears.core.network import Depends, Maybe def add(a: int, b: int = 10) -> int: return a + b def reduce(c1: int, sum: Maybe[int] = Depends(add)) -> int: result = sum - c1 return result def add_one() -> int: return 1 def my_out(reduced: Maybe[int] = Depend...
from collections import Counter from sys import * from collections import defaultdict as dd from math import * # sys.stdin = open('input.txt', 'r') # sys.stdout = open('output.txt', 'w') #input functions def inp(): return int(stdin.readline().strip()) def vinp(): return map(int,stdin.readline().strip().sp...
from functools import partial import logging import os from threading import Thread import time from prometheus_client import start_http_server, Counter, Gauge, Histogram # Note: code below contains additional imports called only when feature is enabled # TODO metric declarations should be based on enabled sensors => ...
#!/usr/bin/env python import re import requests import requests_html import string # Queries for the MediaWiki backend. # Documentation here: https://www.mediawiki.org/wiki/API:Categorymembers CATEGORY = "Category:Japanese_katakana" LIMIT = 500 INITIAL_QUERY = f"https://en.wiktionary.org/w/api.php?action=query&format...
"""Provide utilities""" import ast import inspect import sys import warnings from contextlib import contextmanager from enum import Enum, auto from functools import lru_cache, singledispatch from types import FrameType from typing import Any, Callable, Generator, Mapping, Tuple from diot import Diot from executing imp...
from tqdm import tqdm import pandas as pd import matplotlib.pyplot as plt import matplotlib import numpy as np import math from dateutil.relativedelta import relativedelta from datetime import datetime, date import os, sys import time if 'SUMO_HOME' in os.environ: tools = os.path.join(os.environ['SUMO_HOME'], 'to...
from __future__ import annotations import jax.numpy as np from jax import vmap from jax.tree_util import register_pytree_node_class, tree_flatten, tree_unflatten from jax.flatten_util import ravel_pytree import jax.scipy.optimize from tensorflow_probability.substrates import jax as tfp import ssm.distributions as ssmd...
"""Custom decoder definition for transducer model.""" from typing import Any from typing import Dict from typing import List from typing import Optional from typing import Tuple from typing import Union import torch from espnet.nets.pytorch_backend.transducer.blocks import build_blocks from espnet.nets.pytorch_backe...
# C01P13 - Integer prime factorization # Video - https://youtu.be/CR_19VUt0tI def is_prime(n): if n < 2: return False for d in range(2, n): if n % d == 0: return False return True def next_prime(n): n = n + 1 while not is_prime(n): n = n + 1 return n ...
""" SensorPush for Home Assistant See https://github.com/rsnodgrass/hass-sensorpush """ import logging import time from datetime import timedelta import voluptuous as vol from requests.exceptions import HTTPError, ConnectTimeout from homeassistant.core import callback from homeassistant.helpers import config_validati...