content stringlengths 7 1.05M |
|---|
# -*- coding: utf-8 -*-
# Gruid Translator by Bruno Benkel
# To the extent possible under law, the person who associated CC0 with Gruid Translator has waived
# all copyright and related or neighboring rights to Gruid Translator.
"""
A list of constants used by the entire program. Mainly contains strings hardcoded as a... |
#!/usr/bin/env python3
# simplified and faster method to calculate the Fibonacci dequence
a = 0
b = 1
count = 0
max_count = 10
while count < max_count:
count = count + 1
print(a, b, end=' ') # Notice the magic end=' '
a = a + b
b = a + b
print() # gets a new (empty) line
|
# 1. Invert Values
# Write a program that receives a single string containing numbers separated by a single space.
# Print a list containing the opposite of each number.
string = input()
list = string.split(" ")
list_numbers = numbers = [int(x) for x in list]
myneglist = [-x for x in list_numbers]
print(myneglist) |
# !/usr/bin/python3
# -*- coding: utf-8 -*-
# @Author:梨花菜
# @File: relation.py
# @Time : 2019/5/27 10:16
# @Email: lihuacai168@gmail.com
# @Software: PyCharm
# api模块和数据库api表relation对应关系
API_RELATION = {"default": 66,
"energy.ball": 67,
"manage": 68,
"app_manage": 68,
... |
"""
Config variables using in auth package
"""
LOGIN_METHODS = [
'email_login',
'guest_login',
'facebook_login',
'google_login',
'naver_login',
'kakao_login',
]
|
email_template = \
'''
Dear {salutation} {name},
Thank you for your letter. We are sorry that our {product} {verbed} in your
{room}. Please note that it should never be used in a {room}, especially
near any {animals}.
Send us your receipt and {amount} for shipping and handling. We will send
you another {product} tha... |
a=["taiga","ryuji","minori","ami"]
for c in range(0,4):
print(a[c])
print(a[1:])
print(a[0:2])
print(len(a))
#Não pode mudar uma tupla |
"""
Number Crunching
=============================================================================
Basic operations with numbers.
Example Run
-----------------------------------------------------------------------------
$ python3 numbers.py
2
1
9
...
References
-------------------------------------------------------... |
class Solution:
def minMeetingRooms(self, intervals: List[List[int]]) -> int:
if not intervals:
return 0
intervals.sort(key = lambda x : x[0])
occupiedRooms = []
heappush(occupiedRooms, intervals[0][1])
for interval in intervals[1:]:
if occupiedRooms[0... |
EVAN = 'Evan'
CHALIE = 'Chalie'
JOHN = 'John'
BARRY = 'Barry'
SERVICE = 'Service'
JAKE = 'Jake'
COREY = 'Corey'
CHRIS = 'Chris'
SUB = 'Sub'
NOTAPP = 'NA'
ANGIESLIST = 'AL'
CONTRACTOR = 'CO'
GOOGLE = 'GO'
OLDCUST = 'OC'
OTHER = 'OT'
RECCO = 'RC'
REALTOR = 'RE'
WEBSITE = 'WS'
YELP = 'YL'
SOURCE_CHOICES = (
(NOTAPP,... |
def fancy_divider(divider_length):
divider = ''
for i in range(divider_length):
if i % 2 == 0:
divider += '='
else:
divider += '-'
print(divider)
|
#
# PyUSB definitions
#
# Copyright (C) 2007 Pablo Bleyer Kocik
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any la... |
load("@rules_maven_third_party//:import_external.bzl", import_external = "import_external")
def dependencies():
import_external(
name = "org_scala_lang_scala_compiler",
artifact = "org.scala-lang:scala-compiler:2.12.13",
artifact_sha256 = "ea971e004e2f15d3b7569eee8b559f220e23b9993e688bbe986... |
PLUGIN_METADATA = {
'id': 'dimteleport',
'version': '1.0.0',
'name': 'dimTeleport',
'description': 'A plugin to teleport cross dimension easily',
'author': 'BlissfulAlloy79',
'dependencies': {
'mcdreforged': '>=1.0.0',
}
}
CMDS = [
'overworld',
'nether',
'end',
'ow',... |
# Eyetracker type
# EYETRACKER_TYPE = "IS4_Large_Peripheral" # 4C eyetracker
#EYETRACKER_TYPE = "Tobii T120" # Old eyetracker
EYETRACKER_TYPE = "simulation" # test
# EYETRACKER_TYPE = "Tobii Pro X3-120 EPU" # Tobii X3
SCREEN_SIZE_X = 1920
SCREEN_SIZE_Y = 1080
#Pilot condition
PILOT_CONDITION_TEXT_INTERVENTION = True... |
# -*- coding:utf-8 -*-
# Copyright 2015 NEC Corporation. #
# #
# Licensed under the Apache License, Version 2.0 (the "License"); #
# you may not use this file except in compliance with the License... |
s = 0
for c in range (1, 7):
n = int(input('me diga um numero: '))
if n%2 == 0:
s += n
print('a soma de todos os numeros pares é {}'.format(s)) |
def handler(event, context):
return {
"statusCode": 200,
"headers": {
"Refresh": "0; url=mailto:hello@marvinengelmann.email",
}
} |
class BaseModel:
def __init__(self, config):
self.config = config
self.model = None
def save(self, checkpoint_path):
if self.model is None:
raise Exception("You have to build the model first.")
print("Saving model...")
self.model.save_weights(checkpoint_path... |
command = input().split("#")
water = int(input())
command = ", ".join(command)
fire = command.split(" = ")
fire = ", ".join(fire)
fire_list = fire.split(", ")
cells = []
effort = 0
total_fire = 0
for index, item in enumerate(fire_list):
if item == "High":
fire = int(fire_list[index + 1])
if 81 <=... |
"""
Урок 23. Состояние
Смена режимов обработки команд
Цель:
Применить паттерн Состояние для изменения поведения обработчиков Команд.
В домашнем задании №2 была реализована многопоточная обработка очереди команд.
Предлагалось два режима остановки этой очереди - hard и soft.
Однако вариантов завершения и режимов обраб... |
# Copyright (C) 2019 DLR
#
# All rights reserved. This program and the accompanying materials are made
# available under the terms of the 3-Clause BSD License which accompanies this
# distribution, and is available at
# https://opensource.org/licenses/BSD-3-Clause
#
# Contributors:
# Christoph Suerig <christoph.suerig@... |
# Range Sum of BST
'''
Given the root node of a binary search tree, return the sum of values of all nodes with a value in the range [low, high].
Example 1:
Input: root = [10,5,15,3,7,null,18], low = 7, high = 15
Output: 32
Example 2:
Input: root = [10,5,15,3,7,13,18,1,null,6], low = 6, high = 10
Output: 23
... |
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
def __str__(self):
if not self.next:
return str(self.val)
return f'{self.val}->{self.next}'
# TODO: This one took a while... come back and take another look
cl... |
# 素数のリストを得る
def primes(num):
is_prime_list = [True] * (num + 1)
is_prime_list[0] = False
is_prime_list[1] = False
for i in range(2, int(num**0.5) + 1):
if not is_prime_list[i]:
continue
for j in range(i * 2, num + 1, i):
is_prime_list[j] = False
return [i for ... |
def func(self):
self.info(self.rid, "get store")
users = []
for row in self.datastore.all():
email = row.data.get('email', None)
if not email:
continue
if not row.data['email'] in users:
users.append(email)
return users |
#!/usr/bin/env python
# encoding: utf-8
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
r = 0
hd... |
def main() -> None:
s = input()
print("0" + s[:3])
if __name__ == "__main__":
main()
|
# -*- encoding: utf-8 -*-
"""
@File : database.py
@Time : 2020/4/4 15:26
@Author : chise
@Email : chise123@live.com
@Software: PyCharm
@info :数据库管理
"""
|
# Faça um programa que mostre os n termos da Série a seguir:
# S = 1/1 + 2/3 + 3/5 + 4/7 + 5/9 + ... + n/m.
final = int(input('Informe o numero de repetições: '))
valor = 0
inicioS = 1
finalS =1
sequencia = []
sequencia_imprimir = []
for i in range(1, final):
valor = inicioS / finalS
inicioS += 1
finalS ... |
#Author:
#Dilpreet Singh Chawla
#Indian Institute of Information Technology Kalyani.
#Newton's Method to find square root of a positive number
def square_root(n):
if n<0:
raise RuntimeError("Please enter a positive number!")
else:
root=n/2 #initial_guess
for k in range(20):
... |
class Solution:
def largestSumAfterKNegations(self, A: List[int], K: int) -> int:
A, ncnt = sorted(A), sum([1 for a in A if a < 0])
cnt1, cnt2 = min(K, ncnt), K - ncnt if K > ncnt else 0
for i in range(cnt1): A[i] = -A[i]
return sum(A) - min(A) * 2 * (cnt2 % 2) if cnt2 else sum(A)
|
'''
Stuff for the lambda role
'''
role_parameter_section = """ role:
Description: name of the role
Type: String"""
parameter_role_spec = 'Ref: role'
imported_role_spec = 'Fn::ImportValue: {}'
'''
Stuff for the subnet(s)
'''
subnets_parameter_section = """ subnetIds:
Description: list of subnets
Type:... |
BLOCK_REGISTRY = {}
NO_BLOCK_ERR = 'Block {} not in BLOCK_REGISTRY! Available blocks are {}'
def RegisterBlock(block_name):
"""Registers a block."""
def decorator(f):
BLOCK_REGISTRY[block_name] = f
return f
return decorator
def get_block(block_name):
"""Get block from BLOCK_REGISTRY... |
#unexpected results, can use try statement to make trial statement
try:
print(a) #have not defined a, will return exception
except:
print("a is not defined!")
#these are specific errors
try:
print(a) # a still not defined
except NameError:
print("a is still not defined")
except:
print("something else went wrong... |
MHP = open('numeros.txt','w')
for linha in range(1,101):
arquivo.write('%d\n'%linha)
arquivo.close()
|
class Solution:
def minRemoveToMakeValid(self, s: str) -> str:
invalid_open = []
invalid_close = []
for i,char in enumerate(s):
if char == '(':
invalid_open.append(i)
elif char == ')':
if not invalid_open:
... |
class BBAWriter:
def __init__(self, f):
self.f = f
def pre(self, s):
print("pre {}".format(s), file=self.f)
def post(self, s):
print("post {}".format(s), file=self.f)
def push(self, s):
print("push {}".format(s), file=self.f)
def offset32(self):
print("offset32", file=self.f)
def ref(self, r, comment=""... |
del_items(0x80079E14)
SetType(0x80079E14, "int GetTpY__FUs(unsigned short tpage)")
del_items(0x80079E30)
SetType(0x80079E30, "int GetTpX__FUs(unsigned short tpage)")
del_items(0x80079E3C)
SetType(0x80079E3C, "void Remove96__Fv()")
del_items(0x80079E74)
SetType(0x80079E74, "void AppMain()")
del_items(0x80079F14)
SetType... |
x = 10
y = 'Hi'
z = 'Hello'
print(y)
# breakpoint() is introduced in Python 3.7
breakpoint()
print(z)
# Execution Steps
# Default:
# $python3.7 python_breakpoint_examples.py
# Disable Breakpoint:
# $PYTHONBREAKPOINT=0 python3.7 python_breakpoint_examples.py
# Using Other Debugger (for example web-pdb):
# $PYTHONB... |
n = int(input('Digite um número para ver sua tabuada: '))
#print('===================')
#print('{} x 1 = {}'.format(n, n*1))
#print('{} x 2 = {}'.format(n, n*2))
#print('{} x 3 = {}'.format(n, n*3))
#print('{} x 4 = {}'.format(n, n*4))
#print('{} x 5 = {}'.format(n, n*5))
#print('{} x 6 = {}'.format(n, n*6))
#pri... |
# Test if list is Palindrome
# Using list slicing
# initializing list
test_list = [1, 4, 5, 4, 1]
# printing original list
print("The original list is : " + str(test_list))
# Reversing the list
reverse = test_list[::-1]
# checking if palindrome
res = test_list == reverse
# printing result
print("Is list Palindrome... |
def get_tipo_dia(dia):
dias = {
1: 'Fim de semana',
2: 'Dia de semana',
3: 'Dia de semana',
4: 'Dia de semana',
5: 'Dia de semana',
6: 'Dia de semana',
7: 'Fim de semana',
}
return dias.get(dia, '** inválido **')
if __name__ == '__main__... |
def _file_name(filePathName):
if "/" in filePathName:
return filePathName.rsplit("/", -1)[1]
else:
return filePathName
def _base_name(fileName):
return fileName.split(".")[0]
def qt_cc_library(name, src, hdr, uis = [], res = [], normal_hdrs = [], deps = None, **kwargs):
srcs = src
... |
'''Faça um programa para calcular e exibir a valor do imposto de ICMS de um produto, conforme a classificação do tipo de produto e do valor de custo do mesmo digitado pelo usuário (incluindo centavos – cuidado com o uso do tipo de dados correto).¶
Classificação do Produto Porcentagem de ICMS
Cesta básica isento
Eletrôn... |
#Faça um programa que leia três números e mostre qual é o maior e qual é o menor.
a = int(input('Digite o primeiro valor: '))
b = int(input('Digite o segundo valor: '))
c = int(input('Digite o terceiro valor: '))
if a<b and a<c:
menor = a
if b<c and b<a:
menor = b
if c<a and c<b:
menor = c
maior = a
if b>c... |
seg1 = float(input('Primeiro segmento:'))
seg2 = float(input('Segundo segmento:'))
seg3 = float(input('Terceiro Segmento:'))
if seg1 < seg2 + seg3 and seg2 < seg1 + seg3 and seg3 < seg1 +seg2:
print('\033[1;30;45mOs segmentos acima PODEM FORMAR Triângulo\033[m')
else:
print('\033[1;36;40mNão podem formar triâng... |
def winning_move(board, piece):
# Check horizontal locations for win
# every possibility horizontal 4 in the board
for c in range(COLUMN_COUNT-3):
for r in range(ROW_COUNT):
if board[r][c] == piece and board[r][c+1] == piece\
and board[r][c+2] == piece and b... |
#!/usr/bin/env python
"""
Project: CLIPRT - Client Information Parsing and Reporting Tool.
@author: mhodges
Copyright 2020 Michael Hodges
"""
class MessageRegistry:
"""
The message registry contains all of the message content needed for
error handling throughout the project.
"""
def __init_... |
count = 0
while count < 5:
print(count)
count += 1
else:
print(count)
count = 0
while count < 5:
print(count)
count += 1
if count == 3:
break
count = 0
while count < 5:
if count == 3:
count += 1
continue
print(count)
count += 1
|
class WrapperException(BaseException):
def __init__(self, original_e, subcode=None):
super().__init__()
self.original_exception = original_e
self.subcode = subcode
def __str__(self) -> str:
return self.original_exception.__str__()
class ClientErrorException(WrapperException):
... |
#
# Virtual Block Device (VBD) Xen API Configuration
#
# Note: There is a non-API field here called "image" which is a backwards
# compat addition so you can mount to old images.
#
VDI = ''
device = 'sda1'
mode = 'RW'
driver = 'paravirtualised'
image = 'file:/root/gentoo.amd64.img'
|
# Use this playground to experiment with list methods, using Test Run
list_method = [1, 2, 2, 3, 3, 3, 4, 4, 4, 4]
list_method.append(5, )
print(list_method)
list_method.extend([5, 5, 5, 5])
print(list_method)
list_method.insert(3, 2)
print(list_method)
list_method.remove(2)
print(list_method)
print(list_method.count... |
min3 = 100
max3 = 999
mul = 0
mx = 0 # max palindrome
for i in range(max3, min3-1, -1):
for j in range(i, min3-1, -1):
mul = i*j
rev = int(str(mul)[::-1]) # reversed
if (mul <= mx):
break
if (mul == rev):
mx = mul
print(mx)
|
class VerticeInvalidoException(Exception):
pass
class ArestaInvalidaException(Exception):
pass
class MatrizInvalidaException(Exception):
pass
class Grafo:
QTDE_MAX_SEPARADOR = 1
SEPARADOR_ARESTA = '-'
__maior_vertice = 0
def __init__(self, V=None, M=None):
'''
Constrói u... |
# Slide link: https://kathrinschuler.github.io/slide-python-intro/#/11/4
# Current repl: https://repl.it/@kathrinschuler/Lesson1ExBooleanOperators - question text varies a little
# TASKS is a list of lists. Each sublist follows this structure:
# [
# <string of background information to print>,
# <string of questio... |
###
# Created on Apr 13,2020
# @author: Jordon Malcolm
# jordonm1@umbc.edu
###
class Events:
def __init__(self, arg1=" ", arg2=" ", arg3=" ", arg4=" ", arg5=" ", arg6=" ", arg7=0):
self.subject = arg1
self.courseNum = arg2
self.version = arg3
self.section = arg4
self.instruct... |
# @Time : 2019/4/22 23:31
# @Author : shakespere
# @FileName: Palindromic Substrings.py
'''
647. Palindromic Substrings
Medium
Given a string, your task is to count how many palindromic substrings in this string.
The substrings with different start indexes or end indexes are counted as different substrings... |
countries = input().split(", ")
capitals = input().split(", ")
my_dict = {country: capital for country, capital in tuple(zip(countries, capitals))}
[print (f"{country} -> {capital}") for country, capital in my_dict.items()] |
class Solution(object):
def addBinary(self, a, b):
"""
:type a: str
:type b: str
:rtype: str
"""
i, j = len(a) - 1, len(b) - 1
ret = ""
plus = 0
while True:
ta, tb = 0, 0
if i >= 0:
ta = int(a[i])
... |
class Interface:
QUERY_SCHEDULE = "0"
QUERY_TEAM_STATS = "1"
# add new query type above this line
RESP_SCHEDULE = "0"
RESP_TEAM_STATS = "1"
# add new response type above this line
|
class Solution:
def numWaterBottles(self, numBottles: int, numExchange: int) -> int:
ans = numBottles
while numBottles >= numExchange:
remaining = numBottles%numExchange
numBottles = numBottles // numExchange
ans += numBottles
numBottles += remaining
... |
def get_matrix():
return [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
|
"""
Faça uma função chamada 'comamatriz()' que recebe, por parãmetro, uma matriz A[4][4] e retorna a soma dos seus elementos.
"""
def somamatriz(linha0: list, linha1: list, linha2: list, linha3: list):
"""
:param linha0: Primeira linha da matriz 4x4. Revebe 4 números inteiros.
:param linha1: Segunda linh... |
'''
This is Day 2 of 100 Days of Python
Today, we are going to build a tip calculator
The knowledge that we need are basic school mathematics and the usage of the different operators in Python
In python the different operators used are +, - , *, /, // , **, and the % operators.
Each has its own function, which we shal... |
GENERAL_EXCEPTION = "internal_server_error"
LOGIN_EXCEPTION = "login_error"
REGISTER_EXCEPTION = "register_error"
NOT_AUTHORIZED = "not_authorized"
QUERY_PARAM_EXCEPTION = "query_param_error"
NOT_FOUND = "resource_not_found"
BAD_REQUEST_EXCEPTION = "bad_request_error"
|
# ██╗░░░░░██╗███╗░░██╗░██████╗░░░░██████╗░██╗░░░░░░█████╗░░█████╗░██╗░░██╗
# ██║░░░░░██║████╗░██║██╔════╝░░░░██╔══██╗██║░░░░░██╔══██╗██╔══██╗██║░██╔╝
# ██║░░░░░██║██╔██╗██║██║░░██╗░░░░██████╦╝██║░░░░░███████║██║░░╚═╝█████═╝░
# ██║░░░░░██║██║╚████║██║░░╚██╗░░░██╔══██╗██║░░░░░██╔══██║██║░░██╗██╔═██╗░
# ███████╗██║██... |
#クラス変数、インスタンス変数
class Hoge:
# クラス変数
cls_val = 123456
cls_str = 'class member'
# selfはインスタンスハンドラー
def __init__(self, val, str):
# インスタンス変数
self.inst_val = val
self.inst_str = str
if __name__ == "__main__":
hoge = Hoge(100, 'instance')
# クラスオブジェクトからクラス変数にアクセス
pr... |
# coding: utf-8
class BaseAPI(object):
"""
Base class for API related classes
Provides basic skeleton for API related classes
"""
def __init__(self, client, context=None):
self.client = client
self.context = context or {}
def list(self, *args, **kwargs):
raise NotImplem... |
lista = [2, 4, 2, 2, 3, 3, 1]
def soma_elementos(lista):
soma = 0
for element in lista:
soma += element
return soma
print(soma_elementos(lista)) |
def get_strob_numbers(num_digits):
if not num_digits:
return [""]
elif num_digits == 1:
return ["0", "1", "8"]
smaller_strob_numbers = get_strob_numbers(num_digits - 2)
strob_numbers = list()
for x in smaller_strob_numbers:
strob_numbers.extend([
"1" + x + "1",
... |
PAIRSAM_FORMAT_VERSION = '1.0.0'
PAIRSAM_SEP = '\t'
PAIRSAM_SEP_ESCAPE = r'\t'
SAM_SEP = '\031'
SAM_SEP_ESCAPE = r'\031'
INTER_SAM_SEP = '\031NEXT_SAM\031'
COL_READID = 0
COL_C1 = 1
COL_P1 = 2
COL_C2 = 3
COL_P2 = 4
COL_S1 = 5
COL_S2 = 6
COL_PTYPE = 7
COL_SAM1 = 8
COL_SAM2 = 9
COLUMNS = ['readID', 'chrom1', 'pos1', '... |
def sum(number_one, number_two):
number_one_int = convert_integer(number_one)
number_two_int = convert_integer(number_two)
result = number_one_int + number_two_int
return result
def convert_integer(number_string):
convert_integer = int(number_string)
return convert_integer
answer = sum("1... |
def Bin(L,start,end,x,k):
if end > start:
mid = (start+end)//2
if (x==L[mid]):
j = mid
i = mid
while(i>-1 and L[i]==x):
i-=1
while(j<k and L[j]==x):
j+=1
return(i,j)
elif x<L[mid]:
... |
class Solution:
def findShortestSubArray(self, nums: List[int]) -> int:
if not nums:
return 0
degree = 0
freqs = {}
for num in nums:
if num not in freqs:
freqs[num] = 0
freqs[num] += 1
for key, value in freqs.items():
... |
"""
Created on Nov 12 11:21 2019
@author: nishit
"""
# import pandas as pd
class TimeSeries:
@staticmethod
def expand_and_resample(raw_data, dT, append_next_dT=False):
if TimeSeries.valid_time_series(raw_data):
if append_next_dT:
raw_data = TimeSeries.append_next_dT_value(... |
'''Utilities for generating graphs
This provides a set of utilities that will allow us to geenrate a
girected graph. This assumes that configuration files for all the
modules are present in the ``config/modules/`` folder. The files
should be JSON files with the folliwing specifications:
.. code-block:: JSON
{
... |
expected_regimen_to_treatment = [
{
"id": "1",
"regimen_ontology_term_id": "1",
"treatment_ontology_term_id": "1"
},
{
"id": "2",
"regimen_ontology_term_id": "1",
"treatment_ontology_term_id": "2"
},
{
"id": "3",
"regimen_ontology_term_... |
def test_java_version(host):
ansible_vars = host.ansible.get_variables()
java_version = ansible_vars.get('java__version')
java_output = host.run('java -version')
assert str(java_version) + '.' in java_output.stderr
|
def get_php_handle__sql_command(connect_type):
if (connect_type == "pdo"):
return """try{%s
$r=$con->query(base64_decode('%s'));
$rows=$r->fetchAll(PDO::FETCH_ASSOC);
foreach($rows[0] as $k=>$v){
echo "$k"."%s";
}
echo "%s";
foreach($rows as $array){foreach($array as $k=>$v){echo "$v"."%s";};echo "%s";... |
'''# frase = str(input('Digite alguma frase ou alguma palavra qualquer: ')).upper().strip()
palavra = frase.split()
junto = ''.join(palavra)
print(f'A frase ao contrário fica {frase[::-1]}.')
if junto == junto[::-1]:
print('E é um Palíndromo! ')
else:
print('E não é um Palíndromo! ') (Um dos modos de re... |
# Copyright 2018 Ocean Protocol Foundation
# SPDX-License-Identifier: Apache-2.0
class SecretStoreMock:
args = None
id_to_document = dict()
def __init__(self, secret_store_url, keeper_url, account):
self.args = (secret_store_url, keeper_url, account)
def set_secret_store_url(self, url):
... |
# Faça um programa que peça ao usuário que insira um número
# inteiro e calcule o seu fatorial. O fatorial é a multiplicação do
# número escolhido até 1.
# Exemplo:
# o fatorial de 5 é 120
# (5x4x3x2x1 = 120).
# Entrada de dados: 5
# Saída de dados: 120
num = int(input('Digite um Número ... |
m1 = 0; m2 = 0; n = int(input())
while n:
n -= 1
a, b = map(int, input().split())
m1 = max(m1, a*b)
m = int(input())
while m:
m -= 1
a, b = map(int, input().split())
m2 = max(m2, a*b)
if m1 == m2:
print("Tie")
elif m1 > m2:
print("Casper")
else:
print("Natalie") |
class ListNode:
def __init__(self, val, next = None):
self.val = val
self.next = next
class LinkedList:
def __init__(self):
self.head = None
def getIntersectionNode(self,headA, headB):
if headA is None or headB is None:
return None
pa = headA # 2 pointers
pb = headB
LinkedLi... |
"""
WAP to calculate the sum of following series where n is input by user. 1 + 1/2 + 1/3 + 1/4 + 1/5 + ... 1/n
"""
n = int(input())
result = 0
for i in range(1, n + 1):
result += 1 / i
print(result)
|
class Solution:
def countAndSay(self, n: int) -> str:
"""
The count-and-say sequence is the sequence of integers with the first five terms as
following:
1. 1
2. 11
3. 21
4. 1211
5. 111221
1 is read off as "one 1" or 11.
11 is rea... |
class Credential:
'''
class that generates new instance for credentials
'''
credential_list=[]
def __init__(self,account_name,password):
'''
__init__ method that helps us define properties for our objects.
Args:
account_name: New credential account name.
... |
# aula 23 - Classes (https://www.youtube.com/watch?v=AvS6MNwX3lU&list=PLx4x_zx8csUhuVgWfy7keQQAy7t1J35TR&index=23)
class carro:
velMax = 0
ligado = False
cor = ''
c1 = carro()
c2 = carro()
c3 = carro()
c1.velMax = 200
c1.cor = 'preto'
c1.ligado = False
print(f'velocidade Máxima: {c1.velMax}')
print(f... |
#Задача 1. Вариант 24
#Напишите программу, которая будет сообщать род деятельности и псевдоним под которым скрывается Джон Гриффит Лондон. После вывода информации программа должна дожидаться пока пользователь нажмет Enter для выхода.
#Semyenov A.N.
#09.02.2016
print("Джон Гриффит Лондон более известена, как американск... |
times = input("How many times do I have to tell you? ")
times = int(times)
for time in range(times):
print("CLEAN UP YOUR ROOM")
|
class MultiReferenceAnnotationOptions(object, IDisposable):
"""
Options which control the creation of MultiReferenceAnnotations.
MultiReferenceAnnotationOptions(multiReferenceAnnotationType: MultiReferenceAnnotationType)
"""
def Dispose(self):
""" Dispose(self: MultiReferenceAnnotation... |
touched_files = danger.git.modified_files + danger.git.created_files
has_source_changes = any(map(lambda f: f.startswith("danger_python"), touched_files))
has_changelog_entry = "CHANGELOG.md" in touched_files
is_trivial = "#trivial" in danger.github.pr.title
if has_source_changes and not has_changelog_entry and not is... |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# В списке, состоящем из вещественных элементов, вычислить:
# 1) количество элементов списка, равных 0;
# 2) сумму элементов списка, расположенных после минимального элемента.
# Упорядочить элементы списка по возрастанию модулей элементов.
if __name__ == '__main_... |
"""
@author: acfromspace
"""
class Stack:
def __init__(self):
self.items = []
def is_empty(self):
return print("is_empty():", self.items == [])
def push(self, item):
print("push():", item)
self.items.append(item)
def pop(self):
return print("pop():", self.ite... |
def facerecognizer():
i01.opencv.capture()
i01.opencv.addFilter("PyramidDown")
i01.opencv.setDisplayFilter("FaceRecognizer")
fr=i01.opencv.addFilter("FaceRecognizer")
fr.train()# it takes some time to train and be able to recognize face
#if((lastName+"-inmoovWebKit" not in inmoovWebKit.getSessionNames())):
#... |
class Solution(object):
def myAtoi(self, str):
"""
:type str: str
:rtype: int
"""
if len(str) == 0 or str[0] not in list('+- 0123456789') or '+-' in str or '-+' in str:
return 0
sign = 1
answer = []
for i, s in enumerate(str):
... |
class ARGA ( object ) :
def __init__( self ) :
pass
def __len__( self ) :
return 0
def build_primitive_dispatch( self ) :
return ''
class ARG( ARGA ) :
def __init__( self, *pattern ) :
self.pattern = pattern
CORE.register_pattern( self )
def __repr__( self ) :
return 'ARG[ ' ... |
def setup ():
strokeWeight(140)
size (500, 500)
smooth ()
noLoop ()
noStroke()
def draw ():
background (50)
fill (94, 206, 40, 250)
ellipse (100, 100, 150, 150)
fill (94, 206, 40, 150)
ellipse (100, 200, 150, 150)
fill (94, 206, 40, 100)
ellipse (100, 300... |
{
'targets': [
{
'target_name': 'serialport',
'sources': [
'src/serialport.cpp',
'src/serialport_unix.cpp',
],
'conditions': [
['OS=="win"',
{
'sources': [
"src/serialport_win.cpp",
'src/win/disphelper.c',
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.