content
stringlengths
5
1.05M
from tkinter import * app=Tk() '设置tag属性' text1=Text() text1.tag_config('op1',background='blue',foreground='white') text1.insert(INSERT,'Archer','op1') '创建一个窗口对象在上面' def show(): print('我被点了一下') b=Button(text1,command=show,text='点我点我') b.grid() '创建一个图片对象' img=PhotoImage(file='resources/18.gif') text1.window_cre...
from torchvision import transforms from torchvision.datasets import CIFAR10 from torch.utils.data import DataLoader, Subset def cifar10_dataloaders(train_batch_size=64, test_batch_size=100, num_workers=2, data_dir = 'datasets/cifar10'): train_transform = transforms.Compose([ transforms.RandomCrop(32, padd...
from tree_sitter import Node def get_tokens(code_str, root): if isinstance(code_str, str): code_str = code_str.encode() assert isinstance(root, Node) tokens = [] if root.type == "comment": return tokens if "string" in str(root.type): return [code_str[root.start_byte:root.en...
import traceback import logging from django.core.management.base import BaseCommand import openkamer.dossier logger = logging.getLogger(__name__) class Command(BaseCommand): def add_arguments(self, parser): # Named (optional) arguments parser.add_argument( '--skip-existing', ...
import yaml from pkg_resources import resource_string from .components import Component def load_root_component(): new_data_yaml = resource_string(__name__, 'navigation.yml').decode("UTF-8") navigation_raw = yaml.safe_load(new_data_yaml) return Component.from_dict("root", navigation_raw)
import random import logging import os import numpy # if "path" in self.state_config: # local_path = self.state_config["path"] # local_path = local_path.replace("%HOME%", Configuration.HOME_DIRECTORY) # local_path = local_path.replace("%CONFIG%", self.configuration.config_path) class Playlist: def __i...
from digicomm import wrap import numpy as np import pytest def test_wrap(): assert wrap(0.5,1) == 0.5 assert wrap(-0.5,1) == -0.5 assert wrap(0,0.1) == 0 assert wrap(2,1) == 0 assert wrap(2,3) == 2 assert wrap(4,3) == -2 assert wrap(3,2) == -1 assert wrap(4.1,2) == pytest.approx(.1) ...
# -*- coding: utf-8 -*- from django import template from ..models import * register = template.Library() @register.inclusion_tag('pages/tpl_tag.html') def tag(): """Make keywords template""" tag = Tag.objects.all().filter(cloud=True) return {'tag': tag} @register.inclusion_tag('pages/tpl_carousel.html'...
import os from pathlib import Path from flask import Flask from flask_login import LoginManager from flask_migrate import Migrate from flask_sqlalchemy import SQLAlchemy from flask_bcrypt import Bcrypt from flask_cors import CORS, cross_origin from config import config db = SQLAlchemy() migrate = Migrate() bcrypt = ...
# Thompson sampling for bernoulli # See "old" tools.py from libs.base import * import numpy as np class BBThompsonList(List): """ Class to draw decisions using a Bernoulli Bandit Thompson sampler. :var dict objects: A dict of dict of thetas (which should be \ proportions, see documentation of Proportions...
# Copyright 2020 Huawei Technologies Co., Ltd # # 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...
# @file qot_types.py # @brief QoT Stack Python Data Types and Basic Operations # @author Anon D'Anon # # Copyright (c) Anon, 2018. # All rights reserved. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are met: # 1. Redistribut...
from .pre_seq2eq_trainer import SupervisedTrainer
#!/usr/bin/env python #coding=utf-8 # Copyright 2008 Valentin 'esc' Haenel # # This program is free software. It comes without any warranty, to # the extent permitted by applicable law. You can redistribute it # and/or modify it under the terms of the Do What The Fuck You Want # To Public License, Version 2, as publis...
__version__ = "1.2.88"
""" Provides methods for interacting with the physics engine. @author Ben Giacalone """ from tools.envedit import helper class Physics: def __init__(self, physics_world): self.physics_world = physics_world # Performs a raycast against objects in the scene def raycast(self, ray_origin, ray_dir):...
import roadrunner import teplugins as tel noisePlugin = tel.Plugin ("tel_add_noise") print noisePlugin.name() print noisePlugin.hint() print noisePlugin.description() print '==== List of properties ====' print noisePlugin.listOfProperties() modelPlugin= tel.Plugin("tel_test_model") test_model = modelPlugin....
from .load_UM import load_UM from .load_WRF import load_WRF from .load_MesoNH import load_MesoNH from .load_COSMO import load_COSMO from .load_RAMS import load_RAMS
from rest_framework import status from rest_framework.generics import UpdateAPIView from rest_framework.response import Response from authors.apps.articles.models import Article from authors.apps.articles.serializers import ArticleSerializer class FavoriteArticles(UpdateAPIView): """Class for making an article a...
from __future__ import absolute_import from __future__ import division from __future__ import print_function import _init_paths import os import json import cv2 import numpy as np import time from progress.bar import Bar import torch from external.nms import soft_nms from opts import opts from logger import Logger f...
# Import the necessary packages from .simplepreprocessor import SimplePreprocessor from .aspectawarepreprocessor import AspectAwarePreprocessor from .imagetoarraypreprocessor import ImageToArrayPreprocessor from .meanpreprocessor import MeanPreprocessor from .croppreprocessor import CropPreprocessor from .patchpreproce...
from django.contrib.auth.backends import ModelBackend import re from users.models import User def get_user_or_mobile(account): """判断是手机号还是用户名""" try: if re.match(r'^1[3-9]\d{9}', account): user = User.objects.get(mobile=account) else: user = User.objects.get(username=a...
from rest_framework import status from rest_framework.response import Response from django.utils.translation import ugettext as _ from misago.conf import settings from misago.core.mail import mail_user from misago.users.credentialchange import store_new_credential from misago.users.serializers import ChangeEmailSeria...
num=int(input("qual o número ")) i=1 while i <=10: print("{} x {} = {}".format(num,i,num * i )) i=i+1
print("Welcome to Python Lab!") ''' The Python Playground! '''
""" CacheFile --------- The python interface to the :py:class:`~.CacheFile` which checks for filename validity during instantiation. When one of its properties are called, it loads and parses the metadata and datasets fresh from the hdf5 and aggregatates them. Examples ++++++++ Peek **** The most straightforward exa...
# Generated by Django 2.2.17 on 2021-01-24 07:24 from django.db import migrations, models def forward(apps, schema_editor): """Forward migration Attempts to reconcile and remove duplicate ReviewerSettings """ ReviewerSettings = apps.get_model('review', 'ReviewerSettings') HistoricalReviewer...
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: if len(s) == 0: return 0 current_length = 0 max_length = 0 idx = 0 last_dup_index = -1 count = {} while idx < len(s): if s[idx] not in count or count[s[idx]] < last_dup...
from frameworks.keras.callbacks.logging_callback import LoggingCallback, TrackableType from frameworks.keras.callbacks.mlrun_logging_callback import MLRunLoggingCallback from frameworks.keras.callbacks.tensorboard_logging_callback import ( TensorboardLoggingCallback, )
def square(x): return x * x def my_map(func, arg_list): result = [] for i in arg_list: result.append(func(i)) return result squares = my_map(square, [1, 2, 3, 4, 5]) print(squares)
# Copyright 2012-2016 Jonathan Paugh and contributors # See COPYING for license details from agithub.base import API, Client, ConnectionProperties class Maven(API): """ Maven Search API """ def __init__(self, *args, **kwargs): props = ConnectionProperties( api_url='search.maven.org...
#!/usr/bin/python # -*- coding: utf-8 -*- # __author__ : stray_camel # __date__: 2020/06/16 15:35:10 import wsme from wsme import types as wtypes from apps import types as _types from django.utils.translation import ugettext as _ from apps.api_exception import ParameterException class ComputeSvmBody(wtypes.Base): ...
#!/usr/bin/env python3 # coding: utf8 import os, pyxel, PyxelSpec, x8y12pxTheStrongGamer, PyxelText class App: def __init__(self): pyxel.init(PyxelSpec.Window.Size[0], PyxelSpec.Window.Size[1], caption="PNGフォント") self.font = x8y12pxTheStrongGamer.x8y12pxTheStrongGamer(self.ResDir) self.pyxte...
#!/usr/bin/env python3 """ Calculates the amount spent by each candidate by summing expenditures from column `Calculated_Amount` in the CSV files and stores it in the candidate JSON files under field `file["raised vs spent"][0]["Spent"]`. The summed contributions are rounded to the nearest whole number. """ from shar...
# policyIterationAgent.py # ------------------------------------------------ import mdp import util import random from pprint import pprint from learningAgents import ValueEstimationAgent class PolicyIterationAgent(ValueEstimationAgent): """ Policy Iteration Agent Class It is an implementation o...
import logging from logging.config import dictConfig class SimpleInfoFormatter(logging.Formatter): pass def formatMessage(self, record): pass def set_qiskit_logger(): pass def unset_qiskit_logger(): pass
""" Helpers for CR3 Downloads Author: Austin Transportation Department, Data and Technology Services Description: This script contains methods that help in the download and processing of CR3 files, this can include downloading the file from a CRIS endpoint, uploading files to S3, etc. The application requires the req...
class EndBeforeStartTimeException(Exception): pass
from django.conf.urls import url from .views import get_swagger_view urlpatterns = [ url(r'^$', get_swagger_view()), ]
#!/usr/bin/env python '''Coordinate frame transformations and related functions ''' #Python standard import #Third party import import numpy as np import scipy.optimize import pyorb import pyant import astropy.coordinates as coord import astropy.units as units from astropy.coordinates import TEME, ITRS, ICRS, GCRS...
"""@package testserver @file testserver.py @author Ivan Murashko <ivan.murashko@gmail.com> Copyright (c) 2007-2010 Kalinka Team This file is part of Kalinka mediaserver. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files ...
import gzip import sqlite3 import urllib.request db_connection = sqlite3.connect( database='unigrams.sqlite3', timeout=10, ) db_cursor = db_connection.cursor() db_cursor.execute( ''' CREATE TABLE IF NOT EXISTS unigrams ( unigram TEXT, count INTEGER, UNIQUE(unigr...
# -*- coding: utf-8 -*- """Module exports: Series/Panel conversions.""" from sktime.datatypes._series_as_panel._convert import ( convert_Panel_to_Series, convert_Series_to_Panel, convert_to_scitype, ) __all__ = [ "convert_Panel_to_Series", "convert_Series_to_Panel", "convert_to_scitype", ]
import bpy from bpy.props import * from bpy.types import PropertyGroup from ..utils import ( get_item_scene ) def poll_override_mat(self, object): return (not object.grease_pencil) def poll_camera(self, object): props = bpy.context.scene.rentask colle = props.rentask_colle item = colle[props.rentask_index] tgt...
""" XXX: """ __version__ = '0.1.1'
""" ASGI config for config project. It exposes the ASGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.0/howto/deployment/asgi/ """ import os import django from channels.routing import get_default_application from config.helpers....
class AppleProduct: def __init__(self, name, model, base_price): self.name = name self.model = model self.base_price = base_price def companyInfo(self): st = ("Company Name: Apple\nFouder: Steve Jobs, Steve Wozniak, Ronald Wayne\nCurrent CEO: Tim Cook\nAddress: Apple Inc, 2511 Laguna Blvd, Elk Grove...
#!/usr/bin/python # # Copyright 2018-2021 Polyaxon, 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 ...
# -*- coding: utf-8 -*- from django.conf.urls.defaults import * from django.contrib import admin import dbindexer from django.conf.urls import patterns, include, url from django.contrib.sitemaps import FlatPageSitemap, GenericSitemap from home.models import POST,Category from django.views.generic.simple import direct_t...
from flask_wtf import FlaskForm from wtforms import StringField, SelectField, TextAreaField, SubmitField from wtforms.validators import Required CATEGORY_CHOICES=[('Jokes','Jokes'),('Inspiration','Inspiration'),('Random','Random')] class UpdateProfile(FlaskForm): bio = TextAreaField('Write a brief bio about you.',...
#!/usr/bin/env python3 from speccer import * from typing import T, List def is_sorted(xs: List[T]) -> bool: '''Returns True if 'xs' is sorted ascending, O(nlgn) ''' return list(sorted(xs)) == xs # here the implication is a decorator since it changes the way List[int]'s are generated # but the forall just ...
"""Converts examples from MYRORSS to GridRad format.""" import os.path import argparse import numpy from gewittergefahr.gg_utils import radar_utils from gewittergefahr.gg_utils import time_conversion from gewittergefahr.deep_learning import input_examples from gewittergefahr.deep_learning import training_validation_io...
from django.contrib.auth.decorators import user_passes_test from django.shortcuts import HttpResponseRedirect, get_object_or_404, render from django.urls import reverse, reverse_lazy from django.utils.decorators import method_decorator from django.views.generic.detail import DetailView from django.views.generic.edit im...
a = [1, 2, 3, 4, 5, 6, 7, 8] index_of_the_number = 0 for i in a: if i % 2 != 0: a[index_of_the_number] = 0 else: pass index_of_the_number += 1 print(a)
""" This module collects the Kalman filtering algorithms in one place. All of the implementations are subclasses of the Kalman abstract base class. """ from abc import ABC, abstractmethod from numbers import Number import numpy as np class Kalman(ABC): """ This class represent the base abstract class of all ...
#Tikhon the Great's PythonCivilization! from state import * def iinput(text,default_value): try: return int(input(text)) except: return default_value player_number = iinput("Enter the number of player-controlled nations:",1) for p in range(player_number): new_state = State() new_stat...
import models import processors import numpy as np import matplotlib.pyplot as plt from matplotlib.animation import FuncAnimation # Seed random number generator seed = 20180517 rng = np.random.RandomState(seed) # Define wind model parameters wind_model_params = { 'sim_region': models.Rectangle(0., -50., 100., 50...
class Solution: def leastInterval(self, tasks: List[str], n: int) -> int: taskFrequency = [0] * 26 for task in tasks: taskFrequency[ord(task) - ord('A')] += 1 taskFrequency = [i for i in taskFrequency if i > 0] taskFrequency.sort() maxFrequency = taskFrequency.pop...
import dynamodb import json import emojis def command_balance(_, body): hugs_available = dynamodb.hugs_available(body["user_id"][0], body["user_name"][0]) hugs_received = dynamodb.hugs_received(body["user_id"][0], body["user_name"][0]) message = format_message(hugs_available, hugs_received) return { ...
# BSD 3-Clause License; see https://github.com/scikit-hep/awkward-1.0/blob/main/LICENSE import pytest # noqa: F401 import numpy as np # noqa: F401 import awkward as ak # noqa: F401 def test(): array = ak._v2.Array([3, 3, 3, 5, 5, 9, 9, 9, 9, 1, 3, 3]) assert ak._v2.operations.structure.run_lengths(array)....
import os from fabric import task branch = os.environ['CIRCLE_BRANCH'] if branch == 'master': port = 3032 else: port = 3031 os.environ['PORT'] = f'{port}' if branch == 'master': volume = 'mp-root' else: volume = 'mp-root-test' image = f'desmondrivet/micropub-git-server:{branch}' name = 'micropub-g...
''' Alphabet tree output checker. Takes input as a filename argument, or requests from keyboard if no filename is provided. Reports on whether input matches requirement for the following question: http://codegolf.stackexchange.com/questions/35862/make-me-an-alphabet-tree ''' import string CONNECTIONS = dict(A = [3,...
#!/usr/bin/python import time import math from utils.utils import print_time_log def square_diff(start, end): start_time = time.time() result = int(square_of_sums(start, end) - sum_squares_of_numbers(start, end)) print_time_log(start_time, result) return result def sum_squares_of_...
import numpy as np from PIL import Image import time import matplotlib.pyplot as plt import matplotlib.image as mpimg def getpallete(num_cls): n = num_cls pallete = [0]*(n*3) for j in xrange(0,n): lab = j pallete[j*3+0] = 0 pallete[j*3+1] = 0 pallete[j*3+2] = 0 i = 0...
import numpy as np # Context variable TRANSFORMATION_CTX = None class Transformation(object): """ Generic affine transformation. """ def __init__(self, matrix: np.ndarray): """ :param matrix: Affine matrix of shape `[3, 3]` """ self._matrix = matrix def __call_...
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def isSubtree(self, root: Optional[TreeNode], subRoot: Optional[TreeNode]) -> bool: if not root or n...
import numpy as np # With a Q-learning algorithm returns how good is each response. def player0(data, Q, player, valid, learning_rate, feedback): actual = Q[data[player][0]][data[player][1]][data[player][2] - 1][data[player][3]][ int(np.log2(data[player][4]))] # How much it weights the actual state. ...
""" Codes for correcting and estimating various radar and meteorological parameters. @title: radar_codes @author: Valentin Louf <valentin.louf@monash.edu> @institutions: Monash University and the Australian Bureau of Meteorology @creation: 04/04/2017 @date: 15/05/2017 .. autosummary:: :toctree: generated/ _m...
from setuptools import setup, find_packages LONG_DESCRIPTION = open('README.md', 'rb').read().decode('utf-8') setup_args = dict( name='nbolom', version='0.0.3', maintainer='Adrián Pardini', maintainer_email='github@tangopardo.com.ar', packages=find_packages(), url='https://github.com/pardo-bs...
#!/usr/bin/env python3.6 # -*- encoding=utf8 -*- import logging as log log.basicConfig(format='[%(asctime)s] %(filename)s line:%(lineno)05d [%(levelname)s]: %(message)s', level=log.INFO, datefmt='%Y-%m-%d %H:%M:%S')
from __future__ import absolute_import from django.forms.fields import IntegerField from django.utils.translation import ugettext_lazy as _ from fobi.base import FormFieldPlugin, get_theme from fobi.widgets import NumberInput from . import UID from .forms import IntegerInputForm __title__ = 'fobi.contrib.plugins.fo...
class ProgressiveError(Exception): "Errors from ProgressiVis." def __init__(self, message=None, details=None): self.message = message self.details = details class ProgressiveStopIteration(Exception): "Stop Iteration for coroutines" def __init__(self, message=None, details=None): ...
from django.views.decorators.csrf import csrf_exempt from django.shortcuts import render from django.http import HttpResponseNotAllowed, HttpResponseBadRequest, HttpResponseServerError, JsonResponse from .location import Location from .responses.distance import Distance from .gmaps_client import GMapsClient from .exce...
class BatchRunner: def __init__(self,model,iter_n): self.model = model self.iter_n = iter_n def run_model(self,start,end): """ Runs the model """ for i in range(start,end): self.model.reset(i) self.model.episode() print(...
# -*- coding: utf-8 -*- import numpy as np import pytest from pysteps.nowcasts.lagrangian_probability import forecast from pysteps.tests.helpers import get_precipitation_fields from pysteps.motion.lucaskanade import dense_lucaskanade def test_numerical_example(): """""" precip = np.zeros((20, 20)) precip...
import time import torch import argparse import numpy as np device = torch.device('cuda:0') if torch.cuda.is_available() else torch.device('cpu') time_now = time.strftime('%y%m_%d%H%M') mean = [0.2, 0.9, 0.5, 3, 1.1, 0.9, 2, 2.5, 1.6, 1.8]*30 var = [3, 2, 4, 3, 3.5, 5.5, 5, 3.5, 5, 3.5]*30 dim = 500 lin_para_seed = n...
#!/usr/bin/env python # -*- coding: utf-8 -*- from runner.koan import * class AcercaDeStrings(Koan): def test_strings_con_comillas_dobles_son_strings(self): string = "Hello, world." self.assertEqual(__, isinstance(string, str)) def test_strings_con_comillas_simples_tambien_son_strings(self):...
from enum import Enum class DateFormat(Enum): ENGLISH = "YMD" SPANISH = "DMY"
from helper import CompatTestCase from validator.compat import FX46_DEFINITION class TestFX46Compat(CompatTestCase): """Test that compatibility tests for Gecko 46 are properly executed.""" VERSION = FX46_DEFINITION def test_mTab_renames(self): variations = ( 'filter.removeProgressLis...
from .router import router from django.urls import path, include urlpatterns = [ # api/movies/ path('', include(router.urls)) ] """ router: sets the las endpoint in the urls (from metflix_remake the main) we got 'api' then include the api for movies letting an endpoint: 'api/movies/' So it would be interes...
from preprocessing.preprocessing import preprocess from sentiment_analysis.sentiment import getSentiment class Tweet: """ Tweet class represents tweets from twitter and shows sentiment. """ def __init__(self, tweet): self.tweet = tweet decodedText = self.tweet.text.encode('ascii', 'ignore').decode('utf-8'...
from pyramid import testing from pyramid.config import Configurator from rebecca.repository import repository_config, repository_factory_config from rebecca.repository import get_repository, create_repository def _makeApp(): conf = Configurator() conf.include('rebecca.repository') conf.scan(".") conf....
import json import networkx as nx import numpy as np import os import pandas as pd from sklearn.decomposition import TruncatedSVD from sklearn.feature_extraction.text import TfidfVectorizer from sklearn.preprocessing import LabelEncoder from tqdm import tqdm from config import logger, config def read_profile_data():...
# -*- coding: utf-8 -*- from tokenio import utils from tokenio.proto.gateway.gateway_pb2 import * from tokenio.proto.member_pb2 import MemberUpdate, RecoveryRule, MemberRecoveryRulesOperation, MemberOperation, \ TrustedBeneficiary from tokenio.proto.security_pb2 import Key, Signature from tokenio.proto.token_pb2 im...
# Generated by Django 2.1.2 on 2018-11-29 17:24 from django.db import migrations, models class Migration(migrations.Migration): initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Calls', fields=[ ('id', models.AutoField(pr...
import time from selenium import webdriver from selenium.webdriver.support.ui import WebDriverWait from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.by import By from .BasePage import BasePage from helper import Colors from UImap import home_page_map from .SubscribePag...
import requests from bs4 import BeautifulSoup import time class Slideshare: def __init__(self, config, permutations_list): # 1000 ms self.delay = config['plateform']['slideshare']['rate_limit'] / 1000 # https://slideshare.net/{username} self.format = config['plateform']['slideshare...
def cal_order(m, n, ri, ci): order = ri * n + ci return order print(cal_order(3, 4, 1, 2)) print(cal_order(5, 6, 2, 3))
from __future__ import absolute_import, division, print_function from collections import OrderedDict SMALLEST = 'smallest' LARGEST = 'largest' DIFFERENCE = 'difference' def saferound(iterable, places, strategy=DIFFERENCE, rounder=round, topline=None): """Rounds an iterable of floats while retaining the original ...
# # PySNMP MIB module NQA-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NQA-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 19:33:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)...
import numpy as np import random, pickle, torch, copy, cv2 from glob import glob from sklearn.cluster import MeanShift, estimate_bandwidth from sklearn import mixture from tqdm import tqdm import scene_partition_tree import dataset_loader from config import * # downsample. g_n_pts_per_frame = opt.g_n_pts_per_frame sa...
# Uses python3 def fib_last_digit(n): if n <= 1: return n previous, current = 0, 1 for i in range(n - 1): previous, current = current, (previous + current) % 10 return current print(fib_last_digit(int(input()))) # print(timeit.timeit("fib_last_digit(n = 327305)", set...
#!/usr/bin/env python3 # Copyright (c) Facebook, Inc. and its affiliates. # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. "DANGER: The resulting PAR will not work if copied outside of buck-out." import os import shutil import stat import sub...
from misc import bound from rpc import RPCHost, RPCException class Blockchain: def __init__(self, host=None, start=None, stop=None, step=None): assert (start is None) or (start >= 0), "Negative block heights not allowed" assert (stop is None) or (stop >= 0), "Negative block heights not allowe...
#!/usr/bin/env python from collections import OrderedDict import argparse import importlib import json import logging import pathlib import random import time import numpy as np import torch import torch.nn as nn import torchvision from tensorboardX import SummaryWriter from dataloader import get_loader from config ...
print('---------- Create List ----------') empty_lst = list() print(len(empty_lst)) empty_lst = [] print(len(empty_lst)) fruits = ['banana', 'orange', 'mango', 'lemon'] print(fruits) print(len(fruits)) # Lists can have items of different data types lst = ['Zhang San', 22, True, {'country': 'China', 'city': 'Hangzhou'...
""" Leet spek generator. Leet é uma forma de se escrever o alfabeto latino usando outros símbolos em lugar das letras, como números por exemplo. A própria palavra leet admite muitas variações, como l33t ou 1337. O uso do leet reflete uma subcultura relacionada ao mundo dos jogos de computador e internet, sendo muito...
#!/usr/bin/env python # coding: utf-8 # # Gradient Checking # # Welcome to the final assignment for this week! In this assignment you'll be implementing gradient checking. # # By the end of this notebook, you'll be able to: # # Implement gradient checking to verify the accuracy of your backprop implementation # ##...
from os import mkdir, stat import board import time import digitalio import displayio import neopixel import terminalio import adafruit_imageload import math import adafruit_pcf8523 from adafruit_debouncer import Debouncer from adafruit_displayio_layout.layouts.grid_layout import GridLayout from adafruit_display_text ...
class HubUser: def __init__(self): pass def name(self): raise NotImplementedError("HubUser.name must be implemented") def start_channel(self, payload, tasks): pass def channel_post_url(self, channel): return "/channel/" + channel def has_webhook(self): ret...