content
stringlengths
5
1.05M
import os from helpers import d2df import numpy as np def filenames(project_path): #project_path = os.path.realpath('..') #project_path = os.path.dirname(os.path.realpath(__file__)) #project_path = project_path + os.sep + ".." output = {} # Input files output["dataset_raw"] = project_path + o...
from __future__ import absolute_import, division, print_function import torch from torch.autograd import Variable from pyro.distributions.torch_distribution import TorchDistribution from pyro.distributions.util import broadcast_shape class Delta(TorchDistribution): """ Degenerate discrete distribution (a si...
# coding=utf-8 import requests def get_hitokoto_info(): """ 从『一言』获取信息。(官网:https://hitokoto.cn/) :return: str,一言。 """ print('获取一言...') try: resp = requests.get('https://v1.hitokoto.cn/', params={'c': 'e', 'encode': 'text'}) if resp.status_code == 200: return "开心一言:\r...
from __future__ import print_function import datetime import ipywidgets import os import sys import traceback from IPython.display import display global tee_file tee_file = None # http://stackoverflow.com/questions/29772158/make-ipython-notebook-print-in-real-time class flushfile(): def __init__(self, f): ...
import copy import logging import emcee import numpy as np import numpy.random as random from gbkfit.utils import funcutils, iterutils, parseutils import gbkfit.params.utils as paramutils import gbkfit.params.utils from gbkfit.fitting.prior import prior_parser from gbkfit.fitting.core import FitParam, FitParams, F...
import re from bottle import request from babel import support from .config import Config # Format of http.request.header.Accept-Language. # refs: http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.4 REQUEST_ACCEPT_LANGUAGE_RE = re.compile(r''' ([A-Za-z]{1,8}(?:-[A-Za-z]{1,8})*|\*) # "en", "en-au...
from pycoingecko import CoinGeckoAPI cg = CoinGeckoAPI() def print_coin(coin): print(coin['symbol'], "--- current price: ", coin['current_price'], "$") def sort_by_cap(e): return e['market_cap_rank'] while True: n = int(input("Enter number to filter: ")) coin_list = cg.get_coins_markets("usd")[:n] ...
import json from aiohttp import web from aiohttp.web_urldispatcher import StaticResource from aiohttp_apispec import setup_aiohttp_apispec from yarl import URL def test_app_swagger_url(aiohttp_app): def safe_url_for(route): if isinstance(route._resource, StaticResource): # url_for on StaticRe...
import unittest import json from GitCraw.verify import Verify class TestVerify(unittest.TestCase): def set_up(self): self.verify = Verify() def testKeywordsOk(self): self.set_up() result = self.verify.verified_type("Issues") self.assertEqual(True,result) def testKeywords...
# Generated by Django 3.1.4 on 2020-12-29 01:57 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('home', '0007_auto_20201228_2020'), ] operations = [ migrations.AddField( model_name='shop', name='description', ...
# Copyright 1999-2021 Alibaba Group Holding Ltd. # # 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 a...
# Relative imports from ._estimator import GaussianProcessEstimator __all__ = ['GaussianProcessEstimator']
from . import _version from .display import TyphosDeviceDisplay from .func import TyphosMethodButton from .panel import TyphosCompositeSignalPanel, TyphosSignalPanel from .plugins import register_signal from .positioner import TyphosPositionerWidget from .suite import TyphosSuite from .utils import load_suite, patch_co...
# Generated by Django 3.2.6 on 2021-08-27 02:00 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('app', '0025_alter_report_embed_code'), ] operations = [ migrations.AddField( model_name='usersubmission', name='publ...
from .tokens import error_at, merge_locations from .debug import recur_print def make_ast(tokens,args): # kept up to date by match # is an array so match can edit it lastloc = [tokens[0]["loc"]] # match one of several tokens by kind, # remove that token from the tokens list, # return the...
import json from ibm_watson import LanguageTranslatorV3 from ibm_cloud_sdk_core.authenticators import IAMAuthenticator import os from dotenv import load_dotenv load_dotenv() apikey = os.environ['apikey'] url = os.environ['url'] authenticator = IAMAuthenticator(apikey) language_translator = LanguageTranslatorV3( ...
import numpy as np import librosa import matplotlib.pyplot as plt import scipy.io as sio # constant function test_vector = np.ones(200) stft = librosa.stft(test_vector, hop_length=25, n_fft=100, win_length=100, window='hamming') noise = np.random.random(stft.shape) stft = stft + noise istft = librosa.istft(stft, hop_l...
from hamcrest import assert_that, equal_to, is_ from marshmallow import Schema, fields from microcosm_flask.swagger.api import build_parameter from microcosm_flask.swagger.decorators import swagger_field class MixedField(fields.Field): __swagger_type__ = ["integer", "string"] class TestSchema(Schema): deco...
# Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre sua média. n1 = float(input('Digite a primeira nota:')) n2 = float(input('Digite a segunda nota:')) media = (n1 + n2) / 2 print("A média entre {:.1f} e {:.1f} é igual a {:.1f}".format(n1, n2, media))
import pytest from deepforest import RandomForestClassifier from deepforest import ExtraTreesClassifier from deepforest.forest import _get_n_samples_bootstrap # Load utils from sklearn.ensemble._hist_gradient_boosting.binning import _BinMapper from sklearn.datasets import load_iris, load_wine from sklearn.ensemble._f...
__author__ = 'JordSti' import ctypes import os class sprite_header(ctypes.Structure): _fields_ = [('sprite_name', ctypes.c_char * 64), ('nb_frames', ctypes.c_int32), ('width', ctypes.c_int32), ('height', ctypes.c_int32)] class sprite_image_marker(ctypes.Structure): _fields_ = [('lengt...
# log21.FileHandler.py # CodeWriter21 from logging import FileHandler as _FileHandler from log21.Formatters import DecolorizingFormatter as _DecolorizingFormatter class DecolorizingFileHandler(_FileHandler): terminator = '' def emit(self, record): if self.stream is None: self.stream = se...
#!/usr/bin/env python import glob from setuptools import setup setup(name='hanzo-warc-tools', version='0.2', license="MIT License", description='Command line tools and libraries for handling and manipulating WARC files (and HTTP contents)', author='Thomas Figg', author_email='thomas.fi...
#encoding=utf-8 ''' 天气 webservice: wsdl:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx?wsdl 描述:http://www.webxml.com.cn/WebServices/WeatherWebService.asmx getSupportCity( ) ''' from suds.client import Client from suds.xsd.doctor import ImportDoctor,Import #Import和DoctorImport是提供wsdl中缺...
# # Copyright (c) 2021 Airbyte, Inc., all rights reserved. # from abc import ABC from typing import Any, Iterable, List, Mapping, MutableMapping, Optional, Tuple from datetime import datetime, timedelta import requests from airbyte_cdk.sources import AbstractSource from airbyte_cdk.sources.streams import Stream from...
""" tools ======= This module is a collection of small Python functions and classes which make common patterns shorter and easier. It is by no means a complete collection but you can keep extending it. If you need any other convenient utilities, you would add them inside this module. """ import numpy as np import sys...
__author__ = 'Dante' from reaction import BrendaReaction from reaction import SDFReaction from databases import db_queries as dbq import numpy as np from rdkit import Chem from rdkit.Chem import MCS import fingerprinter as fptr import pybel from sklearn.cluster import AgglomerativeClustering as AC from skle...
import json from collections import Counter import sys from tqdm import tqdm from search.search import bulk_text_query from utils.lcs import LCSubStr from utils.io import load_json_file from utils.general import chunks, make_context from utils.corenlp import bulk_tokenize from scripts.gen_hop1 import CompositeLCS, ...
import functools from ..util import _six import socket from collections import namedtuple RemoteInfo = namedtuple('RemoteInfo', 'ip name') @functools.lru_cache() def get_request_remote_info(remote_ip): remote_name = socket.getnameinfo((remote_ip, 0), 0)[0] if remote_ip else None return RemoteInfo(ip=remote_ip, name...
from collections import Counter import code2vec.splitter as spl def _split_to_sentences(s): return [l.split() for l in s.split('\n')] jmethdeps_01 = { 'com.example.HelloWorld.main': [ 'java.util.ArrayList.<init>', 'java.util.List.addAll', ], 'com.example.HelloWorld.sub': [ '...
''' This module renders inline text containing Quote and Replacement elements. Quote and replacement processing involves splitting the source text into fragments where at the points where quotes and replacements occur then splicing fragments containing output markup into the breaks. A fragment is flagged as 'done'...
"""Solves problem 1 of Project Euler""" def sum_divisible_by_n(n, target=999): p = target/n return (n*p*(p+1))/2 if __name__=='__main__': print sum_divisible_by_n(3) + sum_divisible_by_n(5) - sum_divisible_by_n(15)
# Common settings for deployed servers # Will be imported by staging.py, production.py, etc., # and some settings possibly overridden. import socket from .base import * DATABASES = { "default": { "ENGINE": "django.db.backends.postgresql_psycopg2", "NAME": env_or_default('DB_NAME', ''), "U...
""" Representation of an Activity object """ from .trovebox_object import TroveboxObject from .photo import Photo class Activity(TroveboxObject): """ Representation of an Activity object """ _type = "activity" def __init__(self, client, json_dict): self.data = None self.type = None ...
# Generated by Django 3.1.4 on 2020-12-29 16:43 from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ("issues", "0001_squashed_0010_auto_20210117_1543"), ("events", "0001_initial"), ] operations = [ mig...
import tensorflow.compat.v1 as tf from tensorflow.python.saved_model import signature_constants from tensorflow.python.saved_model import tag_constants def convert_frozen_savedmodel(model_path, output_path, input_node, output_nodes): builder = tf.saved_model.builder.SavedModelBuilder(output_path) with tf....
import can from .at_serial_can import ATSerialBus
#!/usr/bin/python3 if __name__ == "__main__": import sys sum = 0 for i in range(len(sys.argv)): if i == 0: continue sum += int(sys.argv[i]) print("{:d}".format(sum))
# -*- encoding: utf-8 -*- """ Collection of utilities for debugging. :copyright: (c) 2016 H2O.ai :license: Apache License Version 2.0 (see LICENSE for details) """ from __future__ import division, print_function, absolute_import, unicode_literals import colorama import inspect import re import sys from colorama imp...
import json from pymongo import MongoClient client = MongoClient('proximus.modulusmongo.net:27017') client.tepO9seb.authenticate('nasahack', 'hacking4nasa') db = client.tepO9seb if __name__ == '__main__': counts = json.load(open('kw_counts.json')) nasa_kwds = counts['http://data.nasa.gov/data.json'].keys() ...
def getTimeFeatures(T, dateCol): T['year'] = T[dateCol].apply(lambda x: x.year) T['month'] = T[dateCol].apply(lambda x: x.month) T['day'] = T[dateCol].apply(lambda x: x.day) T['dow'] = T[dateCol].apply(lambda x: x.dayofweek) T['hour'] = T[dateCol].apply(lambda x: x.hour) T['days'] = (T[dateCol]-...
""" Analytic approximations for Schwarzschild QNMs. The approximations implemented in this module can be used as initial guesses when numerically searching for QNM frequencies. """ from __future__ import division, print_function, absolute_import import numpy as np def dolan_ottewill_expansion(s, l, n): """ Hig...
import argparse def test_set_param(setup, scene_root, history_db, current_scene_db, query_start, query_end): from src.praxxis.parameter import set_param from src.praxxis.parameter import list_param from src.praxxis.parameter import delete_param from tests.src.praxxis.util import dummy_object name...
#import #region import matplotlib.pyplot as plt import math #endregion #input and output #region inputPath_1 = 'example1.txt' inputPath_2 = 'example2.txt' outputPath_1 = 'outputPath_1.txt' #endregion # some stuff #region empty = lambda s: s != '' def Show(): return 0 def validate(): return 1 #endregio...
"""Implements the `GO` class for handling S. pombe gene ontology annotations. """ import os from contextlib import contextmanager from Bio.UniProt.GOA import gafiterator, record_has from goatools.obo_parser import GODag from goatools.associations import read_gaf from collections import defaultdict from .exceptions impo...
from consolemenu.console_menu import ConsoleMenu
"""PyTorch-backed modules and algorithms.""" from metarl.torch._functions import compute_advantages from metarl.torch._functions import dict_np_to_torch from metarl.torch._functions import filter_valids from metarl.torch._functions import flatten_batch from metarl.torch._functions import global_device from metarl.torch...
import os from django.http.response import Http404, HttpResponse from django.shortcuts import render from django.utils.encoding import smart_str from api.blackbuck import DATA_DIR from api.decorators import authenticated_user, no_test @no_test @authenticated_user def blackbuck_list(request): if not os.path.exis...
from django.conf import settings from django.db.models.signals import pre_save from django.utils.functional import curry from django.db.models.loading import get_model from auditlog.models import LogEntry class AuditLogMiddleware(object): """ Middleware to couple the request's user to log items. This is acco...
from pytorch_lightning.callbacks.base import Callback from uninas.methods.abstract import AbstractMethod from uninas.training.trainer.abstract import AbstractTrainerFunctions from uninas.utils.paths import replace_standard_paths from uninas.utils.args import ArgsInterface, Namespace class AbstractCallback(ArgsInterfa...
from icebath.core import build_xrds from icebath.core import build_gdf import os # import faulthandler # faulthandler.enable() def run_workflow(indir, fjord, outdir, outfn, metastr=None, bitmask=False): ds = build_xrds.xrds_from_dir(indir, fjord, metastr, bitmask) if ds is "nodems": # print("no dems ...
def bubbleSort(arrayToBeSorted): arrayLength = len(arrayToBeSorted); for i in range(arrayLength): for j in range(0, arrayLength-i-1): if arrayToBeSorted[j]> arrayToBeSorted[j+1]: # swap arrayToBeSorted[j], arrayToBeSorted[j+1]= arrayToBeSorted[j+1], arrayToBeS...
from __future__ import absolute_import from .base import Immutable class Provider(Immutable): subsystem = "infra" endpoint = "/provider" is_namespaced = False @classmethod def _pk_key(cls): return 'name' def delete(self): raise AttributeError("'delete' is not supported in 'P...
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** # *** 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 ...
import xml.etree.ElementTree as ET class Configuration: def __init__(self): self.tree = ET.parse('config.xml') self.root = self.tree.getroot() def getUsernamePassword(self,user): credentials = self.root.findall('login') for entry in credentials: if (entry.get('name'...
import numpy as np def _cmc_core(D, G, P): m, n = D.shape order = np.argsort(D, axis=0) match = (G[order] == P) return (match.sum(axis=1) * 1.0 / n).cumsum() def cmc(distmat, glabels=None, plabels=None, ds=None, repeat=None): """Compute the Cumulative Match Characteristic (CMC) This functio...
# -*- coding: utf-8 -*- ''' Author: David J. Morfe Application Name: Speech Handler for C.H.R.I.S. Functionality Purpose: Intake and process speech to recognize requested action ''' import speech_recognition as sr import time, re, os from .keys import CWD, api_key API_KEY = api_key() os.chdir(CWD) class SpeechHan...
import pyotp from django.conf import settings from rest_framework import serializers from rest_framework.exceptions import ParseError from rest_framework.validators import ValidationError from rest_framework_simplejwt.serializers import TokenObtainPairSerializer from .models import CustomUser from .tasks import send_v...
#!/usr/bin/env python #-*- encoding:utf-8 -*- import socket if __name__ == '__main__': s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) # 建立连接: s.connect(('127.0.0.1', 9999)) # 接收欢迎消息: print s.recv(1024) for data in ['Michael', 'Tracy', 'Sarah']: # 发送数据: s.send(data) ...
from Bio import SwissProt for record in SwissProt.parse(open('../0_DB/uniprot_sprot.dat')): pid=record.accessions[0] seq=record.sequence print ">"+pid+"\n"+seq+"\n"
import os import tool import random as rm import mysql.connector import sys from flask import Flask, render_template, redirect, url_for, request, session, jsonify from functools import wraps # DB connection conn = mysql.connector.connect(user='root', password='root', host="localhost", database="book") app = Flask(__n...
#-*- coding: utf-8 -*- """ Jeu du pendu en mode console, version simplifiée On se sert de la fonction 'index' (https://docs.python.org/3.6/tutorial/datastructures.html) pour trouver la position de la lettre proposée dans le mot à deviner 'index' ne renvoie que la position du premier item trouvé pour 'assis' on ne trouv...
''' A PyTorch implementation of MobileNetV2. The original paper can be found at https://arxiv.org/abs/1801.04381. ''' import math import numpy as np import torch import torch.nn as nn import torch.nn.functional as F from .activations import activetion_func class InvBottleneckBlock(nn.Module): def __init__(self...
import glob from shutil import copyfile import sys corpus=sys.argv[1] txt_dir=corpus+"/english/speakers/zs19_data/txt" wav_dir=corpus+"/english/speakers/zs19_data/wav" extension=".wav" all_txt_files=glob.glob(txt_dir+"/*") all_wav_files=glob.glob(wav_dir+"/*") assert len(all_wav_files)==len(all_txt_files),"There s...
# coding: utf-8 # from psydac.linalg.basic import LinearOperator, Matrix, Vector, VectorSpace from psydac.linalg.stencil import StencilMatrix from numpy import zeros as dense_null from scipy.sparse import coo_matrix as sparse_null __all__ = ['NullLinearOperator', 'NullMatrix', 'NullStencilMatrix'] class Nul...
import numpy as np from PIL import Image import matplotlib.pyplot as plt palette = [128, 64, 128, 244, 35, 232, 70, 70, 70, 102, 102, 156, 190, 153, 153, 153, 153, 153, 250, 170, 30, 220, 220, 0, 107, 142, 35, 152, 251, 152, 70, 130, 180, 220, 20, 60, 255, 0, 0, 0, 0, 142, 0, 0, 70, 0, 60, 100, 0...
from corehq.messaging.smsbackends.http.models import SQLHttpBackend class SQLSislogBackend(SQLHttpBackend): class Meta(object): app_label = 'sms' proxy = True @classmethod def get_api_id(cls): return 'SISLOG' @classmethod def get_generic_name(cls): return "Sislog...
# Deobfuscated BY HTR-TECH | Tahmid Rayat # Github : https://github.com/htr-tech # Instagram : https://www.instagram.com/tahmid.rayat # Facebook : https://fb.com/tahmid.rayat.oficial # Messenger : https://m.me/tahmid.rayat.oficial import argparse from collections import OrderedDict from pprint import pformat _...
""" A clean, no_frills character-level generative language model. CS 20: "TensorFlow for Deep Learning Research" cs20.stanford.edu Danijar Hafner (mail@danijar.com) & Chip Huyen (chiphuyen@cs.stanford.edu) Lecture 11 """ import os os.environ['TF_CPP_MIN_LOG_LEVEL']='2' import random import sys sys.path.append('..') im...
from pymoo.model.algorithm import Algorithm from pymoo.operators.sampling.latin_hypercube_sampling import LatinHypercubeSampling from pymoo.util.display import SingleObjectiveDisplay class RandomSearch(Algorithm): def __init__(self, n_points_per_iteration=100, sampling=LatinHype...
#FLM: Font: Move Diacritical Marks # VER: 1.0 #---------------------------------- # Foundry: Karandash # Typeface: Achates # Date: 05.08.2019 #---------------------------------- # - Dependancies import fontlab as fl6 from typerig.proxy import pFont, pGlyph, pShape from typerig.string import upper_diac_marks # - ...
# Generated by Django 3.2.3 on 2021-06-02 15:03 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] ope...
import re import requests import subprocess import time from time import sleep from log import log, log_add, now, RED, WHT, GRN, YEL # Named Constants # A local host that should always be up (ideally, the gateway router) Local_Host = "192.168.1.1" # An internet host that should always be up (Google DNS,for example) ...
#!/usr/bin/env python # -*- coding: utf-8 -*- """ test_flask-nsq ---------------------------------- Tests for `flask-nsq` module. """ import pytest from flask_nsq import Nsq from flask import Flask from .integration_server import NsqdIntegrationServer from gnsq import protocol as nsq from gnsq import states, errors ...
import os from collections import OrderedDict import yaml import json import tempfile import shutil import logging import hashlib from androidcrypto.sample import Sample from androidcrypto import helpers, constants class DatasetException(Exception): pass class Dataset: def __init__(self, root_path): ...
# # Context-Related Pages # import pscheduler from pschedulerapiserver import application from flask import request from .dbcursor import dbcursor_query from .json import * from .response import * # # Contexts # # All contexts @application.route("/contexts", methods=['GET']) def contexts(): return json_query(...
import xml.etree.ElementTree as et import sys with open(sys.argv[1], 'r') as f: r = et.parse(f) documents = r.findall('.//document') for doc in documents: elem = doc.findall('.//{http://collectionspace.org/collectionspace_core/}collectionspace_core') for e in elem: doc.remove(e)...
from setuptools import setup, find_packages import os def read(fname): try: return open(os.path.join(os.path.dirname(__file__), fname), 'r').read() except: return "" setup( name='aws-logging-handlers', packages=find_packages(), version='2.0.4', description='Logging aws_loggin...
################################################## # This is a library for the Adafruit DRV2605L Haptic Driver # # ----> http://www.adafruit.com/products/2305 # # Check out the links above for our tutorials and wiring diagrams # This motor/haptic driver uses I2C to communicate # # Adafruit invests time and resour...
from keras.models import Sequential from keras.layers import Dense from keras.layers import LSTM from keras.layers import Bidirectional from tensorflow import keras from scipy.signal import medfilt import matplotlib.pyplot as plt import pandas as pd import numpy as np from sklearn.preprocessi...
# -*- coding: utf-8 -*- from setuptools import setup packages = \ ['pureapi'] package_data = \ {'': ['*'], 'pureapi': ['schemas.old/517/*', 'schemas/518/*', 'schemas/519/*', 'schemas/520/*', 'schemas/521/*']} install_requires = \ ['addict', 'attrs>=19.3.0,<20.0.0'...
import numpy as np import cv2 import time # from simple_pid import PID cap = cv2.VideoCapture(0) # cap = cv2.VideoCapture('http://192.168.55.6:8080/video') # set res of camera settings = { "window_x": 320, "window_y": 240, "crop_window_height": 80, "contrast_high": 255, "contrast_low": 160, "c...
from ea_server.api.utils.constans import UNIFORM, ALPHA, INDPB from ea_server.model.ea_function_model import EaFunctionModel, KwargModel from deap import tools single_point = EaFunctionModel(function=tools.cxOnePoint, description="https://en.wikipedia.org/wiki/Crossover_(genetic_algorith...
import math import numpy as np import pandas as pd ## Tables for tabulated data fire methods def delta_a(eta_fi, gamma_s, fyk, as_req_prov): sig_s0 = np.array([20, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100, 1200]) sig_kt = np.array([1.0, 0.999999, 0.9, 0.85, 0.8, 0.6, 0.35, ...
# This code is a part of XMM: Generate and Analyse (XGA), a module designed for the XMM Cluster Survey (XCS). # Last modified by David J Turner (david.turner@sussex.ac.uk) 02/08/2021, 17:28. Copyright (c) David J Turner import os import warnings from typing import Tuple, List, Union import numpy as np import pandas...
################################################################################ # The Pyretic Project # # frenetic-lang.org/pyretic # # author: Michael Greenberg (mg19@cs.princeton.edu) ...
#=============================================================================== # # FILE: prep_hyperp_imp_v2.py # # USAGE: C:\apps\Anaconda3\python.exe prep_hyperp_imp_v2.py --count=1 --name=DemoImpModel --config="ConfigImp.yaml" > prep_hyperp_imp_v2_trace.txt 2>&1 # # DESCRIPTION: IMP (integrative...
#!/usr/bin/env python3 from distutils.core import setup setup( name='igcolors', url='https://github.com/innogames/igcolors', author='InnoGames System Administration', author_email='it@innogames.com', packages=[ 'igcolors', ], version='1.0', long_description=( 'Provide a...
class Solution(object): def longestCommonPrefix(self, strs): """ :type strs: List[str] :rtype: str """ if not strs: return "" end_index = 0 for group in zip(*strs): if len(set(group)) > 1: return strs[0][:end_index] ...
import os import signal from typing import Any from celery import Celery from celery.signals import worker_shutting_down from celery.utils.log import get_logger from django.conf import settings from video_transcoding import defaults app = Celery(defaults.CELERY_APP_NAME) app.config_from_object(defaults.VIDEO_TRANSCO...
import numpy as np import scipy.io as sio import stmpy def loadmat(filePath): ''' Load in all variables from a .mat file. If you want to list all the variables in the file, use >>> fo = sio.loadmat(filename) >>> list(fo) STM_View structures will be stored as dictionaries. Ignore any variables ...
import os import time import sqlite3 file = 'example.db' if os.path.exists(file): os.remove(file) conn = sqlite3.connect(file) c = conn.cursor() start = time.time() c.execute('''CREATE TABLE stocks (date text, trans text, symbol text, qty real, price real)''') for i in range(3000): c.execute(f"...
# Burp extension to test StyledDocument and custom styles. # support for burp-exceptions - see https://github.com/securityMB/burp-exceptions try: from exceptions_fix import FixBurpExceptions import sys except ImportError: pass from burp import IBurpExtender # needed for tab from burp import ITab class B...
from namecheapapi.api.domains import DomainAPI
from django.db import models from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from root import settings # This model refer to the generic type of model class Like(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, ...
# Copyright (c) 2010 Chris Moyer http://coredumped.org/ # # 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, ...
import re import PitchClass import Accidental """ 音度から半音数を取得する。 """ class Degree: _Pattern = re.compile(r'[1-9][0-9]*') _Degrees = ((1,0),(2,2),(3,4),(4,5),(5,7),(6,9),(7,11)) @classmethod def Get(cls, name:str): d, a = cls.__Split(name) degree = cls.__GetDegree(d) accidental = A...
''' Based on https://github.com/r9y9/deepvoice3_pytorch/blob/master/train.py ''' import os import numpy as np from config import config import frontend import util.audio as audio ######### TEMPLATE ########## class FileDataSource(object): """File data source interface. Users are expected to implement custum d...
import logging import yaml with open("/etc/staging_api/system.yml") as file: systems = yaml.load(file, Loader=yaml.FullLoader) def validate_encryption_input_body(input_data): try: logging.info(input_data["source_system"]) logging.info(input_data["source_path"]) source_system = input_d...
import os import argparse import torch import torch.nn as nn import sys import numpy as np # Append root directory to system path for imports repo_path, _ = os.path.split(os.path.realpath(__file__)) repo_path, _ = os.path.split(repo_path) sys.path.append(repo_path) from LMSCNet.common.seed import seed_all from LMSCNe...