content stringlengths 7 1.05M |
|---|
# -*- coding: utf-8 -*-
#Se debera generar un sistema que mantenga en memoria datos de una agenda.
# - El programa mostrara las opciones> agregar, editar, borrar, mostrar y salir
# agregar, agenda un contacto (email, telefono, nombre, domicilio, edad y dni)
# editar, permite modificar cualquiera de los contact... |
def get_digits(n):
r = [n % 10, n//10 % 10, n//100 % 10, n//1000 % 10, n//10000 % 10, n//100000 % 10]
return r
def increasing_digits(digits):
result = True
N = len(digits)
for i in range(len(digits) - 1):
result = result and digits[N-1 - i] <= digits[N-1 - i-1]
return result
def two_a... |
'''
Template to create a movie test data by yourself:
['Action', 'Adventure', 'Animation', 'Biography', 'Comedy', 'Crime', 'Documentary', 'Drama', 'Family', 'Fantasy',
'Film-Noir', 'Game-Show', 'History', 'Horror', 'Music', 'Musical', 'Mystery', 'News', 'Reality-TV', 'Romance',
'Sci-Fi', 'Short', 'Sport', 'Thriller', ... |
"""This is a python program to find the minimum number of left or right moves to reach the target card given start card Index and cards array"""
num_of_cards=int(input("Enter the number of cards: "))#ask user of number of cards
cards=list(map(str,input("Enter cards: ").strip().split(',')))[:num_of_cards]#add the array ... |
pracky = [4, 9, 2, 0, 5, 8, 11, 33, 4, 77, 1, 88, 26, 7]
def linSrch(haystack, needle):
for ant in haystack:
if ant == needle:
return haystack.index(ant)
elif haystack.index(ant) == len(haystack) - 1:
return -1
else:
continue
# print(linSr... |
class ReqonError(Exception):
pass
class InvalidTypeError(ReqonError):
def __init__(self, message):
super(InvalidTypeError, self).__init__(message)
class InvalidFilterError(ReqonError):
def __init__(self, message):
super(InvalidFilterError, self).__init__(message)
|
# ROUND_SUM
def round_sum(a, b, c):
return round10(a) + round10(b) + round10(c)
def round10(n):
if n%10>4:
n/=10
return (n+1) * 10
else:
n/=10
return n * 10 |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
# Course: Python programming for life science researchers VT19
# Project: Potential Transcripts Prediction
# Author: Yarong Tian
# Import the original data
sequence=input("Please paste query sequence here: ")
# Read the query sequence
seq=str(sequence)
# Prepare for pr... |
# BS mark.1-55
# /* coding: utf-8 */
# BlackSmith mark.1
# antiwipe.py
# Copyleft
GoodServers = ["jabber.ru", "xmpp.ru", # add 2ch.so maybe
"jabber.cz", "jabbim.cz",
"gtalk.com", "gmail.com",
"jabbers.ru", "xmpps.ru",
"gajim.org", "jabbim.com",
"jabberon.ru", "jabbrik.ru",
"talkonaut.com"... |
# This program computes batting and slugging averages from a given csv file of player data.
# Nigel Myers
# Fundamentals of Programming
# ACC FALL 2018
# lab8.py
# Prof Onabajo
# Version: import .csv; output .txt
#parse csv function
class Player:
def __init__(self, stats):
self.name = stat... |
class MosartKeyboardCodes:
'''
This class allows to convert the Mosart keyboard codes to the corresponding HID code and modifiers.
.. warning::
These values have been collected empirically.
As a result, the corresponding mapping may contains some mistakes or missing data.
'''
@classmethod
def getMosartK... |
# https://leetcode.com/problems/length-of-last-word/#/discuss
class Solution(object):
def lengthOfLastWord(self, s):
"""
:type s: str
:rtype: int
"""
if s == '':
return 0
word_list = s.split(" ")
for w in reversed(word_list):
... |
# -*- coding: utf-8 -*-
# Part of Odoo. See LICENSE file for full copyright and licensing details.
{
'name': 'Odoo 12 Accounting PDF Reports',
'version': '12.0.1.0.0',
'category': 'Invoicing Management',
'summary': 'Accounting Reports For Odoo 12',
'sequence': '10',
'author': 'MP technolabs',
... |
__version__ = "1.0.10"
if __name__ == "__main__": # pragma: no cover
print(__version__)
|
"""
Speech constants for the food truck intent
"""
ADDRESS_NOT_FOUND = "I can't seem to find {}. Try another address"
BAD_API_RESPONSE = "Hmm something went wrong. Maybe try again?"
MULTIPLE_ADDRESS_ERROR = "I found multiple places with the address {}. " \
"What's the zip code?"
ADDRESS_NOT_U... |
# --- Day 2: Inventory Management System ---
# https://adventofcode.com/2018/day/2
file = open("02_input.txt", "r")
data = file.read().splitlines()
twos = 0
threes = 0
rows = 0
for line in data:
rows += 1
ll = []
for i in line:
c = 0
for j in line:
if i == j:
... |
class Employee():
def __init__(self, last, first, money):
self.last = last
self.first = first
self.money = money
def give_raise(self, raises=5000):
self.raises = raises
return raises
|
class Solution:
def longestValidParentheses(self, s: str) -> int:
return self.count(s)
def count(self, s):
s = s.replace("()", "*")
for i in range(1, len(s)):
s = s.replace(f"(" + i * "*" + ")", (i + 1) * "*")
s = s.replace(")", "(")
s = s.split("(")
... |
class CacheException(Exception):
pass
class InvalidCachePackage(CacheException):
pass
class BadLinkError(CacheException):
"""
Error raised when a symbolic link is bad.
Can also arise when the link is possibly malicious.
"""
pass
class BadPathError(CacheException):
pass |
# https://leetcode.com/problems/trapping-rain-water/
class Solution:
def trap(self, height: list[int]) -> int:
# Create a helper array to find actual water levels
held_water = [0 for _ in range(len(height))]
water = 0
# Scan heights from left to right
max_left = height[0]
... |
def createLevelArrayFromCircuitDescription(circuitDescription):
inputs = circuitDescription[0]
gates = circuitDescription[2]
levels = [{
i: {
'leaving': None,
'entering': [k for k in gates if i in gates[k]['inputs']][0]
} for i in inputs
}]
numberOfGatesDone = 0
while numberOfGatesDone < len(gates... |
COLORS = [
"amaranth",
"amber",
"amethyst",
"apricot",
"aqua",
"aquamarine",
"azure",
"beige",
"black",
"blue",
"blush",
"bronze",
"brown",
"chocolate",
"coffee",
"copper",
"coral",
"crimson",
"cyan",
"emerald",
"fuchsia",
"gold",
... |
# Errors
class Error(Exception):
"""Base class for errors. A subclass of `Exception`."""
def __init__(self, trace=None):
"""Extend Exception.__init__() to hold a traceback.
Keyword arguments:
- trace=None: a traceback usually created by `util.getTrace()` or None.
... |
class CompositorNodeBrightContrast:
use_premultiply = None
def update(self):
pass
|
#
# PySNMP MIB module TIMETRA-CFLOWD-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TIMETRA-CFLOWD-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 21:09:44 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, ... |
def factorial(n):
if n == 0:
return 1
return n * factorial(n-1)
def iterativeFactorial(n):
result = 1
for i in range(1,n+1):
result = result * i
return result
def main():
print("The factorial of 5 is", factorial(5))
print("The iterative factorial of 5 is", iterativeFactorial(5))
main() |
# AUTOMATICALLY GENERATED BY GENGUPPY
about = b'\x80\x03cguppy.gsl.Text\nRecordingInter\nq\x00)\x81q\x01}q\x02(X\x07\x00\x00\x00appendsq\x03]q\x04(K\x00X\x16\x00\x00\x00Heapy Profile Browser\nq\x05K\x01X\x01\x00\x00\x00\tq\x06K\x02X\x07\x00\x00\x00Versionq\x07K\x01h\x06K\x03X\x04\x00\x00\x000.1\nq\x08K\x04h\x06K\x02X\... |
expected_output = {
"interface-policer-information": {
"physical-interface": [
{
"admin-status": "up",
"logical-interface": [
{
"admin-status": "up",
"name": "ge-0/0/2.0",
... |
load(
"//scala:scala_cross_version.bzl",
_default_scala_version = "default_scala_version",
_extract_major_version = "extract_major_version",
_scala_mvn_artifact = "scala_mvn_artifact",
)
load(
"@io_bazel_rules_scala//scala:scala_maven_import_external.bzl",
_scala_maven_import_external = "scala_m... |
class Solution:
def romanToInt(self, s: str) -> int:
r2n = {
'I': 1,
'V': 5,
'X': 10,
'L': 50,
'C': 100,
'D': 500,
'M': 1000
}
n = len(s)
# exception
if n == 1:
return r2n... |
#!/usr/bin/env python3
#Creates a list for all of the values of a specific category
def make_list(arr, category, val):
#Checks for special players instance of call
if(category == "Maxplayers"):
return make_list_players(arr, category, val)
position = binary_search(arr, category, 0, len(arr), val)
#Che... |
# was difficult due to very large inputs
# may be able to optimize, but perhaps with a different strategy
#!/bin/python3
t = int(input().strip())
for a0 in range(t):
N = int(input().strip())
prices = list(map(int, input().strip().split(' ')))
if N == 0 or N == 1:
print(0)
else:
#... |
class SearchWagonsByNumOfPass:
"""Basic class for searching wagons by number of passengers"""
MAX_INPUT_VALUE = 54
AVERAGE_INPUT_VALUE = 36
MIN_INPUT_VALUE = 0
def findWagonsByValue(self):
inputValue = int(input(" Enter value for search :"))
if inputValue >= SearchWagonsByNumOfPass.M... |
class User:
"""
Class that generates new User.
"""
user_list= [] #Array of empty user list
def __init__(self,name,password):
self.name=name
self.password=password
def save_user(self):
User.user_list.append(self)
def delete_user(self):
'''
delete... |
'''
Literalemtne es un filtro.
En este ejericio uquiero todos los numero pares de una lista de numeros-
'''
#Numeros del 1 al 99
numbers = [x for x in range(40)]
evens=[]
# print(numbers)
# Quiero todos los números pares de la lsita de forma tradicional.
for even in numbers:
if even % 2 == 0:
evens.... |
def main(request, response):
location = request.GET.first(b"location")
response.status = 302
response.headers.set(b"Location", location)
if b"allow_origin" in request.GET:
response.headers.set(b"Access-Control-Allow-Origin", request.GET.first(b"allow_origin"))
if b"timing_allow_origin" in ... |
# Copyright (C) 2017 Udacity Inc.
# All Rights Reserved.
# Author: Brandon Kinman
class PIDController:
def __init__(self, kp = 0.0, ki = 0.0, kd = 0.0, max_windup = 10, alpha=1.0):
self.kp = kp
self.ki = ki
self.kd = kd
self.max_windup = max_windup
self.target = 0
... |
#Debangshu Roy
#WAP to print the followingseries and find its sum
#1,-9,25,-49...,n
#n is a input by user
num=int(input("Enter a number: "))
count=0
sumseries = 0
for x in range(1,num+1,2):
count+=1
if count%2==0:
sumseries + ((-1)*(2))
print("-",(2), sep="")
else:
sumseries = ... |
year = int(input("Enter Year: "))
# Leap Year Check
if not year % 400:
print(year, "is a Leap Year")
elif not year % 4 and year % 100:
print(year, "is a Leap Year")
else:
print(year, "is not a Leap Year")
|
def inicio(txt):
print('~'*30)
print('TRATANDO VÁRIOS VALORES')
print('~' * 30)
inicio('')
num = cont = soma = 0
num = int(input('Digite um número [999 para sair]: '))
while num != 999:
cont += 1
soma += num
num = int(input('Digite um número [999 para sair]: '))
#Se eu ler o flag do lado de fo... |
#!/usr/bin/env python
#coding: utf-8
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
cl... |
# V0
# V1
# https://blog.csdn.net/fuxuemingzhu/article/details/83422260
class Solution(object):
def longestMountain(self, A):
"""
:type A: List[int]
:rtype: int
"""
N = len(A)
inc = [1] * N
dec = [1] * N
for i in range(1, N):
if A[i] - A... |
text_array = [0x9257e4,
0x925852,
0x9258ce,
0x925be2,
0x925bfa,
0x925ca0,
0x925ccd,
0x925d0b,
0x925fa4,
0x9272bc,
0x9272da,
0x927354,
0x9273d5,
0x927406,
0x92743c,
0x927474,
0x927476,
0x9274b3,
0x9274b5,
0x9274ea,
0x9274ec,
0x927517,
0x927544,
0x927548,
0x927565,
0x927567,
0x9275d8,
0x9275ed,
0x92763f,
0x927648,
0x9276... |
speed=int(input("Insira a velocidade que você atingiu em Km: "))
multa=(speed-80)*7
if speed>80:
print("Você foi multado e pagará uma multa de R${:.2f}.".format(multa))
else:
print("Você não foi multado.") |
"""List of common verbs to make your mother jokes from"""
common_verbs_structured = {
'is': [
'am', 'are', 'be', 'were', 'was',
"you're", "i'm"
],
"'s": [
"he's", "she's", "it's",
"what's", "that's", "they're"
],
"isn't": ["aren't", "weren't"],
'has': ['have', 'ha... |
def isPhoneNumber(text):
# checking the length of the characters of expression
if len(text) != 12:
return False
# checking the first three characters if they are numbers
# if any of them is not a number it will return False
for i in range(0, 3):
if not text[i].isdecimal():
... |
GET_ALL_MEMBERS = """
SELECT username, first_name, last_name, password, email, created_on, last_login
FROM members
"""
GET_MEMBER_BY_USERNAME = f"""
{GET_ALL_MEMBERS}
WHERE username = :username
"""
INSERT_MEMBER = f"""
INSERT INTO members (username, password, first_name, last_name, email, last_login)
VALUES (:usernam... |
def transpose(matrix):
return [[matrix[j][i] for j in range(len(matrix))] for i in range(len(matrix[0]))]
def get_matrix_first_diagonal(matrix):
n = len(matrix)
return set(matrix[i][i] for i in range(n))
def get_matrix_second_diagonal(matrix):
n = len(matrix)
return set(matrix[i][n-i-1] for i in... |
"""
HOW TO USE:
In a string, put the color you want first, with the first item and the second item at the emd. (Example: _str = f"{green[0]}Green!{green[1]}"
"""
reset = [str(u"\u001b[0m"), str(u"\u001b[0m")]
bold = [str(u"\u001b[1m"), str(u"\u001b[22m")]
dim = [str(u"\u001b[2m"), str(u"\u001b[22m")]
itali... |
for number in range(1, 101):
#if number % 3 == 0 or number % 5 == 0: -> "FizzBuzz" has to be displayed when both the conditions are true, not only one of them
if number % 3 == 0 and number % 5 == 0:
print("FizzBuzz")
#if number % 3 == 0: -> elif has to be used as only one condition should be fulfilled at max
... |
def bar1():
"""__NATIVE__
PmReturn_t retval = PM_RET_OK;
/* If wrong number of args, raise TypeError */
if (NATIVE_GET_NUM_ARGS() != 0)
{
PM_RAISE(retval, PM_RET_EX_TYPE);
return retval;
}
NATIVE_SET_TOS(PM_NONE);
return retval;
"""
pass
def bar2():
return bar1()
|
sum = 0
for x in range(101):
sum += x
print(sum)
|
# import <module_name>
"""Test the speed of a code snippet. Import a file and run a function.
The results will be stored in a directory you specify."""
filename = 'json_files/' # Enter save directory
with open(filename, 'w') as f:
exec_times = []
for i in range(1, 31):
start_time = time.time()
# YOUR CO... |
# hostname to listen on
HOST = "0.0.0.0"
# TCP port for the server to listen on
PORT = 8002
|
#Unidade, dezena, centena, milhar
numero = str(input('Digite um número de 0 a 9999: ')).zfill(4)
print()
print('Unidades: {}'.format(numero[3]))
print()
print('Dezenas: {}'.format(numero[2]))
print()
print('Centenas: {}'.format(numero[1]))
print()
print('Milhares: {}'.format(numero[0]))
|
GITHUB_AUTH_TOKEN = ""
EVERNOTE_PROD_TOKEN = ""
EVERNOTE_SANDBOX_TOKEN = ""
NOTEBOOK_TO_SYNC = "gist-evernote"
|
#!/usr/bin/env python
step_down = 0.2
start_z = 0
end_z = -4
start_x = 37.0
end_x = 27.0
retract = 0.5
feed_rate = 30
work_z_level = start_z
g_code = "%\n"
g_code += "G0 X%.4f Z%4f\n" % (start_x, start_z)
while work_z_level > end_z:
work_z_level -= step_down
g_code += "G1 Z%.4f F%4f\n" % (work_z_level, feed... |
# Time: O(n)
# Space: O(1)
#
# You are a professional robber planning to rob houses along a street.
# Each house has a certain amount of money stashed, the only constraint stopping you
# from robbing each of them is that adjacent houses have security system connected
# and it will automatically contact the police if t... |
# open the file.txt in write mode.
fileptr = open("file2.txt", "a")
# overwriting the content of the file
fileptr.write(" Python has an easy syntax and user-friendly interaction.")
# closing the opened file
fileptr.close()
|
def print_helper(val):
if val==-10:
return '_'
elif val==0:
return 'O'
elif val==1:
return 'X'
def display_board(board):
for row in board:
col1, col2, col3 = print_helper(row[0]), print_helper(row[1]), print_helper(row[2])
print(col1, col2, col3)
|
days="Mon Tue Wed Thu Fri Sat Sun"
months="Jan\nFeb\nMar\nApr\nMay\nJune\nJuly\nAug"
print("Here are the days:",days)
print("Here are the months:",months)
print("There's something going on here.")
print("With the three doouble-quotes.")
print("We'll be able to type as much as we like.")
print("Even 4 lines if we want, ... |
col_name_branch = [
"from_bus_id",
"to_bus_id",
"r",
"x",
"b",
"rateA",
"rateB",
"rateC",
"ratio",
"angle",
"status",
"angmin",
"angmax",
"Pf",
"Qf",
"Pt",
"Qt",
"mu_Sf",
"mu_St",
"mu_angmin",
"mu_angmax",
]
col_type_branch = [
"int... |
class Solution:
def singleNumber(self, nums: List[int]) -> int:
nums.sort()
cnt = len(nums)
if cnt == 1:
return nums[0]
if nums[0] != nums[1] and nums[1] == nums[2]:
return nums[0]
if nums[cnt-1] != nums[cnt-2] and nums[cnt-2... |
# this less for loop
# classmates =['ff','erwer','fdsjfkdsf']
#
# for name in classmates:
# print(name)
#
#
#
# sum = 0
# for x in range(101):
# sum = sum + x
# print(sum)
# #print 不要写在缩进,容易
# print(sum)
#
# age =100
# while age>10 :
# age -=2
# print(age)
#注意对应的缩进!!!
age =100
while age >8:
... |
expected_output = {
"tag": {
"1": {
"prefix": {
"3.3.3.0": {
"subnet": "24",
"prefix_attr": {
"x_flag": False,
"r_flag": False,
"n_flag": False
},
... |
'''input
10 30
22
5
2
18
6
21
28
11
18
1
5
9 30
22
5
2
18
6
21
29
11
18
5
4 10
2
8
4
5
3
3 10
1
1
1
2
'''
# -*- coding: utf-8 -*-
# ddcc2017 qual
# Problem C
if __name__ == '__main__':
n, c = list(map(int, input().split()))
l = sorted([int(input()) for _ in... |
class MovieNightBotException(Exception):
pass
class VoteError(MovieNightBotException):
pass
|
# https://atcoder.jp/contests/abc131/tasks/abc131_b
N, L = map(int, input().split())
aji = []
for n in range(1, N + 1):
aji.append(L + n - 1)
ans = 0
min_diff = 10**9 + 7
total = sum(aji)
for a in aji:
diff = abs(total - (total - a))
if min_diff > diff:
min_diff = diff
ans = total - a
pri... |
def swap_case(s):
t = ''
for char in s:
if char.islower():
t += char.upper()
else:
t += char.lower()
return t |
# -*- coding: utf-8 -*-
"""
heroku_env.exceptions
-----------------------
All exceptions used in the heroku.env code base are defined here.
"""
class HerokuEnvException(Exception):
"""
Base exception. All other exceptions
inherit from here.
"""
class HerokuRunError(HerokuEnvException):
"""
... |
# 经理增加了一个变量
num1 = 100
# 张三增加了一个变量
num2 = 200
# 经理增增加变量num3
num3 = 300
# 张三队添加了一个判断功能
if num3 > 100:
print("登录成功")
# 经理添加了了一个循环功能
while num2 > 100:
print("jaja")
num -= 1
if num2 < 50:
break |
#!/usr/bin/python3
class Error(Exception):
pass
class DomainUrlError(Error):
def __init__(self, message):
self.message = message
class SpiderError(Error):
def __init__(self, message):
self.message = message
|
# https://leetcode.com/problems/delete-operation-for-two-strings
class Solution:
def minDistance(self, word1: str, word2: str) -> int:
tmp1 = " " + word1
tmp2 = " " + word2
dp = [[0 for _ in range(len(tmp2))] for __ in range(len(tmp1))]
for r in range(1, len(tmp1)):
for... |
with open('./Input/Names/invited_names.txt') as file_names, open('./Input/Letters/starting_letter.txt') as file_letter:
names = file_names.read().splitlines()
print(names)
starting_letter = file_letter.read()
# print(starting_letter)
for name in names:
new_starting_letter = starting_letter.r... |
matz = list()
colv = list()
colh = list()
sopar = soma3 = mai2 = 0
for v in range(0, 3):
for h in range(0, 3):
colh.append(int(input(f'Digite um valor para [{v}, {h}]: ')))
colv.append(colh[:])
colh.clear()
matz.append(colv[:])
colv.clear()
for pos, m in enumerate(matz):
for pos1, cv in ... |
'''
Created: 19.03.2015
@author: Dennis Ligtenberg
'''
|
expected_output={
"statistics":{
"vlan":{
"vlan":330,
"mdns_pkt_sent":{
"pkt_sent":1,
"ipv4_sent":{
"ipv4_sent_val":1,
"ipv4_adv_sent":0,
"ipv4_qry_sent":1
},
"ipv6_sent":{
"ipv6_sent_v... |
class ModelDatabaseRouter(object):
"""Allows each model to set its own destiny"""
def db_for_read(self, model, **hints):
# Specify target database with field in_db in model's Meta class
if hasattr(model._meta, 'in_db'):
return model._meta.in_db
return None
def db_fo... |
def countLines(name):
"""count number lines in a file"""
with open(name, 'r') as fd:
num_lines = len(fd.readlines())
return num_lines
def countChars(name):
"""count number characters in a file"""
with open(name, 'r') as fd:
num_chars = len(fd.read())
return num_chars
def test... |
class ExampleClass(object):
def __init__(self, number):
self.X = int
self.number = number
def get_number(self):
return self.X(self.number)
def main():
dict_example = {}
obj = ExampleClass(20.123)
print(type(ExampleClass))
dict_example[ExampleClass] = str(obj.get_numbe... |
"""
========================================================================
BasePass.py
========================================================================
An "abstract" base class for all passes.
Author : Shunning Jiang
Date : Dec 17, 2017
"""
class PassMetadata:
pass
class BasePass:
def __init__( self, ... |
# Done by Carlos Amaral (2020/09/21)
# SCU 4.4 - Nested if Statements
value_entered = input("Please, enter a number less than 100: ")
if int(value_entered) > 50:
print("The value entered is greater than 50.")
if int(value_entered) < 75:
print("The value entered is also less than 75")
else:
prin... |
inputfile = open('inputDay02.txt', 'r')
inputlist = [i.split() for i in inputfile.readlines()]
def createrangelist(data):
rangelst = [i[0] for i in data]
rangelst = [i.split('-') for i in rangelst]
rangeaux = []
for i in rangelst:
rangeaux = rangeaux + [[int(j) for j in i]]
rangelst = [tupl... |
class UserName:
def newMember(self, existingNames, newName):
if newName in existingNames:
i = 1
while '{}{}'.format(newName, i) in existingNames:
i += 1
return newName + str(i)
return newName
|
class Person(object):
def __init__(self, name=None, age=None, gender=None):
self.name = name
self.age = age
self.gender = gender
self.hp = 10
self.diseases = []
def __str__(self):
return "%s: %d" % (self.name, self.hp)
|
# coding=utf8
# python cli执行如下命令:
# import debug_code
# import pdb
# pdb.run('debug_code.looper(5)')
# continue
# 也可以通过shell执行
# python -m pdb debug_code.py
def log(number):
print(f'Processing {number}')
print(f'Adding 2 to number: {number + 2}')
def looper(number):
for i in range(number):
log(i)... |
# Do not edit this file directly.
# It was auto-generated by: code/programs/reflexivity/reflexive_refresh
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
def qRCodeGenerator():
http_archive(
name = "QR_Code_generator",
... |
"""Example on pre calculating"""
def nbits(val):
"""Return number of bits set to 1 in n"""
n = 0
while val:
if val & 1:
n += 1
val >>= 1
return n
def test_nbits():
cases = [
(0, 0),
(1, 1),
(2, 1),
(3, 2),
(6, 2),
(7, ... |
def cap_100(percent):
if percent <= 100:
return percent
else:
return 100
|
"""
plugin.py
Base plugin for Grouper plugins. These are plugins that can be written to extend Grouper
functionality.
"""
class BasePlugin(object):
def user_created(self, user):
"""Called when a new user is created
When new users enter into Grouper, you might have reason to set metadata on those... |
class DequeNode:
def __init__(self, data):
self.data = data
self.next = None
self.previous = None
class Deque:
def __init__(self, elems = None):
self._front = None
self._back = None
self._length = 0
if elems:
for e in elems:
self.add_last(e)
def __len__(self):
return self._length
def __... |
expected_output = {
"vrf": {
"default": {
"address_family": {
"ipv4": {
"prefix": {
"10.169.196.241/32": {
"nexthop": {
"10.0.0.10": {
"outg... |
# -*- coding: utf-8 -*-
"""
file: model_dictionary.py
Graph mixin class to add method to a Graph base class that will have it
behave like a python dictionary.
"""
__all__ = ['PythonDictionary']
class PythonDictionary(object):
def items(self, keystring=None, valuestring=None):
"""
Python dict-l... |
supported_resolutions = [
(640, 350, 70),
(640, 350, 85),
(640, 400, 70),
(640, 400, 85),
(640, 480, 60),
(640, 480, 73),
(640, 480, 75),
(640, 480, 85),
(640, 480, 100),
(720, 400, 85),
(768, 576, 60),
(768, 576, 72),
(768, 576, 75),
(768, 576, 85),
(768, 576... |
'''
/*
* @Author: Shawn Zhang
* @Date: 2019-09-08 17:47:48
* @Last Modified by: Shawn Zhang
* @Last Modified time: 2019-09-08 21:11:29
*/
''' |
DEFAULT_BORDER_STYLE = {
'style': 'solid',
'width': '1px',
}
BORDER_STYLES = {
'dashDot': None,
'dashDotDot': None,
'dashed': {
'style': 'dashed',
},
'dotted': {
'style': 'dotted',
},
'double': {
'style': 'double',
},
'hair': None,
'medium': {
... |
a = 12
b = 3
print(a + b) #15
print(a - b) #9
print(a * b) #36
print(a / b) #4.0
print(a // b) # 4 integer division, rounded down towards minus infinity
print(a % b) # 0 modulo: The remainder after interger division
#test for upload
print()
print(a + b / 3 - 4 * 12)
print(a + (b / 3) - (4 * 12))
print(((... |
def greet(name, age, gender):
if gender == 'M' and age < 18:
title = 'Master'
elif gender == 'M':
title = 'Mr.'
else:
title = 'Ms.'
return f"Hello {title} {name}"
print(greet(name='Wayne', gender='M', age=16))
print(greet(name='Joe', gender='M', age=30))
print(greet(name='Barbie... |
class PrivateOrInvalidProfileError(Exception):
def __init__(self, user):
Exception.__init__(self, "User profile " + "'" + user + "'" + " is private or doesn't exist.")
class UserIdNotFoundError(Exception):
def __init__(self):
Exception.__init__(self, "User id not found.")
class OutputDirecto... |
h, w, a, b = map(int, input().split())
mod = 10 ** 9 + 7
MAX_N = 2 * 10 ** 5
factorial = [1] * MAX_N
#事前に階上テーブルを用意
def calc_factorial():
for i in range(1, MAX_N):
factorial[i] = i * factorial[i - 1] % mod
def comb(n, k):
a = factorial[n] % mod
b = (factorial[k] * factorial[n - k]) % mod
b_ = po... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.