content stringlengths 7 1.05M |
|---|
# Topic 1: Basics of programming - Excercise 1
# Gerhard van der Linde
# Copied from Ian McLoughlin
# A program that displays Fibonacci numbers.
#
# Re: Fibonacci exercise responses
# by GERHARD VAN DER LINDE - Monday, 22 January 2018, 4:14 PM
#
# My name is Gerhard, so the first and last letter of my name
# (G + D ... |
posicao= int(input('Digite um numero: '))
seq=0
a=1
b=0
aux=0
while posicao != seq:
print(aux, end=' ')
aux= a+b
a=b
b= aux
seq +=1 |
class Permission:
ADMIN = 1
USER = 21
LIST_USERS = 22
ADD_USER = 23
Edit_USER = 24
DELETE_USER = 25
BLOCK_USER = 26
|
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
'''
Author: Luiz Yao (luizyao@163.com)
Created Date: 2019-10-24 14:23:40
-----
Last Modified: 2019-10-24 14:26:16
Modified By: Luiz Yao (luizyao@163.com)
-----
THIS PROGRAM IS FREE SOFTWARE, IS LICENSED UNDER MIT.
A short and simple permissive license with conditions
only ... |
# -*- coding: utf-8 -*-
"""
Ochrona-cli
:author: ascott
"""
class OchronaException(Exception):
pass
class OchronaFileException(OchronaException):
pass
class OchronaImportException(OchronaException):
pass
|
img_norm_cfg = dict(
mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True)
max_scale, min_scale = 1024, 512
train_pipeline = [
dict(type='LoadImageFromFile'),
dict(type='LoadAnnotations'),
dict(type='Resize', img_scale=(max_scale, min_scale), keep_ratio=True),
dict(type='RandomF... |
n1 = float(input('Digite o 1º número: '))
n2 = float(input('Digite o 2º número: '))
n3 = float(input('Digite o 3º número: '))
maior = n1
menor = n1
if n2 > n1:
maior = n2
if n3 > maior:
maior = n3
if n2 < n1:
menor = n2
if n3 < menor:
menor = n3
print('O menor valor digitado é {}'.format(menor))
prin... |
# testing importing of modules and functions
def make_pizza(size, *toppings):
"""Summarize the pizza we are about to make."""
print(f"\nMaking a {size}-inch pizza with the following toppings:")
for topping in toppings:
print(f"- {topping}")
|
PROC_FUNC_DICT = dict()
def register_forward_proc_func(func):
PROC_FUNC_DICT[func.__name__] = func
return func
@register_forward_proc_func
def forward_batch_only(model, sample_batch, targets=None, supp_dict=None):
return model(sample_batch)
@register_forward_proc_func
def forward_batch_target(model, s... |
w = 105
x = 78658965235632
y = -256
z = 0b00110011
print(type(w)) # <class 'int'>
print(type(x)) # <class 'int'>
print(type(y)) # <class 'int'>
print(type(z)) # <class 'int'> |
class StackOverflowSpider(scrapy.Spider):
name = 'casa'
start_urls = ['http://homelovers.pt/index.php/component/jak2filter/?Itemid=114&isc=1&category_id=2&xf_7_range=0|1200&ordering=order']
def parse(self, response):
for href in response.css('.question-summary h3 a::attr(href)'):
full... |
#
# PySNMP MIB module HM2-LICENSE-MGMT-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HM2-LICENSE-MGMT-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:18:51 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (defau... |
#!/usr/bin/python3
"""Module to find the max integer in a list
"""
def max_integer(list=[]):
"""Function to find and return the max integer in a list of integers
If the list is empty, the function returns None
"""
if len(list) == 0:
return None
result = list[0]
i = 1
while i < ... |
def get_bittrex_rates(self, queue, pairs):
base = pairs['base']
markets = pairs['markets']
rates = dict()
for market in markets:
ticker = "{}-{}".format(base, market)
symbol_info = self.get_ticker(ticker)
price = symbol_info['result']['Last']
symbol = "{}{}".format(ma... |
# 13. *Ски почивка
# Атанас решава да прекара отпуската си в Банско и да кара ски. Преди да отиде обаче, трябва да резервира хотел и да изчисли колко ще му струва престоят. Съществуват следните видове помещения със следните цени за престой:
# "room for one person" – 18.00 лв за нощувка
# "apartment" – 25.00 лв за н... |
"""
Copyright (c) 2016 Marshall Farrier
license http://opensource.org/licenses/MIT
Constants related to the MongoDB schema
"""
SPREADS = [
{ 'key': 'dgb',
'desc': 'Diagonal butterfly'},
{ 'key': 'dblcal',
'desc': 'Double calendar'},
]
|
__title__ = "exercise"
__description__ = "Package to generate HIIT exercises"
__url__ = "https://github.com/deepspaceghost/deme-app/tree/exercise"
__version__ = "0.0.0.153"
__author__ = "deepspaceghost"
__author_email__ = "ghostblac@protonmail.com"
__license__ = "none"
__copyright__ = "© 2021 demiurge"
|
# Visit https://www.reddit.com/prefs/apps/ for credential keys
# For additional detail, visit praw's own document: https://praw.readthedocs.io/en/latest/getting_started/quick_start.html
credentials = {
'client_id' : 'Your client key here',
'client_secret' : 'Your client secret here',
'user_agent' : "Your u... |
# Lesson 3
class Person:
def __init__(self, fname, lname):
self._fname = fname
self._lname = lname
# properties allow us to emulate member variables with correctional logic
@property
def full_name(self):
return self._fname + ' ' + self._lname
# we can also use them to asser... |
"""
Faça um Programa que pergunte quanto você ganha por hora e o número de horas trabalhadas no mês.
Calcule e mostre o total do seu salário no referido mês.
"""
salario_hora = float(input('Informe seu salário por hora trabalhada: '))
qtd_horas = float(input('Informe sua quantidade de horas trabalhadas no mês: '))
tot... |
ZOMATO_API_KEY = 'your key here'
GOOGLE_MAPS_V3_KEY = 'your key here'
ZOMATO_API_URL = '/api/v2.1/search?'
ZOMATO_BASE_URL = 'developers.zomato.com'
ZOMATO_MAX_RESULT = 10
|
"""
959. 由斜杠划分区域
"""
class UnionFind:
def __init__(self, n):
self.father = {x:x for x in range(n)}
#连通分量统计
self.count = n
def find(self, x):
if x != self.father[x]:
self.father[x] = self.find(self.father[x])
return self.father[x]
def merge(self, x, y):
... |
nota1 = float(input('Digite a Primeira Nota: '))
nota2 = float(input('Digite a Segunda Nota: '))
media = (nota1+nota2)/2
print('Sua média:\n Primeiro Semestre: {} \n Segundo Semestre: {} \n Média: {:.1f}'.format(nota1, nota2, media))
|
class Solution:
def videoStitching(self, clips: List[List[int]], T: int) -> int:
index, cnt, maxn = 0, 0, 0
while index < T:
flag = 0
for l in clips:
if l[0] <= index:
tmp = maxn
maxn = max(maxn, l[1])
if maxn != tmp:
flag = 1
if flag == 0:
... |
"""
Author: Michel Peltriaux
Organization: Spatial data infrastructure Rhineland-Palatinate, Germany
Contact: michel.peltriaux@vermkv.rlp.de
Created on: 28.05.19
""" |
test_data = [
{
"float_features":
{
"engines": 2,
"passenger_capacity": 4,
"crew": 3,
"company_rating": 1,
"review_scores_rating": 96
},
"categorical_features":
{
"d_check_complete": "False",
"moon_cl... |
s='''
ÁÀÄÂ
áàäâ
ÉÈËÊ
éèëê
ÏÎïî
ÖÔöô
ÚÙÜÛ
úùüû
Çç
'''
print(s.strip())
|
class RescTypeError(TypeError):
pass
class RescValueError(ValueError):
pass
class RescAttributeError(AttributeError):
pass
class RescKeyError(KeyError):
pass
class RescServerError(Exception):
pass
class RescCronError(Exception):
pass
|
print('Who do you think I am?')
input()
print('How old are you?')
input()
print('Oh, yes!')
|
'''
Created on Jun 7, 2015
@author: dave
'''
class ContextSet: # ContextSet
'''
The context has composed one or more trigger words. These trigger words
will be the spec of another command. That other command will be consumed
by the ContextSeeker and will not be executed.
'''
def __init__(se... |
src = Split('''
mqtt-example.c
''')
component = aos_component('mqttapp', src)
macro_tmp = Split('''
MQTT_TEST
ALIOT_DEBUG
IOTX_DEBUG
USE_LPTHREAD
''')
for i in macro_tmp:
component.add_global_macros(i)
dependencis = Split('''
tools/cli
framework/connectivity/mqtt
utility/cjson
... |
class heap(list):
"""docstring for heap"""
def __init__(self):
super(heap, self).__init__()
self.heap_size = 0
def parent(i):
return ((i+1) / 2) - 1
def left(i):
return 2*i+1
def right(i):
return 2*i+2
def min_heapify(A, i):
l = left(i)
r = left(i)
minmum = i
if l < A.heap_size and A[l] < A[i]:
mi... |
def computeCost(arr, X):
cost = 0
for i in range(len(arr)):
cost += abs(arr[i] - X)
return cost
def computeTriangularCost(arr, X):
cost = 0
for i in range(len(arr)):
cost += sum(range(abs(arr[i] - X) + 1))
return cost
def centerDistance(inputList, fdist):
inputLength = len(inputList)
if inpu... |
print("\t",end="")
for i in range(10):
for j in range(0,i):
print("*",end="")
print("")
l = [i%2 for i in range(10)]
print(l)
|
expected_output = {
"instance": {
"master": {
"areas": {
"0.0.0.1": {
"interfaces": {
"ge-0/0/0.0": {
"state": "PtToPt",
"dr_id": "0.0.0.0",
"bdr_id": "... |
class Compressor:
NUM_COLOR_CHANNELS = 3
MAX_TIMES = 8 # For 3 bits to represent repeats
def feed(self, data):
data_size = len(data)
assert data_size % self.NUM_COLOR_CHANNELS == 0, \
"Size of color data frames must be a multiple 3 which is the no. of color channels!"
... |
def withdraw_list(students, student_id=3, withdraw=15):
output, check = [], []
for item in students:
if item[0] == "108下":
continue
if item[student_id] not in check:
check.append(item[student_id])
output.append(item)
continue
c_index = che... |
"""
A line item for a bulk food order has description, weight and price fields::
>>> raisins = LineItem('Golden raisins', 10, 6.95)
>>> raisins.weight, raisins.description, raisins.price
(10, 'Golden raisins', 6.95)
A ``subtotal`` method gives the total price for that line item::
>>> raisins.subtota... |
'''
Given an integer array nums, handle multiple queries of the following type:
Calculate the sum of the elements of nums between indices left and right inclusive where left <= right.
Implement the NumArray class:
NumArray(int[] nums) Initializes the object with the integer array nums.
int sumRange(int left, int righ... |
# generated from catkin/cmake/template/pkg.context.pc.in
CATKIN_PACKAGE_PREFIX = ""
PROJECT_PKG_CONFIG_INCLUDE_DIRS = "/xavier_ssd/TrekBot/TrekBot2_WS/devel/.private/robot_localization/include;/xavier_ssd/TrekBot/TrekBot2_WS/src/robot_localization/include;/usr/include/eigen3".split(';') if "/xavier_ssd/TrekBot/TrekBot2... |
class SingleConfigs:
def __init__(self, config):
self.attributes = ['n_channels']
self.configs = [config]
def sample(self):
return self.configs[0]
def largest(self):
return self.configs[0]
def smallest(self):
return self.configs[0]
def all_configs(self):
... |
'''
Pattern
Enter number of rows: 5
2
242
24642
2468642
2468108642
'''
print('Number Pattern: ')
number_rows=int(input('Enter number of rows: '))
for row in range(1,number_rows+1):
for column in range(2,(row*2)+1,2):
print(column,end=' ')
for column in range(((row-1)*2),1,-2):
print(column,end=' ')... |
registration_message = 'Вас ещё нет в базе данных, поэтому пройдите простую процедуру регистрации'
registration_success_message = '✅ | Регистрация\n\n' \
'Отлично, Вы зарегистрировались, введенные данные можно посмотреть/отредактировать ' \
'в личном кабине... |
"""
Desenvolva um programa que leia as duas notas de um aluno, calcule e mostre a
sua média
"""
nota1 = float(input('Primeira nota do aluno: '))
nota2 = float(input('Segunda nota do aluno: '))
media = (nota1 + nota2) / 2
print(f'A média entre {nota1} e {nota2} é igual a {media:.1f}')
if media >= 7:
print('\033[34m... |
def layer_xy(m, n, e): # creates a list with all the outer x,y of eth layer
xy = []
for i in range(e, m + e):
xy.append([i, e]) # contains x,y of left side of this layer
for j in range(e + 1, n + e - 1):
xy.append([m - 1 + e, j]) # contains x,y of bottom side
for i in range(m - 1, -1, -1):
xy.append... |
str1 = open("data/cpbdev.txt").read().splitlines()
str2 = open("data/cpbtest.txt").read().splitlines()+['']
str3 = open("data/cpbdev_answer1.txt").read().splitlines()
str4 = open("data/cpbtest_answer1.txt").read().splitlines()+['']
for i in range(len(str1)):
s1 = str1[i].split(' ')
s3 = str3[i].split(... |
class PropertyNames:
ID = 'ID'
Status = 'Status'
FileType = 'FileType'
FileName = 'FileName'
TableName = 'TableName'
DatabaseType = 'DatabaseType'
FileHasHeaders = 'FileHasHeaders'
Delimiter = 'Delimiter'
SheetName = 'SheetName'
CellRange = 'CellRange'
CheckTableExists = 'Ch... |
class Vector:
"""
Constructor
self: a reference to the object we are creating
vals: a list of integers which are the contents of our vector
"""
def __init__(self, vals):
self.vals = (
vals # We're using the keyword self to create a field/property
)
print("A... |
WAIT = 'wait'
PRESENT = 'present'
NOT_PRESENT = 'not_present'
ENABLED = 'enabled'
DISABLED = 'disabled'
CHECKED = 'checked'
UNCHECKED = 'unchecked'
TEXT = 'text'
CONTAINS = 'contains'
NOT_CONTAINS = 'not_contains'
CLASS = 'class'
DISPLAYED = 'displayed'
NOT_DISPLAYED = 'not_displayed'
EXPECTED_VISIBLE = 'expected_visib... |
# coding=utf-8
# @Time : 2020/2/13
# @Author : Wang Xiaoxiao
# @University : Dalian University of Technology
# @FileName : LinkedListQueue.py
# @Software : PyCharm
# @github : https://github.com/i-love-linux/BasicDataStructure
class LinkedListQueue:
class __Node:
def __init__(self, elem... |
class Node:
def __init__(self, data=None, left=None, right=None):
self.data = data
self.left = left
self.right = right
def __str__(self):
return "\n".join(Node.pretty_string(self, 0))
@staticmethod
def pretty_string(root, depth):
if not root:
return ... |
# model settings
norm_cfg = dict(type='BN', requires_grad=True, momentum=0.01)
model = dict(
type='EncoderDecoder',
backbone=dict(
type='FastSCNN',
downsample_dw_channels=(32, 48),
global_in_channels=64,
global_block_channels=(64, 96, 128),
global_block_strides=(2, 2, 1),... |
"""
Escreva um programa que receba quantas entradas o usuário desejar e depois
crie um novo contato para cada entrada (Nome, Telefone, Endereço, Email), e
por fim imprima, em ordem alfabética, a agenda de contatos
"""
def entradas():
"""faz as perguntas sobre o contato e retorna os dados"""
contato = {}
... |
class FillPatternElement(Element,IDisposable):
""" An element that represents a fill pattern. """
@staticmethod
def Create(document,fillPattern):
"""
Create(document: Document,fillPattern: FillPattern) -> FillPatternElement
Creates a new FillPatternElement.
document: The document in ... |
# -*- coding: utf-8 -*-
"""
Create by sandy at 16:57 23/12/2021
Description: ToDo
"""
|
class Solution:
def longestPalindrome(self, s):
ans = 0
count = collections.Counter(s)
for v in count.values():
ans += v // 2 * 2
if ans % 2 == 0 and v % 2 == 1:
ans += 1
return ans
|
text = """
//------------------------------------------------------------------------------
// Explicit instantiation.
//------------------------------------------------------------------------------
#include "Geometry/Dimension.hh"
#include "editMultimaterialSurfaceTopology.cc"
namespace Spheral {
template void editM... |
# coding=utf-8
class _Teams:
def __init__(self, client=None):
self.client = client
def add_user_for_team(self, team_gid, params=None, **options):
"""Add a user to a team
:param str team_gid: (required) Globally unique identifier for the team.
:param Object params: Parameters fo... |
"""Given weights and values of n items, put these items in a knapsack of capacity W to get the maximum total value in the knapsack."""
def MF_knapsack(i, wt, val, j):
'''
This code involves the concept of memory functions. Here we solve the subproblems which are needed
unlike the below example
F is a ... |
"""Given a rows x cols screen and a sentence represented by a list of non-empty words, find how many times the given sentence can be fitted on the screen.
Note:
A word cannot be split into two lines.
The order of words in the sentence must remain unchanged.
Two consecutive words in a line must be separated... |
class Credential:
'''
class that generates new instaces of credentials information
'''
credential_list = [] #credential list
def save_credential(self):
'''
save_credential method saves object in credential list
'''
Credential.credential_list.append(self)
def __ini... |
class CmdActionResponse:
__status: bool
__msg: str
def __init__(self, status: bool, msg: str):
if isinstance(status, bool):
self.__status = status
else:
self.__status = False
self.__msg = msg
def isSuccess(self) -> bool:
return self... |
# -*- coding: utf-8 -*-
{
'!langcode!': 'fr',
'!langname!': 'Français',
'"update" is an optional expression like "field1=\'newvalue\'". You cannot update or delete the results of a JOIN': '"update" est une expression en option tels que "field1 = \'newvalue\'". Vous ne pouvez pas mettre à jour ou supprimer les résultats... |
# coding: utf-8
"""
Joplin-Web Zi App
"""
__version__ = '2.0.0'
|
"""
Given two strings s and t which consist of only lowercase letters.
String t is generated by random shuffling string s and then add one more letter at a random position.
Find the letter that was added in t.
Example:
Input:
s = "abcd"
t = "abcde"
Output:
e
Explanation:
'e' is the letter that was added.
Your ru... |
#!/usr/bin/python
class Device:
def __init__(self, uuid, type, ostype, osversion, brandname):
self.UUID = uuid
self.Type = type
self.OSType = ostype
self.OSVersion = osversion
self.BrandName = brandname
|
# Source : https://leetcode.com/problems/peak-index-in-a-mountain-array/
# Author : foxfromworld
# Date : 17/11/2021
# First attempt
class Solution:
def peakIndexInMountainArray(self, arr: List[int]) -> int:
idx, peak = 0, 0
for i, m in enumerate(arr):
if m > peak:
peak... |
def first_recurring(arr):
count = {}
for char in arr:
if char in count:
return char
count[char] = 1 # adding char into hashtable
print(count)
return None
arr = ["a", "b", "c", "d", "a"]
result = first_recurring(arr)
print(result)
|
p = [
{'nombre': 'portátil', 'significado': 800},
{'nombre': 'portátil', 'significado': 800},
{'nombre': 'portátil', 'significado': 800},
{'nombre': 'portátil', 'significado': 800},
{'nombre': 'portátil', 'significado': 800},
{'nombre': 'portátil', 'significado': 800},
{'nombre': 'por... |
if __name__ == '__main__':
triplets = ((a, b, c)
for c in range(500, 1, -1)
for b in range(c, 1, -1)
for a in range(b, 1, -1))
for a, b, c in triplets:
if a + b + c == 1000 and a ** 2 + b ** 2 == c ** 2:
print(a, b, c, a*b*c)
... |
town = {"Acton Town" : ["Ealing Common","South Ealing","Turnham Green","Chiswick Park"],
"Aldgate" : ["Liverpool Street","Tower Hill"],
"Aldgate East" : ["Tower Hill","Whitechapel","Liverpool Street"],
"All Saints" : ["Devons Road","Poplar"],
"Alperton" : ["Park Royal","Sudbury Town"],
"Amersham" : ... |
class BittrexError(Exception):
pass
class BittrexRestError(BittrexError):
pass
class BittrexApiError(BittrexRestError):
def __init__(self, message):
self.message = message or 'Unknown error'
class BittrexResponseError(BittrexRestError):
def __init__(self, status: int, content: str):
... |
#!/usr/bin/python
# Filename: ex_if.py
color = 'white'
print("In the beginning, the color is {0}.".format(color))
if color == 'red':
color = 'orange'
elif color == 'orange':
color = 'yellow'
else:
color = 'red'
print("At the end, the color is {0}.".format(color))
|
""" Compile is an internal module that compile formulas into Fast C/C++ code.
Options for compiling:
- numba
- C code and OpenMP/pthreads
- C++ code and OpenMP
- Cython code and OpenMP
- Numpy (to solve compatability issue!)
- Python (when the user is forced to use pure python code!)
"""
class ... |
def drap_first_last(grades):
first,*middle,last=grades
return print(middle)
record = ('Dave', 'dave@example.com', '773-555-1212', '847-555-1212')
name, email,*phone_numbers=record
print(name, email, phone_numbers)
*trailing, current = [10, 8, 7, 1, 9, 5, 10, 3]
print(sum(trailing)/len(trailing), current)
rec... |
# nxpy_ply --------------------------------------------------------------------
# Copyright Nicola Musatti 2011 - 2018
# Use, modification, and distribution are subject to the Boost Software
# License, Version 1.0. (See accompanying file LICENSE.txt or copy at
# http://www.boost.org/LICENSE_1_0.txt)
# See https://git... |
# preview of a Python Program
# A Python program that computes a grade-point average(GPA).
print('Welcome to the GPA calculator.')
print('Please enter all your letter grades, one per line.')
print('Enter a blank line to designate the end.')
# map from letter grade to point value
points = {
'A+': 4.0,
'A': 4.... |
{
"targets": [
{
"target_name": "ShortestPathCalculator",
"cflags!": [ "-fno-exceptions" ],
"cflags_cc!": [ "-fno-exceptions" ],
"sources": [
"addon/shortest_path/shortest_path_addon.cc",
"addon/shortest_path/shortest_path_addon.h",
"addon/shortest_path/shortest_path.cpp",
... |
valor1 = int (input ('Digite o primeiro valor: '))
valor2 = int (input ('Digite o segundo valor: '))
soma = valor1 + valor2
print ('A soma entre {} e {} vale {}'.format(valor1, valor2, soma)) |
render = ez.Node()
aspect2D = ez.Node()
camera = ez.Camera(parent=render)
camera.y = -3
target = ez.Node(parent=render)
#Create a camera for the buffer image:
buff_cam = ez.Camera(parent=target)
buff_cam.y = -5
#Create a texture buffer and assign the camera to it:
buffer = ez.TextureBuffer(256, 256)
buffer.camera ... |
# the main() function
def main():
# parse argument
parser = argparse.ArgumentParser(description="Runs Conway's Game of Life simulation.")
# add arguments
parser.add_arguments('--grid-size', dest='N', required=False)
parser.add_arguments('--mov-file', dest='movfile', required=False)
parser.ad... |
bill_id = 101
c_id = 1001
c_name ="rahul"
if_minor = False
bill_amount = 2000.50
print("bill_id is:", bill_id ,"c_id is:", c_id, "c_name", c_name ,if_minor,bill_amount)
|
DEVELOPMENT = False
PORT = 5000
|
# 定义 Spider 类
# 什么是类?请百度了解什么是「面向对象」,以及「类」和「对象」的区别
# 这是一个管理所有 spider 的工具
# 为什么要这样做?一般编程时,我们要考虑程序的可拓展性。我们不可能满足于只爬一个网站。这样设计,就可以管理多个网站的爬虫了
class Spider:
# 构造函数
def __init__(self):
self.spiders = {}
self.enabled = []
# 成员函数
## 注册爬虫
def register(self, name: str, spider: 'function'):
... |
#########################################
# VoiceRss.py
# categories: speech
# more info @: http://myrobotlab.org/service/VoiceRss
#########################################
mouth = Runtime.start("mouth", "VoiceRss")
#possible voices ( selected voice is stored inside config until you change it )
print ("these... |
# Empty list
mapping = dict()
# Charlson score, ICD9
tmpn = "charlson_icd9_quan"
mapping[tmpn] = dict()
mapping[tmpn]["ami"] = (
"410",
"412",
)
mapping[tmpn]["chf"] = (
"39891",
"40201",
"40211",
"40291",
"40401",
"40403",
"40411",
"40413",
"40491",
"40493",
"4254",... |
#
# PySNMP MIB module BAS-FTD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/BAS-FTD-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:33:53 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 0... |
for i in range(int(input())):
n = int(input())
a = [int(j) for j in input().split()]
print(sum(a)-n+1)
|
valor = float(input('Qual valor do saque? '))
if valor >= 10 and valor <= 600:
unidade = valor % 10
unidadeGuardada = int(unidade)
valor = (valor - unidade) / 10
dezena = valor % 10
dezena = int(dezena)
valor = (valor - dezena) / 10
centena = valor % 10
centena = int(centena)
if cen... |
# Time: O(n)
# Space: O(h)
class Solution(object):
def findTarget(self, root, k):
"""
:type root: TreeNode
:type k: int
:rtype: bool
"""
class BSTIterator(object):
def __init__(self, root, forward):
self.__node = root
... |
day = "day12"
filepath_data = f"input/{day}.txt"
filepath_example = f"input/{day}-example.txt"
Connections = dict[str, set[str]]
NODE_START = "start"
NODE_END = "end"
def data_from_file(filename: str) -> Connections:
with open(filename) as f:
conns: Connections = dict()
for line in f:
... |
class Descriptor(object):
def __init__(self, name=None, **opts):
self.name = name
for key, value in opts.items():
setattr(self, key, value)
if 'default' in opts:
self.__dict__.update({self.name: opts.get('default')})
def __set__(self, instance, value):
... |
USER = 'bopjiang'
PASSWORD = 'MY PASSWORD'
DEFAULT_SSH_PORT = 22
## ip address and port
HOSTS = [
"10.10.30.194", ## equal to "10.10.30.194:$DEFAULT_SSH_PORT"
"10.10.30.195",
]
|
MAX_GOAL = "MAXIMIZE"
MIN_GOAL = "MINIMIZE"
INTEGER = "INTEGER"
DOUBLE = "DOUBLE"
CATEGORICAL = "CATEGORICAL"
DISCRETE = "DISCRETE"
|
# -*- coding=utf-8 -*-
class Desconto_Cinco_Items(object):
def __init__(self, proximo):
self.__proximo = proximo
def calcular(self, orcamento):
if orcamento.total_items > 5:
return orcamento.valor * 0.1
else:
return self.__proximo.calcular(or... |
"""
Python Tuple [ 24 exercises]
1. Write a Python program to create a tuple.
2. Write a Python program to create a tuple with different data types.
3. Write a Python program to create a tuple with numbers and print one item.
4. Write a Python program to unpack a tuple in several variables.
5. Write a Python ... |
'''
Write a Python program to calculate the sum of
the positive integers of n+(n-2)+(n-4)... (until n-x =< 0).
sum_series(6) -> 12
sum_series(10) -> 30
'''
class Solution:
def sum_digits(self, num):
if num-2 < 0:
return 0
else:
return num + self.sum_digits(num-2)
if __n... |
npp_Ahmad = {
"Name" : "Ahmad",
"Car" : "Tesla"
}
print(npp_Ahmad["Name"], 'owns a', npp_Ahmad["Car"] )
npp_Billy = {
"Name" : "Billy",
"Car" : "Toyota 1998"
}
print(npp_Billy["Name"], "owns a", npp_Billy["Car"])
npp_Chris = {
"Name" : "Chris",
"Car" : "Honda Cvic"
}
print(npp_Chris["... |
# coding: utf-8
"""
This module provides the base class for a Flask app decorator.
"""
class Decorator:
'''
A base class for decorating a Flask app with additional features.
Some basic decorators are provided. To add more, you must sub-class this
class.
'''
def decorate(self, a... |
# Copyright 2017 ZTE Corporation.
#
# 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 ... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.