content stringlengths 7 1.05M |
|---|
ALPACA_END_POINT = 'https://paper-api.alpaca.markets'
ALPACA_API_KEY = 'PK45PMO9M1JFIAWKW1X1'
ALPACA_SECRET_KEY = 'l6nOaQQvgPqE98MhKjXkrZFvoKPl6ikJ7inBrEed'
POLYGON_ALPACA_WS = 'wss://alpaca.socket.polygon.io/stocks'
# POLYGON_API_KEY = 'jrQpup0rXAdbYrIRXUTOI8bZ1BkQlJiR'
POLYGON_API_KEY = 'PK45PMO9M1JFIAWKW1X1' |
class Solution:
def countVowelPermutation(self, n: int) -> int:
mod = 10**9 + 7
dp = [[0] * 5 for _ in range(n)]
for j in range(5):
dp[0][j] = 1
for i in range(1, n):
dp[i][0] = (dp[i-1][1] + dp[i-1][2] + dp[i-1][4]) % mod
dp[i][1] = (dp[i-1][0]... |
# -*- coding: utf-8 -*-
# AtCoder Beginner Contest
if __name__ == '__main__':
n = int(input())
a = list(map(int, input().split()))
count = 0
# See:
# https://beta.atcoder.jp/contests/abc100/submissions/2675457
for ai in a:
while ai % 2 == 0:
ai //= 2
... |
# -*- coding: utf-8 -*-
class RabbitmqClientError(Exception):
pass
class RabbitmqConnectionError(RabbitmqClientError):
pass
class QueueNotFoundError(RabbitmqClientError):
pass
|
# -*- coding: utf-8 -*-
"""
File __init__.py
@author: ZhengYuwei
""" |
def login():
return 'login info'
a = 18
num1 = 30
num2 = 10
num2 = 20
|
A, B, C = map(int, input().split())
if (A*B*C) % 2 == 0:
print(0)
else:
abc = [A, B, C]
abc.sort()
print(abc[0] * abc[1])
|
class BaseUIHandler(object):
def handle_first_run(self):
pass
def init(self):
raise NotImplementedError('No UI handler specified!')
return False
def start(self):
return 1
|
Encoding = {\
['e']: '000',
['\0x20']: '1111',
['t']: '1100',
['a']: '10111',
['o']: '1000',
['n']: '0111',
['i']: '0110',
['s']: '0100',
['r']: '0011',
['h']: '11011',
['l']: '10101',
['d']: '10010',
['c']: '00101',
['u']: '111001',
['m']: '110101',
['f']: '101001',
['p']: '101000',
['g']: '100111',
['y']: '010110',
[... |
product = {
"name":"book",
"quan":3,
"price":4.25,
}
person ={
"name":"zoy",
"first_name":"mol",
"age":39,
}
print(type(product))
print(dir(product))
print(product)
#Obtener los indices o llaves del diccionario
print(product.keys())
print(product.values())
print(product.items())
tienda = [
... |
# coding=utf-8
ver_info = {"major": 1,
"alias": "Config",
"minor": 0}
cfg_ver_min = 2
cfg_ver_active = 2
|
class DataHeader:
def __init__(self, name, data_type, vocab_file=None, vocab_mode="read"):
self.name = name
self.data_type = data_type
self.vocab_file = vocab_file
self.vocab_mode = vocab_mode
|
def parse_data():
with open('2019/01/input.txt') as f:
data = f.read()
return [int(num) for num in data.splitlines()]
def part_one(data):
return sum(mass // 3 - 2 for mass in data)
def part_two(data):
total = 0
for num in data:
while (num := num // 3 - 2) > 0:
total ... |
# greatest common divisor
def gcd(a, b):
while b:
a, b = b, a % b
return a
# lowest common multiple
def lcm(a, b):
return (a * b) // gcd(a, b)
|
""" ANIMATION CACHE MANAGER
mGear's animation cache manager is a tool that allows generating a Alembic GPU
cache representation of references rigs inside Autodesk Maya.
:module: mgear.animbits.cache_manager.__init__
"""
__version__ = 1.0
|
fname = input("Enter file name: ")
if len(fname) < 1:
fname = "mbox-short.txt"
fh = open(fname)
count = 0
def handle_line(line):
tokens = line.split(' ')
print(tokens[1])
count += 1
for line in fh:
if (line.startswith("From:")):
continue
if (not line.startswith("From")):
continue
handle_line(... |
# Ex012.2
"""Make an algorithm that reads the price of a product, and show it's new price with a 5% discount"""
price = float(input('What is the product price?: '))
new_price = price - (price * 5 / 100)
print(f'The product that coast R$: {price:.2f}')
print(f'Will now coast R$: {new_price:.2f} with 5% discount')
|
#for i in range (1,11):
# print ("%d * 5 = %d" %(i,i*5))
# Printing Pattern
for i in range (1,5):
for j in range (0,i):
print ( " * ", end = '' )
print ('') #NExt line
# For - Else loop
for i in range (5,1,-1):
for j in range(0,i):
print ( " * ", end = '' )
print ('') #... |
"""
https://www.codewars.com/kata/52597aa56021e91c93000cb0/python
Given an array (probably with different types of values inside), move all of the zeros to the end,
keeping the order of the rest.
Example:
move_zeros([false,1,0,1,2,0,1,3,"a"])
# returns[false,1,1,2,1,3,"a",0,0]
"""
def move_zeros(array):
num_ze... |
# Shared constants
SEGMENT_LEN = 3 # duration per spectrogram in seconds
FMIN = 30 # min frequency
FMAX = 12500 # max frequency
SAMPLING_RATE = 44100
WIN_LEN = 2048 # FFT window length
BINARY_SPEC_HEIGHT = 32 # binary classifier spectrogram height
SPEC_HEIGHT = 128 # no... |
def get_input():
puzzle_input = open('./python/inputday01.txt', 'r').read()
return puzzle_input.split('\n')[:-1]
def get_fuel_required(module_mass=0):
return (module_mass//3)-2
def get_fuel_required_for_fuel(fuel_volume=0):
fuel_volume_required = (fuel_volume // 3)-2
if fuel_volume_required <= 0:
... |
# -*- coding: utf-8
def register(user_store, email, username, first_name, last_name, password):
"""
Register command
"""
return user_store.create(
email=email,
username=username,
first_name=first_name,
last_name=last_name,
password=password)
|
#!/usr/bin/env python
# -*- coding: utf-8 -*-
class Solution(object):
'合并两个有序数组'
def merge(self, a, b):
c = []
h = j = 0
while j < len(a) and h < len(b):
if a[j] < b[h]:
c.append(a[j])
j += 1
else:
c.append(b[h])
... |
SUBLIST = 0
SUPERLIST = 1
EQUAL = 2
UNEQUAL = 3
def sublist(list_one, list_two):
one_chars = map(str, list_one)
two_chars = map(str, list_two)
list_one_str = ",".join(one_chars) + ","
list_two_str = ",".join(two_chars) + ","
if list_one_str == list_two_str:
return 2
elif list_one_str ... |
# 285. Inorder Successor in BST
# Runtime: 68 ms, faster than 85.36% of Python3 online submissions for Inorder Successor in BST.
# Memory Usage: 18.1 MB, less than 79.18% of Python3 online submissions for Inorder Successor in BST.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, x):
#... |
# -*- coding: utf-8 -*-
"""@package scrape
@date Created on nov. 15 09:30 2017
@author samuel_r
"""
def get_translation(jp_text):
return
|
# -*- coding: utf-8 -*-
class ArchiveService:
def get_service_name(self):
return 'DEFAULT'
def submit(self, url):
pass
class ArchiveException(Exception):
pass
|
'''
Write a program that calculates the Body Mass Index (BMI) from a user's weight and height.
The BMI is a measure of some's weight taking into account their height. e.g. If a tall person and a short person both weigh the same amount, the short person is usually more overweight.
The BMI is calculated by dividing a per... |
def reverse(st):
st = st.split()
st.reverse()
st2 = ' '.join(st)
return st2 |
class HyperParameter:
def __init__(self, num_batches, batch_size, epoch, learning_rate, hold_prob, epoch_to_report=100):
self.num_batches = num_batches
self.batch_size = batch_size
self.epoch = epoch
self.learning_rate = learning_rate
self.hold_prob = hold_prob,
self.... |
"""
Keep in mind the following table:
╔════════════╦════════════════════════════════════════════════╗
║ ║ BITS ║
║ ╠═════╦═══════╦════════════╦═════════════════════╣
║ ║ 8 ║ 16 ║ 32 ║ 64 ║
╠════════════╬═════╬═════... |
# This project created by urhoba
# www.urhoba.net
#region DB Settings
class DBSettings:
sqliteDB = "db.urhoba"
#endregion
#region Mail Settings
class MailSettings:
fromMail = "ahmetbohur@urhoba.net"
fromPassword = ""
smtpHost = "smtp.yandex.com"
smtpPort = 465
#endregion
#region Download Settings... |
"""python-homewizard-energy errors."""
class HomeWizardEnergyException(Exception):
"""Base error for python-homewizard-energy."""
class RequestError(HomeWizardEnergyException):
"""Unable to fulfill request.
Raised when host or API cannot be reached.
"""
class InvalidStateError(HomeWizardEnergyExc... |
__author__ = 'Chintalagiri Shashank'
__email__ = 'shashank@chintal.in'
__version__ = '0.2.9'
|
{
'targets': [
{
'target_name': 'rulesjs',
'sources': [ 'src/rulesjs/rules.cc' ],
'include_dirs': ["<!(node -e \"require('nan')\")"],
'dependencies': [ 'src/rules/rules.gyp:rules' ],
'defines': [ '_GNU_SOURCE' ],
'cflags': [ '-Wall', '-O3' ]
}
]
}
|
# Generate key with openssl rand -hex 32
JWT_SECRET_KEY = "46e5c95a2d980476afb2d679b37bb2c8990c25b4ea1075514f67f62f77daf306"
JWT_ALGORITHM = "HS256"
JWT_EXPIRATION_MINUTES = 15
# TODO: Move to environment variables
DB_HOST = 'localhost'
DB_NAME = 'bookstore'
DB_USER = 'postgres'
DB_PASSWORD = 'postgres'
DB_PORT = 5432... |
class Difference:
def __init__(self, a):
self.__elements = a
self.maximumDifference = 0
def computeDifference(self):
max_num = max(self.__element)
min_num = min(self.__element)
self.maximumDifference = max_num - min_num
if self.maximumDifference < 0:
... |
t = int(input())
output = []
for _ in range(t):
p, a, b, c = [int(x) for x in input().split()]
if a >= p:
minimum = a - p
elif p % a == 0:
minimum = 0
else:
minimum = a - (p % a)
if b >= p:
minimum = min(minimum, b - p)
elif p % b == 0:
minimum = 0
els... |
n=int(input());r=""
for i in range(1,n+1):
s=input().strip()
if s=="5 6" or s=="6 5":
r+="Case "+str(i)+": Sheesh Beesh\n"
else:
a=[int(k) for k in s.split()]
a.sort(reverse=True)
if a[0]==a[1]:
if a[0]==1:
r+="Case "+str(i)+": Habb Yakk\n"
... |
def order(data):
# new_data = []
for i in range(len(data)):
for j in range(len(data) - 1):
if (data[j] > data[j + 1]):
temp_data_j = data[j]
data[j] = data[j + 1]
data[j + 1] = temp_data_j
return data
|
# %% [markdown]
'''
# How to install NVIDIA GPU driver and CUDA on ubuntu
'''
# %% [markdown]
'''
This post is intended to describe how to install NVIDIA GPU driver and CUDA on ubuntu.
I have myself a GTX 560M with ubuntu 18.04.
'''
# %% [markdown]
'''
## Requirements
Before installing, we will first need to find th... |
#!/usr/bin/env python3
def clean_up():
try:
raise KeyboardInterrupt
finally:
print('Goodbye, world!')
def divide(x, y):
try:
result = x / y
except ZeroDivisionError:
print("division by zero!")
else:
print("result is", result)
finally:
print("exe... |
# Testando as f strings
# Testing the f strings
nome = 'José'
idade = 33
salario = 957.55
print(f'O {nome} tem {idade} anos e ganha R${salario:.2f}') # PYTHON 3.6+
#print('{} is {} years old.'.format(name, age)) #PYTHON 3
#print('%s is %d years old.' % (name, age)) #PYTHON 2
|
test = {
"name": "q3",
"points": 1,
"hidden": False,
"suites": [
{
"cases": [
{
"code": r"""
>>> len(data["flavor"].unique()) == 4
True
""",
"hidden": False,
"locked": False,
},
{
"code": r"""
>>> for l in ["chocolate", "vanilla", "strawberry", "mint"]:
... |
# Just a simple time class
# that stores time in 24 hour format
# and displays in period time (AM/PM)
class SimpleTime:
def __init__(self, hour, minute, period):
# assertions for checking
assert(hour > 0 and hour <= 12)
assert(minute >= 0 and minute < 60)
assert(period == "AM" or per... |
file_pickled_dfas = "helper-dfas.pickled"
file_pickled_dfas = "helper-more-dfas.pickled"
day_in_sec = 86400
now_in_sec = time.time()
def get_dfas():
"""Get DFAs from pickled file. If the file is older than a day regenerate it."""
global day_in_sec
global now_in_sec
global __dfa_list
... |
class BytesIntEncoder:
@staticmethod
def encode(s: str) -> int:
return int.from_bytes(s.encode(), byteorder='big')
@staticmethod
def decode(i: int) -> str:
return i.to_bytes(((i.bit_length() + 7) // 8), byteorder='big').decode()
|
def castleTowers(n, ar):
occurrences_map = {}
max_item = -1
for item in ar:
if item > max_item:
max_item = item
if item in occurrences_map:
occurrences_map[item] += 1
else:
occurrences_map[item] = 1
return occurrences_map[max_item]
if __na... |
def countMinOperations(target, n):
result = 0
while (True):
zero_count = 0
i = 0
while (i < n):
if ((target[i] & 1) > 0):
break
elif (target[i] == 0):
zero_count += 1
i += 1
if (zero_count == n):
... |
# generated from genmsg/cmake/pkg-genmsg.context.in
messages_str = "/home/pi/catkin_ws/src/mobrob_util/msg/ME439SensorsRaw.msg;/home/pi/catkin_ws/src/mobrob_util/msg/ME439SensorsProcessed.msg;/home/pi/catkin_ws/src/mobrob_util/msg/ME439WheelSpeeds.msg;/home/pi/catkin_ws/src/mobrob_util/msg/ME439MotorCommands.msg;/home... |
#
# Find the one food that is eaten by only one animal.
#
# The animals table has columns (name, species, birthdate) for each individual.
# The diet table has columns (species, food) for each food that a species eats.
#
QUERY = '''
select diet.food, count(animals.name) as num from animals, diet where animals.s... |
# IE 11 CustomEvent polyfill
src = r"""
(function () {
if ( typeof window.CustomEvent === "function" ) return false; //If not IE
function CustomEvent ( event, params ) {
params = params || { bubbles: false, cancelable: false, detail: undefined };
var evt = document.createEvent( 'CustomEvent' );
evt.in... |
class EmployeeTaskLink:
def __init__(self, linkID, empID, taskID):
self.linkID = linkID
self.empID = empID
self.taskID = taskID
def get_employee(self, list):
for emp in list:
if emp.empID == self.empID:
return emp
def get_task(self, list):
... |
def findDecision(obj): #obj[0]: Passanger, obj[1]: Time, obj[2]: Coupon, obj[3]: Gender, obj[4]: Age, obj[5]: Children, obj[6]: Education, obj[7]: Occupation, obj[8]: Bar, obj[9]: Coffeehouse, obj[10]: Restaurant20to50, obj[11]: Direction_same, obj[12]: Distance
# {"feature": "Age", "instances": 34, "metric_value": 0.... |
# Copyright 2015 Google Inc. All rights reserved.
#
# 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 a... |
"""
Errors about channels.
"""
class FetchChannelFailed(Exception):
"""Raises when fetching a channel is failed."""
pass
class FetchChannelMessagesFailed(Exception):
"""Raises when fetching messages from channel is failed."""
pass
class FetchChannelMessageFailed(Exception):
"""Raises when fe... |
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License.
class Constants:
SYS_BOOLEAN: str = "boolean"
SYS_BOOLEAN_TRUE: str = "boolean-true"
SYS_BOOLEAN_FALSE: str = "boolean-false"
|
t = int(input())
while t:
A, B = map(int, input().split())
c = 1
while(c>0):
if(c%2==0):
B -= c
else:
A -= c
if(A<0):
print("Bob")
break
if(B<0):
print("Limak")
break
c += 1
t = t-1
|
## Uppercase is BOLT
# to use: from utils.beautyfy import *
def red(string):
return '\033[1;91m {}\033[00m'.format(string)
def RED(string):
return '\033[1;91m {}\033[00m'.format(string)
def yellow(string):
return '\033[93m {}\033[00m'.format(string)
def YELLOW(string):
return '\033[1;93m {}\033[00m'... |
# 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 writing, software
# distrib... |
# Time: O(n log n); Space: O(1)
def ship_within_days(weights, days):
low = max(weights)
high = sum(weights)
min_capacity = high
while low <= high:
mid = low + (high - low) // 2
cur_days, cur_daily_weight = 1, 0
for w in weights:
if cur_daily_weight + w > mid:
... |
# -*- coding: utf-8 -*-
"""Top-level package for nola."""
__author__ = """Raghuveer Naraharisetti"""
__email__ = 'raghuveernaraharisetti@gmail.com'
__version__ = '0.1.0'
|
# config.py
DEBUG = True
DBHOST = '130.211.198.107'
DBPASS = "gregb00th"
DBPORT = 3306
DBUSER = 'root'
DBNAME = 'baseball_2018'
CLOUDSQL_PROJECT = "Baseball-2018"
CLOUDSQL_INSTANCE = "personalwebsite-165915:us-central1:baseball-2018"
CLOUD_STORAGE_BUCKET = 'analytics_data_extraction'
MAX_CONTENT_LENGTH = 8... |
def get_certified_by(filing_data: dict):
user_id = filing_data.get('u_user_id')
if user_id:
first_name = filing_data.get('u_first_name')
middle_name = filing_data.get('u_middle_name')
last_name = filing_data.get('u_last_name')
if first_name or middle_name or last_name:
... |
file_path = '/esdata/test/11.log'
with open(file_path, 'w') as file:
num = 1000
val = 0
while val <= num:
file.write("{:x}\n".format(val).zfill(12))
val += 1
|
load_modules = {
########### Attacker
'uds_engine_auth_baypass': {
'id_command': 0x71
},
'gen_ping' : {},
'uds_tester_ecu_engine':{
'id_uds': 0x701,
'uds_shift': 0x08,
'uds_key':''
},
'hw_TCP2CAN': {'port': 1111, 'mode': 'client', 'address':'127.0.... |
# More indentation included to distinguish this from the rest.
def server(
host='localhost', port=443, secure=True,
username='admin', password='admin'):
return locals()
# Aligned with opening delimiter.
connection = server(host='localhost', port=443, secure=True,
username='admi... |
# yacon.definitions.py
#
# This file contains common values that aren't usually changed per
# installation and therefore shouldn't go in the django settings file
# max length of slugs
SLUG_LENGTH = 25
# max length of title
TITLE_LENGTH = 50
# bleach constants
ALLOWED_TAGS = [
'a',
'address',
'b',
'br... |
# Curso de Python do Curso em Vídeo
# Desafio 05 Aula #07 Operadores aritiméticos
# Faça um algoritimo que leia o salário de um funcionário e mostre seu novo salário com 15% de aumento# preço com 5% de desconto.
# Aluno MaxBarroso
print('Black-Py-Day')
print('Este programa te ajuda a saber qual o novo salário de um fu... |
''' Break statement
''' |
"""
Statically define whether the measurementheaders should be enabled
TODO: Make this adjustable at runtime
"""
class Measurement_Headers():
Active : bool = True |
#greatest among 3
a=int(input("Enter no:"))
b=int(input("Enter no:"))
c=int(input("Enter no:"))
if a>b:
if a>c:
print(a)
else:
print(c)
else:
if b>c:
print(b)
else:
print(c)
|
# -*- coding: utf-8 -*-
def file_decrypt(data,mode,storetype):
return data
|
# not yet finished
H, M = input().split()
H, M = int(H), int(M)
N = int(input())
m = N % 60
H += N // 60
H %= 24
M = m
# for _ in range(N):
# M += 1
# if M == 60:
# M = 0
# H += 1
# if H == 24:
# H = 0
print(H, M) |
"""
53. Maximum Subarray
Easy
Given an integer array nums, find the contiguous subarray (containing at least one number) which has the largest sum and return its sum.
A subarray is a contiguous part of an array.
Example 1:
Input: nums = [-2,1,-3,4,-1,2,1,-5,4]
Output: 6
Explanation: [4,-1,2,1] has the largest s... |
#!/usr/bin/env python3
def part_one():
result = str(1113122113)
for i in range(40):
result = say(result)
return len(result)
def part_two():
result = str(1113122113)
for i in range(50):
result = say(result)
return len(result)
def say(input):
"""
>>> say(1)
... |
""" The problem is that we want to reverse a T[] array in O(N) linear
time complexity and we want the algorithm to be in-place as well!
For example: input is [1,2,3,4,5] then the output is [5,4,3,2,1]
"""
arr = [1, 2, 3, 4, 5, 6]
for i in range(len(arr) // 2):
arr[i], arr[len(arr)-1-i] = arr[len(arr)-1-i... |
"""
Class: Create peripheral objects whenever a new device is found
Methods: Send connection request to given device, disconnect from given device, handle discovery of advertisments
List all available characteristics (services that contain more characteristics)
"""
|
def starify_pval(pval):
if pval > 0.05:
return ""
else:
if pval <= 0.001:
return "***"
if pval <= 0.01:
return "**"
if pval <= 0.05:
return "*"
|
codes = {
"reset": "\u001b[0m",
"black": "\u001b[30m",
"red": "\u001b[31m",
"green": "\u001b[32m",
"light_yellow": "\u001b[93m",
"yellow": "\u001b[33m",
"yellow_background": "\u001b[43m",
"blue": "\u001b[34m",
"purple": "\u001b[35m",
"cyan": "\u001b[36m",
"white": "\u001b[37m... |
################################################################################
# Copyright: Tobias Weber 2020
#
# Apache 2.0 License
#
# This file contains code related to all breadp module
#
################################################################################
class ChecksNotRunException(Exception):
... |
# 1) Um posto está vendendo combustíveis com a seguinte tabela de descontos:
#
#Álcool:
#
#até 20 litros, desconto de 3% por litro
#acima de 20 litros, desconto de 5% por litro
#Gasolina:
#
#até 20 litros, desconto de 4% por litro
#acima de 20 litros, desconto de 6% por litro.
#
#Escreva um algoritmo que leia o número ... |
#
# PySNMP MIB module LIGO-GENERIC-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/LIGO-GENERIC-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:56:36 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar ... |
class Solution:
def bitwiseComplement(self, N: int) -> int:
if N == 0:
return 1
ret = i = 0
while N:
ret |= (((N & 1) ^ 1) << i)
i += 1
N >>= 1
return ret
|
def init():
global games
global debug
global color
global tile_colors
global tile_decorations
global player_colors
global unit_emojis
games = {}
debug = False
color = 0xcc00ff
tile_colors = ["🟥", "🟦", "🟩", "⬛"]
tile_decorations = ["🌲", "🌳"]
player_colors = [0xff3333, 0x3388ff, 0x33ff33, 0x333333]
un... |
# table definition
table = {
'table_name' : 'ap_pmt_batch',
'module_id' : 'ap',
'short_descr' : 'Ap batch of payments',
'long_descr' : 'Ap batch of payments by due date',
'sub_types' : None,
'sub_trans' : None,
'sequence' : None,
'tree_params' : None,
'roll... |
# Given a binary tree, return all root-to-leaf paths.
#
# Note: A leaf is a node with no children.
#
# Example:
#
# Input:
#
# 1
# / \
# 2 3
# \
# 5
#
# Output: ["1->2->5", "1->3"]
#
# Explanation: All root-to-leaf paths are: 1->2->5, 1->3
# Definition for a binary tree node.
class TreeNode:
def __i... |
"""
Doctests
Doctests são testes que colocamos na docstring das funções/métodos Python.
def soma(a, b):
# soma os números a e b
#>>> soma(1, 2)
#3
#>>> soma(4, 6)
#10
#
return a + b
Para rodar um test do doctest:
python -m doctest -v nome_do_mobulo.py
# Saída
Trying:
s... |
"""
This is a dedicated editor for specifying camera set rigs. It allows
the artist to preset a multi-rig type. They can then use the
create menus for quickly creating complicated rigs.
"""
class BaseUI:
"""
Each region of the editor UI is abstracted into a UI class that
contains all of the widgets for t... |
a=input()
b=a[::-1]
if a==b:
print("yes")
else:
print("no")
|
def getBMR(weightLBS, heightINCHES, age):
weightKG = weightLBS*.453592
heightCM = heightINCHES*2.54
BMR = 10*weightKG+.25*heightCM-5*age+5
return BMR
|
s = '¹÷É´¹Ò®¾¤¦ò¤®¾¤µÈ¾¤Â©¨¡¾¨ö®¾¤¦ò¤®¾¤µÈ¾¤Ã¦È'
# s = '¡¾²½ñ¢ñªÒ, ²½ñ, ¦ò¤¢º¤ê†Ã§Éá¾²½ñ'
s = 'À»ñ©Ã¹ÉÁª¡, À»ñ©Ã¹ÉÀ², À»ñ©Ã¹É¹ñ¡, À»ñ©Ã¹ÉçɮÒÄ©É'
s = '¦ô®ªÒ, µøÈªÒ, ´óµøÈ, ª˜¤µøÈ'
s = 'ªó, À£¾½, ¥ñ¤¹¸½, ¡¾Àª˜,-ຊະນະ'
s = 'À»ñ©Ã¹ÉÀ¡ó©¦ó, À»ñ©Ã¹ÉÀ¯ñ¦ó'
# for i in range(161, 255):
# print(chr(... |
class SocialErrorMessages:
"""
Create SocialErrorMessages object
"""
def __init__(self, base_url: str):
self._full_messages = {
"email facebook error": f"""<p>We can't get your email. Please, check <a href=\"https://facebook.com/settings\">your facebook settings</a>. Make sure you h... |
n = int(input("Please Enter a value for N:\n"))
count = 0
sum = 0
while count <= n :
sum = sum+count
count +=1
print("Sum of N natural numbers: " + str(sum)) |
# -*- coding: utf-8 -*-
"""
Created on Wed Oct 21 16:50:47 2020
@author: ucobiz
"""
inputObj = open("newfile.txt")
outputObj = open("output-newfile.txt", "w")
# convert the sentence into UPPERCASE
for sentence in inputObj:
newSentenceUpper = sentence.upper()
outputObj.writelines(newSentenceUppe... |
# subsets 78
# ttungl@gmail.com
# Given a set of distinct integers, nums, return all possible subsets (the power set).
# Note: The solution set must not contain duplicate subsets.
# For example,
# If nums = [1,2,3], a solution is:
# [
# [3],
# [1],
# [2],
# [1,2,3],
# [1,3],
# [2,3],
# [1,2],
# []
# ... |
# integer = int(input("Please fill number:"))
integer = 12
result = tuple()
for i in range(0,integer,2 ):
result = result + (i,)
print(result) |
APIS = {
'apis',
'keyvaluemaps',
'targetservers',
'caches',
'developers',
'apiproducts',
'apps',
'userroles',
}
class Struct:
def __init__(self, **entries):
self.__dict__.update(entries)
def __repr__(self):
return f"{self.__dict__}"
def empty_snapshot():
r... |
# Database
# https://docs.djangoproject.com/en/1.8/ref/settings/#databases
GDAL_LIBRARY_PATH = "/Applications/Postgres.app/Contents/Versions/9.4/lib/libgdal.dylib"
GEOS_LIBRARY_PATH = "/Applications/Postgres.app/Contents/Versions/9.4/lib/libgeos_c.dylib"
DATABASES = {
'default': {
'ENGINE': 'django.contr... |
# -*- coding:UTF-8 -*-
#! /usr/bin/python3
# 字符串 内建函数
String_a = 'iPhone'
String_b = 'Apple'
# 首字母大写
print('=====首字母大写=====\n注意调用方法:')
print(String_a,'->',str.capitalize(String_a))
print(String_b,'->',String_b.capitalize()) # 注意调用方法
print('=====字符填充=====')
print('填充字符,默认填充空格:',String_a.center(20))# 填充字符
prin... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.