content stringlengths 7 1.05M |
|---|
v_carro = float(input("Informe o valor: "))
total_mes_carro = (0.004 * v_carro) +v_carro
p_inicial = 10000
renda_total = (0.007 * p_inicial) + p_inicial
mes = -1
while True:
mes += 1
total_mes_carro = (0.004 * total_mes_carro) + total_mes_carro
if renda_total < total_mes_carro:
renda_total = (0.007 ... |
_kirciuotos_raides = {
"a" : ["a`","a~","a^"],
"ą" : ["ą~","ą^"],
"e" : ["e`","e~","e^"],
"ę" : ["ę~","ę^"],
"ė" : ["ė~","ė^"],
"i" : ["i`","i~","i^"],
"į" : ["į~","į^"],
"y" : ["y~","y^"],
"o" : ["o`","o~","o^"],
"u" : ["u`","u~","u^"],
"ų" : ["ų~","ų^"],
"ū" : ["ū~","ū^"],
"l" : ["l~"],
"m" : ["m~"],
"n" : ["n~"],
"... |
def exception_test(assert_check_fn):
try:
def exception_wrapper(*arg, **kwarg):
assert_check_fn(*arg, **kwarg)
except Exception as e:
pytest.failed(e) |
#########################
# 生成器
#########################
# 创建一个生成器
L = (x * 2 for x in range(5))
print(type(L))
print(L)
for value in L:
print(value, end=' ')
print()
# 创建一个函数生成器
def fib(times):
n = 0
a, b = 0, 1
while n < times:
"""
在循环过程中不断调用 yield ,就会不断中断。当然要给循环设置一个条件来退出循环,不然就会... |
"""
Queries of issue queries
"""
def gql_issues(fragment):
"""
Return the GraphQL issues query
"""
return f'''
query ($where: IssueWhere!, $first: PageSize!, $skip: Int!) {{
data: issues(where: $where, first: $first, skip: $skip) {{
{fragment}
}}
}}
'''
GQL_ISSUES_COUNT = '''
query($where: I... |
"""
@desc Prints informations about the candidate : his/her profile and messages sent
@params candidate: instance of Candidate
"""
def show_candidate_informations(candidate):
print("## CANDIDATE PROFILE ##", end="\n\n")
print("Firstname: {}".format(candidate.firstname))
print("Lastname: {}".format(candid... |
class Korean:
"""Korean speaker"""
def __init__(self):
self.name = "Korean"
def speak_korean(self):
return "An-neyong?"
class British:
"""English speaker"""
def __init__(self):
self.name = "British"
#Note the different method name here!
def speak_english(self):
return "Hello!"
clas... |
def green(text):
return f"\033[92m{text}\033[0m"
def yellow(text):
return f"\033[93m{text}\033[0m"
|
# rainfall_mi is a string that contains the average number of inches of rainfall in Michigan for every month (in inches)
# with every month separated by a comma. Write code to compute the number of months that have more than 3 inches of
# rainfall. Store the result in the variable num_rainy_months. In other words, coun... |
MORSE_CODE_DICT = { 'A':'.-', 'B':'-...',
'C':'-.-.', 'D':'-..', 'E':'.',
'F':'..-.', 'G':'--.', 'H':'....',
'I':'..', 'J':'.---', 'K':'-.-',
'L':'.-..', 'M':'--', 'N':'-.',
'O':'---', 'P':'.--.', 'Q':'--.-',
... |
# -*- coding: utf-8 -*-
class MyClass:
# The __init__ method doesn't return anything, so it gets return
# type None just like any other method that doesn't return anything.
def __init__(self) -> None:
...
# For instance methods, omit `self`.
def my_class_method(self, num: int, str1: str) -> str:
... |
expected_output = {
"bridge_group": {
"D": {
"bridge_domain": {
"D-w": {
"ac": {
"num_ac": 1,
"num_ac_up": 1
},
"id": 0,
"pbb": {
... |
INPUT_TO_DWI_CONVERSION_EDGES = [("dwi_file", "in_file")]
INPUT_TO_FMAP_CONVERSION_EDGES = [("fmap_file", "in_file")]
LOCATE_ASSOCIATED_TO_COVERSION_EDGES = [
("json_file", "json_import"),
("bvec_file", "in_bvec"),
("bval_file", "in_bval"),
]
DWI_CONVERSION_TO_OUTPUT_EDGES = [("out_file", "dwi_file")]
FMAP... |
almacen_api_config = {
'debug': {
'name': 'almacen_api',
'database': 'stage_01',
'debug': True,
'app': {
'DEBUG': True,
'UPLOAD_FOLDER': '/tmp',
},
'run': {
# 'ssl_context': ('ssl/cert.pem', 'ssl/key.pem'),
'port': 8000,
},
'app_tokens': {
'TOKEN': {
... |
# Desenvolva um programa que leia o comprimento de três retas e diga ao usuário se elas podem ou não formar um triângulo.
print('Suas retas formam um triângulo?')
r1 = float(input('Digite a primeira reta: '))
r2 = float(input('Digite a segunda reta: '))
r3 = float(input('Digite a terceira reta: '))
if r1 < (r2+r3) an... |
a=1
def change_integer(a):
a = a+1
return a
print (change_integer(a))
print (a)
b=[1,2,3]
def change_list(b):
b[0]=b[0]+1
return b
print (change_list(b))
print (b)
|
number_1 = int(input())
number_2 = int(input())
if number_1 >= number_2:
print(number_1)
print(number_2)
else:
print(number_2)
print(number_1)
|
def main(input):
myDict = {}
myDict['ก']='k'
for key in ['ข','ค', 'ฆ']:
myDict[key] = 'k'
myDict['ง']='ng'
myDict['จ']='t'
for key in ['ฉ','ฌ', 'ช']:
myDict[key] = 't'
for key in ['ซ','ศ', 'ษ','ส']:
myDict[key] = 't'
for key in ['ย']:
myDict[key] = 'j'
... |
'''
Gas Station
Asked in: Bloomberg, Google, DE Shaw, Amazon, Flipkart
Given two integer arrays A and B of size N.
There are N gas stations along a circular route, where the amount of gas at station i is A[i].
You have a car with an unlimited gas tank and it costs B[i] of gas to travel from station i
to its next stat... |
#!/usr/bin/env python3
# CHECKED
A = [[4.5, -1, -1, 1], [-1, 4.5, 1, -1], [-1, 2, 4.5, -1], [2, -1, -1, 4.5]]
b = [1, -1, -1, 0]
x = [0.25, 0.25, 0.25, 0.25]
x_new = [0, 0, 0, 0]
for k in range(2):
for i in range(4):
x_new[i] = b[i]
for j in range(4):
if j != i:
x_new[... |
class Solution:
# @param num : a list of integer
# @return : a list of integer
def nextPermutation(self, num):
# write your code here
# Version 1
bp = -1
for i in range(len(num) - 1):
if (num[i] < num[i + 1]):
bp = i
if (bp == -1):
... |
X = int(input())
a_list = []
for s in range(1, 32):
for i in range(2, 10):
a = s ** i
if a > 1000:
break
a_list.append(a)
a2 = sorted(list(set(a_list)), reverse=True)
for n in a2:
if n <= X:
print(n)
break |
def presentacion_inicial():
print("*"*20)
print("Que accion desea realizar : ")
print("1) Insertar Persona : ")
print("2) Insertar Empleado : ")
print("3) Consultar las personas : ")
print("4) Consultar por empleados : ")
return int(input("Opcion necesitas : "))
|
class SEHException(ExternalException):
"""
Represents structured exception handling (SEH) errors.
SEHException()
SEHException(message: str)
SEHException(message: str,inner: Exception)
"""
def ZZZ(self):
"""hardcoded/mock instance of the class"""
return SEHException()
instance=ZZZ()
"""har... |
# encoding: utf-8
# module Revit.References calls itself References
# from RevitNodes,Version=1.2.1.3083,Culture=neutral,PublicKeyToken=null
# by generator 1.145
# no doc
# no imports
# no functions
# classes
class RayBounce(object):
# no doc
@staticmethod
def ByOriginDirection(origin, dire... |
load("@io_bazel_rules_docker//go:image.bzl", go_image_repositories="repositories")
load("@io_bazel_rules_docker//container:container.bzl", container_repositories = "repositories")
def initialize_rules_docker():
container_repositories()
go_image_repositories()
load("@distroless//package_manager:package_manager.bzl"... |
a = 15
b = 15
exp = a == b
if a < b:
print(f'{a} e menor que {b}')
elif a > b :
print(f'{a} e maior que {b}')
else:
print('Os valores são iguais')
letra = 'l'
nome = 'Djonatan l'
if letra in nome:
print(f'Contem {letra} no nome')
else:
print(f'Não Contem {letra} no nome')
valor = '2'
valores = '82... |
"""
1. Problem Summary / Clarifications / TDD:
output("abcd", "abecd") = "e"
2. Inuition: xor operator
3. Tests:
output("abcd", "abecd") = "e": The added character is in the middle of t
output("abcd", "abcde") = "e": The added character is at the end of t
ou... |
# urls.py
# urls for dash app
url_paths = {
"index": '/',
"home": '/home',
"scatter": '/apps/scatter-test',
"combo": '/apps/combo-test'
}
|
scoreboard_display = [['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '10', '11', '12', '13', '14', '15', '16', '17', '18', '19', '20', '21', '22', '23', '24', '25'],
['51', '50', '49', '48', '47', '46', '45', '44', '43', '42', '41', '40', '39', '38', '37', '36', '35', '34', '33', '32', '31', '30', '29', '28', '27',... |
# flake8: noqa
# in legacy datasets we need to put our sample data within the data dir
legacy_datasets = ["cmu_small_region.svs"]
# Registry of datafiles that can be downloaded along with their SHA256 hashes
# To generate the SHA256 hash, use the command
# openssl sha256 filename
registry = {
"histolab/broken.svs... |
print('=' * 15, '\033[1;35mAULA 18 - Listas[Part #2]\033[m', '=' * 15)
# --------------------------------------------------------------------
dados = []
pessoas = []
galera = [['Miguel', 25], ['Berta', 59], ['Joaquim', 20]]
# --------------------------------------------------------------------
dados.append('Joaquim')
d... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Created on 22/4/2016 10:57 AM
Author: Qu Dong
"""
class QuikFindUF():
def __init__(self, N):
self.count = N
self.parent = list(range(N))
def count(self):
return self.count
def find(self, p):
self._validate(p)
retu... |
#AUTH Kaio Guilherme
class Node:
def __init__(self, key):
self.key = key
self.left = None
self.right = None
root = Node(0)
root.left = Node(1)
root.right = Node(0)
root.right.left = Node(1)
root.right.right = Node(0)
root.right.left.right = Node(1)
root.right.left.left = Node(1)
def sum... |
P, D = list(map(int, input().split(' ')))
totA, totB = 0, 0
dis = [[0,0,0,0] for i in range(D)]
for i in range(P):
a, b, c = map(int, input().split(' '))
k = (b+c)//2 + 1
dis[a-1][0] += b
dis[a-1][1] += c
for i, (ta, tb, _, _) in enumerate(dis):
k = (ta + tb)//2 + 1
if ta > tb:
wA = ta-k
wB ... |
# -*- coding: utf-8 -*-
def _data_from_bar(ax, bar_label):
"""Given a matplotlib Axes object and a bar label,
returns (x,y,w,h) data underlying the bar plot.
Args:
ax: The Axes object the data will be extracted from.
bar_label: The bar label from which you want to extract the data.
R... |
baklava_price = float(input())
muffin_price = float(input())
shtolen_kg = float(input())
candy_kg = float(input())
bisquits_kg = int(input())
shtolen_price = baklava_price + baklava_price * 0.6
candy_price = muffin_price + muffin_price * 0.8
busquits_price = 7.50
shtolen_sum = shtolen_kg * shtolen_price
candy_sum = ca... |
"""
Generic utilities
"""
def any(seq):
for i in seq:
if i:
return True
return False
|
x=int(input('Enter the number to convert: '))
print('Select the convertion')
print('''
[ 1 ] Binary
[ 1 ] Octal
[ 3 ] HexaDeicmal
''')
y=int(input('1 - Binary 2 - Octal 3 - Hexadecimal'))
if y==1:
bin(x)[2:]
print('{}'.format(x))
elif y==2:
oct(x)
print('{}'.format(x))
elif y==3:
hex(x)
print(... |
"""
给定一个整数n,返回从1到n的数字中1个出现的个数.
例如:
n=5,1~n为1,2,3,4,5.那么1出现了1次,所以返回1.
n=11,1~n为1,2,3,4,5,6,7,8,9,10,11.那么1出现的次数为1(出现
1次),10(出现1次),11(有两个1,所以出现了2次),所以返回4
"""
class OneCounter:
@classmethod
def get_nums_of_one(cls, n):
if n == 0:
return 0
n = abs(n)
high_pos = 1
cur ... |
# -*- coding: utf-8 -*-
"""
meetup.py
~~~~~~~~~
a mock for the Meetup APi client
"""
class MockMeetupGroup:
def __init__(self, *args, **kwargs):
self.name = "Mock Meetup Group"
self.link = "https://www.meetup.com/MeetupGroup/"
self.next_event = {
"id": 0,
... |
# TASK:
# Given an integer, n, perform the following conditional actions:
# If n is odd, print Weird
# If n is even and in the inclusive range of 2 to 5, print Not Weird
# If n is even and in the inclusive range of 6 to 20, print Weird
# If n is even and greater than 20, print Not Weird
if __name__ == '__main__':
... |
#!/usr/bin/python3
def safe_print_list_integers(my_list=[], x=0):
i = 0
for index in range(x):
try:
print("{:d}".format(my_list[index]), end="")
i += 1
except (ValueError, TypeError):
pass
print()
return i
|
class PlacementRuleUtil:
def __init__(self, game_data, placement_data):
self.rule = int(game_data.rule[int(placement_data.obj_number)-1]["placementRule"])
self.placement = placement_data.placement
self.type = game_data.rule[int(placement_data.obj_number)-1]["type"]
self.placement_ty... |
N = int(input())
A, B = (
zip(*(map(int, input().split()) for _ in range(N))) if N else
((), ())
)
ans = len({(min(a, b), max(a, b)) for a, b in zip(A, B)})
print(ans)
|
URLS = [
"url1"
]
STATUSPAGE_API_KEY = ""
STATUSPAGE_PAGE_ID = ""
STATUSPAGE_METRICS = {
"url": "metric_id"
}
STATUSPAGE_COMPONENTS = {
"url": "component_id"
}
PING_WEBHOOKS = []
STATUS_WEBHOOKS = []
ESCALATION_IDS = []
POLL_TIME = 60
OUTAGE_CHANGE_AFTER = 10
DRY_MODE = False
DEGRADED_PERFORMANCE_TARGET_PIN... |
d = {'a': 1, 'c': 3}
match d:
case {'a': chave_a, 'b': _}:
print(f'chave A {chave_a=} + chave B')
case {'a': _} | {'c': _}:
print('chave A ou C')
case {}:
print('vazio')
case _:
print('Não sei')
|
{ 'application':{ 'type':'Application',
'name':'MulticolumnExample',
'backgrounds':
[
{ 'type':'Background',
'name':'bgMulticolumnExample',
'title':'Multicolumn Example PythonCard Application',
'size':( 620, 500 ),
'menubar':
{
'type':'MenuBar',
'menus':
... |
# Refaça o desafio 035, acrescentando o recurso de mostrar que
# tipo de triângulo será formado:
# - Equilátero: todos os lados iguais;
# - Isósceles: dois lados iguais;
# - Escaleno: todos os lados diferentes.
n1 = float(input('\033[34mMedida 1:\033[m '))
n2 = float(input('\033[31mMedida 2:\033[m '))
n3 = float(input(... |
#!/usr/bin/env python3
"""
Models that maps to Cloudformation functions.
"""
def replace_fn(node):
"""Iteratively replace all Fn/Ref in the node"""
if isinstance(node, list):
return [replace_fn(item) for item in node]
if isinstance(node, dict):
return {name: replace_fn(value) for name, val... |
"""Rule and corresponding provider that joins a label pointing to a TreeArtifact
with a path nested within that directory
"""
load("//lib:utils.bzl", _to_label = "to_label")
DirectoryPathInfo = provider(
doc = "Joins a label pointing to a TreeArtifact with a path nested within that directory.",
fields = {
... |
# Programa Simulador de Caixa Eletrônico
# O caixa possui cédulas de 50, 20, 10 e 1
# Forma 1 = MINHA FORMA, COMPLICADA, MEIO NO CHUTE
print('=' * 50)
print('{:^50}'.format(' BANCO SIMÕES '))
print('=' * 50)
valor = int(input('Qual valor você quer sacar: R$'))
while True:
if valor % 50 != 1:
if valor // 5... |
# Find algorithm that sorts the stack of size n in O(log(n)) time. It is allowed to use operations
# provided only by the stack interface: push(), pop(), top(), isEmpty() and additional stacks.
class Stack:
def __init__(self):
self.stack = []
def push(self, value):
self.stack.append(value)
... |
#!/usr/bin/python3
'''
Pegando todos os parametros
Um argumento pocisional sempre deve estar antes de parametros nomeados
def todos_params(*args, **kwargs):
Significa que quer pegar os argumentos de uma forma genérica
tanto pocisionais quanto os nomeados
'''
def todos_params(*args, **kwargs):
print(f'ar... |
N = int(input())
MAX, VAR, FIX = range(3)
# latest=9 r=3 b=4
# max_variable_fixed_values = [
# 3 4 5
# 2 3 3
# 2 1 5
# 2 4 2
# 2 2 4
# 2 5 1
# ]
def try_to_beat(latest_score, r, b, max_var_fixed):
our_score = 0
while b > 0:
if not r:
return -1
best_c_max_b, best_max_b = ... |
#
# PySNMP MIB module CTRON-CHASSIS-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CTRON-CHASSIS-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:44:24 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
class BaseDataset:
def __init__(self, data=list()):
self.data = data
def __getitem__(self, idx):
return self.data[idx]
def __len__(self):
return len(self.data)
|
"""Calculators for different values.
In order to approximate the emissions for a single kWh of produced
energy, per power source we look at the following 2016 data sets.
* Detailed EIA-923 emissions survey data
(https://www.eia.gov/electricity/data/state/emission_annual.xls)
* Net Generation by State by Type of Pr... |
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time : 2020/2/11 14:23
# @Author : Baimohan/PH
# @Site : https://github.com/BaiMoHan
# @File : comment_test.py
# @Software: PyCharm
print("hello world")
# 这是一行注释
'''
多行注释
单引号形式
'''
"""
双引号多注释 三个双引号
"""
print("测试")
a = 5
print(a)
a += 3
print(a)
|
def test():
# Here we can either check objects created in the solution code, or the
# string value of the solution, available as __solution__. A helper for
# printing formatted messages is available as __msg__. See the testTemplate
# in the meta.json for details.
# If an assertion fails, the messag... |
"""EXCEPTIONS
Exceptions used on the project
"""
__all__ = ("VigoBusAPIException", "StopNotExist", "StopNotFound")
class VigoBusAPIException(Exception):
"""Base exception for the project custom exceptions"""
pass
class StopNotExist(VigoBusAPIException):
"""The Stop does not physically exist (as reporte... |
def foo():
'''
>>> from mod import CamelCase as CONST
'''
pass
|
#! python3
###############################################################################
# Copyright (c) 2021, PulseRain Technology LLC
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Lesser General Public License (LGPL) as
# published by the Free Softw... |
class AVLNode:
def __init__(self, key):
self.key = key
self.parent = None
self.left = None
self.right = None
self.balance = 0
def has_left(self): return self.left is not None
def has_right(self): return self.right is not None
def has_no_children(self): return not... |
# Project Euler Problem 11
# Created on: 2012-06-14
# Created by: William McDonald
# Return the minimum number that can be present in
# a solution set of four numbers
def getMin(cap, min):
k = 99 * 99 * 99
for i in range(min, 99):
if i * k > cap:
return i
def importGrid():
... |
def get_final_line(
filepath: str
) -> str:
with open(filepath) as fs_r:
for line in fs_r:
pass
return line
def get_final_line__readlines(
filepath: str
) -> str:
with open(filepath) as fs_r:
return fs_r.readlines()[-1]
def main():
filepath = 'file.txt'
fi... |
price = float(input("Digite o preco do produto: "))
discount = (5/100) * price
total = price - discount
print("O valor com desconto eh: {:.2f}".format(total)) |
def soma(n1, n2):
return n1 + n2
def subtracao(n1,n2):
return n1 - n2
def multiplicacao(n1, n2):
return n1 * n2
def divisao(n1, n2):
return n1 / n2
|
"""
________ ___ __ ________ ________ ___ ___ ________ _______ ________
|\ ____\|\ \ |\ \|\ __ \|\ __ \ |\ \|\ \|\ ____\|\ ___ \ |\ __ \
\ \ \___|\ \ \ \ \ \ \ \|\ \ \ \|\ \ \ \ \\\ \ \ \___|\ \ __/|\ \ \|\ \
\ \_____ \ \ \ __\ \ \ \ __ \ \ ... |
# noinspection PyUnusedLocal
# skus = unicode string
price_table = { 'A': {'Price': 50, 'Offers': ['3A', 130]},
'B': {'Price': 30, 'Offers': ['2b', 45]},
'C': {'Price': 20, 'Offers': []},
'D': {'Price': 15, 'Offers': []}
}
def checkout(skus):
if ((... |
"""
Add `Django Filebrowser`_ to your project so you can use a centralized interface to manage the uploaded files to be used with other components (`cms`_, `zinnia`_, etc.).
The version used is a special version called *no grappelli* that can be used outside of the *django-grapelli* environment.
Filebrowser manage fi... |
def first_non_consecutive(arr: list) -> int:
''' This function returns the first element of an array that is not consecutive. '''
if len(arr) < 2:
return None
non_consecutive = []
for i in range(len(arr) - 1):
if arr[i+1] - arr[i] != 1:
non_consecutive.append(arr[i+1])
if... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Jared
"""
# LATTICE VARIATION
lattice_mul = 20 #how many lattice variations to perform
lattice_variation_percent = 10
keep_aspect = False
# COMPOSITION VARIATION
# upper limit to sim num
lattice_comp_num = 500 #how many crystals to generate (random mixing)
l... |
try:
print('enter try statement')
raise Exception()
print('exit try statement')
except Exception as inst:
print(inst.__class__.__name__)
|
def solution(M, A):
# write your code in Python 3.6
seen = [0] * (M + 1)
count = 0
i,j = 0,0
while(i < len(A) and j < len(A)):
if seen[A[j]]:
seen[A[i]] = 0
i += 1
else:
seen[A[j]] = 1
count += j - i + 1
j += 1
if co... |
# Time: O(n)
# Space: O(1)
# 978
# A subarray A[i], A[i+1], ..., A[j] of A is said to be turbulent if and only if:
# - For i <= k < j, A[k] > A[k+1] when k is odd, and A[k] < A[k+1] when k is even;
# - OR, for i <= k < j, A[k] > A[k+1] when k is even, and A[k] < A[k+1] when k is odd.
# That is, the subarray is turbu... |
# 类装饰器,使用类装饰已有函数
class MyDecorator(object):
def __init__(self, func):
self.__func = func
# 实现__call__方法,让实例对象变为像函数一样的可调用对象
def __call__(self, *args, **kwds):
# 对已有函数进行封装
print("课已经讲完了")
self.__func()
@MyDecorator # MyDecorator => show = MyDecorator(show)
def show():
pri... |
sql_1 = """INSERT INTO `pt_exam`.`user_order` (`id`, `exam_id`, `user_id`, `order_number`, `pre_pay_number`, `entry_fee`, `actual_pay_fee`, `status`, `pay_url`, `pay_time`, `create_time`) VALUES (NULL, {exam_id}, {user_id}, 'zsyl20210811103413909170a3{user_id}{exam_id}', NULL, 1, 1, 1, 'weixin://wxpay/bizpayurl?pr=hDqk... |
class TitleItem:
def __init__(self, title='', title_type='', genre='', directors='', actors='', run_time='', release_date='',
cover_url=''):
"""
:param title: String. The title of the movie/tv show.
:param title_type: String. Options: feature or tv_series.
:param ge... |
class Earth:
"""
Class used to represent Earth. Values are defined using EGM96 geopotential
model. Constant naming convention is intentionally not used since the
values defined here may be updated in the future by introducing other
geopotential models
"""
mu = 3.986004415e5 #km^3/s^2
... |
#
# PySNMP MIB module Wellfleet-DS1-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Wellfleet-DS1-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:39:54 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Ma... |
#import numpy as np
"""
#moving avg
#Parameters
array of ts value
#Returns moving avg
"""
#def moving_average(series, n):
# return np.average(series[-n:])
|
# *args - arguments - it returns tuple
# **kwargs - keyword arguments - it returns dictionary
def myfunc(*args):
print(args)
myfunc(1,2,3,4,5,6,7,8,9,0)
def myfunc1(**kwargs):
print(kwargs)
if 'fruit' in kwargs:
print('my fruit of choice is {}'.format(kwargs['fruit']))
else:
print('... |
"""
Write a program that reads a value in meters and displays it converted to centimeters and millimeters
"""
m = float(input('Uma distância em metros: '))
"""Kilometre --> Divide the length value by 1000"""
km = m / 1000
"""Hectometre --> Divide the length value by 100"""
hm = m / 100
"""Decametre --> Divide the leng... |
class AppConstants:
ADDRESS = {
"서울": [
"강남구",
"강동구",
"강북구",
"강서구",
"관악구",
"광진구",
"구로구",
"금천구",
"노원구",
"도봉구",
"동대문구",
"동작구",
"마포구",
"서대문구",
... |
def test_get_topics(client):
response = client.get("/topics/")
contents = response.get_json()
assert contents["status"] == "OK"
assert type(contents["payload"]) is dict
assert type(contents["payload"]["topics"]) is list
assert type(contents["payload"]["subtopics"]) is dict
assert response.s... |
"""
Find an efficient algorithm to find the smallest distance
(measured in number of words) between any two given words in a string.
For example, given words "hello", and "world" and a text content of
"dog cat hello cat dog dog hello cat world", return 1 because there's only one word "cat" in between the two words.
""... |
# https://practice.geeksforgeeks.org/problems/number-of-palindromic-paths-in-a-matrix0819/1#
# at each node recursively call itself and at bottom,left cornet determine it its a palindrome
class Solution:
def rec(self, matrix, it, jt, ib, jb, cache):
if it > ib or jt > jb:
cache[(it, jt, ib, j... |
# Numbers 0 to 10
print(list(range(0,11)))
print()
# Even numbers 0 to 10
print(list(range(0,11,2)))
print()
# Odd numbers 0 to 10
print(list(range(1,11,2)))
print()
# Numbers 20 to 10
print(list(range(20,9,-1)))
print()
# Numbers 45 to 75 divisable by 5
print(list(range(45, 76, 5)))
|
# https://leetcode.com/problems/monotonic-array/description/
#
# algorithms
# Medium (42.6%)
# Total Accepted: 4.8k
# Total Submissions: 11.2k
# beats 77.52% of python submissions
class Solution(object):
def largestOverlap(self, A, B):
"""
:type A: List[List[int]]
:type B: List[List[int... |
term_mappings = {
'Cell': 'csvw:Cell',
'Column': 'csvw:Column',
'Datatype': 'csvw:Datatype',
'Dialect': 'csvw:Dialect',
'Direction': 'csvw:Direction',
'ForeignKey': 'csvw:ForeignKey',
'JSON': 'csvw:JSON',
'NCName': 'xsd:NCName',
'NMTOKEN': 'xsd:NMTOKEN',
'Name': 'xsd:Name',
'... |
#! /usr/bin/env python3
# -*- coding: utf-8 -*-
# vim:fenc=utf-8
#
# Copyright © 2021 Oleksandr Moskalenko <om@rc.ufl.edu>
#
# Distributed under terms of the MIT license.
"""
Visualize fragments and events in a terminal
"""
def print_region(data):
"""
Print a scaled region to screen with labels and dashes for... |
expected_number_of_transactions = [
2650, 2543, 1395, 2751, 2398, 2827, 2737, 3084, 1998, 2997, 976,
1929, 3268, 1904, 1772, 776, 2553, 2547, 2581, 2226, 2307, 2812,
2618, 177, 1538, 1990, 2323, 2613, 2503, 2140, 2542, 2291, 2782,
1994, 2513, 2773, 1359, 1744, 868, 896, 2228, 2300, 2349, 2440,
2562, 2123,... |
files_c=[
'C/Threads.c',
]
files_cpp=[
'CPP/7zip/UI/P7ZIP/wxP7ZIP.cpp',
'CPP/Common/IntToString.cpp',
'CPP/Common/MyString.cpp',
'CPP/Common/MyVector.cpp',
'CPP/Common/StringConvert.cpp',
'CPP/Windows/FileDir.cpp',
'CPP/Windows/FileFind.cpp',
'CPP/Windows/FileIO.cpp',
'CPP/Windows/FileName.cpp',
'CPP/Commo... |
# Medium
# https://leetcode.com/problems/spiral-matrix/
# Time Complexity: O(N)
# Space Complexity: 0(1)
class Solution:
def spiralOrder(self, matrix: List[List[int]]) -> List[int]:
return Solution.spiralsol(matrix, [])
@staticmethod
def spiralsol(matrix, res):
m = len(matrix)
i... |
a = 5
b = 10
my_variable = 56
any_variable_name = 100
string_variable = "hello"
single_quotes = 'strings can have single quotes'
print(string_variable)
print(my_variable)
# print is a method with one parameter—what we want to print
def my_print_method(my_parameter):
print(my_parameter)
my_print_method(string_v... |
# https://www.reddit.com/wiki/bottiquette omit /r/suicidewatch and /r/depression
# note: lowercase for case insensitive match
blacklist = [
# https://www.reddit.com/r/Bottiquette/wiki/robots_txt_json
"anime",
"asianamerican",
"askhistorians",
"askscience",
"askreddit",
"aww",
"chicagosu... |
# The major optimization is to do arithmetic in base 10 in the main loop, avoiding division and modulo
def problem206():
"""
Find the unique positive integer whose square has the form
1_2_3_4_5_6_7_8_9_0,
where each “_” is a single digit.
"""
# Initialize
n = 1000000000 # The pattern ... |
load("//bazel/rules/cpp:object.bzl", "cpp_object")
load("//bazel/rules/hcp:hcp.bzl", "hcp")
load("//bazel/rules/hcp:hcp_hdrs_derive.bzl", "hcp_hdrs_derive")
def string_tree_to_static_tree_parser(name):
#the file names to use
target_name = name + "_string_tree_parser_dat"
in_file = name + ".dat"
outfile... |
class BaseServerException(Exception):
def __init__(self, detail, status_code, message):
super().__init__(message)
self.detail = detail
self.status_code = status_code
class SearchFieldRequiered(BaseServerException):
def __init__(self):
super().__init__(detail='entity', status_co... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.