content
stringlengths
5
1.05M
import weakref from .utils import Owned __all__ = ['Binds'] class Input: """Discreptor for inputs, can only be assigned once.""" def __get__(self, instance, owner): if instance is None: return self try: return instance.__dict__['__input__'] except KeyError: ...
# encoding: utf-8 """ Custom element classes that correspond to the document part, e.g. <w:document>. """ from .xmlchemy import BaseOxmlElement, ZeroOrOne, ZeroOrMore from .ns import qn, nsmap class CT_Document(BaseOxmlElement): """ ``<w:document>`` element, the root element of a document.xml file. """ ...
from .. import moment import numpy as np import pandas as pd import datetime as dt import tzlocal import pytz import time class TestMoment: def test_moment(self): test0 = float(1580780607) test = test0 assert moment.Moment(test)._posix == test0 test = dt.datetime.fromtimestamp(test...
# Copyright 2016 Leon Poon and Contributors # # 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 ...
#!/usr/bin/env python ## ## See COPYING file distributed along with the ncanda-data-integration package ## for the copyright and license terms ## import os import re import glob import shutil import zipfile import tempfile import subprocess import sibis import check_gradient_tables as cgt # # Verify image count in...
from django.shortcuts import render from django.http.response import HttpResponse, JsonResponse from django.views import generic from django.views.decorators.csrf import csrf_exempt from django.utils.decorators import method_decorator import speech_recognition as sr import requests import json import os class SpeechT...
import random num_arr=[] Prefix_number=["0915","0912","0910"] final="" for total in range(0,500): for num in range(0,7): n=random.randint(0,9) num_arr.append(n) if num == 6: for j in num_arr: final=final+str(j) print(random.choice(Prefix_num...
""" API endpoints """ from flask import jsonify, request, Response, current_app as app from flask_github_signature import verify_signature from app import limiter from app.api import api from app.data_tools import ( get_age_chart_data, get_admins_per_region, get_admins_timeseries_chart_data, get_admins_per_pro...
from moto.swf.models import GenericType import sure # noqa # Tests for GenericType (ActivityType, WorkflowType) class FooType(GenericType): @property def kind(self): return "foo" @property def _configuration_keys(self): return ["justAnExampleTimeout"] def test_type_short_dict_repr...
# coding: utf-8 import random import numpy as np import celery from keras.models import model_from_json from models import Song import utils import writer from settings import MEMORY_LENGTH, MAX_SONG_LENGTH, MODEL_ARC_PATH, MODEL_CHARS_PATH, MODEL_WEIGHTS_PATH class WriterException(Exception): pass model ...
import sys import collections import numpy as np import pandas as pd from sklearn import tree from sklearn.ensemble import RandomForestClassifier from sklearn.metrics import confusion_matrix from sklearn.metrics import accuracy_score import matplotlib.pyplot as plt continuous_columns_global = [0,4,11,12,13,14,15,16,17...
from onegov.agency.custom import get_global_tools from onegov.agency.custom import get_top_navigation from onegov.agency.forms import UserGroupForm from onegov.agency.initial_content import create_new_organisation from onegov.agency.pdf import AgencyPdfAr, AgencyPdfBs from onegov.agency.pdf import AgencyPdfDefault from...
from django.db import models from django.contrib.postgres.fields import JSONField # Create your models here. class Notepad(models.Model): url = models.CharField(max_length=100, blank=True, null=True) notes = JSONField(blank=True, null=True) def __str__(self): return self.url
from .mongodbconnectionmanager import MongoDbConnectionManager from .mongosessioninterface import MongoSessionInterface
# -*- coding: utf-8 -*- """ Created on Thu Feb 1 19:41:21 2018 @author: Gabo """ import numpy as np import matplotlib.pyplot as plt import os #%% ## Importar datos ## # Funciones útiles: # np.loadtxt, np.load, np.genfromtxt, csv.reader (leer: https://docs.python.org/2/library/csv.html) os.chdir(r'un\path\cualquie...
from os import path from setuptools import setup, find_packages with open('requirements.txt') as f: requirements = f.readlines() this_directory = path.abspath(path.dirname(__file__)) with open(path.join(this_directory, 'README.md')) as f: long_description = f.read() setup( name='idasen-controller', v...
# -*- coding: utf-8 -*- # BioSTEAM: The Biorefinery Simulation and Techno-Economic Analysis Modules # Copyright (C) 2020, Yoel Cortes-Pena <yoelcortes@gmail.com> # # This module extends the reaction module from the chemicals library: # https://github.com/CalebBell/chemicals # Copyright (C) 2020 Caleb Bell <Caleb.Andre...
""" Add color bar """ from ...tk.matplotlibTK import color_bar from typing import Dict from .make_color_bar_axis import make_color_bar_axis def add_color_bar(params): # type: (Dict) -> Dict """Refine legend properties Args: params (dict): plotting parameter dictionary Returns: same a...
#!/usr/bin/env python # -*- coding: UTF-8 -*- """ @Email: guangmingwu2010@gmail.com \ guozhilingty@gmail.com @Copyright: go-hiroaki & Chokurei @License: MIT """ import math import torch import torch.nn as nn import torch.nn.functional as F from community import lpips from community import fid eps = 1...
import time from . import Tstat6 global MAX_PRIORITY MAX_PRIORITY = 10 global MIN_PRIORITY MIN_PRIORITY = 0 #format for lists is ID, priority, is on (1/0), mode, can switch (1/0) global equip # Compare the priority of two devices. If priority is the same, # prefer the device that we can actuate. def compare_prior...
from django import forms class ContactForm(forms.Form): subject = forms.CharField(max_length=100) message = forms.CharField() sender = forms.EmailField()
#!/usr/bin/env python import os import os.path import sys import subprocess import socket # gethostname() import re # regular expression #from optparse import OptionParser import getopt # http://docs.python.org/2/library/collections.html#collections.deque from collections import deque # double-ended queue import inspe...
import networkx as nx import seaborn as sns import pandas as pd from matplotlib import pyplot as plt def get_random_graphs(num_graphs=500, num_nodes=20, edge_prob=0.3): # returns a list of random networkx graphs graph_list = [] for i in range(num_graphs): graph = nx.fast_gnp_random_graph(num_nodes...
from .config import get_train_parser as gvae_parser from .config import get_generate_parser as gvae_generate_parser #from .model_cvae import CVAE as GVAE #from .model_gvae import Model as GVAE from .model_gvae_v2 import Model as GVAE from .trainer import GVAETrainer from .generator import GVAEGenerator __all__ = ['gva...
import os from flask import render_template, request, current_app, send_from_directory, flash, redirect, url_for, abort from flask_login import login_required, current_user from sites.extensions import db from sites.forms.main import DescriptionForm, TagForm, CommentForm from sites.models import Photo, Tag, PhotoComm...
# General imports import collections import numpy as np import pandas as pd import matplotlib.axes # Import task and users from bandit.envs import MultiBanditTask from bandit.agents import RW, WSLS, RandomPlayer # Import development helper bundle from modelchecks import ModelChecks # Seed for reproduceability of the...
# Qhue is (c) Quentin Stafford-Fraser 2014 # but distributed under the GPL v2. import requests import json class QhueException(Exception): pass class Resource(object): def __init__(self, url, timeout=5): self.url = url self.timeout = timeout def __call__(self, *args, **kwargs): u...
import tensorflow as tf from configuration import NUM_CLASSES class FireModule(tf.keras.layers.Layer): def __init__(self, s1, e1, e3): super(FireModule, self).__init__() self.squeeze_layer = tf.keras.layers.Conv2D(filters=s1, kernel_size=(1, 1), ...
a="this is a example of reverse indexing string" print(a[::-1]) b="hello world" print(b[8])
from bs4 import BeautifulSoup as bs import os import re import urllib import pandas as pd from institutionList import institutions import time, datetime from dateutil.relativedelta import relativedelta BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def parse_form_13F(): #--...
from data.base_dataset import BaseDataset, get_transform from data.image_folder import make_dataset from util.util import normalize from skimage import io from util import util import numpy as np class DiceImageDataSet(BaseDataset): """This dataset class loads a single 3D image volume and dice it into cubes. --da...
import torch import torch.nn as nn import torch.nn.functional as F class SobelConv2d(nn.Module): def __init__(self, in_channels, out_channels, kernel_size=3, stride=1, padding=0, dilation=1, groups=1, bias=True, requires_grad=True): assert kernel_size % 2 == 1, 'SobelConv2d\'s kernel_siz...
from setuptools import setup import re import os import sys from shutil import rmtree, copytree requirements = [] with open("requirements.txt", "r") as f: requirements = f.read().split("\n") version = None with open("campfire/__init__.py", "r") as f: version = re.search(r'^__version__\s*=\s*[\'"]([^\'"]*)[\'"...
# model for our postgres database # to upgrade the db schema, run: #> python manage.py db migrate #> python manage.py db upgrade # in the virtualenv from server import db from sqlalchemy.dialects.postgresql import JSON class User(db.Model): __tablename__ = 'users' id = db.Column( db.Integer, primary_key=...
# Copyright 2019 The Feast 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 # # https://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in wr...
#0<average_memory &le; 0.037<br/>mse = 0.014<br/>samples = 5002<br/>value = 0.078> #0 -> 1 [headlabel="True", labelangle=45, labeldistance="2.5"]; import os import json from flask import jsonify tree_num = 5 dir_path = os.path.dirname(os.path.abspath(__file__)) def partition(arr,low,high): i = ( low-1 ) ...
# 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 # "License"); you may not u...
import asyncio import copy import logging import os import traceback from asyncio import AbstractEventLoop from typing import Text, Optional from sanic import response, Blueprint, Sanic from sanic.response import json as jsonify from sanic_jwt import protected from sanic_restful_api import Api, Resource from app impo...
# Copyright (c) 2016-present, Facebook, Inc. # All rights reserved. # # This source code is licensed under the BSD-style license found in the # LICENSE file in the root directory of this source tree. An additional grant # of patent rights can be found in the PATENTS file in the same directory. import freeswitch impo...
# -*- coding: utf-8 -*- # ------------------------------------------------------------------------------ # # Copyright 2018-2019 Fetch.AI Limited # # 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 ...
import re from os.path import join from jiwer import wer from io_operations.load_files import load_transcription def transcription_test(ref_path, filename, hyp_path, verbose): ref = load_transcription(join(ref_path, filename)) hyp = load_transcription(join(hyp_path, filename)) ref_texts = ['', ''] hy...
import copy from pprint import pprint def find_all_diffs(adapter_list): adapter_list_high = copy.deepcopy(adapter_list) adapter_list_high.append(max(adapter_list)+3) adapter_list_high.sort() adapter_list_low = copy.deepcopy(adapter_list) adapter_list_low.insert(0, 0) adapter_list_low.sort() ...
import sys import os from parameterized import parameterized sys.path.append(os.path.abspath("../")) from unittest import TestCase, mock from icon_cisco_umbrella_destinations.connection.connection import Connection from icon_cisco_umbrella_destinations.actions.dGet import DGet from icon_cisco_umbrella_destinations.ac...
import boto3 AWS_ACCESS_KEY_ID = "KEY_VALUE" AWS_SECRET_ACCESS_KEY = "SECRET_KEY_VALUE" AWS_DEFAULT_REGION = "ap-northeast-2" logs = boto3.client('logs', aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY, region_name=AWS_DEFA...
import pandas as pd import matplotlib.pyplot as plt from matplotlib.colors import LinearSegmentedColormap from matplotlib.offsetbox import TextArea, AnnotationBbox import numpy as np import seaborn as sns from statistics import mean,stdev from matplotlib import rc if __name__ == '__main__': rc('font', **{'family'...
def is_palindrome(yarn): """Return whether or not a string is a palindrome. A palindrome is a word/phrase that's the same in both directions. """ return yarn == yarn[::-1]
"""Image Processing: image manipulation and image info routines """ # Copyright 2017-2018 Matthew A. Clapp # # 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/licens...
import pygame, sys, easygui, glob import constants from player import Player from platform import Platform from map import Map from textfunctions import * from camera import Camera from button import Button if pygame.joystick.get_count() > 0: controller = pygame.joystick.Joystick(0) controller.init() else: controll...
# -*- coding: utf-8 -*- """ Created on Fri Apr 13 19:24:33 2018 @author: DrLC """ import socket import sys import time import numpy import matplotlib.pyplot as plt DEFAULT_IP = 'localhost' DEFAULT_PORT = 2333 DEFAULT_BUFSIZE = 1024 DEFAULT_TIMEOUT = 10 DEFAULT_LENGTH = 1000 DEFAULT_FIGURE_PATH = "../results/rate.jpg...
from logik import * from logik.sat import * from utils import equivalent def test_remove_implications(): # base expression expr = ('->', ('symb', 'a'), ('symb', 'b')) # base expression without implications exprA = sat.remove_implications(expr) # expected result exprB = ('ou', ('non', ('symb',...
## Exercice avec les fichiers ## Calculer la moyenne des notes d'un fichier, une note par ligne import statistics notes = [] with open('notes.txt', 'r') as f: # pour chaque ligne du fichier for note in f: notes.append(int(note)) total = sum(notes) moyenne = total / len(notes) print(f"La moyenne des no...
#!/usr/bin/env python3.7 # Copyright (c) 2018-2019 Lynn Root """ Initial setup - starting point based off of http://asyncio.readthedocs.io/en/latest/producer_consumer.html Notice! This requires: - attrs==19.1.0 To run: $ python part-0/mayhem_1.py Follow along: https://roguelynn.com/words/asyncio-initial-setup/...
def database(my_input): from firebase import firebase # converting to upper case my_input = my_input.upper() # storing the first letter first_letter = my_input[0] fireurl = ('https://nemo-bot-9ae9c.firebaseio.com/%s/' % first_letter.upper()) firebase = firebase.FirebaseApplication(...
#!/usr/bin/env python # coding: utf-8 # # Copyright 2010 Alexandre Fiori # based on the original Tornado by Facebook # # 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....
from setuptools import setup, find_packages from mailify import __version__ setup( name = "django-mailify", version = __version__, description = "Enhance the builtin Django mail functionality to " + \ "include task queueing or deferment.", author = "Keith Hall", author_email = "code@keith....
import unittest import os import sys PACKAGE_ROOT = '../..' SCRIPT_DIR = os.path.dirname(os.path.realpath(os.path.join(os.getcwd(), os.path.expanduser(__file__)))) PACKAGE_PATH = os.path.normpath(os.path.join(SCRIPT_DIR, PACKAGE_ROOT)) sys.path.append(PACKAGE_P...
import pynvim as nvim from typing import List from tmuxdir.rplugin import TmuxDirPlugin from tmuxdir.tmux_session_facade import TmuxFacadeException from tmuxdir.util import echoerr, expanduser_raise_if_not_dir @nvim.plugin class TmuxDirRPlugin: def __init__(self, nvim: nvim.Nvim) -> None: try: ...
# utils.py # External imports from numpy.linalg import norm # Normalize vector def normalize(vector): return vector/norm(vector)
from iexfinance.stocks import Stock from scraper import popularTickers IEX_TOKEN = "ENTER YOUR OWN" def closePrice(ticker): a = Stock(ticker, token = IEX_TOKEN) previousClose = a.get_quote()['previousClose'] currentClose = a.get_quote()['iexClose'] return previousClose, currentClose x, y = popula...
# See LICENSE for licensing information. # # Copyright (c) 2016-2019 Regents of the University of California and The Board # of Regents for the Oklahoma Agricultural and Mechanical College # (acting for and on behalf of Oklahoma State University) # All rights reserved. # from globals import OPTS class sram_factory: ...
import os, sys, time import datetime from datetime import datetime, timedelta from pytz import timezone import mysql.connector import logging DIR = os.path.dirname(os.path.realpath(__file__)) sys.path.insert(1, DIR+'/../src/garage') sys.path.insert(1, DIR+'/../src/greenhouse') sys.path.insert(1, DIR+'/../s...
## @ingroup Components-Energy-Networks # PyCycle.py # # Created: Sep 2020, E. Botero # Modified: # ---------------------------------------------------------------------- # Imports # ---------------------------------------------------------------------- # package imports import numpy as np from copy import deepcopy ...
from global_ import * from global_var_ import MINIMUM_SEEN_MOVIES, MINIMUM_SEEN_USERS import pandas as pd import numpy as np from collections import Counter from sklearn.preprocessing import MultiLabelBinarizer import scipy from tqdm import tqdm import itertools as it # Loading data def load_data(path, dataset_type=...
import matplotlib.pyplot as plt import numpy as np import scipy as sc import sounddevice as sd def generate_signal_from_spectrum(C_k: np.ndarray)-> np.ndarray: """ generates a real valued time domain signal from frequency coefficients for ifft. Signal is aprox. scaled to ~[-1;1]. :param C_k: np.n...
#!/bin/bash # -------------------------------------------------- # Filename: Update_Initialization.py # Revision: 1.0 # Data: 2018/12/09 # Author: Yue Cao # Email: ycao009@cs.ucr.edu # Description: Update the initialization of target variables at source code. Then compile codes and link the bc files...
#!/usr/bin/python # coding=utf-8 from . import GetDht11,GetSys,GY30,HCSR04,SR501
import re from django import template register = template.Library() @register.filter def strip_cut_tags(text): ''' Strips partial tags that might have left at the end of cut html string after the `striptags` filter. ''' return re.sub(r'<[^>]+?(\.*)$', ' \1', text) @register.filter def message_t...
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Wed Dec 2 11:28:26 2020 Copyright 2020 by Hadrien Montanelli. """ # Standard imports: from math import factorial, pi, sqrt import numpy as np from scipy.special import lpmv def spharm(l, m): """Return spherical harmonic Y_{l,m}.""" if (m >=0): ...
#----------------------------------------------------------------------------- # Copyright (c) 2013-2022, PyInstaller Development Team. # # Distributed under the terms of the GNU General Public License (version 2 # or later) with exception for distributing the bootloader. # # The full license is in the file COPYING.txt...
import tempfile from mock import MagicMock, patch def test_CommandList(): """ Test the CommandList class """ from router.command import CommandList clist = CommandList() clist.append(20, "b") clist.append(20, "c") clist.append(10, "a") commands = list(clist.commands()) asser...
# OBSOLETE, DO NOT USE def main(): import tbaapiv3client import csv TOKEN = "REPLACEME" class Api: def __init__(self, token): self.token = token # config = tbaapiv3client.Configuration() config.api_key["X-TBA-Auth-Key"] = self.token ...
""" Platform for DS-AIR of Daikin https://www.daikin-china.com.cn/newha/products/4/19/DS-AIR/ """ import logging from homeassistant.config_entries import ConfigEntry from homeassistant.const import CONF_HOST, CONF_PORT from homeassistant.core import HomeAssistant from .const import CONF_GW, DEFAULT_HOST, DEFAULT_PORT...
from django.contrib import messages from django.contrib.auth import views as auth_views from django.contrib.auth.mixins import ( LoginRequiredMixin, UserPassesTestMixin, ) from django.contrib.auth.tokens import default_token_generator from django.http import ( HttpRequest, HttpResponse, ) from django.sh...
# -*- coding: utf-8 -*- import sys from PyQt5 import QtWidgets from PyQt5.QtCore import pyqtSlot from PyQt5.QtWidgets import QApplication, QTreeView from jsonTreeView import JsonModel, final_mapping, mapping_test_old, mapping_test_new, mapping_test_select from treeveiwUI import Ui_Form class TreeView(QtWidgets.QWi...
import glob import math import os.path from random import sample from unidecode import unidecode from collections import Counter import matplotlib.pyplot as plt import numpy as np #import sys #sys.stdout = open('rez_odstavki.txt','wt') # FUNKCIJE def kmers(s, k): # s je beseda iz kjere terko nardimo for ...
# -*- coding: utf-8 -*- """Feature selection tools. @authors: Lantian ZHANG """ import pandas as pd import numpy as np def selection_with_iv_corr(trans_woe, encoded_X, threshold_corr=0.6): """Retrun a table of each feature' IV and their highly correlated features to help users select features. Parameters ...
# -*- coding: utf-8 -*- """ Created on Sat Dec 17 11:41:46 2016 @author: Myself """ from functools import wraps from collections import namedtuple _parameters = {} def boundry(func): points = func() if points[0] != points[-1]: try: points.append(points[0]) except Exception: ...
#!/usr/bin/env python3 import asyncio import asyncpg # import datetime async def main(dsn='postgresql://postgres:passwd+123@localhost/test'): # Establish a connection to an existing database named "test" # as a "postgres" user. conn = await asyncpg.connect(dsn) await conn.execute(''' DROP TAB...
import boto3 import json # enter bucket name BUCKET_NAME = 'new-s3-bucket-spinningops' def s3_client(): s3 = boto3.client('s3') return s3 def create_bucket(bucket_name): """ creates a new s3 bucket """ return s3_client().create_bucket( Bucket=bucket_name, CreateBucketConfiguration=...
# coding: utf-8 """ @Topic: @Date: 2021/2/1 @Author: other.z @Copyright(C): 2020-2023 other.z Inc. All rights reserved. """ import json import functools from custombot.core.lex.functional import * def __get_string(value): if isinstance(value, Scope): return str(value) elif isinstance(value,...
#!/usr/bin/env python # coding=utf-8 import json host1ip = ['192.168.31.101'] host2ip = ['192.168.31.102','192.168.31.103'] group = 'k8s-master' group2 = 'k8s-nodes' hostdata = {group:{"hosts":host1ip},group2:{"hosts":host2ip}} print (json.dumps(hostdata,indent=4)) #ansible -i test.py all -m ping -vvv
import threading import numpy as np import tensorflow as tf import pylab import time import gym from keras.layers import Dense, Input from keras.models import Model from keras.optimizers import Adam from keras import backend as K # global variables for threading episode = 0 scores = [] EPISODES = 200...
import sys if __name__ == "__main__": import asamplelib.cli sys.exit(asamplelib.cli.main()) # pragma: no cover
# every episode, switch the replay buffer # train a neural network # use a special loss function # https://github.com/jetsnguns/realtime-policy-distillation
 # https://github.com/decisionforce/ESPD from stable_baselines.common.policies import MlpPolicy from stable_baselines import DQN import random from torch import ...
from tir import Webapp import unittest class ATFA012(unittest.TestCase): @classmethod def setUpClass(inst): inst.oHelper = Webapp() inst.oHelper.Setup("SIGAATF", "01/04/2016", "T1", "D MG 01 ", "01") inst.oHelper.Program("ATFA012") inst.oHelper.AddParameter("MV_UL...
from typing import Callable, Dict, List, Optional from web3 import Web3 from brownie.network.middlewares import BrownieMiddlewareABC class TxRevertCatcherMiddleware(BrownieMiddlewareABC): """ Middleware to handle reverting transactions, bypasses web3 error formatting. As of web3.py version 5.13.0, a n...
# -*- coding: utf-8 -*- import os all_bins = ['expand', 'ls', 'ptx', 'sha1sum'] def get_overhead(fp): with open(fp) as f: ohs = eval(f.read()) return (sum(ohs[1:]) / len(ohs[1:]) / ohs[0] - 1.0) * 100 #def table_perf(): # print(' ' * 17 + ' 10 30 50 100') # perfs = ['10', ...
import random import inspect from TBC.core.Tasklet import Tasklet class Task(Tasklet): """ An aggregate of one or more Tasklets """ def __init__(self, parent, path): super(Task, self).__init__(parent, path) self._tasklets = self._gather_tasklets() self._next_tasklet = None ...
import numpy as np import logging, os np.random.seed(1) np.set_printoptions(precision=10) try: name = os.environ['SISFFT_LOG'].upper() if name: logging.basicConfig(level = getattr(logging, name)) except KeyError: pass # logging.basicConfig(level = logging.INFO)
"""Multivariate t-distribution. Author: Gregory Gundersen 2020. Architecture based on SciPy's `_multivariate.py` module by Joris Vankerschaver 2013. """ import numpy as np from scipy._lib._util import check_random_state from scipy.stats._multivariate import _PSD, multi_rv_generic, multi_rv_frozen from scipy.spec...
from chargebee.api_error import APIError,PaymentError,InvalidRequestError,OperationFailedError from chargebee.models import * from chargebee.main import ChargeBee def configure(api_key, site): ChargeBee.configure({ 'api_key': api_key, 'site': site, })
import random import operator import abc class Gene: def __init__(self): return class Individual(object): __metaclass__ = abc.ABCMeta __sequence = [] Fitness: int = 0 def __init__(self, sequence): self.__sequence = sequence return @abc.abstractmethod def calculate...
from browserist import Browser def test_get_all_window_handles(browser_default_headless_scope_function: Browser) -> None: browser = browser_default_headless_scope_function assert browser.window.handle.count(selenium=True) == browser.window.handle.count(selenium=False) == 1 browser.window.open.new_tab() ...
import numpy as np SIZE = 12 def beautify_print_matrix(A, b, format="{:3}"): for A_i, b_i in zip(A,b): print((" ".join([f"{format}" for i in range(len(A_i))]) + f" | {format}").format(*A_i, b_i)) def symmetric(A, b): return A.T @ A, A.T @ b diag_A = np.array([[ 73, -8, -1, -2, 2, -9, 3, 1, -10, ...
from __future__ import absolute_import import numpy as np import matplotlib.pyplot as plt from .. import utils from ..config import DEFAULT_POPULATION_COLORS class NeuroVis(object): '''This class is used to visualize firing activity of single neurons. This class implements several conveniences for visualiz...
""" This module implements the `se lint` command. """ import argparse import regex from termcolor import colored import se from se.se_epub import SeEpub def lint() -> int: """ Entry point for `se lint` """ parser = argparse.ArgumentParser(description="Check for various Standard Ebooks style errors.") parser....
#! /usr/bin/env python ############################################################################## ## DendroPy Phylogenetic Computing Library. ## ## Copyright 2010-2015 Jeet Sukumaran and Mark T. Holder. ## All rights reserved. ## ## See "LICENSE.rst" for terms and conditions of usage. ## ## If you use this wo...
# -*- coding: utf-8 -*- import os import numpy as np import argparse import logging import matplotlib.pyplot as plt import matplotlib.image as mpimg from index import extract_feat try: import cPickle as pickle except: import pickle logger = logging.getLogger(__name__) logging.basicConfig(level=logging.INFO) ...
import os from flask import make_response from flask import request from flask_restful import Resource from .common_rest import RestCommon from fields import ADMIN_TOKEN_FIELD_NAME class Logs(Resource): def __init__(self, rest_helper: RestCommon, log_dir: str = "../logs/"): super().__init__() se...
def build_empirical_cov(kdiffs,kcoadds,wins,mask,lmins,lmaxs, anisotropic_pairs,do_radial_fit,save_fn, signal_bin_width=None, signal_interp_order=0, delta_ell=400, rfit_lmaxes=None, ...