content
stringlengths
5
1.05M
import distutils.log distutils.log.set_verbosity(distutils.log.DEBUG) import os.path import cffi ffibuilder = cffi.FFI() shared_path = os.path.abspath(os.path.join(os.path.dirname(__file__), '../../picohttpparser')) print(shared_path) ffibuilder.set_source("libpicohttpparser", """ ...
#!/usr/bin/env python from leginon import leginondata import event import threading from pyami import ordereddict import sys target_types = ('acquisition', 'focus', 'preview', 'meter') class TargetHandler(object): ''' nodes should inherit this if they want to work with targets ''' ############# DATABASE INTERACTI...
# coding: utf-8 """ Mux API Mux is how developers build online video. This API encompasses both Mux Video and Mux Data functionality to help you build your video-related projects better and faster than ever before. # noqa: E501 The version of the OpenAPI document: v1 Contact: devex@mux.com Gener...
# def print_cube(num): # """ # function to print cube of given num # """ # print("Cube: {}".format(num * num * num)) # def print_square(num): # """ # function to print square of given num # """ # print("Square: {}".format(num * num)) # if __name__ == '__main__': # # creating pro...
# Generated by the protocol buffer compiler. DO NOT EDIT! # source: peer/fabric_proposal.proto import sys _b=sys.version_info[0]<3 and (lambda x:x) or (lambda x:x.encode('latin1')) from google.protobuf import descriptor as _descriptor from google.protobuf import message as _message from google.protobuf import reflect...
import os import json import glob import sqlite3 with sqlite3.connect("data.db") as conn: c = conn.cursor() c.execute("drop table if exists github") c.execute(""" create table github ( owner text, name text, description text, language text, ...
# coding: utf-8 # Copyright (c) Pymatgen Development Team. # Distributed under the terms of the MIT License. from __future__ import division, unicode_literals """ Development script to test the algorithms of a given model coordination environments """ __author__ = "David Waroquiers" __copyright__ = "Copyright 2012, ...
from django.apps import AppConfig class RedboxConfig(AppConfig): name = 'redbox'
# flake8: noqa """collection of common Remo physics constants. """ # descritions from REMO #!C** #!C** BESCHREIBUNG DER VARIABLEN: #!C** T0 : NULLPUNKT DER TEMPERATUR (K) #!C** R : GASKONSTANTE FUER TROCKENE LUFT (J/(KG*K)) #!C** RD : GASKONSTANTE FUER WASSERDAMPF ...
import net_sir_sim as sim import enum class EnumResult(): def get(self, msg): return msg.value @enum.unique class BaseModel(enum.Enum): EGO = 'Ego' BOWDOIN = 'Bowdoin47' HAVERFORD = 'Haverford76' SIMMONS = 'Simmons81' FB01 = 'Facebook01' FB02 = 'Facebook02' FB03 = 'Facebook03...
def get_php_detectd_exec(php_init): return """ $a=array('system', 'exec', 'shell_exec', 'passthru', 'proc_open', 'popen','pcntl_exec'); if(@!function_exists('get_ini_value')) { %s } $disabled = explode(',', get_ini_value('disable_functions')); foreach ($a as $v){ if (function_ex...
import gc import os import pickle import threading import time from timewise.general import main_logger from timewise.parent_sample_base import ParentSampleBase logger = main_logger.getChild(__name__) class BigParentSampleBase(ParentSampleBase): """ This should not be used. It was a bad idea. The better way...
'''Tests for querying provenance information''' import unittest import requests_mock from geoengine.types import InternalDatasetId, Provenance, ProvenanceOutput import geoengine as ge class ProvenanceTests(unittest.TestCase): '''Test runner for provenance tests''' def setUp(self) -> None: ge.reset(...
#!/usr/bin/env python3 import optparse import struct def convert(opts): edges_count = 0 with open(opts.output, "wb") as out_file: for line in open(opts.input): if line.startswith("#"): continue (src, tgt) = line.split() out_file.write(struct.pack("<l"...
import cv2 def sketch(image): img_gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY) img_gray_blur = cv2.GaussianBlur(img_gray, (5, 5), 0) canny_edges = cv2.Canny(img_gray_blur, 10, 70) ret, mask = cv2.threshold(canny_edges, 70, 255, cv2.THRESH_BINARY_INV) return mask cap = cv2.VideoCaptu...
# -*- coding: utf-8 -*- # @Time : 8/9/2021 12:10 PM # @Author : Paulo Radatz # @Email : pradatz@epri.com # @File : smart_inverter_functions.py # @Software: PyCharm class SmartInverterFunction: def __init__(self, dss, bus, kV_base, kW_rated, kVA, smart_inverter_function): self.dss = dss ...
from sys import * import copy as cc def main(): print("\n----COPY FILE-----\n") if len(argv)>3 or len(argv)<2 or len(argv)==1: print("INVALID ARGUMENT\nEnter -u for Usage\nEnter -h for Help") if len(argv)==2: if argv[1]=="-u" or argv[1]=="-U": print("USAGE : This is u...
from __future__ import print_function import unittest import json from bs4 import BeautifulSoup from knowledge_repo import KnowledgeRepository from knowledge_repo.app.models import Comment, Post, User from knowledge_repo.app.proxies import db_session class CommentTest(unittest.TestCase): def setUp(self): ...
# Calcule a soma entre todos números ímpares múltiplos de 3, entre 1 e 500 stock = 0 for count in range(1, 501): # Também pode fazer range(1, 501, 2) ou range(3, 501, 3). E tirar metade do IF abaixo if count % 2 != 0 and count % 3 == 0: stock += count print(f'{count} - {stock}') print(f'\n{stock...
__author__ = 'dcyoung23' import math from scipy import stats ''' ConfidenceInterval = ci ConfidenceLevel = cl SampleErrors = X SampleSize = n Population = N SampleErrorRate = phat ''' def wilson_ci(ci,cl,X,n,N): phat = float(X)/n alpha = 1-cl z = stats.norm.ppf(1-alpha/ci) # Break down calculation...
from random import randint soma = 0 resultado = 1 sorteio = randint(0, 10) while resultado != 0: print('---' * 13) print('Vou escolher um numero entre 0 e 10 aleatoriamente') usuario = int(input('tente a sorte escolha um numero 1 a 10: ')) soma += 1 if sorteio == usuario: resultado = 0 ...
# coding=utf-8 ''' Problem 50 15 August 2003 The prime 41, can be written as the sum of six consecutive primes: 41 = 2 + 3 + 5 + 7 + 11 + 13 This is the longest sum of consecutive primes that adds to a prime below one-hundred. The longest sum of consecutive primes below one-thousand that adds to a prime, c...
import logging from googleapiclient.discovery import build from googleapiclient.errors import HttpError from oauth2client.client import GoogleCredentials from cache_service import CRMProjects, CRMProjectIam, CRMFolders, CRMFolderIam, ServiceAccountService, \ ServiceAccountKeyService, BQDataset, BQDatasets, GCSBucke...
import pandas as pd import numpy as np import instrumentdb as idb import math import pickle def good_entries(ohlcv, min_days = 3, days_out = 15, vola_len = 35, days_pos = 0.6, stop_loss = 1.5): if days_out <= min_days: raise RuntimeError('days_out must be greater than min_days.') hi = ohlcv['high'] ...
import cv2 # Video capture settings PICAMERA = False FRAME_WIDTH = 480 CAMERA_FPS = 30 DISPLAY = True # Motion detection settings BACKGROUNDSUB_FRAMES = 256 DISTANCE_TO_THRESHOLD = 16 DETECT_SHADOWS = False # Object detection settings COCO_LABELS_PATH = 'yolo-coco/coco.names' YOLO_CONFIG_PATH = 'yolo-coco/yolov4/yol...
from sqlalchemy import Column, Integer, BigInteger, String from src import constants as const class Server(const.BASE): __tablename__ = 'server' server_id = Column(BigInteger, primary_key=True) server_name = Column(String, nullable=False) message_chance = Column(Integer, default=25) image_chance...
def __main(): b = open('F:\\_Algorithm_Assignment\\9\\input.txt') n = int(next(b)) a = [0]*n c = next(b)[0:-1] a = [int(i) for i in c.split(' ')] print(BestServe(a,n)) c = 1 def BestServe(a,n): a = FastSort(a) alltime = 0 for i in range(n): alltime += (n-i)*a[i] ...
from _pytest.logging import LogCaptureFixture from ddb.__main__ import main from ddb.config import Config class TestErrorHandling: def test_invalid_jsonnet(self, project_loader, caplog: LogCaptureFixture): Config.defaults = None project_loader("invalid-jsonnet") exceptions = main(["conf...
#!/usr/bin/env python3 """ pgmerge - a PostgreSQL data import and merge utility. Copyright 2018-2021 Simon Muller (samullers@gmail.com) """ import logging import networkx as nx from sqlalchemy import inspect from typing import Any, List, Optional from . import db_graph _log = logging.getLogger(__name__) def print...
row,col = map(int,input().split()) arr = [] for i in range(row): arr.append(list(map(int,input().split()))) n,m = map(int,input().split()) chg = m*n bchg = m*n*2 for i in range(row): for j in range(col): if i==0 or j==0 or i==row-1 or j==col-1: print(arr[i][j]+bchg,end=" ") else: print(arr[i][j]+chg,end=" ") pri...
#------------------------------------------------------------------------------ # Copyright (c) 2005, Enthought, Inc. # All rights reserved. # # This software is provided without warranty under the terms of the BSD # license included in enthought/LICENSE.txt and may be redistributed only # under the conditions describe...
# -*- coding: utf-8 -*- """Generic RDF utility methods to parse and serialize RDF.""" import logging import sys from rdflib import Graph def read_rdf(sources, infmt): """Read a list of RDF files and/or RDF graphs. May raise an Exception.""" rdf = Graph() for source in sources: if isinstance(sou...
import os os.system('cd .. \n bash ./scripts/demo_pix3d.sh')
from pyrogram import Client from pyrogram import filters from pyrogram.types import Message as message @Client.on_message(filters.command(["id"]) & (filters.private | filters.group)) async def showid(client, message): user_id = message.chat.id await message.reply_text( f"Your ID : `{user_i...
"""Netatmo base class.""" import time import requests import logging from http.client import HTTPConnection # log = logging.getLogger("urllib3") # log.setLevel(logging.DEBUG) # # HTTPConnection.debuglevel = 1 # TODO: Save token locally to reuse it. save/load methods needed class Netatmo: def __init__(self, cl...
# AUTOGENERATED! DO NOT EDIT! File to edit: nbs/datasets/datasets.steam.ipynb (unless otherwise specified). __all__ = ['SteamDataset'] # Cell import os import ast import json import pandas as pd import numpy as np from ..utils.common_utils import * from .bases.common import Dataset # Cell class SteamDataset(Datase...
############################################################################## # # Copyright (c) 2003-2018 by The University of Queensland # http://www.uq.edu.au # # Primary Business: Queensland, Australia # Licensed under the Apache License, version 2.0 # http://www.apache.org/licenses/LICENSE-2.0 # # Development unti...
from jumpscale import j import textwrap import time app = j.tools.prefab._getBaseAppClass() class PrefabWordpress(app): NAME = "wordpress" def _init(self): self.user = "wordpress" def build(self, reset=False): """ build wordpress 1- install php 2- install mysql ...
# -*- coding: utf-8 -*- from odoo import models, fields, api, SUPERUSER_ID, _ from odoo.exceptions import UserError, ValidationError #from odoo.tools import float_is_zero import logging _logger = logging.getLogger(__name__) # class {{pascalCase name}}(models.Model): # _name = '{{snakeCase name}}.{{snakeCase name...
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return "" shortest = min(strs, key=len) for i, c in enumerate(shortest): for str in strs: i...
#!/usr/bin/env python # -*- coding: utf-8 -*- #author:range #refer:http://wooyun.org/bugs/wooyun-2015-094886 def assign(service, arg): if service == "metinfo": return True, arg def audit(arg): payload1 = '/admin/include/common.inc.php?met_admin_type_ok=1&langset=123&met_langadmin[123][]=1234...
from setuptools import setup, find_packages # read the contents of your README file from os import path this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f: long_description = f.read() version = '0.0.8' author = 'nucklehead' github_url = f...
import datetime DESCRIBE_SNAPSHOTS = [ { 'Description': 'Snapshot for testing', 'Encrypted': True, 'OwnerId': '000000000000', 'Progress': '56', 'SnapshotId': 'sn-01', 'StartTime': datetime.datetime(2018, 10, 14, 16, 30, 26), 'State': 'completed', 'Vol...
from random import random from core import ( create_total_selection, colors, tokenize_sentences, summarize ) class App: text = '' selection = [] sentences = [] priorities = [] @staticmethod def set_text(text: str): App.text = text @staticmethod def reduce(): ...
# -*- coding: utf-8 -*- from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): def __unicode__(self): return self.username
#!/usr/bin/python3 -u import random import string import subprocess def random_string(n): return ''.join(random.choice(string.ascii_lowercase) for _ in range(n)) def check_pow(bits): r = random_string(10) print(f"hashcash -mb{bits} {r}") solution = input("Solution: \n").strip() if subprocess.call(...
#Desafio: Faça um programa que leia um número qualquer e mostre seu fatorial. # Ex: 5! = 5 X 4 X 3 X 2 X 1 = 120 num = int(input('Digite um número inteiro: ')) num1 = num res = num while res > 1: num = num * (res - 1) res = res - 1 print('O fatorial de {} é {}'.format(num1, num))
# coding: utf-8 from __future__ import unicode_literals from .common import InfoExtractor class SkylineWebcamsIE(InfoExtractor): _VALID_URL = r'https?://(?:www\.)?skylinewebcams\.com/[^/]+/webcam/(?:[^/]+/)+(?P<id>[^/]+)\.html' _TEST = { 'url': 'https://www.skylinewebcams.com/it/webcam/italia/lazio/r...
# -*- coding: utf-8 -*- from __future__ import absolute_import from abc import abstractmethod, abstractproperty from hotline.command import Command class Mode(object): prompt = None def __init__(self, app): self.app = app def __str__(self): return self.label def __hash__(self): ...
import numpy as np import cv2 import yaml from numpy.linalg import inv with open('camera_calibration.yaml') as f: loaded_dict = yaml.load(f) mtx = loaded_dict.get('camera_matrix') mtx = np.asarray(mtx) dist = loaded_dict.get('dist_coeff') dist = np.asarray(dist) 39.71869 imagePoints = np.array([[722, 539], [351,...
cont = 0 num = 0 flag = 0 while num != 999: num = int(input("insert any number, please: to exit of program type 999 ")) if num == 999: flag = num else: num = num sume = num + num cont += 1 print('end') print(''' the total of number inserted was {}'''.format(cont)) print("tot...
# Copyright (c) 2021 - present / Neuralmagic, Inc. 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 b...
import cv2 import sys img = cv2.imread("039.png" , cv2. IMREAD_GRAYSCALE) if img is None : print("Image load failed!") sys.exit() cv2.namedWindow('banana Image') cv2.imshow("banana Image", img) cv2.waitKey(0) cv2.destroyAllWindows()
#!/usr/bin/env python from __future__ import print_function from __future__ import unicode_literals from __future__ import division from __future__ import absolute_import from builtins import open from future import standard_library standard_library.install_aliases() import json from grq2.lib.geonames import get_citi...
"""Walk maximums temperature in Celsius""" import lisptick HOST = "uat.lisptick.org" PORT = 12006 def main(): """Ask for max temperatures at Poitiers airport""" conn = lisptick.Socket(HOST, PORT) # maxium T° progression since start date # change T° form Kelvin to Celsius print("Maximum T° progres...
"""Handlers that compose handlers.""" __all__ = [ 'Chain', 'MethodRouter', 'PathPatternRouter', # Context. 'PATH_MATCH', 'get_path', 'get_path_str', 'group', ] import re from g1.bases import labels from g1.bases.assertions import ASSERT from .. import consts from .. import wsgi_apps ...
''' Copyright (c) 2015-2016 Skylable Ltd. <info-copyright@skylable.com> License: see LICENSE.md for more details. ''' from django.contrib import messages from django.http import Http404 from django.shortcuts import redirect from django.utils.translation import ugettext_lazy as _ from .views import UserViewMixin def...
import xgboost as xgb import crast.sampling import numpy as np import crast.ctree import crast.shap from matplotlib import pyplot as plt import seaborn as sbn def violin_plot(SVs, labels, out_path, x_min = -1, x_max = 1, y_labels = []): nsamples = len(SVs) nftrs = len(SVs[0]) g1_idxs = [] g2_idxs = [] ...
import tensorflow as tf import numpy as np from keras.datasets import mnist from keras.models import Sequential from keras.layers import Dense, Dropout, Flatten, Conv2D, MaxPool2D from keras import backend as k import keras batch_size = 100 num_classes = 10 epochs = 10 filas,columnas = 28,28 (xt,yt),...
"""This module contains the general information for RackUnitPersonality ManagedObject.""" from ...imcmo import ManagedObject from ...imccoremeta import MoPropertyMeta, MoMeta from ...imcmeta import VersionMeta class RackUnitPersonalityConsts: pass class RackUnitPersonality(ManagedObject): """This is RackUn...
from setuptools import setup, find_packages __version__ = '1.0.1' long_desc = """Deckparser O Deckparser é um pacote Python que implementa importadores de dados para os arquivos de entrada dos modelos oficiais do sistema elétrico brasileiro. Os modelos NEWAVE, DECOMP e DESSEM são os formatos contemplados. Estes model...
import aiosqlite import discord from discord.ext import commands import discordSuperUtils class Leveling(commands.Cog, discordSuperUtils.CogManager.Cog): def __init__(self, bot): self.bot = bot self.LevelingManager = discordSuperUtils.LevelingManager(bot, award_role=False) self.ImageMana...
# coding=UTF-8 # ex:ts=4:sw=4:et=on # Copyright (c) 2013, Mathijs Dumon # All rights reserved. # Complete license can be found in the LICENSE file. from .insitu_behaviour import InSituBehaviour from .SSSR0Behaviour import SSSR0Behaviour __all__ = [ "InSituBehaviour", "SSSR0Behaviour" ]
from django.test import TestCase from .models import Chef,Recipe,foods import datetime as dt from django.test import TestCase from .models import Image, Category, Location # Create your tests here. class ChefTestClass(TestCase): # Set up method def setUp(self): self.cynthia= Chef(first_name = 'Cynthia...
"""SCGI XMLRPC Transport. XMLRPC in Python only supports HTTP(S). This module extends the transport to also support SCGI. SCGI is required by rTorrent if you want to communicate directly with an instance. Example: Small usage example literal blocks:: from xmlrpc.client import ServerProxy proxy = Server...
from collections import OrderedDict from pprint import pprint as pp scores = [10, 50, 100, 175, 250, 400, 600, 800, 1000] belts = 'white yellow orange green blue brown black paneled red'.split() HONORS = OrderedDict(zip(scores, belts)) MIN_SCORE, MAX_SCORE = min(scores), max(scores) def get_belt(user_score)...
#sorting the queue import queue q = queue.Queue() q.put(100) q.put(67) q.put(11) q.put(8) q.put(13) # Here, we use bubble sort algorithm for sorting n = q.qsize() for i in range(n): # Remove the element x = q.get() for j in range(n-1): # Remove the element ...
import numpy import decimal class GammaCalculator: def __init__(self, weights, nSlots): assert nSlots>0, "NSLOTS MUST BE POSITIVE" self.nDocs = len(weights) self.nSlots = nSlots self.nTypes = 0 self.weightToType = {} self.typeToWeight = [] self.typeToDo...
#!/usr/bin/env python # # Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright 2017 theloop, 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 req...
# -*- coding: utf-8 -*- """ Created on Wed Apr 01 21:38:37 2015 @author: Mickael Grima """ import logging import sys import time from collections import defaultdict, namedtuple from sortedcontainers import SortedListWithKey from optimizedGPS import options __all__ = [] log = logging.getLogger(__name__) class Sim...
# make sure to set SESSION_COOKIE_HTTPONLY to False import requests FORUM_URL = 'https://misago-project.org/' USERNAME = '' PASSWORD = '' s = requests.Session() # make a GET request to the token API endpoint url = '{}/api/auth/token/'.format(FORUM_URL) r = s.get(url) # extract the CSRF token csrftoken = s.cookies...
import maya.cmds as mc def isContainer(node): ''' Check if node is a valid container node. @param containerNode: Node to check as container. @type containerNode: str ''' # Check Node Exists if not mc.objExists(node): return False # Check Node Inheritance if not 'containerBase' in mc.nodeType(node,i=True): ret...
#!/usr/bin/env python3 """ A simple calendar made with rofi and python3. Cycle through month and create linked note to days. """ __license__ = "MIT-0" import glob, os, sys, subprocess, shutil import re, argparse, configparser import datetime, calendar, locale from itertools import chain from functools import wraps ...
''' Created on 13 Mar 2012 @author: brian ''' from __future__ import division # make sure that all division results in floating point numbers from PyQt4.QtGui import ( QMatrix ) from PyQt4.QtCore import ( Qt, QObject, QPointF, QRegExp, QFile, QIODevice, QTextStream, QString ) from pycasadata import...
from vision.model import PathModel from vision import convolution from vision import * from vision.visualize import highlight_box from vision import features from vision.toymaker import * from PIL import Image import numpy import pylab from scipy.io import savemat as savematlab import logging logging.basicConfig(level...
from sklearn.feature_extraction.text import CountVectorizer as fuckkk from sklearn.feature_extraction.text import TfidfVectorizer as tf from sklearn.model_selection import train_test_split as fuck from sklearn.ensemble import RandomForestClassifier from sklearn.model_selection import cross_val_score from sklearn.linear...
# # This source file is part of the EdgeDB open source project. # # Copyright 2008-present MagicStack Inc. and the EdgeDB authors. # # 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...
"""Test the data generation for the f16 gcas""" import random from typing import Dict import torch from neural_clbf.datamodules.episodic_datamodule import EpisodicDataModule from neural_clbf.systems.tests.mock_system import MockSystem params: Dict[str, float] = {} model = MockSystem(params) def test_episodic_data...
import django_filters from ...app import models from ..utils import filter_by_query_param def filter_app_search(qs, _, value): if value: qs = filter_by_query_param(qs, value, ("name",)) return qs class AppFilter(django_filters.FilterSet): search = django_filters.CharFilter(method=filter_app_sea...
import pandas as pd from torch.utils.data import Dataset class Dataset(Dataset): def __init__( self, data: pd.DataFrame ): self.data = data def __len__(self): return len(self.data) def __getitem__(self, index): 'Generates one sample of data' # Select ...
from airflow.hooks.postgres_hook import PostgresHook from airflow.models import BaseOperator from airflow.utils.decorators import apply_defaults class DataQualityOperator(BaseOperator): """ Performs data quality checks on fact and dim tables. For now, just makes sure they have some rows. Redshift should e...
#!/usr/bin/env python # annotate transcripts with reference annotation from GENCODE or RefSeq # annotation files can be: 1. GFF file from RefSeq 2. GFF file from GENCODE import os import sys import argparse as ag from lncmodule import organizeGencodeGFF from lncmodule import organizeRefSeqGFF from lncmodule import ...
from django.urls import path from . import views urlpatterns = [ path('predict/', views.predict, name='result'), path('', views.formclass, name='classifier') ]
import MySQLdb class Connection_factory(object): def get_connection(self): connection = MySQLdb.connect( host="localhost", user="root", passwd='', db='alura') return connection
from __future__ import unicode_literals import os import uuid import json import datetime import pytz B58_CHARS = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' B58_BASE = len(B58_CHARS) def b58encode(s): """Do a base 58 encoding (alike base 64, but in 58 char only) From https://bitcointalk.o...
import scipy scipy.test()
#!/usr/bin/env python3 import pytest from MCP2221 import MCP2221 def testDeviceInfo(): mcp2221 = MCP2221.MCP2221() info = mcp2221.GetDeviceInfo() m = "manufacturer" in info p = "product" in info s = "serial" in info assert (m, p, s) == (True, True, True) def testWriteReadFlash(): mcp2...
""" link: https://leetcode.com/problems/decode-ways problem: 给定非负数组,用 ord 顺序代表 chr,问有几种可能的组合方式 solution: DP。注意存在字符0,且0不可转换 """ class Solution: def numDecodings(self, s: str) -> int: def ff(ss: str): return (ord(ss[0]) - 48) * 10 + ord(ss[1]) - 48 if len(s) == 0: return 0 f ...
# Generated by Django 2.1.7 on 2019-02-22 01:14 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('torrents', '0003_auto_20190222_0029'), ] operations = [ migrations.AddField( model_name='torrent', name='download_lo...
# Generated by Django 2.2.10 on 2020-04-27 21:27 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('categories', '0005_auto_20200104_2144'), ('searching', '0006_auto_20200421_2250'), ] operations = [ ...
from tibanna.stepfunction_cost_updater import StepFunctionCostUpdater def test_StepFunctionCostUpdater(): sf = StepFunctionCostUpdater() assert sf.sfn_start_lambda == 'Wait' assert sf.definition['States'] == sf.sfn_state_defs assert sf.definition['StartAt'] == 'Wait' assert 'Wait' in sf.sfn_state_d...
# -*- coding: utf-8 -*- """ Created on Tue Mar 16 11:13:37 2021 @author: dv516 """ import numpy as np import pickle import pyro pyro.enable_validation(True) # can help with debugging pyro.set_rng_seed(1) from algorithms.PyBobyqa_wrapped.Wrapper_for_pybobyqa import PyBobyqaWrapper from algorithms.Bayesian_opt_Pyro....
snapshots_select__snapshot_sql = """ {% snapshot snapshot_castillo %} {{ config( target_database=var('target_database', database), target_schema=schema, unique_key='id || ' ~ "'-'" ~ ' || first_name', strategy='timestamp', updated_at='"1-updated_a...
# coding: utf-8 # # Copyright 2022 :Barry-Thomas-Paul: Moss # # 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 applicab...
import os.path import re import logging from gii.core import AssetLibrary, AssetManager, getProjectPath def getFntTexture( path ): fp = open( path, 'r' ) txt = fp.read() fp.close() pattern = re.compile('page id=\w+ file="(\w+(\.\w+)?)"') result = [] for mo in pattern.finditer( txt ): filename = mo.group( 1 ) ...
import argparse import tableprint from piicatcher.dbexplorer import SqliteExplorer, MySQLExplorer def get_parser(parser_cls=argparse.ArgumentParser): parser = parser_cls() parser.add_argument("-s", "--host", required=True, help="Hostname of the database. File path if it is SQLite") ...
from inqbus.rpi.widgets.base.display import Display from inqbus.rpi.widgets.interfaces.display import IDisplay from zope.interface import implementer @implementer(IDisplay) class ConsoleDisplay(Display): """ Displays the changes of the gui on the console. Mostly usefull for debugging or developing on ...
import os as _os import io import numpy as _np from datetime import datetime as _datetime import math as _math from . import config from bs4 import BeautifulSoup as _BS import urllib.request, urllib.parse, urllib.error import urllib.request, urllib.error, urllib.parse import requests import pandas as pd ...
import sys import math def main(): for word in sys.stdin: word = list(word.rstrip()) n = len(set(word)) # case 1 all distinct # n! is how many different ways we can arrange this word if n == len(word): print(math.factorial(n)) continue # case 2 duplicates # take the factoria...