content
stringlengths
5
1.05M
# -*- coding: utf-8 -*- import numpy as np def main(): lst = [1,2,3,4,5] lst_01 = get_average_by_sum(lst) print('by sum(): ') print(lst_01) lst_02 = get_average_by_numpy(lst) print('by numpy: ') print(lst_02) # Using sum() def get_average_by_sum(lst): average = sum(lst)/len...
import configparser import os con=configparser.ConfigParser() def readconf(n): con.read('step.ini') step=con.get("config",n) step=int(step) return step def writestep(num,n): con.read('step.ini') con.set("config",n,str(num)) con.write(open('step.ini','w'))
import pygame import sys import serial ser = serial.Serial('/dev/cu.usbmodem14202', 115200, timeout = 1000) serial_buffer = '' pygame.init() pygame.display.set_mode((320,200)) pygame.display.set_caption('Serial communication') clock = pygame.time.Clock() while True: clock.tick(60) serial_data = ser.read() ...
from recorder import Recorder from twitch import TwitchClient, constants as tc_const # Checker class # It's check streams and import logging class Checker: # Twitch client from main.py client: TwitchClient = None # Twitch user id for check id = None # Twitch user name for check username = ""...
#!/usr/bin/env python3 import argparse import os import requests import sys import sqlite3 import time __author__ = "pacmanator" __email__ = "mrpacmanator at gmail dot com" __version__ = "v1.0" def get_file(): """ Downloads a list of OUIs. """ url = "https://linuxnet.ca/ieee/oui/nmap-mac-prefixe...
# GENERATED FILE - DO NOT EDIT VERSION = '201909061227' BUILDS = {}
"""Choice type. A union type similar to the `Result` type. But also allows for higher number of choices. Usually you would most likekly want to use the `Result` type instead, but choice can be preferered in non-error cases. """ from abc import ABC from typing import Any, Generic, Iterable, TypeVar, get_origin, overloa...
from . import utils class ContinuousScale(object): def __init__(self, data_lim, svg_lim): self.data_0 = data_lim[0] self.data_len = utils.lims2len(data_lim) self.svg_0 = svg_lim[0] self.svg_len = utils.lims2len(svg_lim) def __call__(self, value): return self.svg_0 + s...
#!/usr/bin/python3 # Copyright 2020 Uraniborg 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 # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law ...
import tensorflow as tf import numpy as np with tf.Session() as sess: with tf.gfile.GFile('./artifacts/model2.pb', 'rb') as f: graph_def = tf.GraphDef() graph_def.ParseFromString(f.read()) _ = tf.import_graph_def(graph_def) input_node = sess.graph.get_tensor_by_name('import/inpu...
from PIL import Image from PIL import ImageFilter def resizeImgInsta(imgOrig,useBGBlurInsteadOfWhiteBG=False,fotoSeries=False): #from PIL import Image #from PIL import ImageFilter MAX_INSTA_IMG_PortSide_HEIGHT = 1350; MAX_INSTA_IMG_LandSide_SIZE=1080; MIN_INSTA_ING_LANDSIZE_HEIGHT=608; BG_COL...
# # PySNMP MIB module TIARA-NETWORKS-CONFIG-MGMT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIARA-NETWORKS-CONFIG-MGMT-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:16:27 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python ...
""" Demonstration handle dump for CMIP/ESGF files .. USAGE ===== -h: print this message; -v: print version; -t: run a test -f <file name>: examine file, print path to replacement if this file is obsolete, print path to sibling files (or replacements). -id <tracking id>: examine handle record of tracking id. -V:...
# 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...
# Escreva um programa que pergunte o salário de um funcionário e calcule o valor do seu aumento. Para salários superiores a R$ 1.250,00, calcule um aumento de 10%. Para salários inferiores ou iguais o aumento é de 15%. nome = str(input('Informe o seu nome: ')) salario = float(input('Informe o seu salário: ')) salariom...
from test.apps.openapi._fastapi.app import app import pytest import schemathesis from schemathesis import Case from schemathesis.constants import SCHEMATHESIS_TEST_CASE_HEADER, USER_AGENT schema = schemathesis.from_dict(app.openapi()) @pytest.mark.parametrize("headers", (None, {"X-Key": "42"})) @schema.parametrize...
import torch, os def mask_(matrices, maskval=0.0, mask_diagonal=True): """ Masks out all values in the given batch of matrices where i <= j holds, i < j if mask_diagonal is false In place operation :param tns: :return: """ b, h, w = matrices.size() indices = torch.triu_indices(h, ...
# coding: utf-8 """ Encoding DER to PEM and decoding PEM to DER. Exports the following items: - armor() - detect() - unarmor() """ from __future__ import unicode_literals, division, absolute_import, print_function import base64 import re import sys from ._errors import unwrap from ._types import type_name, str...
# Copyright (c) 2021, erpcloud.systems and contributors # For license information, please see license.txt # import frappe from frappe.model.document import Document import frappe, erpnext, json from frappe import _, scrub, ValidationError, throw from frappe.utils import flt, comma_or, nowdate, getdate, cint from erpne...
from django.contrib import admin from .models.board_model import Board # Register your models here. from .models.todo_model import TblTodo admin.site.register(TblTodo) admin.site.register(Board)
from flask import Flask, jsonify, request import docker from flask_cors import CORS DEBUG = True CONTAINERS = [] app = Flask(__name__) app.config.from_object(__name__) CORS(app, resources={r'/*': {'origins': '*'}}) def remove_container(container_id): container = client.containers.get(container_id) container...
def read_file_and_convert_to_list(file_path, ignore_comment=True): """ This method read in file and convert it to list, separated by line-breaker :param file_path: path to the file :param ignore_comment: if True, will ignore the line start with '#'; if False, read all. :return: list of strings ...
# -*- coding: utf-8 -*- # coding: utf8 """ /*************************************************************************** coller A QGIS plugin Paste selected vetors to vector layer ------------------- begin : 2017-12-01 git sh...
import numpy as np from colors import bcolors from os import listdir from sklearn.externals import joblib from os.path import isfile, join from neural_net_trainer import Collision_NN_Trainer import os class Config_Engine: def __init__(self, collision_graph, vars, config_fn='', override=False): self.collis...
# License: MIT import time import os import numpy as np import pickle as pkl from openbox.utils.logging_utils import get_logger, setup_logger from openbox.core.message_queue.master_messager import MasterMessager PLOT = False try: import matplotlib.pyplot as plt plt.switch_backend('agg') PLOT = True except...
# generated from catkin/cmake/template/pkg.context.pc.in CATKIN_PACKAGE_PREFIX = "" PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/home/ubuntu/catkin_ws/src/rosserial/rosserial_server/include;/usr/include".split(';') if "/home/ubuntu/catkin_ws/src/rosserial/rosserial_server/include;/usr/include" != "" else [] PROJECT_CATKIN_DEPEN...
CID=0 CFROM=1 CTO=2 CSPEED=3 CPLANTIME=4 RID=0 RLENGTH=1 RSPEED=2 RCHANNEL=3 RFROM=4 RTO=5 RISDUPLEX=6 XID=0 XXY=0 XUP=1 XRIGHT=2 XDOWN=3 XLEFT=4 X=0 Y=1 global cars global roads global crosses global crossxy global crossid cars={} roads={} crosses={} crossxy={} crossid={} with open('car.txt','r') as f: for i in f....
"""PyTorch implementation of the LARNN, by Guillaume Chevalier.""" import math import copy from collections import deque import torch from torch import nn import torch.nn.functional as F from multi_head_attention import MultiHeadedAttention, PositionalEncoding __author__ = "Guillaume Chevalier" __license__ = "MIT...
#!/usr/bin/python2.5 # # Copyright 2009 Google 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...
"""Example package for generating stardoc from rules_nodejs at source""" load("@build_bazel_rules_nodejs//packages/typescript:index.bzl", "ts_library") def custom_ts_library(name, deps = [], **kwargs): """ Helper wrapper around ts_library adding default attributes and dependencies Args: name: The...
from app import db class Player(db.Model): __tablename__ = "players" id = db.Column(db.Integer, primary_key=True, autoincrement=True) name = db.Column(db.String(128)) # TODO maybe make uid and provider TOGETHER be unique # UniqueConstraint('col2', 'col3', name='uix_1') uid = db.Column(d...
from tempConversions import * def test_temp_conversions_fToC_32_0(): assert fToC(32.0) == 0.0 def test_temp_conversions_fToC_212_100(): assert fToC(212.0) == 100.0 def test_temp_conversions_cToF_0_32(): assert cToF(0.0) == 32.0 def test_temp_conversions_cToF_100_212(): assert cToF(100.0) == 212.0
range(5, 10) # 5, 6, 7, 8, 9 range(0, 10, 3) # 0, 3, 6, 9 range(-10, -100, -30) # -10, -40, -70 range(-10, -101, -30) # -10, -40, -70 -100
# -*- coding: utf-8 -*- # # Poio Tools for Linguists # # Copyright (C) 2009-2014 Poio Project # Author: Peter Bouda <pbouda@cidles.eu> # URL: <http://media.cidles.eu/poio/> # For license information, see LICENSE.TXT from __future__ import unicode_literals import os import poioapi.io.mandinka import poioapi.data impo...
#!/usr/local/bin/python3.7 # -*- coding: utf-8 -*- # @Author skillnull # @Function 获取网易云音乐评论 import os import random import sys import json import time import base64 import codecs import requests import multiprocessing # 多进程 from Crypto.Cipher import AES import re # 正则表达式库 import numpy as np # numpy数据处理库 import co...
import os import sys import base64, json, re import time import requests import api from time import sleep as timeout from requests import get R='\033[1;31m'; B='\033[1;34m'; C='\033[1;37m'; Y='\033[1;33m'; G='\033[1;32m'; RT='\033[;0m' os.system('git pull && clear') a='aHR0cDovL3d3dy5qdXZlbnR1ZGV3ZWIubXRlL...
""" Copyright (c) 2018-2021 Intel Corporation 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...
input_data = list(map(int, input().split())) row = input_data[0] column = input_data[1] graph = [] result = 0 for i in range(row): graph.append(list(map(int, input()))) def dfs(x, y): if x < 0 or x > row - 1 or y < 0 or y > column - 1: return False if graph[x][y] == 1: return False graph[x][...
# Generated by Django 2.2 on 2019-05-19 12:29 from django.conf import settings from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] opera...
from justgood import imjustgood media = imjustgood("YOUR_APIKEY_HERE") tgl = "17-08-1945" # example birth date data = media.lahir(tgl) # Get attributes result = "Lahir : {}".format(data["result"]["lahir"]) result = "\nHari : {}".format(data["result"]["hari"]) result = "\nZodiac : {}".format(data["result"]["zodiak"]) ...
from keras.models import Sequential from keras.layers import Embedding import numpy as np model = Sequential() model.add(Embedding(1000, 1, input_length=10)) # the model will take as input an integer matrix of size (batch, input_length). # the largest integer (i.e. word index) in the input should be no larger than 999...
"""Redis: Delete emote hashes Revision ID: 5f746af0a82d Revises: 186928676dbc Create Date: 2019-06-04 19:07:25.109751 """ from pajbot.managers.redis import RedisManager from pajbot.streamhelper import StreamHelper # revision identifiers, used by Alembic. revision = '5f746af0a82d' down_revision = '186928676dbc' br...
from django.conf.urls import url from wagtailnetlify.views import success_hook, redirects urlpatterns = [ url(r"^success$", success_hook, name="success_hook"), url(r"^redirects$", redirects, name="redirect_builder"), ]
from reversion.revisions import create_revision, set_user, set_comment, deactivate class RevisionMiddleware: """Wraps the entire request in a revision.""" manage_manually = False using = None atomic = True def __init__(self, get_response): self.get_response = get_response def __c...
#!/usr/bin/env python -*- coding: utf-8 -*- from config import * from flask import Flask, render_template, Response, jsonify, request, redirect, url_for from jinja2 import Template import json import pigpio from i2c import I2c from motor import Motor import time from threading import Thread import sys import sqlite3 im...
from PyDictionary import PyDictionary import sys import warnings if not sys.warnoptions: warnings.simplefilter("ignore") dictionary=PyDictionary() s = "" old_s = "" while(s != "0"): s = input("Word / option: ") print("") if s == "1": if old_s == "": print("No previous records") else: print(dict...
import os import numpy import tensorflow as tf import scipy as scp import scipy.misc KITTI_TRAIN_DIR_PREFIX = '/usr/local/google/home/limeng/Downloads/kitti/data_road/training/image_2/' KITTI_GT_DIR_PREFIX = '/usr/local/google/home/limeng/Downloads/kitti/data_road/training/gt_image_2/' UM_TRAIN_TEMPLATE = "um_0000%02...
from urllib.parse import urlparse, unquote from records_mover.url.gcs.gcs_directory_url import GCSDirectoryUrl from typing import IO from records_mover.url import BaseFileUrl from smart_open.gcs import open as gs_open import google.cloud.storage from google.cloud.storage.blob import Blob import google.api_core.exceptio...
# -*- coding: utf-8 -*- from openerp import SUPERUSER_ID from openerp.osv import orm, fields class PaymentTransaction(orm.Model): _inherit = 'payment.transaction' _columns = { # link with the sale order 'sale_order_id': fields.many2one('sale.order', 'Sale Order'), } def form_feedbac...
#!/usr/bin/env python from multi_circle_2 import Multi_circle_2 if __name__ == '__main__': multi_circle_2 = Multi_circle_2( [ #x , y, z, yaw, sleep [0.0 , 0.0, 1.0, 0, 8], [0.0 , 0.0 ,1.0, 0, 3], [-0.3 , -1.4, 0.0, 0, 0], ] ) multi_circle_2.run(...
# Given a column title as appear in an Excel sheet, return its corresponding column number. # For example: # A -> 1 # B -> 2 # C -> 3 # ... # Z -> 26 # AA -> 27 # AB -> 28 class Solution: # @param s, a string # @return an integer def titleToNumber(self, s): d = {'...
""" Clustered/Convolutional/Variational autoencoder, including demonstration of training such a network on MNIST, CelebNet and the film, "Sita Sings The Blues" using an image pipeline. Copyright Yida Wang, May 2017 """ import matplotlib import tensorflow as tf import numpy as np from scipy.misc import imsave import o...
""" This provides wrappers for FMUs so they are easy to assemble in a short script, as well as support writing data in HDF5 format using pytable, as well as a library of FMUs ready to be assembled. The structure of the file starts with the FMU utilities, goes on to define modules and simulations, and ends with a list...
import numpy as np from jitcdde import input as system_input from symengine import exp from ..builder.base.constants import EXC, INH, LAMBDA_SPEED from ..builder.base.network import SingleCouplingExcitatoryInhibitoryNode from ..builder.base.neural_mass import NeuralMass from .model_input import OrnsteinUhlenbeckProces...
import os import shutil os_license = '{{ cookiecutter.license }}' notebooks = '{{ cookiecutter['jupyter notebooks'] }}' containers = '{{ cookiecutter.containers }}' if os_license == "No license file": os.remove("LICENSE") if notebooks == "No": shutil.rmtree("src/notebooks") if containers == "one": shuti...
"""Basic functionality sanity tests""" from urllib.parse import urljoin import pytest # Various sub-urls for the main page PAGE_URL_LIST = ["", "about/", "docs/", "scls/"] # Various sub-urls for a collection SCL_URL_LIST = ["", "edit/", "coprs/", "repos/", "acl/", "review_req/"] @pytest.mark.django_db def test_scl_...
from collections import OrderedDict import jsonschema from django.db.models import Q from jsonschema import Draft4Validator from rest_framework import serializers from architecture_tool_django.modeling.models import Edgetype, Nodetype from ..models import Edge, Node class EdgeSerializer(serializers.ModelSerializer...
#!/usr/bin/env python # -*- coding: utf-8 -*- from patsy import dmatrix from patsy import DesignMatrix, DesignInfo from patsy import LookupFactor,ModelDesc,Term X = [[1, 10], [1, 20], [1, -2]] print(dmatrix(X)) design_info = DesignInfo(["Intercept!", "Not intercept!"]) X_dm = DesignMatrix(X, design_info) print(dmatri...
table_file_template = """ import argparse from deriva.core import ErmrestCatalog, AttrDict, get_credential import deriva.core.ermrest_model as em from deriva.core import tag as chaise_tags from deriva.utils.catalog.manage.update_catalog import CatalogUpdater, parse_args {groups} table_name = '{table_name}' schema_na...
from opentelemetry import trace from opentelemetry.exporter.cloud_trace import CloudTraceSpanExporter from opentelemetry.sdk.trace import TracerProvider from opentelemetry.sdk.trace.export import SimpleExportSpanProcessor trace.set_tracer_provider(TracerProvider()) cloud_trace_exporter = CloudTraceSpanExporter() trac...
# Duas formas para se fazer a leitura de um número inteiro...# def leiaint(msg): valor = 0 while True: n = str(input(msg)) if n.isnumeric(): valor = int(n) break else: print('\033[31mERRO ! Digite um número inteiro válido.\033[m') retur...
from torch.nn import CrossEntropyLoss class GPT2Loss(CrossEntropyLoss): def __init__(self, pad_token_id): super(GPT2Loss, self).__init__(ignore_index=pad_token_id) def forward(self, output, labels): """ Loss function for gpt2 :param output: :param labels: :retu...
from mccq.cli import cli
import sys from bidi.algorithm import get_display # variable length print, the string constants are adjusted for bidi. # an unrelated editor is that vs code doesn't support bidi. # the workaround is to put bidi text into separate string variables. #not entirely sure, if we need to swap each element seperately... def...
import os from pathlib import Path from string import Template template = Template(""" Package: zram-swap Version: $version Depends: python3, libpython3-stdlib Section: custom Priority: optional Architecture: all Essential: no Installed-Size: $size Maintainer: Dmitry Orlov <me@mosquito.su> Description: Easy way to co...
"""Test label""" from napari.components.text_overlay import TextOverlay def test_label(): """Test creating label object""" label = TextOverlay() assert label is not None
import sys, clr import ConfigParser from os.path import expanduser # Set system path home = expanduser("~") cfgfile = open(home + "\\STVTools.ini", 'r') config = ConfigParser.ConfigParser() config.read(home + "\\STVTools.ini") # Master Path syspath1 = config.get('SysDir','MasterPackage') sys.path.append(syspath1) # Bui...
import json from urllib.parse import urlencode from flask import Response, request def _create_link(path, limit, offset, order_by, order_how, args_dict): # copy of the dict passed in so we don't modify the original params = dict(args_dict) params["limit"] = limit params["offset"] = offset params...
from distutils.core import setup setup( name='http_request', version='1.1', packages=['http_request'], url='https://github.com/dennisfischer/http_request', license='MIT', author='Dennis Fischer', author_email='dennis.fischer@live.com', description='A small python library to parse and bu...
# -*- coding: utf-8 -*- # * Copyright (c) 2009-2018. Authors: see NOTICE file. # * # * 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...
import pandas as pd from age.data.load.countries import base from age.data.load import transformations from age.data.load import utils from age.data.load import ined import logging import datetime from urllib.request import urlopen _CASES_PATH = 'https://data.rivm.nl/covid-19/COVID-19_casus_landelijk.csv' _INED_URL = ...
""" MIT License Copyright (c) 2018 Elias Doehne 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, publish, ...
#!/usr/bin/env python # -*- coding: utf-8 -*- import sys import os import os.path import xml.dom.minidom import argparse class Config(): def __add_server(self, parent_node, settings, server_name): try: os.environ["TRAVIS_SECURE_ENV_VARS"] except KeyError: print "no secur...
#!/usr/bin/python import gzip import socket #UDP_IP = "127.0.0.1" UDP_IP = "0.0.0.0" UDP_PORT = 6550 sock = socket.socket(socket.AF_INET, # Internet socket.SOCK_DGRAM) # UDP sock.bind((UDP_IP, UDP_PORT)) f = gzip.open('flight.dat.gz', 'wb') print "Aura Logger" print "listening for", UDP_IP,...
"""REST API endpoints""" from fastapi import APIRouter from app.api.api_v1.endpoints import items, users api_router = APIRouter() api_router.include_router(users.router, prefix="/users", tags=["users"]) api_router.include_router(items.router, prefix="/items", tags=["items"])
import os import sys import time import gc import copy import random import numpy as np import pandas as pd import torch.optim as optim import torch.nn.functional as F import torch.nn as nn from torch.autograd import Variable from image_util import * from data_util import * from env import * from sum_tree import * im...
from py_queryable import Model from py_queryable import Column, PrimaryKey, ForeignKey class StubModel(Model): __table_name__ = u'test_table' test_int_column = Column(int, 'int_column') class StubModel2(Model): __table_name__ = u'test_table' test_int_column = Column(int) class StubPrimary(Model): ...
from mmcv.utils import Registry,build_from_cfg TRANSFORMER = Registry('Transformer') POSITIONAL_ENCODING = Registry('Position encoding') def build_transformer(cfg,default_args=None): """Builder for Transfomer.""" return build_from_cfg(cfg,TRANSFORMER,default_args) def build_positional_encoding(cfg,default_ar...
from sports.nba.nba_team import NBA_Team class HoustonRockets(NBA_Team): """ NBA Golden State Warriors Static Information """ full_name = "Houston Rockets" name = "Rockets" team_id = 1610612745 def __init__(self): """ """ super().__init__()
# -*- coding: utf-8 -*- # Generated by Django 1.11 on 2019-02-17 09:46 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('backend', '0043_backend_filteredlanguage'), ] operations = [ migrations.AddFi...
import sys import secrets from toolbox._common import PlaybookRun class OCMAddon: """ Commands for managing OCM addons """ @staticmethod def install(ocm_refresh_token, ocm_cluster_id, ocm_url, ocm_addon_id, wait_for_ready_state=False): """ Installs an OCM addon Args: ...
# -*- coding: utf-8 -*- # Generated by Django 1.9.4 on 2016-03-31 08:21 from __future__ import unicode_literals from django.db import migrations, models import django.db.models.deletion class Migration(migrations.Migration): dependencies = [ ('first_app', '0005_inventory'), ] operations = [ ...
import random from shop import db from shop.models import Menu, Computers class Computer: computers = 1 def __init__(self): self.name = "Model: MacBook {}".format(self.computers) self.price = random.randint(20000, 30000) self.currency = '₽' self.disk_size = "Disk size:{} Gb".f...
import math from collections import OrderedDict from typing import Optional, Dict, List, Union import numpy import shapely.geometry from OpenGL.GL import GL_RGB8 from pyrr import Vector3 from rasterio import features from rasterio import transform from rasterstats import zonal_stats from shapely.geometry import Polygo...
# Copyright (c) 2014-2015, NVIDIA CORPORATION. All rights reserved. from gevent import monkey; monkey.patch_all() from nose.tools import assert_raises import mock from . import scheduler as _ from config import config_value from job import Job from digits.utils import subclass, override class TestScheduler(): ...
from pathlib import Path from flask_wtf import FlaskForm from wtforms import SelectMultipleField, SubmitField from wtforms.validators import DataRequired path = Path(".") forecast = sorted(path.glob("data/forecast_*.json"), reverse=True) choices = [(p, p) for p in forecast] class YearSelectForm(FlaskForm): year ...
""" 1. Clarification 2. Possible solutions - Brute force - HashMap 3. Coding 4. Tests """ # T=O(n^2), S=O(1) class Solution: def twoSum(self, nums: List[int], target: int) -> List[int]: if len(nums) < 2: return [-1, -1] for i in range(len(nums)): for j in range(i + 1, len(nums)...
import enum from typing import Dict class PropertyType(enum.Enum): HOUSE = 0 FLAT = 1 BUNGALOW = 2 class BuiltForm(enum.Enum): MID_TERRACE = 0 SEMI_DETACHED = 1 DETACHED = 2 END_TERRACE = 3 class OccupantType(enum.Enum): OWNER_OCCUPIED = 0 RENTED_PRIVATE = 1 RENTED_SOCIAL =...
import pdb import logging import numpy as np import sys sys.path.append('..') import MRATools as mt def determine_radius(k, h): if k==0: raise ValueError("Ensemble size must be stricly positive") s = np.floor(np.sqrt(k)) if s % 2==0: sf = s-1 else: sf = s if k==sf**2...
# -*- coding: utf-8 -*- """Code for creating diagrams."""
from .confirmationwindow import ConfirmationWindow from .menu import Menu from .popupwindow import PopupWindow from .scrollselector import ScrollSelector from .filemenu import FileMenu __all__ = ["PopupWindow","ScrollSelector", "ConfirmationWindow","Menu", "FileMenu"]
from typing import Optional import torch from anndata import AnnData from scvi.model import SCVI use_gpu = torch.cuda.is_available() def unsupervised_training_one_epoch( adata: AnnData, run_setup_anndata: bool = True, batch_key: Optional[str] = None, labels_key: Optional[str] = None, ): if run_...
from jmanager.utils.print_utils import get_progress_text PROGRESS_TEXT = "test |========================= | 50.0%" class TestPrintUtils: def test_get_progress_text(self): assert get_progress_text(msg="test", iteration=1, total=2) == PROGRESS_TEXT
import numpy as np def get_pieces_count(state): count = 0 for s in state: if s.isalpha(): count += 1 return count def is_kill_move(state_prev, state_next): return get_pieces_count(state_prev) - get_pieces_count(state_next) def create_position_labels(): labels_array = [] l...
import numpy as np import theano import theano.tensor as T import util def vanilla(params, gradients, opts): return [(param, param - opts.learning_rate * gradient) for param, gradient in zip(params, gradients)] def momentum(params, gradients, opts): assert opts.momentum >= 0.0 and opts.momentum <...
distancia = float(input('Qual é a distancia da sua viagem?' )) print('voce esta prestes a começa uma viagem de {}km.'.format(distancia)) preço = distancia * 0.50 if distancia <= 200 else distancia * 0.45 print('É o preço da sua passagem sera de R${:2f}'.format(preço)) opcao4 = '' while opcao4!= 'S' and opcao4 != 'N': ...
# ### 1.5 function that post process the ccs results import numpy as np import pandas as pd # define a function that could calculate the overall annual emission and lock emission def bau_ccs_post (df): coal_annual_existing_emission = df.loc[:,('coal_power_annual_emission_existing')].values coal_annual_n...
from bokeh.models import HoverTool, ColumnDataSource from bokeh.plotting import figure, output_file, show from bokeh.models.markers import marker_types import bokeh.layouts import datetime import numpy as np import DownloadData age, year_week, data = DownloadData.incidence() np_data = np.array(data) np_data[np_data ...
#!/usr/bin/env python # # Copyright 2014 Hewlett-Packard Development Company, L.P. # # 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...
#!/usr/bin/env python3 """ Author : Ken Youens-Clark <kyclark@gmail.com> Date : 2020-11-11 Purpose: Find patterns in files """ import argparse import re from typing import List, NamedTuple, TextIO class Args(NamedTuple): """ Command-line arguments """ pattern_file: TextIO search_files: List[TextIO] ...