content
stringlengths
5
1.05M
""" Example showing how to compute a family of basis polynomials """ # -------------------------------------------------------------------------------------------------------------------- # # Importing packages # --------------------------------------------------------------------------------------------------------...
"""seed: shared evaluation environment for sdn """ from setuptools import setup setup(name='seed', version='0.1.2', description='shared evaluation environment for sdn', url='https://git.scc.kit.edu/pdf-tm-ws1617/seed', author='Addis Dittebrandt, Michael Koenig, Felix Neumeister', author_...
from django import forms from django.contrib import admin from django.contrib.contenttypes import generic from bible import Verse, RangeError # python-bible from models import Scripture class ScriptureForm(forms.ModelForm): class Meta: model = Scripture def clean(self): # Checking to see if...
#!/usr/bin/python3 import logging import sys logging.basicConfig(stream=sys.stderr) sys.path.insert(0, '/app') from app import app as application application.secret_key = 'P4ssw0rd'
""" Django settings for myshop project. Generated by 'django-admin startproject' using Django 3.0.8. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os imp...
from abc import ABC import numpy as np import rl.common.Constant as CNSTNT class BaseControl(ABC): def __init__(self, env, discount_factor): self.action_space = env.action_space.n self.state_space = env.observation_space.n self.discount_factor = discount_factor self.PI = np.random....
import youtube_dl def download_video(url: str, output: str): ydl_opts = { 'outtmpl': output } with youtube_dl.YoutubeDL(ydl_opts) as ydl: ydl.download([url]) def get_info(url: str): with youtube_dl.YoutubeDL({}) as ydl: return ydl.extract_info(url, download=False, force_gener...
# flake8: noqa from .evaluation import distances
#!/usr/bin/python2.7 #!-*- coding: utf8 -*- import numpy as np import matplotlib.pyplot as plt # Carregando arrays a partir de arquivos X = np.load('data/X.npy') Y = np.load('data/Y.npy') U = np.load('data/U.npy') print "Quantos snapshots voce deseja?" N = input() # Definindo passo h = U.shape[2] / N counter = 0 ...
def escreva(texto): tam_string = len(texto) + 2 print('~' * tam_string) print(f' {texto:>2}') print('~' * tam_string) escreva('Olá, Mundo!') escreva('Palhaçada Descomunal')
"""Fauxmo plugin for simple MQTT requests. The on and off methods publish a value to the given MQTT queue. The get_status method subscribes to an MQTT queue to asynchronously receive the status published from the device. If the device doesn’t publish a status via MQTT then omit the state_cmd and the plugin will return...
# # DX Package # # Valuation -- Plotting Options Statistics # # plot_option_stats.py # # Python for Finance, 2nd ed. # (c) Dr. Yves J. Hilpisch # import matplotlib.pyplot as plt def plot_option_stats(s_list, p_list, d_list, v_list): ''' Plots option prices, Deltas and Vegas for a set of differe...
from mrcrowbar import models as mrc # source: http://dev.gameres.com/Program/Other/LZSS.C class LZSSCompressor( mrc.Transform ): N = 4096 F = 18 THRESHOLD = 2 def import_data( self, buffer, parent=None ): r = self.N - self.F flags = 0 text_buf = bytearray( b' '*(self.N+sel...
import json, subprocess from .... pyaz_utils import get_cli_name, get_params def disable(pool_id, account_name=None, account_key=None, account_endpoint=None): params = get_params(locals()) command = "az batch pool autoscale disable " + params print(command) output = subprocess.run(command, shell=Tr...
import inspect #inspired by: #https://stackoverflow.com/questions/5432964/is-it-somehow-possible-to-live-modify-python-code-like-in-lisp-or-erlang#comment6159803_5436556 def patchClass(old, new): print 'patching class', old, new for key in old.__dict__.keys(): if key not in new.__dict__: p...
import os import re import sys import pdb import numpy as np import pandas as pd import matplotlib.pyplot as plt from tensorflow import keras from tensorflow import debugging from tensorflow.keras import backend as K from tensorflow.keras.models import Sequential, load_model from tensorflow.keras.layers import Dense, ...
import json import logging from typing import Any, Generator, List, Optional from google.appengine.api import urlfetch from google.appengine.ext import ndb from backend.common.consts.webcast_status import WebcastStatus from backend.common.consts.webcast_type import WebcastType from backend.common.memcache import Memc...
#!/usr/bin/env python3 import csv from flask import Flask import yaml import logging from prettytable import from_csv import json # Instantiate a logger because we're taking user input and it can always go bad. logger = logging.getLogger(__name__) application = Flask(__name__) @application.route('/list') def list_it...
from datetime import datetime as dt from collections import namedtuple Jam = namedtuple('Jam', 'number, theme, start_datetime, timediff') def __get_jams(jams, api): return [Jam(**k) for k in api[jams]] def ongoing(api): r"""Is there an ongoing jam? :return: bool """ if len(api['current_jams']) ...
""" Asynchronous Advantage Actor Critic (A3C) Most of the work is done in `a3c_worker.py`. Based on: - Pseudo code from Asynchronous Methods for Deep Reinforcement Learning - Tensorflow code from https://github.com/yao62995/A3C/blob/master/A3C_atari.py and https://github.com/openai/universe-starter-agent/tree/f16f37d...
#!/usr/bin/env python3 """ YATIB - Yet Another Twitter IRC Bot Dependencies: requests python-irc python-twitter apt-get install python3-requests python3-irc python3-twitter Usage: ./yatib.py twitterbot_conf.ini Configuration file: [general] robust=no # whether to not die on unknown error [loggi...
# Generated by Django 3.1 on 2020-09-11 08:22 from django.db import migrations, models import wagtail.core.fields import wagtail_color_panel.fields class Migration(migrations.Migration): dependencies = [ ('home', '0014_homepage_title_icon'), ] operations = [ migrations.AddField( ...
import cv2 import numpy as np import matplotlib.pyplot as plt def image(img): #GaussianBlur img = cv2.GaussianBlur(img, (5,5), 0 ) #convert BGR to HSV hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) #defined the range of a color lower_color = np.array([0,0,30]) upper_color = np.array([180,43,19...
from django import forms from website.models import contact,NEWSLETTER from captcha.fields import CaptchaField class ContactForm(forms.ModelForm): captcha = CaptchaField() class Meta: model = contact fields = '__all__' class NewsletterForm(forms.ModelForm): class Meta: model = NEWS...
from typing import List, Tuple from sc2 import BotAI from sc2.ids.unit_typeid import UnitTypeId from .data import * class BOStep(): def __init__(self, condition, unit: UnitTypeId): self.condition = condition self.unit_id: UnitTypeId = unit def try_condition(self) -> bool: return self.c...
# -*- coding: utf-8 -*- from recommonmark.parser import CommonMarkParser templates_path = ['_templates'] source_suffix = '.md' source_parsers = { '.md': CommonMarkParser } master_doc = 'index' project = u'sphinxproj' copyright = u'2015, rtfd' author = u'rtfd' version = '0.1' release = '0.1' highlight_language = 'pyt...
# Copyright (c) 2019 Matthew Monteleone # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to i...
import RPi.GPIO as GPIO import time class Ultrasonic: def __init__(self): self.value = None self.trig_pin = 26 self.echo_pin = 11 self.setup() def setup(self): GPIO.setmode(GPIO.BOARD) def get_value(self): return self.value def upda...
import argparse import os from tqdm import tqdm import torch import pytorch_lightning as pl from vocab import Vocab from utils import load_data, load_sent, load_model, makedir, write from dataset import get_eval_dataloader def main(args): pl.seed_everything(args.seed) model = load_model(args.checkpoint).to(...
class Email: def __init__(self, sender, receiver, content, is_send=False): self.sender = sender self.receiver = receiver self.content = content self.is_send = is_send def send(self): self.is_send = True def get_info(self): return f"{self.sender} says to {sel...
# -*- coding: utf-8 -*- """ This module serves the class for wrapping any known client specific exceptions. """ class FullContactException(Exception): pass
"""框架运行示例文件""" import logging import flask import leaf import config init = leaf.Init() init.kernel(config.basic) init.logging(config.logging) init.server(config.devlopment) init.database(config.database) # 以下模块请根据需要启用/禁用初始化 init.weixin(config.weixin) # 微信公众平台支持模块 init.wxpay(config.wxpay) # 微信支付支持模块 init.plugins(...
# Experiment for Lasso CV # License: BSD (3-clause) import numpy as np import celer from libsvmdata import fetch_libsvm from sklearn.datasets import make_regression from celer import LassoCV from sklearn.model_selection import KFold from sparse_ho import ImplicitForward from sparse_ho import grad_search, hyperopt_wr...
#!/usr/bin/python import sys sys.path.insert(0, "/usr/local/lib/python2.7/site-packages/") import argparse import cPickle as pickle import math import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D import numpy as np import os.path sys.path.append('../lib') import ProjectMgr parser = argparse.Argu...
from archstrap.mode import make_mode from archstrap.specification import Specification def run(specification: Specification, mode_name: str, install_root: str): mode = make_mode(mode_name) specification.apply(install_root, mode)
import unittest import sys sys.path.insert(1, '..') import easy_gui class GUI(easy_gui.EasyGUI): def __init__(self): sec = self.add_section('test_section', equal_button_width=True) btn1 = sec.add_widget(type='button', text='Button1', command_func=lambda e: print('Button1 working!')) btn1....
import pybullet as sim import time pc = sim.connect(sim.GUI) sim.setGravity(0, 0, -9.8) path = "path to your URDF file" armID = sim.loadURDF(path, basePosition=[0, 0, 0], useFixedBase=True) while pc != 0: sim.stepSimulation() time.sleep(0.01)
from _repo import join, read_local_version, REPO, spec, system_call ENDL = '\n' IS_TERMUX = ( spec.LINUX and system_call('uname -o').strip() == 'Android' and bool(system_call('command -v termux-open-url', shell=True)) ) VERSION = None def fres(filename, mode='r'): return open(join(PROJECT.RES, filename), mode, en...
""" Author: Peratham Wiriyathammabhum """ import numpy as np import pandas as pd import matplotlib.pyplot as plt eps = np.finfo(float).eps def logistic_regression(Xin, yin, opts, thres=10**-5, max_epochs=200): """ Perform logistic regression on an input row matrix X and a target vector y. See: http://www.ciml....
from django.db import models class Movie(models.Model): title = models.CharField(max_length=256) length = models.PositiveIntegerField() release_year = models.PositiveIntegerField() def __str__(self): return f"{self.title} ({self.release_year})" class Customer(models.Model): first_name = m...
# -*- coding: utf-8 -*- """chat table and chat model.""" from sqlalchemy import Column, ForeignKey, Integer, String from sqlalchemy.orm import relationship from greyd.db.base import Base from greyd.models.user_to_lobby import UserToLobby # pylint: disable=too-few-public-methods class Chat(Base): """Chat objec...
import pandas as pd import logging import os import django from django.core.management.base import BaseCommand class Command(BaseCommand): help = 'Takes in the authoritative_agencies_list.csv and the broker_agency_list.csv to make' \ 'a modified_authoritative_agencies_list.csv' logger = logging.g...
# commands.py import discord # local imports # from Database import database as db from src.Botdata import Botdata from src.Commands import Command from src.Database import DB from src.ranks import Rank class Commands: def get_command(self, name): if name in self.command_registry: return se...
# -*- coding: utf-8 -*- import sys from pathlib import Path if str(Path().resolve().parent.parent) not in sys.path: sys.path.insert(1, str(Path().resolve().parent.parent)) import numpy as np from scipy.signal import find_peaks from constants import DEFAULT_MAX_GAIN, DEFAULT_TREBLE_F_LOWER, DEFAULT_TREBLE_F_UPPER, ...
__author__ = "the.triops404@gmail.com" __copyright__ = "Copyright (C) 2017 Snowwolf" __license__ = "Apache"
# -*- coding: utf-8 -*- import threading import time def log(text): print("{0}:{1}".format(text, time.time())) def hello(): log("hello") def main(): # 5秒後に実行 t = threading.Timer(5, hello) t.start() log("main ") time.sleep(7) log("main ") if __name__ == '__main__': main()
"""Copyright 2012, System Insights, 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 required by applicable law or agreed t...
''' Created on Jan 13, 2017 @author: muth ''' import time import spidev import RPi.GPIO as GPIO import PIL.ImageOps from PIL import Image from PIL import ImageEnhance from picamera import PiCamera from io import BytesIO from smemlcd import SMemLCD from Adafruit_Thermal import * #Screen resolution ...
from klgists.common.tools import * from klgists.common.tools.datatype_tools import * from klgists.common.tools.unit_tools import * from klgists.common.tools.sys_tools import * from klgists.common.tools.timing_tools import * class GistTools( CommonTools, StringTools, NumericTools, ConsoleTools, FilesysTools, IoTools,...
import json, datetime item = input('Item Name: ') with open('data.json', 'r') as f: data = json.load(f)[item] highest = [0,0] for num,i in enumerate(data): if num == 24: print('\nHighest:') print(datetime.datetime.fromtimestamp(highest[0]).strftime("%H:%M"), highest[1]) ...
""" Copyright 2013 Steven Diamond Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software...
MASSES = [57,71,87,97,99,101,103,113,114,115,128,129,131,137,147,156,163,186] def Expand(Peptides): expanded = [] for peptide in Peptides: for mass in MASSES: expanded.append(peptide + [mass]) return expanded def Cyclospectrum(Peptide): mass = sum(Peptide) spectrum = [0, mass] ...
import numpy as np import pandas as pd from scipy import sparse from scipy.sparse import linalg from .sparse_matrix_builder import build_from_conceptnet_table def build_ppmi(conceptnet_filename, ndim=300): sparse_csr, index = build_from_conceptnet_table(conceptnet_filename) ppmi = counts_to_ppmi(sparse_csr) ...
import os import logging from .base import BaseReport import numpy as np import h5py from scipy.stats import threshold from scipy.misc import imsave class FileReport(BaseReport): logger = logging.getLogger("ddvt.rep.file") def __init__(self, file, temp_dir): self.file = file # all files are valid until p...
# Ex. 012 preco = float(input("Digite o preço do produto: R$")) print(f"O produto, com 5% de desconto, custa R${preco-(preco*0.05):.2f}")
#!/usr/local/bin/python # encoding: utf-8 """ work with the Flickr API to upload images, sort images, generate MD image reference links etc. """ import sys import os import re import time from os.path import expanduser import requests import yaml import webbrowser from requests_oauthlib import OAuth1 from fundamental...
import asyncio from typing import Optional from discord import FFmpegPCMAudio from discord.ext.commands import Context from dropbox.dropbox_client import Dropbox from amadeus.library.dropbox_handler import retrieve_temporary_file_link class MusicPlayer: _dropbox_client: Dropbox _music_location: str # TOD...
""" Django settings for wallet project. Generated by 'django-admin startproject' using Django 3.2.3. For more information on this file, see https://docs.djangoproject.com/en/3.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.2/ref/settings/ """ from pathlib ...
#! /usr/bin/env python3 from colorama import Fore, Style import sys import subprocess as sub from subprocess import Popen, PIPE import os import time import os.path import argparse # Globals currentDir = os.getcwd() binDir = currentDir + "/bin/" info = (Fore.BLUE + "[*] ") recc = (Fore.YELLOW + "[*] ") good = (For...
import numpy as np import pandas as pd import matplotlib.pyplot as plt import seaborn as sns import warnings warnings.filterwarnings('ignore') data = pd.read_csv('255/clustering.csv') data.head() data = data[['ApplicantIncome', 'LoanAmount']] data = data.loc[:, ['ApplicantIncome', 'LoanAmount']] data.head(2) X = da...
#!/usr/bin/env python from app.models import * from django.contrib.auth.models import Permission, Group, ContentType from django.core.management.base import BaseCommand class Command(BaseCommand): args = '' help = 'Populate Database with the seed at /app/management/commands/populate_db.py' def _permission...
import threading from typing import List, Optional from time import sleep, monotonic from tokenize import Number from jacdac.transport import Transport from jacdac.util import buf2hex, hex2buf, now from gpiod import Chip, Line, LineBulk, LINE_REQ_EV_RISING_EDGE, LINE_REQ_FLAG_ACTIVE_LOW, LINE_REQ_DIR_OUT # type: ignore...
# Copyright 2015 Google 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 by applicable law or a...
import mock OAuth20Authentication = mock.Mock()
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ # Meta-info Author: Nelson Brochado Created: 01/07/2015 Updated: 06/04/2018 # Description Contains the abstract class BinaryHeap. # References - Slides by prof. A. Carzaniga - Chapter 13 of Introduction to Algorithms (3rd ed.) - http://www.math.clemson.edu/~war...
import os import random root='/home/tdteach/data/yellowset/' jfs = os.listdir(root) rate = 0.01 split_number = 10000 import pickle def read_from_bin(fname): print('read from '+fname) with open(fname,'rb') as f: data = pickle.load(f) return data def write_to_bin(data,fname,k=0): st = 0 sp = split_numb...
from api.models import Revenue from rest_framework import serializers class RevenueSerializer(serializers.Serializer): seller_id = serializers.UUIDField() total_received = serializers.IntegerField()
import numpy from pylab import * from scipy.interpolate import * L,W,grid,e,ee,f,ef,s=numpy.loadtxt("PEC_combined_results_temp.txt",unpack=True,skiprows=1) f=-f*31.6e-15 tgrid=0.4 lens=numpy.unique(L) for i in range(0,len(lens)): gpts = numpy.where((L == lens[i]) & (grid == tgrid)) x=W[gpts] y=f[gpts] ...
""" Our representation of OpenFlow 1.3 forwarding rules in a match+action pipeline. We refer to an OpenFlow Flow as a Rule. """ # Copyright 2019 Richard Sanger, Wand Network Research Group # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the Lic...
import h5py import random import tensorflow as tf from tensorflow.keras.utils import Sequence ''' Data generator for PieAPP and TID 2008, 2013 datasets, we use horizontal and vertical flips and 90, 180, 270 rotations of the images for data augmentation ''' H5_TRAINING_DIR = './prepare_dataset/data_train.h5' H5_VALID...
import glob import os PATH="/home/ma/masterthesis/datasets/YCB_Video_Dataset/" TEST=["0048","0049","0050","0051","0052","0053","0054","0055","0056","0057","0058","0059"] TOPLEVEL_FOLDER = ["test", "train", "train_seg"] folders=glob.glob(PATH+"data/*") train_folder_count = int((len(folders) - len(TEST))/2) non = 0 ...
#!/usr/bin/env python3 # # ===============LICENSE_START======================================================= # Acumos # =================================================================================== # Copyright (C) 2018 AT&T Intellectual Property. All rights reserved. # ==========================================...
# https://leetcode.com/problems/construct-binary-tree-from-string/ from typing import List import re class TreeNode: def __init__(self, val=0, left=None, right=None): self.val = val self.left = left self.right = right class Solution: def str2tree(self, s: str) -> TreeNode: ...
from app.validators.placeholders.placeholder_validator import PlaceholderValidator def test_invalid_repeating_section_title_placeholders(): placeholder_container = { "text": "{person}", "placeholders": [ { "placeholder": "person_name", "transforms": [ ...
from __future__ import absolute_import, division, print_function, unicode_literals import datetime import math import sys import time ITERATIONS = 10 MICROSECONDS_PER_SECOND = 1000000. PRESKIP = 0 USAGE = 'Usage: TestSleepAccuracy [iterations] [waitTimeInFloatingPointSeconds]' WAIT_TIME = 0.005 # Copied from http://...
# Gaussian process binary classification in 1d # Code is based on #https://github.com/aloctavodia/BAP/blob/master/code/Chp7/07_Gaussian%20process.ipynb import pymc3 as pm import numpy as np import pandas as pd from scipy import stats from scipy.special import expit as logistic import pyprobml_utils as pml import mat...
# ------------------------------------------------------------------------------------------------- # Database Module # ------------------------------------------------------------------------------------------------- # Author: Maxime Sirois # ----------------------------------------------------------------------------...
from __future__ import print_function import os import argparse from tinydb import TinyDB from datetime import datetime import json_tricks.np as jt from song_classes import Song, Slice, beatTrack, Features from src.self_similarity import segmentation, slicer from numpy import vstack from scipy.misc import imresize ...
""" Modules for queries and user responses. :TODO: OrdinalQuery classes will be implemented so that the library will include ordinal data, which was used for reward learning in: K. Li, M. Tucker, E. Biyik, E. Novoseller, J. W. Burdick, Y. Sui, D. Sadigh, Y. Yue, A. D. Ames; "ROIAL: Region of Interest Active Le...
from theseus.segmentation.datasets import DATASET_REGISTRY, DATALOADER_REGISTRY from .cutmix_loader import CutmixLoader DATALOADER_REGISTRY.register(CutmixLoader)
# -*- coding: utf-8 -*- from __future__ import absolute_import from __future__ import with_statement import anyjson import os import sys import time from datetime import datetime, timedelta from kombu.transport.base import Message from kombu.utils.encoding import from_utf8, default_encode from mock import Mock, patc...
import json import os from flask import Blueprint from flask import current_app from flask import redirect from flask import render_template from flask import url_for import jinja2 from flask_login import login_required from shopyoapi.enhance import get_setting from shopyoapi.enhance import set_setting from shopyoap...
#!/usr/bin/env python # Copyright (C) 2007-2018, GoodData(R) Corporation. All rights reserved # Derived from # http://code.activestate.com/recipes/576819-logging-to-console-without-surprises/ # # # MIT License # # Copyright (c) Sridhar Ratnakumar, GoodData # # Permission is hereby granted, free of charge, to any perso...
#!/usr/bin/python # -*- coding: utf-8 -*- import numpy as np import mathutils class MHMesh: def __init__(self, obj, context=None, allow_modifiers=False): """ Parse the mesh into a set of numpy arrays, separated per vertex group. There are two dicts here, where each item is an array. ...
import torch from torch import nn from torch.nn.utils import spectral_norm import utils.radam torch.optim.RAdam = utils.radam.RAdam from generators.common import blocks import math class Wrapper: @staticmethod def get_args(parser): parser.add('--dis_padding', type=str, default='zero', help='zero|refl...
import FWCore.ParameterSet.Config as cms idealMagneticFieldRecordSource = cms.ESSource("EmptyESSource", recordName = cms.string('IdealMagneticFieldRecord'), iovIsRunNotTime = cms.bool(True), firstValid = cms.vuint32(1) ) ParametrizedMagneticFieldProducer = cms.ESProducer("ParametrizedMagneticFieldProducer...
try: from setuptools import setup except ImportError: print "Falling back to distutils. Functionality may be limited." from distutils.core import setup config = { 'description' : 'A implementation of tee in Python', 'author' : 'Brandon Sandrowicz', 'url' : 'http:...
#!/usr/local/bin/python3 from math import prod def read_input(): file = open('input/2020/day3-input.txt', 'r') return [[c == '#' for c in line.strip()] for line in file.readlines()] def count_trees(data, route): """ >>> count_trees([ ... [False, False, True, True, False, False, False, False...
#!/usr/bin/env python # -*- coding: utf-8 -*- # Copyright (c) Facebook, Inc. and its affiliates. # All rights reserved. # # This source code is licensed under the license found in the # LICENSE file in the root directory of this source tree. import argparse import numpy as np import cv2 import tensorflow as tf from t...
#!/usr/bin/env python # Copyright 2019 Division of Medical Image Computing, German Cancer Research Center (DKFZ). # # 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...
#!/usr/bin/env python """ nn_manager A simple wrapper to run the training / testing process """ from __future__ import print_function from collections import OrderedDict import numpy as np import torch __author__ = "Xin Wang" __email__ = "wangxin@nii.ac.jp" __copyright__ = "Copyright 2020, Xin Wang" ##############...
import logging from typing import Dict, List, Optional, Tuple from hdx.utilities.text import multiple_replace from unidecode import unidecode from hdx.location.country import Country from hdx.location.names import clean_name from hdx.location.phonetics import Phonetics logger = logging.getLogger(__name__) class Ad...
# Ciholas, Inc. - www.ciholas.com # Licensed under: creativecommons.org/licenses/by/4.0 # System libraries import numpy as np import pyqtgraph as pg from collections import deque from pyqtgraph.Qt import QtGui, QtCore # Local libraries from cdp import * from network_objects import * from settings import * class Plo...
import numpy as np def preprocess_function(examples, tokenizer): return tokenizer(examples["text"], padding="max_length",max_length=201 , truncation=True) def compute_metrics(eval_pred, metric): predictions, labels = eval_pred predictions = np.argmax(predictions, ax...
# MIT License # # Copyright (c) 2021 Sangchun Ha # # 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, merge, ...
import numpy as np from src.mri_loader import _get_vol_files_list, MRIDataset, voxelmorph_labels, _load_vol_and_seg def _test_get_vol_files_list(): # test training set train_files = _get_vol_files_list(mode='train', get_unnormalized=True, exclude_PPMI=True) assert np.all(['train' in tf for tf in train_fi...
from src.setup.setup_load import DataLoader from src.processing.belt import AssemblyBelt import pprint from multiprocessing import Process, Manager from src.setup.setup_load import assembler_config, assembly_config class AssemblyLines: """The AssemblyLines is a multi-processing class""" def __init__(self, te...
import os import warnings from argparse import _SubParsersAction, Namespace from typing import Callable import tensorflow as tf from numpy import ndarray from keras import Model from keras.models import load_model SubParsers = _SubParsersAction Args = Namespace def shut_the_logging_up(): os.environ['TF_CPP_MIN...
""" gallerize ~~~~~~~~~ :Copyright: 2007-2021 Jochen Kupperschmidt :License: MIT, see LICENSE for details. """ VERSION = '0.5-dev'
import numpy as np import ransac from vp import geom_tools class SegmentVPModel(ransac.Model): """Fits a vanishing point to a set of lines. The error measure is segment_midpoint_vp_error(). """ def fit(self, data): best_vp_point = choose_best_vp_by_max_error(data) if best_vp_poi...