content
stringlengths
5
1.05M
import torch from torch import nn from torch import optim from torch.nn import init from torch.nn import functional as F class Distance(object): def __init__(self): pass def is_adversarial(self): return False class Joint(Distance): def __init__(self, distances): self.distances =...
#!/usr/bin/python ############################################################## # Very cute little class that gets a yes or no from the user # ############################################################## class yesno(): valid_all = ["Y", "y", "YES", "yes", "Yes", "N", "n", "NO", "no", "No", ""] valid_yes_d...
# --- # jupyter: # jupytext: # text_representation: # extension: .py # format_name: light # format_version: '1.5' # jupytext_version: 1.3.2 # kernelspec: # display_name: Python [conda env:py27] # language: python # name: conda-env-py27-py # --- import plotly # #############...
import gym from gym import spaces from gym.utils import seeding import numpy as np from numpy import linalg as LA import math import os class RaceCarEnv(gym.Env): """Custom Environment that follows gym interface""" metadata = {'render.modes': ['human', 'rgb_array'],'video.frames_per_second': 25} def __in...
"""This ugly module is fighting with res.py to make some useful job.""" import os import platform import pygame from lib import tts from lib.msgs import nb2msg from lib.screen import set_screen from lib.sound import init_sound, sound_stop, get_volume, set_volume from lib.sound_cache import sounds from lib.voice impo...
import paho.mqtt.client as mqtt import cv2 as cv import numpy as np import argparse from detecto.core import Model import time SERVER_PORT = 1883 TOPIC_TX = 'AI-tx' TOPIC_RX = 'AI-rx' FILENAME = 'model_weights.pth' parser = argparse.ArgumentParser() parser.add_argument("-i", "--ip", help="mqtt server IP address", def...
import sys from fabric.colors import red from fabric.api import local,task @task(default=True) def check(): PY3 = sys.version_info[0]==True if not (PY3): print(red('Please install python3 to build the project')) quit() @task def clean(): local('./bin/clean.py && fclear python') @task(ali...
import numpy as np import imageio import os import torch from tqdm import tqdm from genmotion.render.python.renderer import get_renderer import genmotion.render.python.utils as geometry def get_rotation(theta=np.pi/3): axis = torch.tensor([0, 1, 0], dtype=torch.float) axisangle = theta*axis matrix = geomet...
from unittest.mock import patch import pandas as pd import pytest from evalml.automl import AutoMLSearch, search from evalml.automl.automl_algorithm import DefaultAlgorithm from evalml.utils import infer_feature_types @patch("evalml.data_checks.default_data_checks.DefaultDataChecks.validate") @patch("evalml.automl....
from collections import OrderedDict d = OrderedDict() d['Import'] = 'Bring a document' d['Print'] = 'Print' d['Class'] = 'Code for creating objects' d['Def'] = 'To define a method' for key,value in d.items(): print(str(key) + ": " + str(value) + "\n")
import os import hydra import logging logger = logging.getLogger(__name__) def run(args): import unet import tensorflow as tf import dataset_loader from tensorflow.keras.optimizers import Adam import soundfile as sf import datetime from tqdm import tqdm import numpy as np path_ex...
import flask from flask import request, jsonify import fdb, json, collections #import uvicorn app = flask.Flask(__name__) app.config["DEBUG"] = False con = fdb.connect( host='127.0.0.1', database='E:\\CienciaDeDados\\PythonIniciante\\apiRest\\AGRO.FDB', user='sysdba', password='masterkey' ) #con = fdb.conne...
# Copyright 2015, 2016 Altova GmbH # # 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 wri...
from unittest import TestCase from namesparser import HumanNames, Token as T COMMA = T("COMMA") AND = T("AND") class TestHumanNames(TestCase): def test_clean(self): self.assertEqual("Harris Tweed", HumanNames._clean("Harris Tweed")) self.assertEqual("Harris Tweed", HumanNames._clean("Harris Tweed...
import helpers import itertools import collections def main() -> None: z, x, aim = 0, 0, 0 lines = helpers.read_input_split(" ", 2) for cmd, v in lines: n = int(v) if cmd == "up": aim -= n elif cmd == "down": aim += n else: x += n ...
from models.evolution import Evolution from models.phenotype import Phenotype from models import visualize import config import os import json import sys ''' Steps to use the library: 1. Set the configuration parameters 2. Import the configuration variables 3. Set the fitness function you would like to eva...
import os import sys from sqlalchemy import Column, ForeignKey, Integer, String, Boolean, DateTime from sqlalchemy.ext.declarative import declarative_base from sqlalchemy.orm import relationship from sqlalchemy import create_engine Base = declarative_base() class Recept(Base): __tablename__ = 'recept' recept_...
#!/usr/bin/env python # -*- coding: utf-8 -*- # # name: main.py (Python 3.x). # description: Software para la medición de IMU 9DOF # purpose: Analisis de la marcha y movimientos corporales # mediante IMU # author: David Avila Quezada # #------------------------------------------------------...
# Post processing algorithm # # This program proprietary to Team Titans of AlphaPilot Challenge # Authors: Carson Wilber # Team Captain: Ashok Yannam #---------------------------------------------------# ordered_corner_keys = ["UL", "UR", "LR", "LL"] def ordered_xy_predictions_to_dict(ordered_xy_predictions): corne...
import argparse parser = argparse.ArgumentParser() parser.add_argument('--job_name', type=str, default='demo_job') parser.add_argument('--log_path', type=str, default='./', help="default path is ../log") # The basic configuration of the cluster parser.add_argument('--ps_ip', type=str, default='127.0.0.1') parser.add_...
# -*- coding: utf-8 -*- """ [googleSearch.py] Google Search Plugin [Author] Justin Walker [About] Returns the first three links from a google search. [Commands] >>> .google <<search term>> returns search links """ try: from googlesearch import search except ImportError: print("No modu...
#!/usr/bin/env python3 # # __init__.py """ yapf 💌 isort. """ # # Copyright © 2020 Dominic Davis-Foster <dominic@davis-foster.co.uk> # License: Apache Software License 2.0 # See the LICENSE file for details. # # stdlib from typing import Optional # 3rd party import click import isort # type: ignore from consolek...
import math x = math.pi print(x)
import datetime import pickle import unittest import pytest from geopy.timezone import Timezone, from_fixed_gmt_offset, from_timezone_name try: import pytz import pytz.tzinfo pytz_available = True except ImportError: pytz_available = False @pytest.mark.skipif("not pytz_available") class TimezoneTes...
from SCons.Script import * import filecmp ######################################################################## # # comparison with reference output # def __compare_action_exec(target, source, env): __pychecker__ = 'no-argsused' [_source] = source linestring = open(str(_source), 'r').read() if ...
#-*- coding:utf-8 -*- import func def main(): args = func.get_args() if hasattr(args, 'file'): print(args.file) func.write_file((func.chop_categoly(func.get_file(args.file)))) # main関数呼び出し if __name__ == "__main__": main()
from random import randint from pybook.ch13.FIleTestConst import TEST_PATH def main(): # Open file for writing data fileName = TEST_PATH + "Numbers.txt" outfile = open(fileName, "w") for i in range(10): outfile.write(str(randint(0, 9)) + " ") outfile.close() # Close the file # Open ...
from dotenv import load_dotenv import os load_dotenv(dotenv_path=os.path.join(os.getcwd(), '.env')) os.environ.setdefault('SIMPLE_SETTINGS', 'stare.settings.base') from simple_settings import settings __all__ = ['settings']
cache_max_age = 3600 * 10 # 10h static = { "Strict-Transport-Security": "max-age={}".format(cache_max_age), "Cache-Control": "public max-age={}".format(cache_max_age) } api = { "Strict-Transport-Security": "max-age={}".format(cache_max_age), "Cache-Control": "no-cache" }
import logging from demo_adapter_python.config import demo_adapter_config try: with open("VERSION", "r", encoding="utf8") as version_file: VERSION = version_file.read().strip() except FileNotFoundError: VERSION = "dev snapshot" def configure_logging(the_logger: logging.Logger) -> None: """Setup...
#!/usr/bin/env python import vtk def main(): colors = vtk.vtkNamedColors() # Create the RenderWindow, Renderer and both Actors renderer = vtk.vtkRenderer() renderWindow = vtk.vtkRenderWindow() renderWindow.AddRenderer(renderer) renderWindowInteractor = vtk.vtkRenderWindowInteractor() render...
import os import unittest from urllib.parse import urlparse, parse_qs from server import create_app from server.services.users.authentication_service import AuthenticationService from tests.server.helpers.test_helpers import ( get_canned_osm_user_details, get_canned_osm_user_details_changed_name, ) class Tes...
########################################################################## # # Copyright (c) 2013-2014, Image Engine Design Inc. All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redis...
from gityping.gityping import generate_class_stubs def test_gdk_color(): from gi.repository import Gdk stub_lines = generate_class_stubs(Gdk, Gdk.Color) print("\n".join(stub_lines)) foo = """ class Color: MAX_VALUE = ... # type: int blue = ... # type: int blue_float = ... # type: typi...
# -*- coding: utf-8 -*- """ Class to represent a point cloud via a vtkPolyData, with the ability to dynamically add points """ from numpy import hstack, ones, int64, arange, ascontiguousarray, warnings from vtk import (vtkPoints, vtkCellArray, vtkPolyData, vtkPolyDataMapper, # pylint: disable=no-name-in-module ...
#!/usr/bin/env python3 """ tests for the rclone driver """ # std modules: from unittest import TestCase try: # py2 from mock import MagicMock except ImportError: # py3 from unittest.mock import MagicMock # dependencies: from backdat.RemoteInterface import rclone class Test_rclone_driver(TestCase): ...
""" Tests for utils.py """ # ignore missing doc-string warnings # pylint: disable=C0116 import tarfile import pytest from lyncs_io.utils import find_file, get_depth, find_member, format_key from lyncs_io.testing import tempdir from lyncs_io.base import save def test_find_file(tempdir): open(tempdir + "data.npy"...
#!/usr/bin/env python # # Copyright (C) 2009-2020 the sqlparse authors and contributors # <see AUTHORS file> # # This module is part of python-sqlparse and is released under # the BSD License: https://opensource.org/licenses/BSD-3-Clause """Module that contains the command line app. Why does this file exist, and why ...
from moto.core.responses import BaseResponse class SpotFleets(BaseResponse): def cancel_spot_fleet_requests(self): spot_fleet_request_ids = self._get_multi_param("SpotFleetRequestId.") terminate_instances = self._get_param("TerminateInstances") spot_fleets = self.ec2_backend.cancel_spot_fl...
import gensim.downloader as api import numpy as np import pandas as pd from src.configs.variables_const import VariablesConsts from src.data.processing.build_vector_spaces import build_vector_space from src.evaluation.evaluation_method import EvaluationMethod from src.graph_model.BiGIT import BiGIT class Word2VecExp...
""" Copyright 2019 Google LLC Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at https://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software di...
try: from zcrmsdk.src.com.zoho.crm.api.exception import SDKException from zcrmsdk.src.com.zoho.crm.api.util import APIResponse, CommonAPIHandler, Constants except Exception: from ..exception import SDKException from ..util import APIResponse, CommonAPIHandler, Constants class TerritoriesOperations(object): def _...
import re import requests import xbmc from ..scraper import Scraper from ..common import clean_title class dlvaio(Scraper): domains = ['http://dl3.vaiomusic.org/'] name = "dlvaio" sources = [] def __init__(self): self.base_link = 'http://dl3.vaiomusic.org/Movie/' self.link1 = 'http://...
from __future__ import annotations import enum from datetime import datetime from .snowflake import Snowflake class EpochType(enum.IntEnum): BEFORE = enum.auto() AFTER = enum.auto() AROUND = enum.auto() class BaseEpoch: __slots__ = ('type', 'snowflake') def __init__(self, *, type: EpochType, ...
from common.helpers import print_mesage from common.constants import PRINT_CHOICE class OptionsHandler: """ """ def __init__(self, book_choices, vendor): """Constructor.""" self.choices = book_choices self.vendor = vendor def display_choices(self): """Display a list of gi...
import pygame import settings import math from vector import Vector2D from animation import Animation, OneTimeAnimation # http://www.gamasutra.com/view/feature/3938/the_pacman_dossier.php?print=1 class Player(pygame.sprite.Sprite): def __init__(self, position=(0, 0)): super(Player, self).__init__() ...
def stimulus_fft(type, wl, ratio): # STIMULUS_FFT uses fast fourier transform to plot the amplitude spectrum of a potential stimulus pattern # Inputs: # type - type of stimulus, e.g. 'bar'/'dog'/'square'/'log' (see below for full list) # wl - wavelength of stimulus in degrees (definition depen...
import sys, json from pathlib import Path try: import acmacs except: import pprint print(f"> ERROR: cannot import acmacs\n{pprint.pformat(sys.path)}", file=sys.stderr) raise # ====================================================================== sGrey = "#D0D0D0" sTestAntigenSize = 10 sReferenceAntig...
class Mensaje: def __init__(self, estacionamiento=None, puerta=None, placa=None, tipo=None): self.estacionamiento = estacionamiento self.puerta = puerta self.placa = placa self.tipo = tipo def toJSON(self): return self.__dict__
# ICRAR - International Centre for Radio Astronomy Research # (c) UWA - The University of Western Australia, 2017 # Copyright by UWA (in the framework of the ICRAR) # All rights reserved # # This library is free software; you can redistribute it and/or # modify it under the MIT license # # Created ...
#!/usr/bin/env python """ Test the GeneticCnnModel using the MNIST dataset """ import os import sys sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) if __name__ == '__main__': import mnist import random from sklearn.preprocessing import LabelBinarizer from gentun im...
import numpy as np from sklearn.linear_model import LinearRegression import os import pandas as pd import statsmodels.api as sm # Define working folder out_folder = 'results' if not os.path.exists(out_folder): os.makedirs(out_folder) os.chdir(out_folder) # Define countries and states to loop over file_list = ['A...
import discord from discord.ext import commands from sqlalchemy import engine, create_engine from sqlalchemy.orm import sessionmaker from sqlalchemy import any_ import arrow import asyncio from tabulate import tabulate import random, string from models import * import config REACTIONS = ['✅', '❌', '⏲'] engine = c...
from slideatlas import site_slideatlas as site import pymongo import datetime # Boilerplate to get database connection conn = pymongo.Connection(site.MONGO_SERVER) admindb = conn["admin"] if site.LOGIN_REQUIRED: admindb.authenticate(site.USERNAME, site.PASSWORD) def logparse(dbname): """ Parse the log and...
"""Custom click parameters.""" import ipaddress from typing import Literal, Union import click import pydantic from click_params import ListParamType, ValidatorParamType from certipie.core import is_domain_name class IpModel(pydantic.BaseModel): ip: Union[ipaddress.IPv6Network, ipaddress.IPv4Network, ipaddress....
#!/usr/bin/env python ''' Test_dedalusRewriter.py Defines unit tests for dedalusRewriter.py from src/dedt/. ''' ############# # IMPORTS # ############# # standard python packages import inspect, os, sqlite3, sys, unittest from StringIO import StringIO # ------------------------------------------------------ # # ...
# -*- coding: utf-8 -*- # Part of Odoo. See LICENSE file for full copyright and licensing details. from odoo import api, fields, models, _ class MrpProduction(models.Model): _inherit = 'mrp.production' sale_order_count = fields.Integer( "Count of Source SO", compute='_compute_sale_order_coun...
# -*- encoding: utf-8 -*- # Source: https://packaging.python.org/guides/distributing-packages-using-setuptools/ import io import re from setuptools import find_packages, setup dev_requirements = [ 'bandit', 'flake8', 'isort', 'pytest', ] unit_test_requirements = [ 'pytest', ] integration_test_req...
import re from fnmatch import fnmatch from functools import lru_cache from typing import List, NamedTuple from django.conf import settings from rest_framework.utils.encoders import JSONEncoder from multiselectfield.db.fields import MSFList def remove_non_member_fields(d: dict): return {k: v for k, v in d.items(...
# -*- coding: utf-8 -*- # Copyright (c) 2017, Frappe Technologies Pvt. Ltd. and Contributors # See license.txt from __future__ import unicode_literals import frappe import unittest from frappe.utils import nowdate, now_datetime, flt from erpnext.stock.doctype.item.test_item import create_item from erpnext.manufacturin...
"""In this module we test the pydeck functionaly""" import pydeck as pdk # pylint: disable=redefined-outer-name,protected-access from awesome_panel.express import PyDeck def test__repr_html(): """We need a way to convert a pydeck.Deck into HTML that can be shown in a Pane in Panel. We test that fu...
import unittest from selenium import webdriver import requests import os from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from selenium.webdriver.support.ui import WebDriverWait class LoginForm(unittest.TestCase): def setUp(self): # Put your use...
import py_cui from pprint import pprint """ A playground to see Attributes of widgets which document is not complete about. """ class TestSubject: def __init__(self, root_): self.root = root_ self.widgets = [ self.root.add_button("test", 0, 0, command=self.passer), self....
import os import string import typing from dataclasses import dataclass from jinja2cli import cli, capact import pytest # change dir to tests directory to make relative paths possible os.chdir(os.path.dirname(os.path.realpath(__file__))) @dataclass class RenderTestCase: name: str template: str data: ty...
#Definition the variable print("Ejercicio 1:Area de un triangulo") #Datos de entrada mediante dispositivos de entrada b=int(input("Ingrese Base")) h=int(input("Ingrese Altura")) #Proceso area=(b*h)/2 #Datos de Salida en dispositivos de Salida print("Area de triangulo:", area)
from .draggable import DraggableMixin # noqa from .clickable import ClickableMixin # noqa from .keyable import KeyableMixin # noqa
#!/usr/bin/env python3 import enum import functools import json import pprint import sys import pymongo class JobState(enum.IntEnum): error = 0 pending_approval = 1 queued = 2 running = 3 done = 4 def _resolve_analysis_state(v): # Test for names try: state_num = JobState[v] e...
import unittest from app.models import Blog,User from flask_login import current_user from app import db class TestBlogs(unittest.TestCase): def setUp(self): self.user_Derrick = User(username="derrokip34",password="zlatan",email="derrokip@gmail.com") self.new_blog = Blog(blog_title="Batman",blog_c...
import dataclasses import math from typing import Union import pytest from pycertainties.val import Real, Val @pytest.mark.parametrize( "val1, val2, expected", ( (Val(10, math.sqrt(7)), Val(5, math.sqrt(2)), Val(5, 3)), (Val(10, 3.21), 2, Val(8, 3.21)), (10, Val(5, 3.21), Val(5, 3.21...
import unittest import os import math from osgeo import ogr import numpy as np from gdalhelpers.functions.create_points_at_angles_distance import create_points_at_angles_distance POINTS_PATH = os.path.join(os.path.dirname(__file__), "..", "test_data", "points.gpkg") class CreatePointsAtAnglesDistanceTestCase(unittes...
from django.shortcuts import render from django.views.defaults import bad_request, page_not_found, server_error def index(request): return render(request, "Pages/index.html") def google_file(request): return render(request, "google5c02155bdaa39045.html") def sitemap(request): return render(request, "sitemap...
""" The MIT License Copyright (c) 2014- High-Mobility GmbH (https://high-mobility.com) 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...
#!/usr/bin/env python3 from bitbots_test.test_case import RosNodeTestCase from bitbots_test.mocks import MockSubscriber from geometry_msgs.msg import Twist from bitbots_msgs.msg import JointCommand import rospy class WalkRunsTestCase(RosNodeTestCase): def test_walk_runs(self): sub = MockSubscriber('walkin...
#!/usr/bin/env python """celerybeat .. program:: celerybeat .. cmdoption:: -s, --schedule Path to the schedule database. Defaults to ``celerybeat-schedule``. The extension ".db" will be appended to the filename. .. cmdoption:: -S, --scheduler Scheduler class to use. Default is celery.beat.PersistentSch...
#! /home/sheffler/.conda/envs/rpxdock/bin/python import logging, itertools, concurrent, tqdm, rpxdock as rp import numpy as np def get_rpxdock_args(): kw = rp.options.get_cli_args() if not kw.architecture: raise ValueError("architecture must be specified") return kw def get_spec(arch): arch = arch.upper(...
import bpy from bpy.props import * from bpy.types import Node, NodeSocket from arm.logicnode.arm_nodes import * class IsFalseNode(Node, ArmLogicTreeNode): '''Is False node''' bl_idname = 'LNIsFalseNode' bl_label = 'Is False' bl_icon = 'CURVE_PATH' def init(self, context): self.inputs.n...
import time import tm1640 import machine from setting import PORTS_DIGITAL from utility import * class Image: HEART = [0x00,0x00,0x00,0x0c,0x1e,0x3e,0x7e,0xfc, 0xfc,0x7e,0x3e,0x1e,0x0c,0x00,0x00,0x00] SMILE = [0x00,0x00,0x00,0x3c,0x42,0x91,0xa5,0xa1, 0xa1,0xa5,0x91,0x42,0x3c,0x00,0x00,0x00] SAD = [0x00,0x0...
def region_normalize(): # Normalize by the size of the original region # n_ccs, ccs = cv2.connectedComponents(mask) # prob_fg = dist_fg.copy() # for i in range(1, n_ccs): # cc_mask = ccs == i # cc_fgvals = prob_fg[cc_mask] # prob_fg[cc_mask] = cc_fgvals / cc_fgvals.max()
# -*- coding: utf-8 -*- # Copyright 2020 Scriptim (https://github.com/Scriptim) # # 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...
import numpy as np from .abstract_gradient_descent import AbstractGradientDescent class AdamGradientDescent(AbstractGradientDescent): """Adam Gradient Descent Class This class implements adaptive moment estimation (Adam) for updating the particles in Stein variational gradient descent. Adam computes an i...
from ckeditor_uploader.widgets import CKEditorUploadingWidget from django import forms from .models import Comment, Article class EmailPostForm(forms.Form): name = forms.CharField(max_length=25) email = forms.EmailField() to = forms.EmailField() comments = forms.CharField(required=False, widget=forms...
from enum import Enum from json import JSONEncoder from typing import Any from strips_hgn.features import AbstractFeatureMapper class MetricsEncoder(JSONEncoder): """ For encoding evaluation metrics """ def default(self, o: Any) -> Any: if isinstance(o, Enum): return o.value else...
"""handles all exporting logic""" import csv import enum import json import click from paragon import Paragon from paragon.utils import Utils class Format(enum.Enum): """file types as enums""" MARKDOWN = 1 JSON = 2 CSV = 3 class Exporter: """handles writing to various file formats""" @staticmethod def ...
def faasm_main(): return 0
# -*- coding: utf-8 -*- # emacs: -*- mode: python; py-indent-offset: 4; indent-tabs-mode: nil -*- # vi: set ft=python sts=4 ts=4 sw=4 et: from halfpipe import resource TESTS_ONLINE_RESOURCES = { "wakemandg_hensonrn_statmaps.tar.gz": "https://api.figshare.com/v2/file/download/25621988", "ds000108fixed.tar.gz":...
"""Test clone graph from VT.""" import json import os import pytest import vt_graph_api.errors import vt_graph_api.graph with ( open(os.path.join( os.path.dirname(os.path.abspath(__file__)), "resources/virustotal_graph_id.json"))) as fp: GRAPH_RESPONSE_DATA = json.load(fp) VIEWERS_RESPONSE_DA...
# GENERATED BY KOMAND SDK - DO NOT EDIT import komand import json class Component: DESCRIPTION = "List an issue's events" class Input: ISSUE_ID = "issue_id" class Output: EVENTS = "events" class ListIssueEventsInput(komand.Input): schema = json.loads(""" { "type": "object", "title...
valor = int(input()) print('{}'.format(valor)) numero100 = valor//100 print('{} nota(s) de R$ 100,00'.format(numero100)) valor -= numero100*100 #valor - valor (menos ele mesmo) numero50 = valor//50 print('{} nota(s) de R$ 50,00'.format(numero50)) valor -= numero50*50 numero20 = valor//20 print('{} nota(s) de R$ 20,...
# coding=utf-8 # Copyright 2020 The Google Research 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 applicab...
from ..haupdater import HaUpdater from ..globalinfo import GlobalInfo from .faketime import FakeTime from ..dev.testbackend import HelperTestBackend from ..logbase import LogBase STALE_ATTRIBUTES = { "friendly_name": "Snapshots Stale" } def test_init(updater: HaUpdater, global_info, server): backend: HelperT...
import random from core.buckets import BucketOrderInfo, BucketExtend from core.monte_carlo import StratifiedSample2D, LatinHypercube1d, LatinHypercube2d from core.sample import Sample from core.sampler import Sampler import maths.tools class StratifiedSampler(Sampler): def __init__(self, bucket_extend:...
import logging import yaml from cloud_admin.systemconnection import SystemConnection from cloud_utils.log_utils.eulogger import Eulogger from cloud_utils.log_utils import get_traceback from cloud_utils.system_utils.machine import Machine from nephoria.usercontext import UserContext from nephoria import __DEFAULT_API...
from flask import render_template import flask_ipywidgets import traitlets app = flask_ipywidgets.app() def echo_state(*args): print('changes', args) import ipywidgets slider_shared = ipywidgets.FloatSlider(description='shared slider') slider_shared.observe(echo_state, 'value') @app.route('/') def index(): ...
from assembler.formats._template import fileFormatClass class ELF(fileFormatClass): def __init__(self, parameters): fileFormatClass.__init__(self, parameters) if parameters.verbose: print('selected output file format: ELF') def generateTemplate(self): elfHeader = [0x7f, 0x...
import os from io import StringIO from os import path from unittest import TestLoader, TextTestRunner, mock from unittest.mock import MagicMock from django.core.exceptions import MiddlewareNotUsed from django.test import TestCase, override_settings from django.test.runner import DiscoverRunner from test_query_counter....
class Card(): """Class Card # Attributes: value = None # (int) suit = None # (string) """ # Operations def __init__(self, suit: str, value: int, active=True): self.value = value self.suit = suit self.active = active def get_str(self): if self.value ==...
# -*- coding: utf-8 -*- """ fix_new mantém as informações sobre um fixo revision 0.2 2015/nov mlabru pep8 style conventions revision 0.1 2014/nov mlabru initial release (Linux/Python) """ # < imports >-------------------------------------------------------------------------------------- # python library import ...
from django.urls import path from django.conf.urls import include, url from .views import DepositMoneyView, WithdrawMoneyView, TransactionRepostView, RequestLoanView app_name = 'transactions' urlpatterns = [ path("deposit/", DepositMoneyView.as_view(), name="deposit_money"), path("report/", TransactionRepos...
# -*- coding: utf-8 -*- """ walle-web :copyright: © 2015-2017 walle-web.io :created time: 2017-06-11 15:40:38 :author: wushuiyong@walle-web.io """ import logging from functools import wraps from flask import current_app from flask_login import current_user class Access: def __init__(self): ...
#!/usr/bin/env python2 # -*- coding: utf-8 -*- # # dailyprogrammer 218 easy # https://github.com/vesche # def main(): n, c = input(), 0 print n, while n != int(str(n)[::-1]): n, c = n + int(str(n)[::-1]), c + 1 print "gets palindromic after {} steps: {}".format(str(c), str(n)) if __name__...