content
stringlengths
5
1.05M
# SVG parser in Python # Copyright (C) 2013 -- CJlano < cjlano @ free.fr > # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later vers...
import os import json import requests import config from tools import log from tools import DDingWarn from tools.reply_template import * import pyttsx3 auth = None logger = log.logger pyttsx3_engine = pyttsx3.init() # 获取调用百度api的token,auth为返回的结果 def get_token(): global auth APIKey = 'bpLlUme0C61GisOY9Ce2QYzu...
# -------------------------------------------------------------------# # Released under the MIT license (https://opensource.org/licenses/MIT) # Contact: mrinal.haloi11@gmail.com # Enhancement Copyright 2016, Mrinal Haloi # -------------------------------------------------------------------# import random import os impo...
# get the splines import numpy as np import scipy.interpolate as si # TODO - BSpline.predict() -> allow x to be of any shape. return.shape = in.shape + (n_bases) # MAYBE TODO - implement si.splev using keras.backend. # - That way you don't have to hash the X_spline in memory. class BSpline(): """Cl...
# Python Standard Library Imports from itertools import combinations from utils import ingest TARGET = 150 INPUT_FILE = '17.in' EXPECTED_ANSWERS = (654, 57, ) # TARGET = 25 # INPUT_FILE = '17.test.in' # EXPECTED_ANSWERS = (4, 3, ) def main(): solution = Solution() answers = (solution.solve1(), solution.so...
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations class Migration(migrations.Migration): dependencies = [ ("twitter", "0003_auto_20150730_1112"), ] operations = [ migrations.AlterField( model_name="user", nam...
from django.contrib.auth.models import AbstractUser from django.conf import settings from rest_framework import permissions from ..utils import raise_context class IsAuthenticatedOpenApiRequest(permissions.IsAuthenticated): __slots__ = () def is_openapi(self, request): return ( request.p...
import gc import os import struct import zlib from collections import defaultdict from contextlib import closing import lmdb import msgpack import numpy as np from pyroaring import BitMap from tqdm import tqdm from lz4 import frame import config as cf from core import io_worker as iw def is_byte_obj(obj): if isi...
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def flatten(self, root: TreeNode) -> None: if not root: return self.flatten(root.left) self.flatten(root.right...
from rc.test.util import Timer from rc import gcloud from rc.util import go, pmap, as_completed def create_or_get(*, name, **kwargs): return gcloud.get(name) or gcloud.create(name=name, **kwargs) def test_create_delete_5_instance(): futures = [] machines = [] with Timer('create 5 instances'): ...
import zmq import time import subprocess context = zmq.Context() socket = context.socket(zmq.REP) socket.bind('tcp://localhost:5555') while True: message = socket.recv() action, ip = str(message).split(': ') # print('Received action {} from ip {}'.format(action, ip)) # action = action.decode('utf-8')...
import ast import heisenberg.library.orbit_plot import heisenberg.util import numpy as np import optparse import sys class OptionParser: def __init__ (self, *, module): help_prolog = heisenberg.util.wrap_and_indent(text=module.subprogram_description, indent_count=1) self.__op = optparse.OptionParse...
import sys def read_input_definitions(): input_names = {} with open('chipster-inputs.tsv') as inputs: for line in inputs: # remove \n line = line[:-1] if line.startswith('#'): continue columns = line.split('\t') input_name = co...
#!/usr/bin/env python import elasticapm from assemblyline_core.server_base import ServerBase from assemblyline.common import forge from assemblyline.common.metrics import MetricsFactory from assemblyline.remote.datatypes import get_client from assemblyline.remote.datatypes.queues.named import NamedQueue from assembly...
from .users import User from .profiles import Profile from .phone_codes import PhoneCode
from django.shortcuts import render # Create your views here. from django.http import HttpResponse from django.template import loader from django.db.models import Sum import django from .models import TypyBiletow,Transakcje,NosnikiKartonikowe,Nieimienne, MiejscaTransakcji, TypyUlgi, MetodyPlatnosci, NosnikiElektron...
from bottleneck.slow.func import * from bottleneck.slow.move import *
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.13.7 # kernelspec: # display_name: 'Python 3.7.9 64-bit (''workflow-calcium-imaging'': conda)' # name: python379jvsc74a57bd01a512f474e195e32ad84...
import re from flatland import String from flatland.validation import ( IsEmail, HTTPURLValidator, URLCanonicalizer, URLValidator, ) from flatland.validation.network import _url_parts from tests._util import eq_, unicode_coercion_allowed def email(value): return String(value, name=u'email', ...
import random class Book: def __init__(self, description, title, author, page, images, publish): self.description = description # опис self.title = title #назва книги self.author = author # автор self.page = page # кількість сторінок self.images = images # кількість ілюстра...
import os import math import pandas as pd import sklearn.metrics as metrics from sklearn.ensemble import RandomForestClassifier from sklearn.linear_model import LogisticRegression from sklearn.metrics import classification_report, confusion_matrix, roc_auc_score, accuracy_score from sklearn.metrics import average_preci...
#!/usr/bin/env python import os.path import tornado.httpserver import tornado.ioloop import tornado.web from tornado.options import options from settings import settings from urls import url_patterns class MakeApp(tornado.web.Application): def __init__(self): tornado.web.Application.__init__(self, url_patterns,...
# Copyright 2014-2018 ARM 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 License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in w...
import os from mediawiki import MediaWiki import Algorithmia as algorithmia import requests from robots.state import loadApikey algorithmiaApiKey = loadApikey( path='./credential/algorithmia.json')['apiKey'] def apiAlgorithmia(): algorithmiaAutheticated = algorithmia.client(algorithmiaApiKey) wikipediaAl...
# ***************************************************************************** # ***************************************************************************** # # Name : wordindex.py # Purpose : Allocate each keyword a specific, final identifier ID. # Author : Paul Robson (paul@robsons.org.uk) # Date : 15th Jan...
from typing import List from engine.gameController import GameController from engine.gameModel import GameModel class ChessGameController(GameController): def __init__(self, gameModel: GameModel): super().__init__(gameModel) self.signalHandlers["playerJoinRequested"] = self.onPlayerJoinRequested self.signalHa...
'''User management User admin page, user edit page, adding/removing users, logging in/out TODO(Connor): Improve remove user double check.''' from flask import Flask, Blueprint, render_template, \ abort, session, request, redirect, url_for from flask_bcrypt import Bcrypt import chores.blueprints.database as DATABAS...
"""Web Routes.""" from masonite.routes import Get, RouteGroup ROUTES = [ RouteGroup([ Get('/social/@provider/login', 'WelcomeController@auth'), Get('/social/@provider/callback', 'WelcomeController@callback'), ]), Get('/', 'WelcomeController@show').name('welcome'), ]
import json import threading import psutil import minidiagram import payload timer = None cpu_percent = [0] * 80 def record_data(): global cpu_percent cpu_percent.append(psutil.cpu_percent()) cpu_percent.pop(0) def get_config(): global cpu_percent diagram = minidiagram.MiniDiagram(bgcolor=(0.6,...
# Authors: Alexandre Gramfort <alexandre.gramfort@telecom-paristech.fr> # Matti Hamalainen <msh@nmr.mgh.harvard.edu> # Martin Luessi <mluessi@nmr.mgh.harvard.edu> # # License: BSD (3-clause) from os import path from .io.meas_info import Info from . import pick_types from .utils import logger, verbos...
import pickle from tkinter import * from PIL import ImageTk, Image import tkinter.font as fonts from tkinter import messagebox import os # initialise root = Tk() root.title("Space Defence") root.iconbitmap("game_icon.ico") root.wm_geometry("1280x720") root.resizable(False, False) # functions for butto...
# # PySNMP MIB module CISCO-TRUSTSEC-TC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-TRUSTSEC-TC-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:57:57 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (def...
import torch from mmhuman3d.models.builder import build_body_model body_model_load_dir = 'data/body_models/smpl' extra_joints_regressor = 'data/body_models/J_regressor_extra.npy' def test_smpl(): random_body_pose = torch.rand((1, 69)) # test SMPL smpl_54 = build_body_model( dict( t...
""" # --------------------------- # GLOBAL packages imports # --------------------------- """ from tests.utils.FileExtenTests import *
"""Wrappers building transformation from configuration""" import logging from PIL import Image from utils.config import Configuration def _build_param_dict(conf, required_params, optional_params=[], key_renames={}, kwargs={}): # Filter out params which are passed in kwargs required_params ...
lista_numeros = [] for contador in range(0, 5): numero = int(input('Digite um valor: ')) if contador == 0 or numero > lista_numeros[-1]: lista_numeros.append(numero) print('Adicionado ao final da lista...') else: posicao = 0 while posicao < len(lista_numeros): ...
import os import time import logging import tempfile import shutil from django.conf import settings from operator import itemgetter from django.utils import module_loading from papermerge.core.import_pipeline import LOCAL logger = logging.getLogger(__name__) def import_documents(directory): files = [] pipe...
import numpy as np from matplotlib import pyplot as plt runtime_data = np.array([8.1, 7.0, 7.3, 7.2, 6.2, 6.1, 8.3, 6.4, 7.1, 7.0, 7.5, 7.8, 7.9, 7.7, 6.4, 6.6, 8.2, 6.7, 8.1, 8.0, 6.7, 7.9, 6.7, 6.5, 5.3, 6.8, 8.3, 4.7, 6.2, 5.9, 6.3, 7.5, 7.1, 8.0, 5.6, 7.9, 8.6, 7.6, 6.9, 7.1, 6.3, 7.5, 2.7, 7.2, 6.3, 6.7, 7.3, 5.6...
''' Copyright 2019 Secure Shed Project Dev Team 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 ...
# -*- coding: utf-8 -*- """ Process that handles the Community Statistics from Finn """ __author__ = 'Samir Adrik' __email__ = 'samir.adrik@gmail.com' from source.util import Assertor, Profiling, Tracking, Debugger from .engine import Process, InputOperation, Signal, Extract, Separate, Multiplex, \ OutputOperat...
"""Test the server version helper.""" from unittest.mock import AsyncMock, call from zwave_js_server.version import get_server_version async def test_get_server_version(client_session, ws_client): """Test the get server version helper.""" version_data = { "driverVersion": "test_driver_version", ...
# ------------------------------------------------------------------------------------------ # Copyright (c) Microsoft Corporation. All rights reserved. # Licensed under the MIT License (MIT). See LICENSE in the repo root for license information. # -------------------------------------------------------------------...
## NOTE: web-app to receive commands from Fiat phone ## Author: Matteo Varvello (matteo.varvello@nokia.com) ## Date: 10/06/2021 ## TEST ## curl -H "Content-Type: application/json" --data '{"data":"testing data"}' http://localhost:8080/command #!/usr/bin/python #import random import string import json import cherrypy ...
""" * Francis Bui * SDEV 300 * Professor Chris Howard * Lab 5 - Data Analysis Application (with File I-O and Exceptions) * Sept 18, 2020 * The purpose of this program is to import various csv files with try and except * function. After the file has been imported, it will be converted into an array * with Pandas...
import numpy as np # pythran export _cplxreal(complex[]) def _cplxreal(z): tol = 100 * np.finfo((1.0 * z).dtype).eps z = z[np.lexsort((abs(z.imag), z.real))] real_indices = abs(z.imag) <= tol * abs(z) zr = z[real_indices].real if len(zr) == len(z): return np.array([]), zr z = z[~real...
# -*- coding: utf-8 -*- # # SelfTest/Random/Fortuna/test_SHAd256.py: Self-test for the SHAd256 hash function # # Written in 2008 by Dwayne C. Litzenberger <dlitz@dlitz.net> # # =================================================================== # The contents of this file are dedicated to the public domain. To...
#!/usr/bin/env python # -*- encoding: utf-8 -*- """ @File : live_like.py @Contact : 379327479@qq.com @License : MIT @Modify Time @Author @Version @Description ------------ ------- -------- ----------- 2021/10/25 17:43 zxd 1.0 None """ import uiautomator2 as u2 from uia...
import psycopg2 import psycopg2.extras import md5 def getOperator(conn,prefix=None,website=None): cur = conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) if website is None: website = 'http://www.example.com' if prefix is None: prefix = 'DINO' cur.execute(""" SELECT DISTINCT O...
# =============================================================================== # Copyright 2013 Jake Ross # # 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...
""" Inpainting using Generative Adversarial Networks. The dataset can be downloaded from: https://www.dropbox.com/sh/8oqt9vytwxb3s4r/AADIKlz8PR9zr6Y20qbkunrba/Img/img_align_celeba.zip?dl=0 Instrustion on running the script: 1. Download the dataset from the provided link 2. Save the folder 'img_align_celeba' to '../../d...
"""Herein lies the ability for ansible-runner to run the ansible-config command.""" from typing import Optional from typing import Tuple from ansible_runner import get_ansible_config from .base import Base class AnsibleConfig(Base): """Abstraction for ansible-config command-line.""" def fetch_ansible_conf...
import numpy as np from random import choice ## Note: Non-smooth surfaces or bad triangulations may lead to non-spiral orderings of the vertices. ## Common issue in badly triangulated surfaces is that there exist some edges that belong to more than two triangles. In this ## case the mathematical definition of the spir...
from rpython.jit.tl.tinyframe.tinyframe import main from rpython.jit.codewriter.policy import JitPolicy def jitpolicy(driver): return JitPolicy() def entry_point(argv): main(argv[1], argv[2:]) return 0 # _____ Define and setup target ___ def target(*args): return entry_point, None
#========================================== # Reward Predictor Model # Author: Nasim Alamdari # Date: Dec. 2020 #========================================== import keras from keras.models import Sequential, Model from keras.layers import Input, Dense, TimeDistributed, LSTM, Dropout, Activation, Bidirectional from ker...
# Copyright (C) 2019 SAMSUNG SDS <Team.SAIDA@gmail.com> # # This code is distribued under the terms and conditions from the MIT License (MIT). # # Authors : Uk Jo, Iljoo Yoon, Hyunjae Lee, Daehun Jun from __future__ import absolute_import from collections import deque, namedtuple import warnings import random import n...
import os import json from tweepy.error import TweepError from pandas import DataFrame from dotenv import load_dotenv from app import DATA_DIR, seek_confirmation from app.decorators.datetime_decorators import logstamp from app.bq_service import BigQueryService from app.twitter_service import TwitterService load_dot...
from __future__ import print_function import matplotlib.pyplot as plt import numpy as np from importlib import reload from rbvfit import rb_vfit as r from rbvfit import rb_setline as rt def set_one_absorber(N,b,lam_rest): zabs=0. line = r.model() N=np.array(N) b=np.array(b) v=np.array([0.]) ...
from unittest import TestCase from datetime import datetime from qcodes.data.location import FormatLocation from qcodes.instrument.parameter import Parameter from qcodes.measure import Measure from .instrument_mocks import MultiGetter, MultiSetPointParam import numpy as np from numpy.testing import assert_array_equa...
from qdrant_client.http.models.models import Distance DISTANCES = { 'cosine': Distance.COSINE, 'euclidean': Distance.EUCLID, 'dot': Distance.DOT, }
""" Commonly used utils: evaluation metrics e.g. similarity, AUC, AP@k, MAP@k graph related operation testing data generator file I/O visualization etc... by Chengbin Hou """ import time import numpy as np from scipy import sparse import pickle import networkx as nx # -----------------------------------------------...
import functools import logging import torch import torch.nn as nn from torch.nn import init from options.options import opt_get #import models.modules.sft_arch as sft_arch logger = logging.getLogger('base') #################### # initialize networks #################### def weights_init_normal(m, bias_fill=0, mean=0...
#!/usr/bin/env python3 #py3.7 with open('hello_foo.txt', 'w') as f: f.write('hello, world!') #same as: # f = opent('hello_foo.txt', 'w') # try: # f.wtite('hello, world') # finally: # f.close() with open('hello_foo.txt', 'r') as f: print(f.read()) print() #more advanced...
import numpy as np import tensorflow as tf from pyuvdata import UVData, UVCal, UVFlag from . import utils import copy import argparse import itertools import datetime from pyuvdata import utils as uvutils from .utils import echo from .utils import PBARS from . import cal_utils from . import modeling import re OPTIMIZ...
import logging import sys from difflib import SequenceMatcher from fetch_menu import fetch_menu_image from read_menu import MenuReader from chrome_proxy import ChromeProxy import settings def word_similarity(a, b): return SequenceMatcher(None, a, b).ratio() class WordDictionary: def __init__(self, filename)...
from typing import TYPE_CHECKING, Callable, Optional from hpcrocket.typesafety import get_or_raise from hpcrocket.watcher.watcherthread import WatcherThread, WatcherThreadImpl try: from typing import Protocol except ImportError: # pragma: no cover from typing_extensions import Protocol # type: ignore if T...
from django.contrib.auth.models import User from django.http import HttpResponseRedirect from django.shortcuts import render from dashboard.forms import BrotherForm, BrotherEditForm from dashboard.models import Position, Brother from dashboard.utils import verify_position from dashboard.views import DashboardUp...
''' Crie um programa que tenha um tupla com várias palavras (não usar acentos). Depois disso, você deve mostrar, para cada palavra, quais são suas vogais. ''' palavras = ('arroz', 'computador', 'piscina', 'copo', 'dentista', 'lazer', 'mouse', 'telefone', 'vestido', 'bermuda', 'aspirador') for p in palavra...
from collections import defaultdict import json from django.http.response import HttpResponse, FileResponse import pandas as pd import tempfile import mimetypes from django.views.generic import TemplateView from django.forms import formset_factory, BaseFormSet, modelformset_factory, inlineformset_factory from django....
default_app_config = "world.magic.apps.MagicConfig"
#!/usr/local/bin/python3.7 # -*- coding: utf-8 -*- def hammingWeight(n: int) -> int: m = 0 while n: m += 1 n = n & (n - 1) return m def hammingWeight2(n: int) -> int: m = 0 flag = 1 while n >= flag: if n & flag: m += 1 flag = flag << 1 return m ...
from typing import List from XivDbReader.collections import Weapon from XivDbReader import Reader, ExportCsv #r: Reader = Reader(job='pld') #pldArms: List[Weapon] = r.getArms(recordLimit=1) whmReader: Reader = Reader(job='whm') whmArms: List[Weapon] = whmReader.getArms(recordLimit=1) ec = ExportCsv(recordType='we...
import unittest import checksieve from . import util class TestCommandsAST(util.DiffTestCase): def test_require(self): self.assertNoDiff(util.diff(util.run_mock('commands/require_single.sieve'), 'commands/require_single.out')) def test_require_list(self): self.assertNoDiff(util.diff(util....
from datetime import datetime from decimal import Decimal import json import os from corehq.apps.userreports.models import DataSourceConfiguration, ReportConfiguration from corehq.util.dates import iso_string_to_date def get_sample_report_config(): folder = os.path.join(os.path.dirname(__file__), 'data', 'configs...
import itertools matches = set() for i in itertools.permutations('123456789', 9): for s in xrange(1, 4): for s2 in xrange(s + 1, (14 - s) / 2): a = int(''.join(i[:s])) b = int(''.join(i[s:s2])) c = int(''.join(i[s2:])) if a * b == c: matches.a...
import re class Game: def __init__(self, player1, player2): self.fields = [Field() for i in range(9)] self.player1 = player1 self.player2 = player2 # display fields the way your numpad is configured for the best # user experience (7 is top left, 3 is bottom right, etc.) def __d...
#### Values from the SWMF soucecode, Batsrus.jl code, #### and also some extra named contants and indices # Possible values for the status variable Unset_ = -100 # index for unset values (that are otherwise larger) Unused_ = -1 # unused block (not a leaf) Refine_ = -2 # parent block to be refined DontC...
#!/usr/bin/env python # Example server used to test Simple-CSRF-script.py and Advanced-CSRF-script.py # GET creates the token # POST verifies itand creates a new one from BaseHTTPServer import HTTPServer, BaseHTTPRequestHandler from optparse import OptionParser import string, random, re html = """ <!DOCTYPE html> ...
import os import shutil import subprocess import tempfile from base import Base from strings import Strings class MacSource(Base): def __init__(self): Base.__init__(self) def extract_strings_from_filename(self, filename): output_dir = self._get_output_directory() self._run_genstrings_...
#! /usr/bin/env python import scipy as s import pylab as p import scipy.integrate as si from scipy import stats #I need this module for the linear fit import smtplib from email.MIMEMultipart import MIMEMultipart from email.MIMEBase import MIMEBase from email.MIMEText import MIMEText from email import Encoders import os...
from amaranth_boards.icebreaker import * from amaranth_boards.icebreaker import __all__ import warnings warnings.warn("instead of nmigen_boards.icebreaker, use amaranth_boards.icebreaker", DeprecationWarning, stacklevel=2)
from .converter import Converter from .core import get_labelstudio_export_from_api from .pseudolabels import compute_labelstudio_preds __all__ = [ "Converter", "compute_labelstudio_preds", "get_labelstudio_export_from_api", ]
from __future__ import print_function from future import standard_library standard_library.install_aliases() from builtins import range from builtins import object import MalmoPython import json import logging import os import random import sys import time if sys.version_info[0] == 2: import Tkinter as tk else:...
# -*- coding: utf8 -*- # vim: ts=4 sts=4 sw=4 et: from django.conf.urls import include, url from django.contrib import admin from burndown_for_what.views import BurndownTemplateView, SprintView, SprintDetailView, MilestoneView, IssueView urlpatterns = [ url( r'^sprint/(?P<sprint_id>\d+)/$', Burnd...
from __future__ import print_function, division, absolute_import, unicode_literals import io from fontTools.misc.py23 import * from ufo2ft import ( compileOTF, compileTTF, compileInterpolatableTTFs, compileVariableTTF, compileVariableCFF2, ) import warnings import difflib import os import sys import...
import unittest from belleflopt.support import day_of_water_year, water_year class TestWaterYearDates(unittest.TestCase): def test_day_of_water_year(self): self.assertEqual(1, day_of_water_year(2010, 10, 1)) self.assertEqual(1, day_of_water_year(2020, 10, 1)) self.assertEqual(366, day_of_water_year(2020, 9, 30...
# ------------------------------------------------------------------------------ # Copyright (c) 2010-2013, EVEthing team # All rights reserved. # # Redistribution and use in source and binary forms, with or without modification, # are permitted provided that the following conditions are met: # # Redistributions of...
# coding=utf8 # Copyright 2018 JDCLOUD.COM # # 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 ...
# -*- coding: utf-8 -*- import cv2 import numpy as np import collections def SeedFill(point, src, label): queue = collections.deque() queue.append(point) while len(queue) != 0: pt = queue.popleft() label[pt[0],pt[1]] = 255 if src[pt[0]-1,pt[1]] == src[pt[0],pt[1]] and label[p...
import numpy as np import matplotlib.pyplot as plt from constants import Constants as cts import warnings; warnings.filterwarnings('ignore') class ImageReader: def __init__(self, mode): assert mode in [0, 1, 2], 'Insert a valid mode. Print cts.__doc__ for help.' self.mode = mode de...
"""Routes then builds a get_state response object""" import logging from hive.server.bridge_api.objects import load_posts_keyed from hive.server.common.helpers import ( return_error_info, valid_account, valid_permlink) log = logging.getLogger(__name__) @return_error_info async def get_discussion(context...
import numpy as np class BackPropagationNetwork: """a bp network""" # class members # layerCount=0 shape=None weights=[] # # class members # def __init__(self,layerSize): """Initialize the network""" # Layer info self.layerCount=len(layerSize)-1 self.shape=layerSize # Data from last run self...
from .trainset import TrainSet, MatrixTrainSet from .testset import TestSet from .reader import Reader __all__ = ['TrainSet', 'MatrixTrainSet', 'TestSet', 'Reader']
#!/usr/bin/env python # -*- coding: utf-8 -*- """config for pytest.""" def pytest_configure(config): """Configure pytest.""" plugin = config.pluginmanager.getplugin("mypy") plugin.mypy_argv.append("--ignore-missing-imports")
from backend.handler.project import project from backend.handler.project import project_group
from random import randint from retrying import retry import apysc as ap from apysc._display.rotation_around_center_interface import \ RotationAroundCenterInterface from apysc._expression import expression_data_util class _TestInterface(RotationAroundCenterInterface): def __init__(self) -> None...
''' quando se trabalha com groupby os dados devem estar ordenados para que ele consiga agrupar todos iguais em um dicionario ''' from itertools import groupby alunos = [ {'nome': 'Adriana', 'nota': '10' }, {'nome': 'Eragon', 'nota': '5' }, {'nome': 'João', 'nota': '7' }, {'nome': 'Maria', '...
from collections import namedtuple # input int n and collection of input (n, m) = (int(input()), input().split()) Grade = namedtuple('Grade', m) marks = [int(Grade._make(input().split()).MARKS) for _ in range(n)] # print avarage print((sum(marks) / len(marks)))
import pathlib import textwrap import jiml import pytest def test_imports(): t = jiml.load_template(textwrap.dedent( ''' # options globals: - urllib --- host: {{ urllib.parse.urlparse(url).hostname }} ''' )) assert t({'url': 'https://example.com...
"""Basic thermodynamic calculations for pickaxe.""" from typing import Union import pint from equilibrator_api import ( Q_, ComponentContribution, Reaction, default_physiological_ionic_strength, default_physiological_p_h, default_physiological_p_mg, default_physiological_temperature, ) fro...
'''Main functionality for artifact creation''' import copy import os import logging import random import re import shutil import string import tempfile import zipfile from os import path from multiplexer.source import Github import boto3 import yaml LOG = logging.getLogger(__name__) S3_REGEX = r'^s3:\/\/([a-zA-Z0-9...