content
stringlengths
5
1.05M
from .graph_export import export_scenegraph, export_subtree from .graph_import import import_scenegraph, import_subtree
import requests import json from datetime import datetime,timedelta class T(object): ENDPOINT = "http://realtime.mbta.com/developer/api/v2/{apicall}" def __init__(self, api_key, response_format='json'): if api_key == "YOUR API KEY HERE" or api_key.strip() == "": raise ValueError("Fill in a...
"""templates """ from flask import render_template, request, flash, url_for, redirect, \ send_from_directory, session from flask_login import current_user import datajoint as dj from ast import literal_eval from loris import config from loris.app.forms.dynamic_form import DynamicForm from loris.app.utils import u...
# 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 # d...
# -*- coding: utf-8 -*- """ 存储器,支持redis存储,使用zset对代理去重加评分,提供flask的api接口 """ import random import re import redis from proxypool.error import PoolEmptyError from proxypool.settings import HOST,PORT,PASSWORD,DB,INITIAL_SCORE,REDIS_KEY,MIN_SCORE,MAX_SCORE class RedisClient(object): def __init__(self): if PA...
# -*- coding: utf-8 -*- ''' julabo.py Contains Julabo temperature control see documentation http://www.julabo.com/sites/default/files/downloads/manuals/french/19524837-V2.pdf at section 10.2. :copyright: (c) 2015 by Maxime DAUPHIN :license: MIT, see LICENSE for details ''' import serial import time from .pytempera...
import os import sys from pathlib import Path import numpy as np # Utils filepath = Path(__file__).resolve().parent # sys.path.append( os.path.abspath(filepath/'../ml') ) from ml.keras_utils import r2_krs from ml.data import extract_subset_fea try: import tensorflow as tf if int(tf.__version__.split('.')[0])...
# -*- coding: utf-8 -*- # Copyright (c) 2020 Future Internet Consulting and Development Solutions S.L. # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Affero General Public License as # published by the Free Software Foundation, either version 3 of the # License,...
import time from nesta.server.define import define def test_server(control): # send stop command and check status resp = control.execute(command="server", argv=["stop"]) assert resp.exitcode == 0 time.sleep(0.5) resp = control.execute(command="server", argv=["status"]) assert resp.exitcode =...
#!/usr/bin/env python import copy def split_train_override_patch(patch, train_parameter_list:list): """ This function returns a list of tuples containing only those parameters that are in the train_parameter_list, and a second list of tuples with the overridden parameters :param patch: original patch ...
from ._UFDLObjectDetectionRouter import UFDLObjectDetectionRouter
import cv2 img = cv2.imread("./images/sample_01.jpg", cv2.IMREAD_COLOR) cv2.imshow("My image", img) cv2.waitKey(0) gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) cv2.imshow("My image", gray) cv2.waitKey(0) cascade = cv2.CascadeClassifier(cv2.haarcascades + "haarcascade_frontalcatface.xml") faces = cascade.detectMult...
"""rest_url has to be hidden. Move it from ui_metadata to the lux_layer_internal_wms Revision ID: 46cb4ef6fd45 Revises: 1b9b2d6fb6e Create Date: 2015-01-07 11:32:20.615816 """ # revision identifiers, used by Alembic. revision = '46cb4ef6fd45' down_revision = '1b9b2d6fb6e' branch_labels = None depends_on = None from...
import logging import os from handler.handler_context import HandlerContext from handler.model.base import FieldMask, HandlerBase, merge_resource from handler.model.model_reply import ModelReply from handler.model.model_thread import ModelThread from handler.model.model_user import ModelUser from handler.model.user im...
''' Criação de um cronometro feito com POO''' from tkinter import * from tokenize import String class Stopwatch(Frame): def __init__(self, window = None): # Instancias da classe super().__init__(window) self.window = window self.running = False # Utilizado para con...
import numpy as np # linear algebra import tensorflow as tf import matplotlib.pyplot as plt import pandas as pd from sklearn.metrics import accuracy_score, precision_score, recall_score from sklearn.model_selection import train_test_split from tensorflow.keras import layers, losses from tensorflow.keras.datase...
from PythonPLC import plc import snap7.client as c from snap7.util import * from snap7.snap7types import * # Custom functions def ReadOutput(plc,byte,bit,datatype = S7WLBit): result = plc.read_area(areas['PA'],0,byte,datatype) if datatype==S7WLBit: return get_bool(result,0,bit) elif datatype==S7WLB...
############################################## # MusicAnalyzer | 15-112 Term Project # Joel Anyanti | Janyanti ############################################## ############################################## # Imports ############################################## from GameObjects import MusicNote from Settings import ...
import os import re import StringIO class Viewer(object): def __init__(self): ''' ''' self.__query_viewer_regex = re.compile('^/deep/.*$') self.__web_dir = 'web/' def content_type(self, extension): ''' ''' return { '.js': 'text/javascript', '.html': 'text/html', '.p...
#!/usr/bin/env python3 # Pedir al usuario dos números válidos, si no son válidos seguir pidiendo valores. Efectuar con ellos la suma, resta, multiplicación, división, división entera, resto, y potencias. Utilice control de errores para evitar el error de división entre cero.
""" @author: Rossi @time: 2021-01-26 """ from collections import OrderedDict, defaultdict import re from Broca.message import BotMessage from .event import ExternalEnd, ExternalStart, SkillStarted, SkillEnded from .event import BotUttered, SlotSetted, Form, Undo class Skill: def __init__(self): self.nam...
#!/usr/bin/env python # -*- coding: utf-8 -*- import logging import os import hydra import combustion config_path = "../conf" config_name = "config" log = logging.getLogger(__name__) if "WORLD_SIZE" not in os.environ: combustion.initialize(config_path=config_path, config_name=config_name) print("Called in...
__all__ = [ "Currencies", "CurrencyResource", ] from decimal import Decimal from typing import Optional from pydantic import validator from decaf.api.client.machinery import BaseResource, ResourceListEndpoint, ResourceRetrieveEndpoint, command from decaf.api.client.types import Currency, Date class Currenc...
# coding: utf-8 # Copyright (c) Max-Planck-Institut für Eisenforschung GmbH - Computational Materials Design (CM) Department # Distributed under the terms of "New BSD License", see the LICENSE file. from unittest import TestCase from pyiron_feal.utils import JobName, bfs import numpy as np class TestJobName(TestCase...
""" ======================= Coarse Motor Processes ======================= """ import os import random import math import numpy as np from numpy import linspace # vivarium-core imports from vivarium.core.process import Process # plots from chemotaxis.plots.coarse_motor import plot_variable_receptor # directories f...
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. from recipe_engine import recipe_api DEPS = [ 'commit_position', 'recipe_engine/path', 'recipe_engine/properties', 'recipe_engine/raw_io', ...
import math import matplotlib.pyplot as pl import numpy as np def euler1(F, a, b, x0, y0, n): Ly = [y0] Lx = [x0] x= x0 y= y0 h=(b-a)/n while x <= b: y= h*F(x,y)+y x+=h Lx.append(x) Ly.append(y) x= x0 y= y0 while x >= a: y=...
import autograd.numpy as anp from pymoo.model.problem import Problem from pymoo.problems.util import load_pareto_front_from_file class CTP(Problem): def __init__(self, n_var=2, n_constr=1, option="linear"): super().__init__(n_var=n_var, n_obj=2, n_constr=n_constr, xl=0, xu=1, type_var=anp.double) ...
def bumps(road: str) -> str: return "Woohoo!" if road.count('n') <= 15 else "Car Dead"
# Generated by Django 2.1.5 on 2019-01-25 09:45 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('products', '0004_auto_20190125_1230'), ] operations = [ migrations.RenameField( model_name='choice', old_name='feature1', ...
"""All output classes. AffineDynamicOutput - Base class for outputs with dynamics that decompose affinely in the input. FeedbackLinearizableOutput - Base class for feedback linearizable outputs. Output - Base class for outputs PDOutput - Base class for outputs with proportional and derivative components. RoboticSystem...
# coding: utf-8 # DO NOT EDIT # Autogenerated from the notebook kernel_density.ipynb. # Edit the notebook and then sync the output with this file. # # flake8: noqa # DO NOT EDIT # # 核密度估计 # # 核密度估计是使用 *核函数* $K(u)$ 估计一个未知概率密度函数的过程。 直方图可以对任意区域中数据点的数量进行计数, # 而核密度估计是定义每个数据点的核函数之和的函数。 核函数通常具有以下属性: # # 1. 对称,使得 $K(u) = K(-...
import logging from functools import wraps from .rpc import RPC logger = logging.getLogger(__package__) class NFSv4(RPC): pass
import gym import gym_maze from agent.q_learning import QLearning env = gym.make("maze-sample-10x10-v0") env = gym.wrappers.Monitor(env, "q_learning", force=True) agent = QLearning(env, discount_factor=0.9) episodes = 10000 horizon = 10000 epsilon = 0.8 alpha = 1 for episode in range(episodes): observation = env....
#!/usr/bin/env python3 # -*- coding: utf-8 -* from warnings import simplefilter # ignore all future warnings simplefilter(action='ignore', category=FutureWarning) import pandas as pd pd.options.mode.chained_assignment = None # default='warn' import argparse import os import pdb __author__ = "Rickard Hammarén @hammarn...
# Generated by Django 2.0.6 on 2018-07-13 06:55 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('parkingsystem', '0021_ticket_amount'), ] operations = [ migrations.RemoveField( model_name='ticket', name='amount', ...
from selenium.webdriver.support.select import Select from common.webdriver_factory import get_driver driver = get_driver('chrome') driver.get('https://formsmarts.com/form/axi?mode=h5') first_name = driver.find_element_by_id('u_LY9_60857') first_name.clear() first_name.send_keys('Angie') last_name = driver.find_elemen...
from crosswalk_client import Client import pytest def test_setup(token, service): client = Client(token, service) client.create_domain("presidents") client.create_domain("politicians") client.bulk_create([{"name": "George W. Bush"}], domain="politicians") client.bulk_create([{"name": "George W. Bu...
# -*- coding: utf-8 -*- from .server import RaspiIOServer, get_registered_handles if __name__ == "__main__": server = RaspiIOServer() for handle in get_registered_handles(): server.register(handle) server.run_forever()
from django.contrib.auth import get_user_model from django.contrib.auth.models import Permission from django.contrib.auth.backends import BaseBackend from django.db.models import Exists, OuterRef, Q from django.core.exceptions import ValidationError from rbac_auth.utils import validate_email UserModel = get_user_mode...
#!/usr/bin/env python import random import re import time import datetime import sqlite3 import os import itertools import requests import eveapi from bs4 import BeautifulSoup conn = sqlite3.connect(os.path.expanduser("~/eve.sqlite")) HOME = "PR-8CA" def calc_jumps(system, start): url = "http://evemaps.dotlan.net/ro...
# # Copyright (c) 2012-2016 The ANTLR Project. All rights reserved. # Use of this file is governed by the BSD 3-clause license that # can be found in the LICENSE.txt file in the project root. from antlr4.atn.ATNState import StarLoopEntryState from antlr4.atn.ATNConfigSet import ATNConfigSet from antlr4.dfa.DFAState im...
import numpy as np """ this file will create a GM(grey prediction machine), and enable user to predict the future data based on current array of data. please note that this machine is based on first order differential equation, so it will be good at predicting data with certain trend( growing or minimizing), not very ...
""" Test the gva logger, this extends the Python logging logger. We test that the trace method and decorators raise no errors. """ import os import sys sys.path.insert(1, os.path.join(sys.path[0], '..')) from gva.logging import LEVELS, get_logger, error_trap, verbose_logger try: from rich import traceback ...
import logging, json, requests, jieba, sys, os, copy, re #from nlutools import tools as nlu from english_corrector import EnglishCorrector from data_utils import load_word_freq_dict, _get_custom_confusion_dict from utils import re_en, re_salary, is_alphabet_string, pinyin2hanzi, ErrorType, PUNCTUATION_LIST from config ...
from .redict import ReDict, update_with_redict
import numpy as np import pandas as pd import matplotlib.pyplot as plt import random df = pd.DataFrame(np.random.choice(np.arange(0, 2), p=[0.9, 0.1],size=(10000, 5)), columns=list('ABCDE')) total_views = 10000 num_ads = 5 ad_list = [] total_reward = 0 for view in range(total_views): ad = random.randrange(num_ad...
""" Optimizers --------- Module description """ from abc import ABC, abstractmethod from collections.abc import Iterable import copy import torch from brancher.standard_variables import Link from brancher.modules import ParameterModule, EmptyModule from brancher.variables import BrancherClass, Variable, Probabilistic...
from PyQt5.QtWidgets import (QWidget, QToolButton, QPushButton, QVBoxLayout, QHBoxLayout, QWidgetAction, QMenu) from PyQt5.QtCore import Qt, pyqtSignal, QModelIndex, QSize from transcode.pyqtgui.qitemmodel import (QItemModel, Node, ChildNodes, NoCh...
from wafw00f.main import WafW00F from wafw00f.lib.evillib import oururlparse from util.http_util import http_client __plugin__ = "Subdomain Scanner" SEQUENCE = 2 URL = "https://www.virustotal.com/vtapi/v2/domain/report" API_KEY = "a0283a2c3d55728300d064874239b5346fb991317e8449fe43c902879d758088" async def run(ur...
# Licensed under a 3-clause BSD style license - see LICENSE.rst import numpy as np from numpy.testing import assert_allclose import astropy.units as u from astropy.io import fits from gammapy.irf import Background3D, EffectiveAreaTable2D, EnergyDispersion2D class TestIRFWrite: def setup(self): self.energy...
link='https://www.giveindia.org/certified-indian-ngos' def List_of_Indian_NGOs_to_donate(url): from bs4 import BeautifulSoup import pprint import requests page = requests.get(url) soup = BeautifulSoup(page.text,"html.parser") man_class=soup.find('table',class_='jsx-697282504 certified-ngo-table') list1=[] for ...
""" Copyright (c) 2004-Present Pivotal Software, Inc. This program and the accompanying materials are made available under the terms of the 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....
import types __all__ = ["lzip", "lfilter", "lfilternone", "copy_func", "find_in_bases"] def lzip(*iterables): r""" Shorthand for list(zip(*iterables)) """ return list(zip(*iterables)) def lfilter(func, iterable): r""" Shorthand for list(filter(func, iterable)) """ return list(filter(func, iterable)) def lfi...
from pathlib import Path from statistics import median_high, mean import tensorflow as tf from metrics.base import Metric class SATAccuracy(Metric): def __init__(self) -> None: self.mean_acc = tf.metrics.Mean() self.mean_total_acc = tf.metrics.Mean() def update_state(self, model_output, st...
class Dimensions(): """ Two dimensions: width and height """ def __init__(self, width, height): self.width = int(width) self.height = int(height)
import numpy as np import pandas as pd from scipy import stats from math import isnan def apply(series, period, func, category=None, return_as_cat=None) -> pd.Series: """ Apply 'func' to rolling window grouped by 'category' :param series: time-series :param period: rolling window period :param fun...
""" python consumer, consume messages from amqp and execute python code """ __version__ = '0.1.0'
import numpy as np import matplotlib.pyplot as plt from open_spiel.python.egt import dynamics from open_spiel.python.project.part_1.visualization import paths from open_spiel.python.project.part_1.visualization.probarray_visualization import prepare_plot payoff_matrix_prisoners_dilemma = np.array([[[3,0],[5,1]],[[3...
from django.db import models class Mod(models.Model): fld = models.IntegerField() class M2mA(models.Model): others = models.ManyToManyField('M2mB') class M2mB(models.Model): fld = models.IntegerField()
from math import prod import qiskit import numpy as np from generate_training_set import insert_pauli from qiskit import QuantumCircuit from random import sample, seed from itertools import product def get_measuring_circuit(basis_list: list) -> QuantumCircuit: qc = QuantumCircuit(len(basis_list[0][1])) # Find...
""" The `domain` package provides a data structure for representing multi-zone meshes and their related data. The goal is to be able to represent all concepts from CGNS, though not necessarily in the same way. It also provides functions for obtaining flow values across a mesh surface and reading/writing in files vario...
# -*- coding: utf-8 -*- # @Time : 2019-11-03 13:04 # @Author : ljj0452@gmail.com import datetime from mongoengine import ( Document, StringField, DateTimeField, IntField, FloatField, BooleanField, EmbeddedDocument, EmbeddedDocumentListField ) class WorkerDetail(EmbeddedDocument): ...
import csv import argparse data = [] parser = argparse.ArgumentParser(description='file input for parse bank information') parser.add_argument('--file', metavar='str', type=str) args = parser.parse_args() with open(args.file, 'rb') as csvfile: reader = csv.reader(csvfile) i = 0 for row in reader: ...
#!/usr/bin/env python from __future__ import print_function import sys import glob import time import os, os.path import doctest import unittest try: import coverage except ImportError: print("No 'coverage' module found. Try:") print(" sudo apt-get install python-coverage") sys.exit(1) import logg...
# -*- coding: utf-8 -*- # --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.5.2 # kernelspec: # display_name: Python 3 # language: python # name: python3 # --- import numpy as np from scipy i...
a = float(input()) b = float(input()) media = ((a*3.5) + (b*7.5)) / 11 print('MEDIA = {:.5f}'.format(media))
from django.shortcuts import render # Create your views here. from django.http import HttpResponse def homePageView(request): return HttpResponse('OK!')
"""Error handling utils.""" import nestor_api.lib.io as io from nestor_api.utils.logger import Logger def non_blocking_clean(path: str, *, message_prefix: str = None): """Try to clean directory/file at path but don't raise an error if it fails (only log it).""" message = "Error trying to clean temporary ...
from flask import Flask, jsonify, render_template, request from flask_sqlalchemy import SQLAlchemy from random import choice app = Flask(__name__) # Connect to Database app.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cafes.db' app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False db = SQLAlchemy(app) # Cafe TABLE...
from random import randint def quicksort(array): less = [] equal = [] greater = [] if len(array) > 1: pivot = array[0] for x in array: if x < pivot: less.append(x) if x == pivot: equal.append(x) if x > pivot: ...
# https://packaging.python.org/en/latest/distributing.html from setuptools import setup, find_packages from codecs import open from os import path here = path.abspath(path.dirname(__file__)) with open(path.join(here, 'README.rst'), encoding='utf-8') as f: long_description = f.read() setup( # details nam...
# Copyright (c) 2019 PaddlePaddle Authors. All Rights Reserve. # #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...
class Solution(object): def maxSlidingWindow(self, nums, k): """ :type nums: List[int] :type k: int :rtype: List[int] """ if not nums or k==0: return [] n=len(nums) queue=collections.deque() res=[] """ using the dequ...
from django.core.cache import cache from django.views.generic import TemplateView class IndexView(TemplateView): template_name = "verspaeti/home.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) verspaeti_data_cache = cache.get('verspaeti_data') ...
from rest_framework import serializers from rest_framework.authtoken.models import Token from .models import User from .authentication import token_expire_handler, expires_in class UserSerializer(serializers.HyperlinkedModelSerializer): money_deposits = serializers.HyperlinkedRelatedField( many=True, rea...
# example environment, rolegroup, and role defs environmentdefs = { "environment1": ["host1", "host2"], } roledefs = { "role1": ["host1"], } componentdefs = { "role1": ["component1"], }
import json from climate_simulation_platform.db import save_revision, save_step from climate_simulation_platform.message_broker import send_preprocessing_message from climpy.interactive import ValueChanger import panel as pn import xarray as xr import numpy from scipy.ndimage import measurements import holoviews as h...
# -*- coding: utf-8 -*- """ Created on Tue Aug 4 10:56:00 2020 @author: Jimit.Dholakia """ import feedparser import time import urllib.parse import os os.environ['TZ'] = 'Asia/Kolkata' time.tzset() #updated ='Last Updated on: ' + time.strftime('%b %d, %Y %X %Z', time.localtime()) current_time = ...
import re from argparse import ArgumentParser from dodo_commands.dependencies import yaml_round_trip_dump from dodo_commands.framework.singleton import Dodo def _args(): parser = ArgumentParser(description="Print the full configuration.") parser.add_argument("key", nargs="?") args = Dodo.parse_args(parse...
# -*- coding: utf-8 -*- """ Created on Thu Feb 2 10:56:02 2017 @author: FuckYouMicrosoft """ high = 100 low = 0 ans = (high+low)//2 print('Please think of a number between 0 and 100') print('Is your secret number '+ str(ans)+'?') userInput = str(input("Enter 'h' to indicate the guess is too high. Enter '...
import numpy as np import tkinter import matplotlib.pyplot as pyplot from matplotlib.path import Path import matplotlib.patches as patches class GridWorldMDP(object): # Construct an GridWorld representation of the form # # 20 21 22 23 24 # 15 x 17 18 19 # 10 x 12 x 14 # 5 ...
from django import forms from .models import Loan from books.models import Book class LoanForm(forms.ModelForm): code = forms.CharField(label='Book Code') class Meta: model = Loan fields = [ 'to', ]
from time import sleep from operator import itemgetter oficial = str(input('Palpite oficial: ')).strip().split("/") jogadores = int(input('Quantos jogadores vão participar na rodada ? ')) print ('-'* 50) print ('Analizando',end=' ') sleep(1) print ('.',end=' ') sleep(1) print ('.',end=' ') sleep(2) print('.', end=' //...
# -*- coding: utf-8 -*- """ Created on Sun Mar 15 19:58:26 2020 @author: Ravi """ from collections import Counter def gameOfThrones(s): odd = 0 se = Counter(s) for i in se.values(): if i%2!=0: odd+=1 if odd>1: return 'NO' return 'YES' s = in...
"""Simple heartbeat library""" import logging from datetime import timedelta from typing import Optional import requests import isodate heartbeat_app_url = "http://localhost:5000/" __VERSION__ = "0.1.2" __AUTHOR__ = "Joshua Coales" __EMAIL__ = "dr-spangle@dr-spangle.com" __URL__ = "https://github.com/joshcoales/simp...
# Generated by Django 3.0.6 on 2020-10-15 14:27 from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('limb', '0004_metalsite_ion'), ] operations = [ migrations.AddField( model_name='metalsite', name='ready_for_presenta...
# Generated by Django 2.2 on 2019-06-28 12:02 from django.db import migrations class Migration(migrations.Migration): dependencies = [ ('users', '0006_auto_20190628_1200'), ] operations = [ migrations.RenameModel( old_name='Roles', new_name='Role', ), ...
from conftest import data_path from kitt.image.objdetect.annotation import AnnotationType from kitt.image.objdetect.voc import voc_to_annotated_image def test_load_voc_xml(): annotated = voc_to_annotated_image(data_path("example.xml")) width, height = annotated.width, annotated.height assert width == 500...
import numpy as np import glob, os import random from imageio import imread, imwrite import shutil from skimage import img_as_ubyte, img_as_float from math import ceil, sqrt, pi from scipy.signal import convolve2d import tensorflow as tf from tensorflow.keras.layers import UpSampling2D def generate_patches_pngs(noisy_...
import os from landolfio.settings.base import * # noqa # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = os.environ.get("DJANGO_SECRET_KEY") # SECURITY WARNING: don't run with debug turned on in production! DEBUG = False ALLOWED_HOSTS = ["landolfio.vofdoesburg.nl"] SESSION_COOKIE_SE...
import sys import json from mlscratch.measurer import ProbsMeasurer, Measurer from sacnn.core import SacnnModel, get_arch, compute_labels_accuracy, ConfusionMatrixMeasurer from sacnn.core.fs_utils import load_np_tensor def get_test_data(num_labels): load_folder = 'data_reduced' if num_labels == 3 else 'data' ...
"""Auto-generated file, do not edit by hand. AM metadata""" from ..phonemetadata import NumberFormat, PhoneNumberDesc, PhoneMetadata PHONE_METADATA_AM = PhoneMetadata(id='AM', country_code=None, international_prefix=None, general_desc=PhoneNumberDesc(national_number_pattern='[148]\\d{2,4}', possible_length=(3, 4, ...
import numpy as np import sys sys.path.insert(0, '../QLearning/' ) from simpleQLearning import QLearningAgent import matplotlib.pyplot as plt import os import random from collections import deque class ReplayBuffer(object): def __init__(self, size): """ Create Replay buffer. Parameters ...
class ChromeSpider(object): pass
class TestExample: def test_me(self): assert True def but_me(self): assert True class DescribeExample: def it_has_some(self): assert True
# -*- coding: utf-8 -*- """Indexing hdf5 files""" ext = '.h5' import os from .. import csutil from .interface import SharedFile class FileManager(object): file_class = SharedFile def __init__(self, store=False): if store is False: self.log = csutil.FakeLogger() else: ...
import numpy as np from utils import * def main(): DIMS = (500, 500) data_path = './data/' # load 4 cat images img1 = img_to_array(data_path + 'cat1.jpg', DIMS) img2 = img_to_array(data_path + 'cat2.jpg', DIMS, view=True) # concat into tensor of shape (2, 400, 400, 3) input_img = np.con...
import sys import pygame from checkerboard import * import ai_minmax as am def _get_init_player(): flag = input("输入 0(人)/ 1(电脑)指定先手(执黑): ") if flag == "0": return BLACK_CHESSMAN, 0 elif flag == "1": return WHITE_CHESSMAN, 1 else: return None, None def _get_next(cur_runner): ...
""" Useful functions for making pretty plots in matplotlib of accuracy of stock predictions. @author: Riley Smith Created: 1-21-2021 """ import matplotlib.pyplot as plt import matplotlib.patches as mpatches import numpy as np from utils import COLORS def plot_predicted_close(ticker, pred, true, save_to=None): ""...