content stringlengths 7 1.05M |
|---|
#!/usr/bin/python3
# -*- coding: utf-8 -*-
# Author :AmosWu
# Date :2019/1/26
# Features :利用条件运算符的嵌套来完成此题:学习成绩>=90分的同学用A表示,60-89分之间的用B表示,60分以下的用C表示。
def main():
s = int(input('Enter a number:'))
if s >= 90:
grade = 'A'
elif s >= 60:
grade = 'B'
else:
grade = 'C'
pri... |
# Created by MechAviv
# Map ID :: 402000630
# Desert Cavern : Below the Sinkhole
# Update Quest Record EX | Quest ID: [34931] | Data: dir=1;exp=1
sm.curNodeEventEnd(True)
sm.setTemporarySkillSet(0)
sm.setInGameDirectionMode(True, False, False, False)
sm.setStandAloneMode(True)
sm.removeAdditionalEffect()
sm.zoomCamera... |
'''
StockSlayer is a multiplayer network game themed on the stock market.
This module creates all game companies and events.
Copyright (c) 2016 by Daniel Vedder and Niklas Götz.
Licensed under the terms of the MIT license.
'''
global companies
global events
companies, events = [], []
def new_company(name,... |
# "directions" are all the ways you can describe going some way;
# they are code-visible names for directions for adventure authors
direction_names = ["NORTH","SOUTH","EAST","WEST","UP","DOWN","RIGHT","LEFT",
"IN","OUT","FORWARD","BACK",
"NORTHWEST","NORTHEAST","SOUTHWEST","SOUTHE... |
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution(object):
def upsideDownBinaryTree(self, root):
"""
:type root: TreeNode
:rtype: TreeNode
... |
REQUIRED_SECTIONS = ['模块', '标题', '描述', '前提条件', '步骤', '期望结果', '优先级']
# project: 1, module: 2, plan: 3, case: 4
NUMBER_TYPE = {"1": "project", "2": "module", "3": "plan", "4": "case"}
CASE_COLOR_DIC = {"Pending": "black", "Pass": "green", "Fail": "red", "Block": "gray"}
MSG_USERNAME_OR_PASSWORD_WRONG = "用户名或密码错误"
STATUS_... |
"""Top-level package for clinepunk."""
__author__ = """Taylor Monacelli"""
__email__ = "taylormonacelli@gmail.com"
__version__ = "0.1.14"
|
# -*- coding:utf-8 -*-
__author__ = 'zhangzhibo'
__date__ = '202018/5/18 16:56'
|
#Clases del ciclo de lavado
class lavando:
#Etapa 1. Lavado
def lavado(self):
print("Lavando...")
class enjuagando:
#Etapa 2. Enjuagado
def enjuagado(self):
print("Enjuagando...")
class centrifugando:
#Etapa 3. Centrifugado
def centrifugado(self):
print("Centrifugando.... |
'''
Date: 01/08/2019
Problem description:
===================
This problem was asked by Google.
Given an array of integers where every integer occurs three times
except for one integer, which only occurs once, find and return the
non-duplicated integer.
For example, given [6, 1, 3, 3, 3, 6, 6], return 1.
Given [1... |
"""
Faça um programa que preencha um vetor com 10 números reais, calcule e mostre a quantidade de números negativos e a
soma dos números positivos desse vetor.
"""
lista = []
for x in range(10):
n1 = float(input('Digite: '))
lista.append(n1)
soma = 0
quan = 0
for x in lista:
if x >= 0:
soma += x
... |
# considerando o dollar 3.27$
carteira = float(input("quanto você tem na sua carteira: "))
dollar = float(3.27)
total = float(carteira / dollar)
print(f"Com total de R$ {carteira:.2f} você pode comprar US$ {total:.2f}") |
"""
Desafio 089
Problema: Crie um programa que leia nome e duas notas de vários alunos
e guarde tudo em uma lista composta. No final, mostre um
boletim contendo a média de cada um e permita que o usuário
possa mostrar as notas de cada aluno individualmente.
Resolução do problema:
"""
his... |
# -*- coding: utf-8 -*-
# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: http://doc.scrapy.org/en/latest/topics/item-pipeline.html
class FormatPipeline(object):
"""
All crawled items are passed through this pipeline
"""
def process_item(self... |
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def mergeKLists(self, lists):
"""
:type lists: List[ListNode]
:rtype: ListNode
"""
head = ListNode(0)
curr = ... |
# ---------------------------------------------------------------------------------------------------------------------
# # # PARTE 1 # # #
# ---------------------------------------------------------------------------------------------------------------------
class Persona(object):
def __init__(self, **args):
... |
"""
link: https://leetcode-cn.com/problems/reconstruct-itinerary
problem: 给有向图和起点,求字典序最小的欧拉通路,保证解存在
solution: Hierholzer 算法。从起点开始做dfs,搜索的同时删除每次跳转的边,搜完的节点入栈,搜索遍历顺序的逆序即为结果。
"""
class Solution:
def findItinerary(self, tickets: List[List[str]]) -> List[str]:
m = collections.defaultdict(list)
for x ... |
START_BRAKING = 17
END_BRAKING = 25
BRAKE_SPEED = 1
""" Straight, please """
def reward_function(params):
# No rewards shaping yet, just add a brake by track position
if params['closest_waypoints'][0] >= START_BRAKING and params['closest_waypoints'][0] >= END_BRAKING and params['speed'] == BRAKE_SPEED:
... |
#!/usr/bin/env python3
table = {i: chr(i + 0xFEE0) for i in range(33, 127)}
table[ord(' ')] = '\N{IDEOGRAPHIC SPACE}'
def ascii_to_fullwidth(text):
return text.translate(table)
def main():
assert ascii_to_fullwidth('h') == 'h'
if __name__ == '__main__':
main()
|
# See file COPYING distributed with xnatrest for copyright and license.
class XNATRESTError(Exception):
"""base class for xnatrest exceptions"""
class CircularReferenceError(XNATRESTError):
def __init__(self, url):
self.url = url
return
def __str__(self):
return 'circular refere... |
# Start and end date
gldas_start_date = '2010-01-01'
gldas_end_date = '2014-01-01'
# Location (Latitude and Longitude)
gldas_geo_point = AutoParam([(38, -117), (38, -118)])
# Create data fetcher
gldasdf = GLDASDF([gldas_geo_point],start_date=gldas_start_date,
end_date=gldas_end_date, resample=Fals... |
class IDGroup:
"""
The IDGroup Type
================
This type supports both iteration and the []
operator to get child ID properties.
You can also add new properties using the [] operator.
For example::
group['a float!'] = 0.0
group['an int!'] = 0
group['a string!'] = "hi!"
group['an array!'] = [0, ... |
"""
Let's call an array A a mountain if the following properties hold:
A.length >= 3
There exists some 0 < i < A.length - 1 such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] > ... > A[A.length - 1]
Given an array that is definitely a mountain, return any i such that A[0] < A[1] < ... A[i-1] < A[i] > A[i+1] >... |
c.NotebookApp.ip = '0.0.0.0'
c.NotebookApp.port = 80
c.NotebookApp.allow_root = True
c.NotebookApp.open_browser = False
c.NotebookApp.password = 'sha1:8e4f16cf0aa6:30644b99b9930e0179359266c359461493c2cec5' #填入刚刚复制的字符 |
def hola():
def bienvenido():
print("hola!")
return bienvenido
# hola()()
def mensaje():
return "Este es un mensaje"
def test(function):
print(mensaje())
test(mensaje)
|
def combination(a: int, b: int) -> int:
"""
Choose b from a. a >= b
"""
b = min(b, a - b)
numerator = 1
dominator = 1
for i in range(b):
numerator *= (a - i)
dominator *= (b - i)
return int(numerator / dominator)
if __name__ == '__main__':
t = int(input())
for... |
# Getting all PAL : Prime and pallindrome numbers between two given numbers
def pallindrome(n):
temp=n
rev=0
while(n>0):
dig = n % 10
rev=rev*10 +dig
n = n/10
if temp == rev:
return True
else:
return False
def isprime(n):
if n<=1:
return False
if n<=3:
return True
if n % 2 == 0 or n % 3 == ... |
async def iter_to_aiter(iter):
"""
:type iter: synchronous iterator
:param iter: a synchronous iterator
This converts a regular iterator to an async iterator.
"""
for _ in iter:
yield _
|
# buttons
PIN_BUTTON_PROG = 17
PIN_BUTTON_ERASE = 27
# LEDs
PIN_RED = 23
PIN_GREEN = 24
PIN_BLUE = 20
PIN_BLUE2 = 25
# Jumpers
PINS_PROFILES = [5, 6, 13, 19]
# MCU
PIN_RESET_ATMEGA = 16
PIN_MASTER_POWER = 12
PIN_ESP_RESET = 8
PIN_ESP_GPIO_0 = 4
# MISC
PIN_BUZZER = 26
# Interfaces
DEFAULT_SERIAL_SPEED = 9600
DEFAUL... |
# -*- coding: utf-8 -*-
smtpserver = "smtp.qq.com" # will be read by smtp fixture
def test_showhelo(smtp_connection):
assert 0, smtp_connection.helo() |
# -*- coding: utf-8 -*-
project = 'test'
master_doc = 'index'
|
s, n = map(int, input().split())
arr = [0] * n
for i in range(s):
p = int(input())
for j in range(0, len(arr), p):
arr[j] = 1
for i in arr:
print(i, end=" ")
print()
|
CHAMP_ID_TO_EMOJI = {'266': '<:champ_266:601909182748164097>', '103': '<:champ_103:601909185243774976>', '84': '<:champ_84:601909188612063233>', '12': '<:champ_12:601909190809878530>', '32': '<:champ_32:601909193456222221>', '34': '<:champ_34:601909195968610356>', '1': '<:champ_1:601909198799896690>', '22': '<:champ_22... |
"""Module that defines constants shared between agents."""
# pattoo-snmp constants
PATTOO_AGENT_SNMPD = 'pattoo_agent_snmpd'
PATTOO_AGENT_SNMP_IFMIBD = 'pattoo_agent_snmp_ifmibd'
|
class Preciousstone:
def __init__(self):
self.preciousStone = []
def storePreciousStone(self,name):
self.preciousStone.append(name)
if( len(self.preciousStone) > 5):
del(self.preciousStone[0])
def displayPreciousStone(self):
if(... |
class BufferList:
def __init__(self, maxlen):
self.data = []
self.maxlen = maxlen
def append(self, el):
if len(self.data) == self.maxlen:
popped = self.data.pop(0)
else:
popped = None
self.data.append(el)
return popped
de... |
actor_name = input("Enter the actor's name: ")
initial_points = int(input("Enter the points form academy: "))
judges_count = int(input("Enter the number of jury: "))
points_needed = 1250.5
for jury in range(judges_count):
judges_name = input("Enter the name of jury: ")
points_from_judge = float(input("Enter t... |
print("hello world")
a = 3
b = 4
c = a * b
print(c)
|
#################################################
### THIS FILE WAS AUTOGENERATED! DO NOT EDIT! ###
#################################################
def get_resize_target(img_sz, crop_target, do_crop=False):
if crop_target is None: return None
ch,r,c = img_sz
target_r,target_c = c... |
# -*- coding: utf-8 -*-
"""
Created on August 26 20:16:44 2018
@author: ahmad
"""
"""
a program to encrypt and decrypt data in 8-bit XOR encryption using all
built-in functions. No libraries used. This program is for learning puposes
"""
def xor(x,y): #function to cypher text
g = []
for i in range(len(x)):
if ... |
def func3(a):
a/0;
def func2(a, b):
func3(a);
def func1(a, b, c):
func2(a, b);
if __name__ == "__main__":
func1(12, 0, 89) |
def setup():
global pg
pg = createGraphics(1000, 1000)
noLoop()
def draw():
pg.beginDraw()
pg.colorMode(HSB, 360, 100, 100, 100)
pg.background(0, 0, 25)
pg.stroke(60, 7, 86, 100)
pg.noFill()
for i in range(100):
pg.ellipse(random(pg.width), random(pg.height), 100, 100)
pg.endDraw()
pg.save(... |
"""
File: anagram.py
Name: Yujing Wei
----------------------------------
This program recursively finds all the anagram(s)
for the word input by user and terminates when the
input string matches the EXIT constant defined
at line 19
If you correctly implement this program, you should see the
number of anagrams for each... |
n=list(map(int,input("Enter the list").split(",")))
le=max(n)
while max(n)==le:
n.remove(max(n))
print(max(n))
|
class Solution(object):
def arrayPairSum(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
return sum([c for i, c in enumerate(sorted(nums)) if i % 2 == 0]) |
for i in range(int(input())):
text = input().replace('.', '')
countOpen = 0
countDiamonds = 0
for char in text:
if char == '<':
countOpen += 1
elif char == '>' and countOpen > 0:
countDiamonds += 1
countOpen -= 1
print(countDiamonds) |
def read_n_values(n):
print("Please enter", n, "values.")
values = []
for i in range(n):
values.append(input("Value {}: ".format(i + 1)))
return values
def compute_average(values):
# set sum to first value of list
total_sum = values[0]
# iterate over remaining values and add them... |
load("@rules_python//python:python.bzl", "py_binary", "py_library", "py_test")
def py3_library(*args, **kwargs):
py_library(
srcs_version = "PY3",
*args,
**kwargs
)
def py3_binary(name, main = None, *args, **kwargs):
if main == None:
main = "%s.py" % (name)
py_binary(
... |
try:
test = int(input().strip())
while test!=0:
k,d0,d1 = map(int,input().strip().split())
d2 = (d1+d0)%10
if k == 2:
if (d1+d0)%3 == 0:
print("YES")
continue
else:
print("NO")
continue
elif k... |
##
# This software was developed and / or modified by Raytheon Company,
# pursuant to Contract DG133W-05-CQ-1067 with the US Government.
#
# U.S. EXPORT CONTROLLED TECHNICAL DATA
# This software product contains export-restricted data whose
# export/transfer/disclosure is restricted by U.S. law. Dissemination
# to ... |
def hypotenuse_triangle(side1, side2):
hypotenuse = side1 ** 2 + side2 ** 2
return hypotenuse
print(hypotenuse_triangle(2, 4))
|
GRADING_POST = {
'tags': ['Interview'],
'description': '면접 결과 제출',
'parameters': [
{
'name': 'access_token',
'description': '엑세스 토큰, 헤더의 Authentication',
'in': ' header',
'type': 'str',
'required': True
},
{
'nam... |
# Tuplas sao imutaveis, nao se pode substituir um valor enquanto o programa estiver rodando
# oq foi definido no inicio permanece ate o final
lanche = ('hamburguer', 'pizza', 'suco', 'refri')
print(lanche[1])
print(lanche[-1]) #-1 mostra o ultimo elemento
print(sorted(lanche)) #para organizar a lista em ordem alfa... |
#-*-coding:utf-8-*-
ALPHABET = ['а', 'б', 'в', 'г', 'д', 'е', 'ё', 'ж', 'з',
'и', 'й', 'к', 'л', 'м', 'н', 'о', 'п', 'р',
'с', 'т', 'у', 'ф', 'х', 'ц', 'ч', 'ш', 'щ',
'ъ', 'ы', 'ь', 'э', 'ю', 'я', ' ']
callnumber = input()
message = ''
while callnumber != 'End':
message += str(A... |
class Solution:
def moveZeroes(self, nums):
"""
:type nums: List[int]
:rtype: void Do not return anything, modify nums in-place instead.
"""
n = len(nums)
zeroindex = -1
for i in range(n):
if nums[i] == 0 and zeroindex == -1:
zeroi... |
# Time: O(m * n)
# Space: O(1)
class Solution(object):
def shiftGrid(self, grid, k):
"""
:type grid: List[List[int]]
:type k: int
:rtype: List[List[int]]
"""
def rotate(grids, k):
def reverse(grid, start, end):
while start < end:
... |
FULL_ACCESS_GMAIL_SCOPE = "https://mail.google.com/"
LABELS_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.labels"
SEND_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.send"
READ_ONLY_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.readonly"
COMPOSE_GMAIL_SCOPE = "https://www.googleapis.com/auth/gmail.c... |
def read():
x = int(input())
return x
a = read()
b = read()
c = read()
d = read()
if b == c and b + c == d and b + c + d == a:
print("S")
else:
print("N")
|
def test_home(client):
response = client.get('/')
#import pdb;pdb.set_trace()
assert response.status_code == 200
assert response.template_name == ['home.html']
|
print('{:=^40}'.format('Lojas Gui'))
n = float(input('Coloque o valor do produto: R$ '))
print('''forma de pagamento.
[1] Dinheiro/cheque.
[2] Cartão.
[3] 2x cartão.
[4] 3x ou mais.''')
n2 = int(input('Coloque a opção: '))
print('===')
if n2 == 1:
print(f'O valor a ser pago e R$ {n-(n*(10/100))}.')
elif n2 == 2... |
# MIT licensed
# Copyright (c) 2013-2020 lilydjwg <lilydjwg@gmail.com>, et al.
HACKAGE_URL = 'https://hackage.haskell.org/package/%s/preferred.json'
async def get_version(name, conf, *, cache, **kwargs):
key = conf.get('hackage', name)
data = await cache.get_json(HACKAGE_URL % key)
return data['normal-version']... |
#!/usr/bin/env python3 -u
# coding: utf-8
__author__ = ["Markus Löning"]
__all__ = []
|
load(
"//scala:advanced_usage/providers.bzl",
_ScalaRulePhase = "ScalaRulePhase",
)
load(
"//scala/private:phases/phases.bzl",
_phase_bloop = "phase_bloop",
)
ext_add_phase_bloop = {
"attrs": {
# "bloopDir": attr.label(
# allow_single_file = True,
# doc = "Bloop output ... |
soma = 0
quantidade = 0
while True:
n = int(input("Digite um número inteiro: "))
if n==0:
break;
soma = soma + n
quantidade = quantidade + 1
print(f"Quantidade de números digitados: {quantidade}")
print(f"Soma: {soma}")
print(f"A média é: {soma / quantidade:10.2f}")
|
angka = {
0: 'tepat',
1: 'satu',
2: 'dua',
3: 'tiga',
4: 'empat',
5: 'lima',
6: 'enam',
7: 'tujuh',
8: 'delapan',
9: 'sembilan',
10: 'sepuluh',
11: 'sebelas',
12: 'dua belas',
}
def eja(n):
lut1 = ['nol', 'satu', 'dua', 'tiga', 'empat',
... |
"""
Expert list created from Kompetenzpool data.
List contains Microsoft Academic Graph Ids
"""
kompetenzpool_expert_list = {
"Internet of Things": [
2241467651,
673846798,
2236413454
],
"blockchain": {
1245553041,
2021103267,
},
"natural language proc... |
# Ex. 023
num = str(input("Digite um número: ")) # .zfill(4) -> preenche com 0 até completar 4 casas
while len(num) < 4:
num = "0" + num
print("Unidade: ", num[3])
print("Dezena: ", num[2])
print("Centena: ", num[1])
print("Unidade de milhar: ", num[0])
|
#!/usr/bin/env python
# coding: utf-8
# In[99]:
class TreeNode:
def __init__(self, val = None, par = None):
self.left = None
self.right = None
self.value = val
self.parent = par
def left_child(self):
return self.left
def right_child(self):
return self... |
ColorNames = \
{ u'aliceblue': (240, 248, 255),
u'antiquewhite': (250, 235, 215),
u'aqua': (0, 255, 255),
u'aquamarine': (127, 255, 212),
u'azure': (240, 255, 255),
u'beige': (245, 245, 220),
u'bisque': (255, 228, 196),
u'black': (0, 0, 0),
u'blanchedalmond': (255, 235, 205),
u'blu... |
# https://stackoverflow.com/questions/63626389/how-to-sort-points-along-a-hilbert-curve-without-using-hilbert-indices
N=9 # 9 points
n=2 # 2 dimension
m=3 # order of Hilbert curve
def BitTest(x,od):
result = x & (1 << od)
return int(bool(result))
def BitFlip(b,pos):
b ^= 1 << pos
return b
def partiti... |
"""
# ==============================================================================
# ToPy -- Topology optimization with Python.
# Copyright (C) 2012, 2015, 2016, 2017 William Hunter.
# Copyright (C) 2020, 2021 Tarcísio L. de Oliveira
# ==============================================================================
"""... |
# Authorization data
host = '*****'
user = '*****'
passwd = '*****'
db = 'hr'
|
#
# PySNMP MIB module ENTERASYS-VLAN-AUTHORIZATION-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/ENTERASYS-VLAN-AUTHORIZATION-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:04:50 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Pyt... |
"""Exercício 7:
Dadas duas listas, retorne uma nova lista contendo valores que aparecem nas duas da entrada"""
def repetidos_versao_1(lista1: list, lista2: list):
saida = list(set([x for x in lista1 for y in lista2 if x == y]))
return saida
def repetidos_versao_2(lista1: list, lista2: list):
auxiliar =... |
#!/usr/bin/env python
"""
_Step.Templates_
Package for containing Step Template implementations
"""
__all__ = []
|
class BookStore:
def __init__(self, book):
self.booklst = book
class Book:
def __init__(self, title, author, chapter, price):
self.title = title
self.author = author
self.chapter = list(chapter)
self.price = int(price)
book1 = Book("han kubrat", "Tangra", ['1', '3', '... |
"""submodopt - A package for maximizing submodular functions"""
__version__ = '0.1.0'
__author__ = 'Satwik Bhattamishra <satwik55@gmail.com>'
__all__ = []
|
# Contains the objects found on our user greetings page.
# Imports --------------------------------------------------------------------------------
# Page Objects ---------------------------------------------------------------------------
class PatientGreetingPageObject(object):
bio = 'This is a test bio.'
... |
Dict = {'Tim': 18,'Charlie':12,'Tiffany':22,'Robert':25}
Boys = {'Tim': 18,'Charlie':12,'Robert':25}
Girls = {'Tiffany':22}
studentX=Boys.copy()
studentY=Girls.copy()
print(studentX)
print(studentY)
students = list(Dict.keys())
students.sort()
for s in students:
print(":".join((s,str(Dict[s]))))
|
"""Utilities for interacting with databases"""
def generate_connect_string(
host: str,
port: int,
db: str,
user: str,
password: str,
) -> str:
conn_string = f"postgresql://{user}:{password}@"
if not host.startswith('/'):
conn_string += f"{host}:{port}"
conn_string += f"/{db}"
... |
class RaiseException:
def __init__(self, exception: Exception):
self.exception = exception
|
EVENT_ALGO_LOG = "eAlgoLog"
EVENT_ALGO_SETTING = "eAlgoSetting"
EVENT_ALGO_VARIABLES = "eAlgoVariables"
EVENT_ALGO_PARAMETERS = "eAlgoParameters"
APP_NAME = "AlgoTrading"
|
class AminoAcid:
def __init__(self,name='AA'):
self.name = name
self.name3L = ''
self.Hydrophobic = 0 # 1: Hydrophobic, 0: Hydrophilic
self.charge = 0
self.polar = 0
self.corner = 0 # Would prefer to be at a corner : give positive value
self.loop = 0 # ... |
initialized = True
class TestFrozenUtf8_1:
"""\u00b6"""
class TestFrozenUtf8_2:
"""\u03c0"""
class TestFrozenUtf8_4:
"""\U0001f600"""
def main():
print("Hello world!")
if __name__ == '__main__':
main()
|
nome = 'Pedro Silva Mendonça'
print("O nome com todas as letras maiusculas:")
print(nome.upper())
print("O nome com todas as letras minusculas:")
print(nome.lower())
#da pra fazer assim
print('(Primeiro jeito) Quantas letras ao todo(sem considerar os espaços):')
print(len(nome.strip().replace(" ", "")))
#ou assim
prin... |
# -*- coding: utf-8 -*-
'''
username :
password :
'''
acts = ActionSet(tag=tag,desc=desc,mp=mp)
#act1
arg = { "detectRegion" : gl.R_Screen,
"imagePattern" : Pattern("6.png").similar(0.90).targetOffset(0,-69),
"loopWaitingTime": 0,
"failResponse" : "Ignore",
"loopTime": 0,
"saveI... |
'''
A collection of classes corresponding to fixed-income securities, to be fed into (and used with)
other classes and methods available in this repository (eg trees.py, Monte Carlo, etc)
'''
class SelfAmortizingMortgage:
def __init__(self, dates=mats6, early=False, rate=5.5 / 100, T=6, N=100):
''' Inputs... |
AVG = 70
FUNCTIONS = [
lambda geslacht: 0 if geslacht == 'man' else 4,
lambda rookt: -5 if rookt else 5,
lambda sport: -3 if not sport else sport,
lambda alcohol: 2 if not alcohol else -((alcohol - 7) * 0.5) if alcohol > 7 else 0,
lambda f... |
class CommentHandlers(object):
def __init__(self):
self.handlers = []
self.comments = {}
def handler(self):
def wrapped(func):
self.register(func)
return func
return wrapped
def register_handler(self, func):
for handler in self.handlers:
... |
def incrementing_time(start=2000, increment=1):
while True:
yield start
start += increment
def monotonic_time(start=2000):
return incrementing_time(start, increment=0.000001)
def static_time(value):
while True:
yield value
|
"""
Common constants and functions
Markus Konrad <markus.konrad@wzb.eu>
"""
DEFAULT_TOPIC_NAME_FMT = 'topic_{i1}'
DEFAULT_RANK_NAME_FMT = 'rank_{i1}'
|
class Solution:
def reverseBits(self, n: int) -> int:
val = 0
for i in range(32):
val <<= 1
val += n & 1
n >>= 1
return val
|
stages = iter(['alpha','beta','gamma'])
try:
next(stages)
next(stages)
next(stages)
next(stages)
except StopIteration as ex:
err_msg = 'Ran out of iterations'
|
class Payment:
def __init__(self):
pass
def setPayment(self, payment):
Payment.payment = payment
def getPayment(self):
print("Total yang harus dibayarkan Rp. ", Payment.payment)
|
#from pageParser
'''
lines = []
with open('output111.txt', 'rt') as in_file:
for line in in_file:
lines.append(line.rstrip('\n'))
counter = (len(lines))
holder = 0
for element in range(0, counter):
if(lines[holder].find('a') == -1):
... |
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
c = x^y
r = 0
while c != 0:
r += (c & 1)
c = c>>1
return r
|
#Faça um Programa que peça dois números e imprima o maior deles.
num1 = int(input("Informe o primeiro numero: "))
num2 = int(input("Informe o segundo numero: "))
if(num1>num2):
print("O maior numero eh %.0f"%num1)
elif(num2>num1):
print("O maior numero eh %.0f"%num2)
else:
print("Os dois numeros tem o me... |
v = "vvv"
a = [f"aaa{vvv}"
"bbb"]
print(a)
|
# worst case O(n^2)
# good case O(n)
def insertion_sort(array):
for i in range(1, len(array)):
key = array[i]
j = i -1
while (j>=0 and array[j]>key):
# scoot
array[j+1] = array[j]
j-=1
array[j+1] = key
return array
arr = [3,-9,5, 100,-2, 294,... |
x=int(input("Enter first number:\n"))
y=int(input("Enter second number:\n"))
print("Before swapping:\n",x,"\n",y,"\n")
#Inputting two numbers from user
x,y=y,x
#Swapping two variables
print("After swapping:\n",x,"\n",y,"\n") |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.