content stringlengths 7 1.05M |
|---|
# -*- coding:utf-8 -*-
# learn the closure in python
# 计算移动平均数的高阶函数
def make_average():
"""
:return:
>>> avg = make_average()
>>> avg(10)
10.0
>>> avg(11)
10.5
>>> avg(12)
11.0
"""
series = []
def average(new_value):
series.append(new_value)
total = s... |
def partition(lst, low, high):
# pick last element as pivot
pivot = lst[high]
# index of where pivot should be
index = low
for j in range(low, high):
if lst[j] < pivot:
lst[index], lst[j] = lst[j], lst[index]
index += 1
# place pivot at index
lst[index], lst[h... |
USERNAME = None
PASSWORD = None
REQUESTS_URL = 'https://ebusiness.dpb.nhs.uk/claimsrequests.asp'
RESPONSE_URL = 'https://ebusiness.dpb.nhs.uk/claimsresponses.asp'
|
# name_to_binary.py
def to_binary(name):
text = ''
for let in name:
code = ord(let)
text += bin(code).replace('0b', '')
return text
# __main__
string = input("Enter a name: ")
binary = to_binary(string)
print(binary)
|
class Config(object):
_config = {}
@classmethod
def get_config(cls, name):
return cls._config.get(name, None)
@classmethod
def set_config(cls, name, config):
config_dict = {key: getattr(config, key) for key in dir(config) if
not key.startswith('__') and not c... |
#choose 4-9.py
cubes=[value**3 for value in range(1,11)]
print(cubes)
print("The first three items in the list are: "+str(cubes[:3]))
print("Three items from the middle of the list are: "+str(cubes[4:7]))
print("The last three items in the list are: "+str(cubes[-3:]))
|
def extract_shapekey(c):
d=c.split(",")
e=d[0]
f=d[1]
g=e.split("(")
h=f.split(")")
part_1=g[1]
part_2=h[0]
shapekey=(int(part_1),int(part_2))
return shapekey |
print("#############################################################")
print("## Faturamento Ticket Veículos Estacionamento Seu Jertuz ##")
print("#############################################################")
veiculo = int(input("Digite o numero do Veículo: \n 1 - Moto; \n 2 - Carro de passeio; \n 3 - Pick-Up; \n ... |
def find_full_matches(sequence, answer):
return find_sub_list(answer, sequence)
def find_matches(sequence, answer):
elements = set(answer)
return [index for index, value in enumerate(sequence) if value in elements]
def find_sub_list(sublist, list):
results = []
sll = len(sublist)
for ind in ... |
def fact(n):
fact=1
for i in range(1,n+1):
fact=fact*i
return fact
num=int(input("enter a number: "))
factorial=fact(num)
print(factorial)
|
class AddInId(object, IDisposable):
"""
Identifies an AddIn registered with Revit
AddInId(val: Guid)
"""
def Dispose(self):
""" Dispose(self: AddInId) """
pass
def GetAddInName(self):
"""
GetAddInName(self: AddInId) -> str
name of addin associate... |
_base_ = [
'../_base_/models/mask_rcnn_r50_fpn_22cls.py',
'../_base_/datasets/trashcan_instance.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
|
def compute_potential_drain(height_change, rover):
mars_grav_constant = 3.177
potential_change = height_change * rover.mass * mars_grav_constant / 10
return (0, potential_change)[potential_change > 0]
def compute_energy_drain(old_loc, new_loc, rover):
min_adjust = rover.battery_base_movement
min... |
print("This is practice of everything in the first half of the book...Round 2 Review ")
print('You\'d need to know \'bout escapes with \\ that do: ')
print('\n newlines and \t tabs.')
poem = """
\t The lovely world
with logic so firmly planted
cannot discern \n the needs of love
nor comprehend passion from intuition
a... |
# http://www.django-rest-framework.org/
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'ara.classes.pagination.PageNumberPagination',
'DEFAULT_FILTER_BACKENDS': (
'rest_framework_filters.backends.RestFrameworkFilterBackend',
),
'DEFAULT_PERMISSION_CLASSES': (
'rest_framework.permissions... |
"""
"""
__author__ = 'Yukinari Tani'
__version__ = '0.1'
__licence__ = 'MIT'
|
def iq_test(numbers):
lst=numbers.split(" ")
odd=0
even = 0
for i in lst:
if float(i)%2==0:
even=even+1
else:
odd+=1
u="e" if even>odd else "o"
if u=="e":
for i in lst:
if float(i)%2!=0:
indexval=lst.index(i... |
# do not change this line manually
# this is managed by git tag and updated on every release
__version__ = '0.0.46'
# do not change this line manually
# this is managed by shell/make-proto.sh and updated on every execution
__proto_version__ = '0.0.10'
|
class Solution:
def sortList(self, node: ListNode) -> ListNode:
"""O(nlogn) time"""
if not node or node.next is None: return node
slow = node
fast = node.next
while fast is not None:
if fast.next is None: break
slow = slow.next
... |
YES_NO = ["No", "Yes"]
FEATURES = [
("Name", None),
("Does it have fur?", YES_NO),
("Does it have feathers?", YES_NO),
("Does it lay eggs?", YES_NO),
("Does it produce milk?", YES_NO),
("Can it fly?", YES_NO),
("Can it swim?", YES_NO),
("Is it a predator?", YES_NO),
("Does it have t... |
'''
See:
http://en.wikipedia.org/wiki/List_of_HTTP_status_codes
'''
class HttpStatusCode(object):
# 1xx
CONTINUE = 100
SWITCHING_PROTOCOLS = 101
PROCESSING = 102
# 2xx
OK = 200
CREATED = 201
ACCEPTED = 202
NON_AUTHORITATIVE_INFORMATION = 203
NO_CONTENT = 204
RESET_CONTENT ... |
class Mission:
def __init__(self, name, func):
self.name = name
self._func = func
def run(self):
self._func() |
# -*- coding: utf-8 -*-
# Load appconfid
default_app_config = 'devilry.devilry_qualifiesforexam_plugin_points.apps.DevilryQualifiesForExamPointsAppConfig'
|
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# vim: fenc=utf-8
# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
#
#
"""
File name: list_misc.py
Author: dhilipsiva <dhilipsiva@gmail.com>
Date created: 2017-01-15
"""
DOMAINS = [
"006.free-counter.co.uk",
"006.freecounters.co.uk",
"0101011.com",
... |
def P_G(G, i, n):
t = (1 + i) ** n
return (G / i) * (((t - 1) / (i * t)) - (n / t))
def A_G(G, i, n):
t = (1 + i) ** n
return G * ((1/i) - (n / (t - 1)))
|
def checkio(number: int) -> str:
res = str(number);
if(number % 5 == 0 and number % 3 == 0):
return "Fizz Buzz";
elif(number % 3 == 0):
return "Fizz";
elif(number % 5 == 0):
return "Buzz";
return res; |
# -*- coding: utf-8 -*-
# Scrapy settings; see https://doc.scrapy.org/en/latest/topics/settings.html#
BOT_NAME = 'jailscraper'
SPIDER_MODULES = ['jailscraper.spiders']
NEWSPIDER_MODULE = 'jailscraper.spiders'
RETRY_ENABLED = False
USER_AGENT = 'ProPublica Cook County Jail Scraper - contact david.eads@propublica.org... |
print('Lista 1')
teste = list()
teste.append('Gustavo')
teste.append(40)
galera = list()
galera.append(teste[:])
teste[0] = 'Maria'
teste[1] = 22
galera.append(teste[:])
print(galera)
print('-='*30)
print()
print('Lista 2')
galera = [['João', 19], ['Ana', 33], ['Joaquim', 13], ['Maria', 45]]
for p in galera:
prin... |
"""Base driver module to inherit from."""
class BaseDriver(object):
"""Base driver that will be called from all pages and elements."""
# pylint: disable=too-few-public-methods
def __init__(self, driver):
"""Create the base driver object."""
self.driver = driver
|
def rubel(price):
rub = price // 100
return rub
def cents(penny):
penny = penny % 100
return penny
def check1(rubel):
if rubel(penny) % 10 == 1 and rubel(penny) % 100 not in range(11, 15):
ending1 = "ь"
elif 4 >= rubel(penny) % 10 >= 2 and rubel(penny) not in range(11, 1... |
FEA_DIMENSION = 80
label_dict = {'alv': 0, 'fas': 1, 'prs': 2, 'pus': 3, 'urd': 4, 'mul': 5}
path_conf = {
"dev_data": '',
"dev_labels": '',
"train_list": '',
}
log_conf = {
"base_dir": '',
"file_name": '',
}
summary_conf = {
"checkpoint_dir": '',
"model_directory": '',
"model_name":... |
#
# PySNMP MIB module IPOMANII-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/IPOMANII-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:45:07 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,... |
#!/usr/bin/python3
# -*-coding:utf-8-*-
# python面向对象相关
"""
面向对象:
https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/001431864715651c99511036d884cf1b399e65ae0d27f7e000
""" |
"""Software class"""
class Software:
def __init__(self, name):
self.name = name
self._images = []
def add_image(self, image):
self._images.append(image)
def images(self):
return sorted(self._images, key=lambda i: i.path)
def nb_images(self):
return len(self.... |
def test_signup_page(test_client):
"""
GIVEN a Flask application configured for testing
WHEN the '/signup' page is requested (GET)
THEN check that the response is valid
"""
response = test_client.get('/sign-up')
assert response.status_code == 200
assert b"Currency Exchange" in response.d... |
class AioDiskDBException(Exception):
pass
class RunningException(AioDiskDBException):
pass
class NotRunningException(AioDiskDBException):
pass
class TimeoutException(AioDiskDBException):
pass
class ReadTimeoutException(AioDiskDBException):
pass
class DBNotInitializedException(AioDiskDBExce... |
"""
houses support routines and the command-line dispatchers for carml
command.
"""
__all__ = []
__version__ = '20.0.0'
|
''' Provides a set of normalizing functions
'''
FAKE_SCROLL_ID = 'fake-scroll-id'
def normalizeResponse(response):
'''
Take raw a raw Elasticsearch response and fix it for the Fake
implemenation
'''
# Remove these fields
remove = ['_shards', 'timed_out', 'took']
for field in remove:
... |
#c. Se tiene que calcular el área de un rombo, teniendo en cuenta que:
print("¡Calcular área de un rombo!")
diagonal_Mayor=float(input("Ingrese diagonal mayor= "))
Diagonal_Menor=float(input("Ingrese Diagonal menor = "))
area=(diagonal_Mayor*Diagonal_Menor)/2
print("El area de un Rombo es = ",area)
|
# input
drink_type = input()
sugar = input()
drinks_count = int(input())
drink_price = 0
if drink_type == 'Espresso':
if sugar == 'Without':
drink_price = 0.90
elif sugar == 'Normal':
drink_price = 1
elif sugar == 'Extra':
drink_price = 1.20
elif drink_type == 'Cappuccino':
if ... |
a = [1, 2, 3, 4]
sumNum = 0
for i in a:
# In the for loop, "i" will sequentially read the values in list a.
sumNum += i
# sumNum = sumNum + i, means, 0 + 1 > (0+1) + 2 > (1+2) + 3 > (3+3) + 4
print(sumNum)
|
# Constant.py
# Color
BLUE = 'BLUE'
GREEN = 'GREEN'
# LISTENER
HTTPS_TUPLE = ('HTTPS', 443)
HTTP_TUPLE = ('HTTP', 80)
# Target group
TARGET_GROUP_COLOR_TAG_NAME = 'Color'
TARGET_GROUP_TYPE_TAG_NAME = 'Type'
# Default type means 'api gateway'
TARGET_GROUP_DEFAULT_TYPE = 'DEFAULT'
TARGET_GROUP_MAINTENANCE_TYPE = 'MAIN... |
class ConfigurationException(Exception):
pass
class InternalException(Exception):
pass
class InvalidMessage(Exception):
pass
class InvalidPartialUpdate(Exception):
pass
|
def f(x: int):
y = x
def g(i: int):
f(i + 2)
g(3)
|
def get_int(prompt, int_range):
i = 0
while True:
try:
i = int(input(prompt))
if i in int_range:
break
except ValueError:
pass
return i
|
# Guardando o texto em uma variável do tipo string
font = None
quote = "Testando strings"
def setup():
global font
size(480, 120)
font = createFont("SourceCodePro-Regular.ttf", 32)
textFont(font)
def draw():
background(102)
text(quote, 26, 24, 240, 100)
|
fights = int(input())
helmet_price = float(input())
sword_price = float(input())
shield_price = float(input())
armor_price = float(input())
shield_counter = 0
expenses = 0
for fight in range(1, fights + 1):
if fight % 2 == 0:
expenses += helmet_price
if fight % 3 == 0:
expenses +=... |
output = '''
Using interface 'wlan0'
bssid=14:d6:4d:ec:1e:88
ssid=AU Test Network
id=1
mode=station
pairwise_cipher=CCMP
group_cipher=CCMP
key_mgmt=WPA2-PSK
wpa_state=COMPLETED
ip_address=192.168.20.70
p2p_device_address=e0:cb:1d:3d:84:71
address=e0:cb:1d:3d:84:71
'''
mac = "e0:cb:1d:3d:84:71"
ip = "19... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
MONGO_URL = 'localhost'
MONGO_DB = 'huawei'
MONGO_TABLE = 'huawei_product'
|
class Solution:
def minInsertions(self, s: str) -> int:
# use stack
stack = []
count = 0
i=0
while i < len(s):
if s[i] == '(':
stack.append(s[i])
i += 1
else:
# when facing empty stack
if ... |
# ===============================================================================
# Copyright 2011 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/licens... |
"""
:synopsis: Supported loss functions to use with NPU API for training.
.. moduleauthor:: Naval Bhandari <naval@neuro-ai.co.uk>
"""
# CrossEntropyLoss = "CrossEntropyLoss" #:
SparseCrossEntropyLoss = "SparseCrossEntropyLoss" #:
MSELoss = "MSELoss" #:
# CTCLoss = "CTCLoss" #:
L1Loss = "L1Loss" #:
# NLLLoss = "NL... |
def test_loop(num):
for a in num:
print ("a : ", a)
yield a
num = [1, 2, 3]
tl = test_loop(num)
for aa in tl:
print ("aa : ", aa)
|
class SchedulerNoam(object):
def __init__(self, warmup: int, model_size: int):
super().__init__()
self.warmup = warmup
self.model_size = model_size
def get_learning_rate(self, step: int):
step = max(1, step)
return self.model_size ** (-0.5) * min(step ** (-0.5), step ... |
names=['yash','manan','jahnavi','rahul','rutu','Harry']
print(names[0])
names[1]='Manan Sanghavi'
print(names[1])
names[1]=3
print(names[1])
print(type(names))
|
class Solution:
def numFactoredBinaryTrees(self, A: 'List[int]') -> 'int':
ids = {x : i for i, x in enumerate(A)}
g = {x : [] for x in A}
A.sort()
for i in range(len(A)):
for j in range(len(A)):
if A[j] % A[i] == 0 and (A[j] // A[i]) in ids:
... |
"""
Programa 086
Área de estudos.
data 01.12.2020 (Indefinida) Hs
@Autor: Abraão A. Silva
"""
# Área de declaração e inicialização de variaveis.
cont_atleta = 1
soma_saltos = 0
maior, menor = 0, 1000
# corpo do meu programa.
print('Para finalizar aperte "space" e em seguida "enter".')
while True: # loop inifinit... |
# this files contains basic metadata about the project. This data will be used
# (by default) in the base.html and index.html
PROJECT_METADATA = {
'title': 'Dokuplattform Thunau am Kamp',
'author': 'Karl Burkhart',
'subtitle': 'A django project to bootstrap further web-app developments',
'description':... |
# Python does not have built-in support for Arrays,
# but Python Lists can be used instead.
def showArrays():
cars = ["Ford", "Volvo", "BMW"]
for car in cars:
print("Car Type : ", car)
# Add some new cars
cars.append("Mercedes")
cars.append("Maruti")
print("All cars : ", cars)... |
data = open("input.txt", "r").readlines()
fold = []
points = []
for line in data:
if len(line.strip()) == 0:
continue
elif line.startswith("fold"):
[x_or_y, value] = line.replace("fold along ", "").split("=")
fold.append((int(value) if x_or_y == "x" else 0,
int(valu... |
def count(N):
cnt = 0
for i in range(666,3000000):
if str(i).find('666') != -1:
cnt += 1
if cnt == N:
return i
N = int(input())
print(count(N))
# 완전탐색(브루트포스 알고리즘) 문제이다.
# 규칙 찾아서 효율적으로 풀어보려 했으나.. 너무 피곤하다.
# 맞은 사람 풀이 보니까 규칙 찾으신 분들도 있던데 이해를 못하겠다.. |
# #Q1
def eh_quadrada(mat):
null=[]
l=len(mat)
if mat == null or l == len(mat[0]):
return True
for i in range(l):
if mat[i] == null:
return True
else:
return False
#Q2
def conta_numero(n,mat):
ls=[]
l=len(mat)
if mat == ls:
return 0
for i i... |
class Solution:
def insertIntoBST(self, root: TreeNode, val: int) -> TreeNode:
if not root:
return TreeNode(val)
if val > root.val:
root.right = self.insertIntoBST(root.right, val)
else:
root.left = self.insertIntoBST(root.left, val)
r... |
def MinerTransaction():
"""
:return:
"""
return b'\x00'
def IssueTransaction():
"""
:return:
"""
return b'\x01'
def ClaimTransaction():
"""
:return:
"""
return b'\x02'
def EnrollmentTransaction():
"""
:return:
"""
return b'\x20'
def VotingTran... |
num = [[], []]
pares = list()
impares = list()
for c in range (0,7):
v = int(input(f'Digite o {c+1}° valor: '))
if v % 2 == 0:
num[0].append(v)
else:
num[1].append(v)
num[0].sort()
num[1].sort()
print(f'Os valores pares digitados foram: {num[0]}\nOs valores ímpares digitados foram: {num[1]}'... |
#Kunal Gautam
#Codewars : @Kunalpod
#Problem name: Difference of Volumes of Cuboids
#Problem level: 8 kyu
def find_difference(a, b):
return abs((a[0]*a[1]*a[2])-(b[0]*b[1]*b[2]))
|
#! /root/anaconda3/bin/python
# 例子一
def outer1():
a = 10
def inner():
# nonlocal a
a = 11
print('例子一 内函数:', a)
'''
这里的a变量 已经替换掉了外函数的a变量,在PyCharm里面会报错因此不建议这么使用
'''
print('例子一 外函数:', a)
return inner
outer1()()
print('例子一__closure__: #闭包值为None', outer1()._... |
class AnalyticalRigidLinksOption(Enum,IComparable,IFormattable,IConvertible):
"""
Specifies how Rigid Links will be made for the Analytical Model.
enum AnalyticalRigidLinksOption,values: Disabled (1),Enabled (0),FromColumn (2)
"""
def __eq__(self,*args):
""" x.__eq__(y) <==> x==yx.__eq__(y) <==> x==... |
class Solution:
def checkIfCanBreak(self, s1: str, s2: str) -> bool:
"""String.
Running time: O(nlogn) where n == len(s1).
"""
s1 = sorted(s1)
s2 = sorted(s2)
s1bs2, s2bs1 = True, True
for i in range(len(s1)):
if s1[i] < s2[i]:
s1b... |
# constants #
team_number = 0
# flags #
# simulation
sim_enable_flag = False
sim_activate_flag = False
# telemetry transmission
cx_flag = False
sp1x_flag = False
sp2x_flag = False
# mqtt
mqtt_flag = False
# payload deployment
sp1_deployed_flag = False
sp2_deployed_flag = False |
class BasePermission(object):
def __init__(self, queryset, lookup_field):
self.queryset = queryset
self.lookup_field = lookup_field
def has_permission(self, user, action, pk):
pass
class AllowAny(BasePermission):
def has_permission(self, user, action, pk):
return T... |
class ModelObjectFactory(object):
# no doc
@staticmethod
def GetCorrectInstance(
model, identifier, modelObjectType=None, modelObjectSubType=None
):
"""
GetCorrectInstance(model: Model,identifier: Identifier,modelObjectType: ModelObjectEnum,modelObjectSubType: int) -> ModelObjec... |
items = []
class ItemsModel():
def __init__(self):
self.items = items
def add_item(self, name, price, image, quantity):
self.item_id = len(items)+1
item = {
"item_id": self.item_id,
"name": name,
"price": price,
"image": image,
... |
def returnyield(x):
"""Using return in generator"""
yield x
# available only in python3!!!
return "Hi there"
if __name__ == '__main__':
# create generator
ry = returnyield(5)
print(ry)
# advance to next value
print(next(ry))
# this call throws StopIteration error with return's ... |
class Solution:
def maxProfit(self, prices: List[int]) -> int:
ret, mn = 0, float('inf')
for price in prices:
if price < mn:
mn = price
if price - mn > ret:
ret = price-mn
return ret
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 19-1-12 下午10:39
# @Author : Insomnia
# @Desc : 所有数出现两次, 只有一个出现一次
# @File : SingleNumI.py
# @Software: PyCharm
class Solution:
def singleNum(self, arr):
res = 0
for val in arr:
res^=val
return res
if __name__ == '... |
# Gerard Hanlon, 2018-13-02
# Factorial number is the number multiplied by all of the numbers smaller than it
def sumall(upto):
sumupto = 0
for i in range(1, upto + 1):
sumupto = sumupto + i
return sumupto
print("The Factorial Number of the number 5 is: ", sumall(5))
print("The Factorial Number o... |
#
# PySNMP MIB module A3COM-HUAWEI-EFM-COMMON-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/A3COM-HUAWEI-EFM-COMMON-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 16:49:58 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python versio... |
# encoding=utf-8
# General Header Fields
CACHE_CONTROL = b"Cache-Control".lower()
CONNECTION = b"Connection".lower()
DATE = b"Date".lower()
PRAGMA = b"Pragma".lower()
TRAILER = b"Trailer".lower()
TRANSFER_ENCODING = b"Transfer-Encoding".lower()
UPGRADE = b"Upgrade".lower()
VIA = b"Via".lower()
WARNING = b"Warning".lo... |
"""
Author WG 2019
ESP32 Micropython module for the Maxim MAX44009 sensor.
https://datasheets.maximintegrated.com/en/ds/MAX44009.pdf
The MIT License (MIT)
Usage:
import max44009
from machine import I2C, Pin
i2c = I2C(scl=Pin(22), sda=Pin(21), freq=100000)
max44009 = max44009.MAX44009(i2c)
lux = max... |
def anonymize_phone_number(phone_number: str) -> str:
public_digits_num = 6
phone_number = phone_number.replace("-", "")
public_digits = phone_number[:public_digits_num]
number_of_private_digits = len(phone_number) - public_digits_num
private_digits = "-" * number_of_private_digits
return f"{pub... |
'''Exercício Python 048: Faça um programa que calcule a soma entre todos os números que são múltiplos de três e que se encontram no intervalo de 1 até 500.'''
print('=+=+=+=+=+=+=+=+='*3)
titulo = str('SOMA ÍMPARES DE 1 À 500')
print('{:^51}'.format(titulo))
print('=+=+=+=+=+=+=+=+='*3)
soma = 0
soma2 = 0
cont = 0
for ... |
'''
This place-holder module makes the extensions directory
into a Python "package", so that external user-specific
modules can act as umbrella modules, and, for example:
import structural_dhcp_rst2pdf.extensions.vectorpdf_r2p
to bring in the PDF extension.
'''
|
EMBED_FOOTER_TEXT = "Create by Fらんdy#6057"
DEFAULT_ID_SLACK = 100000
DEFAULT_RANGES = (
(1, 1250000),
(2520000, 7960000),
(8000000, 9930000),
(9960000, 10760000),
(10790000, 12340000)
)
|
for number in [0, 1, 2, 3, 4]:
print(number)
for number in range(5):
print(number)
|
# FILE MODES:
# Example:
# with open(name, 'w+') as f:
# f.write(data)
# "r"
# Read from file - YES
# Write to file - NO
# Create file if not exists - NO
# Truncate file to zero length - NO
# Cursor position - BEGINNING
#
# "r+"
# Read from file - YES
# Write to file - YES
# Create file if not exists - NO
# Trunc... |
_base_ = [
"../_base_/models/cascade_rcnn_r50_fpn.py",
"../_base_/datasets/coco_detection.py",
"../_base_/schedules/schedule_1x.py",
"../_base_/default_runtime.py",
]
pretrained = "https://github.com/SwinTransformer/storage/releases/download/v1.0.0/swin_small_patch4_window7_224.pth"
model = dict(
ba... |
class Event:
def __init__(self, name, **kwargs):
self.name = name
self.args = kwargs
def __str__(self):
return f"Event(name='{self.name}', args={self.args})"
|
class Solution:
def fourSum(self, nums: List[int], target: int) -> List[List[int]]:
def kSum(nums: List[int], target: int, k: int) -> List[List[int]]:
res = []
if len(nums) == 0 or nums[0] * k > target or target > nums[-1] * k:
return res
if k == 2:
... |
'''
pede um número e mostra o fatorial, exemplo: 5! = 5x4x3x2x1 = 120 (while e for)
'''
# from math import factorial
def main():
print('Calcular o fatorial:')
num = int(input('Número: '))
cont = num # irá diminuir do número até 1
f = 1 # fator nulo da multiplicação
print(f'{num}! => ', end=' ')... |
'''
Exercise 2 for Day 5 of 100 Days of Python
In this exercise, we are going to find out the highest score from a given list of scores of a certain number of students
We are going to discuss 2 methods of finding the maximum
'''
def find_maximum_score(scores):
''' METHOD 1
Using the inbuilt max() function, ... |
class Registry(object):
def __init__(self):
self.models = []
def add(self, model):
"""Register a model as a valid comment target"""
self.models.append(model)
def __contains__(self, model):
"""Check if a model (or one of its parent classes) is registered"""
return an... |
"""Top-level package for Parallel TQDM."""
__author__ = """Piotr Szymański"""
__email__ = 'niedakh@gmail.com'
__version__ = '0.1.0'
|
def dfsUtil(G, visited, travel, s):
if(visited[s]):
return
visited[s] = True
for u in G[s]:
if(not visited[u]):
dfsUtil(G, visited, travel, u)
travel.append(s)
def dfs(G, s=1):
visited = {k: False for k in G.nodes}
travel = []
for u in G.nodes:
if(not vi... |
# Given a non-empty string s and an abbreviation abbr,
# return whether the string matches with the given abbreviation.
# A string such as "word" contains only the following valid abbreviations:
# ["word", "1ord", "w1rd", "wo1d", "wor1", "2rd", "w2d", "wo2", "1o1d",
# "1or1", "w1r1", "1o2", "2r1", "3d", "w3", "4"]
# ... |
'''
python 字符串的操作
'''
name = 'liGang'
address = 'china'
# 3种不同的打印方式
print(name,address)
print(name+" "+address)
print('my name is %s,I live in %s'%(name,address))
print("圆周率PI的值:%f"%3.14) # 默认一般是八位
print("圆周率PI的值:%.2f"%3.14159) # 小数点后2位
print("圆周率PI的值:%12f"%3.14) # 字符宽度为12,剩余4个空格
print("圆周率PI的值:%*f"%(1... |
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
return str(bin(int(a, 2) + int(b, 2))[2:])
def test_add_binary():
s = Solution()
assert "100" == s.addBinary("11", "1")
assert "10101" == s.addBinary("1010",... |
#Exercício Python 30:
#Crie um programa que leia um número inteiro e mostre na tela se ele é PAR ou ÍMPAR.
num = int(input('Digite um qualquer: '))
resultado = num % 2
if resultado == 0:
print(f'O número {num} é PAR!')
else:
print(f'O número {num} é IMPAR') |
def double(x):
return x*2
# Lambda Functions
# In Python, you can declare a variable of type function, where implementations can be simply assigned
# In some use cases, you may have to function pointer to a function for some processing logic
# Best Scenario: Callback scenarios
# A mechnism of defining a method i... |
#
# PySNMP MIB module DLSW-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/DLSW-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:07:01 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:1... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.