content stringlengths 7 1.05M |
|---|
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT license.
class SpecialStrings:
"""Special strings in stringified turn parts.
"""
# an empty value (we need it since some library doesn't like an empty string)
NULL = "__NULL"
# indicates there is a break between the two utterance segments
BREAK = "__BREAK"
# indicates the user is the speaker for the following utterance
SPEAKER_USER = "__User"
# indicates the agent is the speaker for the following utterance
SPEAKER_AGENT = "__Agent"
# start of a program
START_OF_PROGRAM = "__StartOfProgram"
|
#
# @lc app=leetcode.cn id=1389 lang=python3
#
# [1389] minimum-moves-to-move-a-box-to-their-target-location
#
None
# @lc code=end |
class Post():
def __init__(self, post_json):
self.post_id = post_json["id"]
self.annotations = {}
if "annotations" in post_json:
self.annotations = post_json["annotations"]
self.user_id = post_json["user"]["id"]
self.user_followers_count = post_json["user"]["followers_count"]
self.url = post_json["url"]
self.title = post_json["title"]
self.body = post_json["body"]
self.rendered_body = post_json["rendered_body"]
def quality(self, zero_one=True):
score = 0
if len(self.annotations) == 0:
return -1
for a in self.annotations:
score += int(a["quality"])
if not zero_one:
return score
else:
if score > 1:
return 1
else:
return 0
|
class EntropyException(Exception):
pass
class EntropyHttpUnauthorizedException(EntropyException):
pass
class EntropyHttpMkcolException(EntropyException):
pass
class EntropyHttpPropFindException(EntropyException):
pass
class EntropyHttpNoContentException(EntropyException):
pass
class EntropyHttpPutException(EntropyException):
pass
class EntropyVerifyCodeDirectoryException(EntropyException):
pass
|
class Dog:
def __init__(self, name):
self.name = name
class Cat:
def __init__(self, age):
self.age = age
def classify(pet):
match pet:
case Cat(age=age):
print("A cat that's {} years old".format(age))
case Dog:
print("A dog named {}".format(pet.name))
def number(x):
match x:
case 1: print("one"),
case 2 | 3: print("two or three"),
case x if x >=4: print("four or bigger"), # range matching not yet possible
case _: print("anything"),
if __name__ == "__main__":
for x in range(0, 6):
number(x)
classify(Dog("Fido"))
classify(Cat(3))
|
comprimento = float(input('Qual o comprimento da parede? '))
largura = float(input('Qual a largura da parede? '))
area = comprimento * largura
print(f'A parede tem a deminsão de {comprimento}x{largura} e sua área é de {area}m².')
tinta = area / 2
print(f'Para pintar a parede, você precisará de {tinta:.2f}L de tinta.') |
# Exercise 1 and 2, PROGRAMMING AND SCRIPTING
# A program that displays Fibonacci numbers using people's names.
# Exercise 1:
# My name is David, so the fist and last letters of my name (d + d = 4 + 4) give 8.
# Fibonacci number 8 is 21.
# Exercise 2
def fib(n):
"""This function returns the nth Fibonacci number."""
i = 0
j = 1
n = n - 1
while n >= 0:
i, j = j, i + j
n = n - 1
return i
# I have added my understanding of how the program works by way of comments within the code itself:
name = "Sheils" # assigns the string to variable name
first = name[0] # first letter of the string name
last = name[-1] # last letter of the string name
firstno = ord(first) # assigns to firstno the Unicode number of the first letter of name
lastno = ord(last) # assigns the Unicode number of the first letter of name
x = firstno + lastno # assigns to x the sum of firstno and lastno (i.e the sum of the unicode numbers for the first and last letters of the name)
ans = fib(x) # calls function fib on x (see above function definition)
print("My surname is", name)
print("The first letter", first, "is number", firstno)
print("The last letter", last, "is number", lastno)
print("Fibonacci number", x, "is", ans)
# Output of program:
# My surname is Sheils
# The first letter S is number 83
# The last letter s is number 115
# Fibonacci number 198 is 107168651819712326877926895128666735145224
# I have added my understanding of how the program works by way of comments within the code itself:
|
###############EXAMPLE 4: Inputs #################
#input() function waits for an input from the keyboard
salutation = "Hello"
name = input("Tell me your name: ")
complete_salut = salutation + ', ' + name + '!'
print (complete_salut)
weight = input("Enter your weight in lb: ")
weight = int(weight) #what am I doing here???
weight_kg = weight/2.205
print (weight_kg)
###############EXAMPLE 5: Conditionals #################
if (x > y):
print ("x is greater than y")
elif (y < x):
print ("y is greater than x")
else:
print ("they are equal!")
###############EXAMPLE 6: Functions #################
def BMI(weight, height):
bmi = weight / (height ** 2)
return bmi
def convert_lb_to_kg (weight_lb):
weight_kg = weight_lb/2.205
return weight_kg
def convert_ft_in_to_m(feet, inches):
meters = feet*0.305 + inches*0.0254
return meters
print (BMI(convert_lb_to_kg(210),convert_ft_in_to_m(6,0)))
###############EXAMPLE 7: Lists #################
list_of_numbers = [1,2,3,4,5]
len(list_of_numbers)
list_of_numbers[0]
print(list_of_numbers)
list_of_numbers[4]
print(list_of_numbers)
list_of_numbers[-2]
print(list_of_numbers)
#extending it
list_of_numbers.extend([6,7,8])
print(list_of_numbers)
#slicing it
piece = list_of_numbers[:4] #beginning to 4
print (piece)
piece = list_of_numbers[2:6] #from position 2 to 6
print (piece)
#shrinking it
del list_of_numbers [2:5]
print(list_of_numbers)
#merging
list1 = [1,2,3]
list2 = [4,5,6]
list3 = list1 + list2
print(list3)
list1.extend(list2)
print(list1)
#sorting
list1 = [-1,4,0,9,2,7]
list1.sort()
print (list1)
|
"""
Crie um programa que leia uma frase e diga se ela é um palindromo, a mesma coisa de frente pra tras e tras pra frente
desconsiderando os espaços
"""
frase = input('Diga uma frase: ').strip().upper()
palavras = frase.split()
palin = ''.join(palavras)
inverso = palin[::-1]
print(f'O inverso de {palin} é {inverso}.')
if palin == inverso:
print('Temos um Palindromo!!!')
else:
print('A frase digitada não é um Palindromo.')
|
# Importação de bibliotecas
# Título do programa
print('\033[1;34;40mTUPLAS COM TIMES DE FUTEBOL\033[m')
# Objetos
times = ('Corinthians', 'Palmeiras', 'Santos', 'Grêmio', 'Cruzeiro', 'Flamengo', 'Vasco', 'Chapecoense', 'Atlético', 'Botafogo', 'Atlético-PR', 'Bahia', 'São Paulo', 'Fluminense', 'Sport Recife', 'EC Vitória', 'Coritiba', 'Avaí', 'Ponte Preta', 'Atlético-GO')
# Lógica
print('\033[33m-=\033[m' * 30)
print(f'Lista de Times do Brasileirão: {times}')
print('\033[33m-=\033[m' * 30)
print(f'Os 5 primeiros são {times[:5]}')
print('\033[33m-=\033[m' * 30)
print(f'Os 4 últimos são {times[-4:]}')
print('\033[33m-=\033[m' * 30)
print(f'Times em ordem alfábetica: {sorted(times)}')
print('\033[33m-=\033[m' * 30)
print(f'O Chapecoense está na {times.index("Chapecoense") + 1}ª posição') |
class LegacyDatabaseRouter(object):
"""
This implements the Django DatabaseRouter protocol though we are using it to know which
role to use for the same db and to turn off migrations.
Though our underlying DB is new. We refer to this as "Legacy" because most of the time
when someone is looking to turn off Django migrations it is because of an old/existing
DB moving to a Django project that can then be managed by migrations. Not being allowed
to change schema, we are the minority. Knowing this will help you google.
The reader/writer roles most closely match a read slave/write master style setup so that
is what you google for that.
See: http://www.mechanicalgirl.com/post/reporting-django-multi-db-support/
For a nice (but dated) example that is similar to what we want for reader/writer.
As an aside, this is also good to know:
http://stackoverflow.com/questions/2628431/in-django-how-to-create-tables-from-an-sql-file-when-syncdb-is-run
"""
def db_for_read(self, model, **hints):
"""Typically for indicating a read slave. We use it to indicate the legacy db"""
return 'legacy'
def db_for_write(self, model, **hints):
"""Typically for indicating a master. We use it to indicate the 'writer' role"""
return 'legacy'
def allow_migrate(self, db, model):
"""This is the legacy bit"""
return False
def allow_relation(self, obj1, obj2, **hints):
"""This is ok as we don't actually have multiple databases"""
return True
|
class CachePolicy:
def __init__(self):
self.cache = []
self.cache_size = 5
|
cube = lambda x: x ** 3
def fibonacci(n):
first, second = 0, 1
for i in range(n):
yield first
first, second = second, first + second
if __name__ == '__main__':
n = int(input())
print(list(map(cube, fibonacci(n))))
|
FACE_CASCADE = "C:/openCV/sources/data/haarcascades/haarcascade_frontalface_alt.xml"
EYE_CASCADE = "C:/openCV/sources/data/haarcascades/haarcascade_eye.xml"
DEFAULT_FACE_SIZE = (200, 200)
RECOGNIZER_OUTPUT_FILE = "train_result.out" |
'''
* @Author: csy
* @Date: 2019-04-28 08:29:11
* @Last Modified by: csy
* @Last Modified time: 2019-04-28 08:29:11
'''
# pizza = {
# 'crust': 'thick',
# 'toppings': ['mushrooms', 'extra cheese']
# }
# print('You order a '+pizza['crust'] +'-crust pizza with the following toppings:')
# for topping in pizza['toppings']:
# print('\t' + topping)
#
# def make_pizza(*toppings):
# '''打印顾客点的所有配料'''
# print('Following toppings:')
# for topping in toppings:
# print('\t-'+topping.title())
# make_pizza('pepperoni')
# make_pizza('mushrooms','green peppers','extra cheese')
#
# def make_pizza(size,*toppings):
# '''概述要做的披萨'''
# print('Make a '+str(size)+'-inch pizza with the following toppings:')
# for topping in toppings:
# print('\t-'+topping.title())
# make_pizza(16,'pepperoni')
# make_pizza(12,'mushrooms','green peppers','extra cheese')
#
def make_pizza(size, *toppings):
'''概述要做的披萨'''
print('Make a '+str(size)+'-inch pizza with the following toppings:')
for topping in toppings:
print('\t-'+topping.title())
|
split = 'exp'
dataset = 'folder'
height = 320
width = 640
disparity_smoothness = 1e-3
scales = [0, 1, 2, 3, 4]
min_depth = 0.1
max_depth = 100.0
frame_ids = [0, -1, 1]
learning_rate = 1e-4
depth_num_layers = 50
pose_num_layers = 18
total_epochs = 45
device_ids = range(8)
depth_pretrained_path = './weights/resnet{}.pth'.format(depth_num_layers)
pose_pretrained_path = './weights/resnet{}.pth'.format(pose_num_layers)
in_path = './datasets/my_dataset/image_undistort'
gt_depth_path = ''
checkpoint_path = '/node01_data5/monodepth2-test/model/refine/smallfigure.pth'
imgs_per_gpu = 2
workers_per_gpu = 4
model = dict(
name = 'mono_fm',# select a model by name
depth_num_layers = depth_num_layers,
pose_num_layers = pose_num_layers,
frame_ids = frame_ids,
imgs_per_gpu = imgs_per_gpu,
height = height,
width = width,
scales = [0, 1, 2, 3],# output different scales of depth maps
min_depth = 0.1, # minimum of predicted depth value
max_depth = 100.0, # maximum of predicted depth value
depth_pretrained_path = './weights/resnet{}.pth'.format(depth_num_layers),# pretrained weights for resnet
pose_pretrained_path = './weights/resnet{}.pth'.format(pose_num_layers),# pretrained weights for resnet
extractor_pretrained_path = './weights/autoencoder.pth', # pretrained weights for autoencoder
automask = False if 's' in frame_ids else True,
disp_norm = False if 's' in frame_ids else True,
perception_weight = 1e-3,
smoothness_weight = 1e-3,
)
validate = False
png = False
scale_invariant = False
plane_fitting = False
finetune = False
perception = False
focus_loss = False
scale_invariant_weight = 0.01
plane_fitting_weight = 0.0001
perceptional_weight = 0.001
optimizer = dict(type='Adam', lr=learning_rate, weight_decay=0)
optimizer_config = dict(grad_clip=dict(max_norm=35, norm_type=2))
# learning policy
lr_config = dict(
policy='step',
warmup='linear',
warmup_iters=500,
warmup_ratio=1.0 / 3,
step=[15,25,35],
gamma=0.5,
)
checkpoint_config = dict(interval=1)
# yapf:disable
log_config = dict(interval=50,
hooks=[dict(type='TextLoggerHook'),])
# yapf:enable
# runtime settings
dist_params = dict(backend='nccl')
log_level = 'INFO'
load_from = None
resume_from = None
workflow = [('train', 1)] |
def kadane(a):
max_current = max_global = a[0]
for i in range(1, len(a)):
max_current = max(a[i], max_current + a[i])
if max_current > max_global:
max_global = max_current
return max_global
n = int(input())
a = [int(x) for x in input().split()]
print(kadane(a))
|
#
# @lc app=leetcode id=22 lang=python3
#
# [22] Generate Parentheses
#
class Solution:
def parse(self, acc: str):
nl, nr = 0, 0
for c in acc:
if c == '(':
nl += 1
else:
nr += 1
return nl, nr
def gen(self, n: int, acc: str) -> List[str]:
nl, nr = self.parse(acc)
if nr > nl:
raise RuntimeError('should not reach here')
if nl == n:
acc += ')' * (n - nr)
return [acc]
if nl == nr:
return self.gen(n, acc + '(')
return self.gen(n, acc + '(') + self.gen(n, acc + ')')
def generateParenthesis(self, n: int) -> List[str]:
if n == 0:
return []
return self.gen(n, '')
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Copyright (c) 2021, Cisco Systems
# GNU General Public License v3.0+ (see LICENSE or https://www.gnu.org/licenses/gpl-3.0.txt)
DOCUMENTATION = r"""
---
module: certificate_profile
short_description: Resource module for Certificate Profile
description:
- Manage operations create and update of the resource Certificate Profile.
version_added: '1.0.0'
author: Rafael Campos (@racampos)
options:
allowedAsUserName:
description: AllowedAsUserName flag.
type: bool
certificateAttributeName:
description: Attribute name of the Certificate Profile - used only when CERTIFICATE
is chosen in usernameFrom. Allowed values - SUBJECT_COMMON_NAME - SUBJECT_ALTERNATIVE_NAME
- SUBJECT_SERIAL_NUMBER - SUBJECT - SUBJECT_ALTERNATIVE_NAME_OTHER_NAME - SUBJECT_ALTERNATIVE_NAME_EMAIL
- SUBJECT_ALTERNATIVE_NAME_DNS. - Additional internal value ALL_SUBJECT_AND_ALTERNATIVE_NAMES
is used automatically when usernameFrom=UPN.
type: str
description:
description: Certificate Profile's description.
type: str
externalIdentityStoreName:
description: Referred IDStore name for the Certificate Profile or not applicable
in case no identity store is chosen.
type: str
id:
description: Certificate Profile's id.
type: str
matchMode:
description: Match mode of the Certificate Profile. Allowed values - NEVER - RESOLVE_IDENTITY_AMBIGUITY
- BINARY_COMPARISON.
type: str
name:
description: Certificate Profile's name.
type: str
usernameFrom:
description: The attribute in the certificate where the user name should be taken
from. Allowed values - CERTIFICATE (for a specific attribute as defined in certificateAttributeName)
- UPN (for using any Subject or Alternative Name Attributes in the Certificate
- an option only in AD).
type: str
requirements:
- ciscoisesdk
seealso:
# Reference by Internet resource
- name: Certificate Profile reference
description: Complete reference of the Certificate Profile object model.
link: https://ciscoisesdk.readthedocs.io/en/latest/api/api.html#v3-0-0-summary
"""
EXAMPLES = r"""
- name: Update by id
cisco.ise.certificate_profile:
ise_hostname: "{{ise_hostname}}"
ise_username: "{{ise_username}}"
ise_password: "{{ise_password}}"
ise_verify: "{{ise_verify}}"
state: present
allowedAsUserName: true
certificateAttributeName: string
description: string
externalIdentityStoreName: string
id: string
matchMode: string
name: string
usernameFrom: string
- name: Create
cisco.ise.certificate_profile:
ise_hostname: "{{ise_hostname}}"
ise_username: "{{ise_username}}"
ise_password: "{{ise_password}}"
ise_verify: "{{ise_verify}}"
state: present
allowedAsUserName: true
certificateAttributeName: string
description: string
externalIdentityStoreName: string
id: string
matchMode: string
name: string
usernameFrom: string
"""
RETURN = r"""
ise_response:
description: A dictionary or list with the response returned by the Cisco ISE Python SDK
returned: always
type: dict
sample: >
{
"UpdatedFieldsList": {
"updatedField": [
{
"field": "string",
"oldValue": "string",
"newValue": "string"
}
]
}
}
"""
|
def math():
test_case = int(input())
for i in range(test_case):
i_put = input()
count = len(i_put)
res = (count/100).__format__('.2f')
print(res)
if __name__ == '__main__':
math()
|
# Empty Box (2002016) | Treasure Room of Queen (926000010)
reactor.incHitCount()
reactor.increaseState()
if reactor.getHitCount() >= 4:
sm.removeReactor()
|
def on_bluetooth_connected():
basic.show_leds("""
. # # # .
# . . . .
# . . . .
# . . . .
. # # # .
""")
bluetooth.on_bluetooth_connected(on_bluetooth_connected)
def on_bluetooth_disconnected():
basic.show_leds("""
# # # . .
# . . # .
# . . # .
# . . # .
# # # . .
""")
bluetooth.on_bluetooth_disconnected(on_bluetooth_disconnected)
basic.show_leds("""
# . . # #
# . . # #
# # # . .
# . # . .
# # # . .
""")
bluetooth.start_accelerometer_service()
bluetooth.start_button_service()
bluetooth.start_led_service()
bluetooth.start_temperature_service()
|
NONE_ENUM_INDEX = 0
ACTIVATE_ENUM_INDEX = 1
ABORT_ENUM_INDEX = 2
SUSPEND_ENUM_INDEX = 3
RESUME_ENUM_INDEX = 4
STOP_ENUM_INDEX = 5
TERMINATE_ENUM_INDEX = 6
REMOVE_ENUM_INDEX = 7
|
# -*- coding: utf-8 -*-
def goes_after(word: str, first: str, second: str) -> bool:
if first in word and second in word:
if word.index(second) - word.index(first) == 1:
result = True
else:
result = False
else:
result = False
return result
# another pattern
try:
return word.index(second)-word.index(first) == 1
except ValueError:
return False
if __name__ == '__main__':
print("Example:")
print(goes_after('world', 'w', 'o'))
# These "asserts" are used for self-checking and not for an auto-testing
assert goes_after('world', 'w', 'o') == True
assert goes_after('world', 'w', 'r') == False
assert goes_after('world', 'l', 'o') == False
assert goes_after('panorama', 'a', 'n') == True
assert goes_after('list', 'l', 'o') == False
assert goes_after('', 'l', 'o') == False
assert goes_after('list', 'l', 'l') == False
assert goes_after('world', 'd', 'w') == False
print("Coding complete? Click 'Check' to earn cool rewards!")
|
class Solution(object):
# Time Complexity: O(n)
# Space Complexity: O(1)
@staticmethod
def remove_element(nums, val):
size = len(nums)
j = size -1 # going backwards
i = 0
while i <= j:
if nums[i] == val:
if nums[j] != val:
nums[i] = nums[j]
j -= 1
i += 1
else:
j -= 1
else:
i += 1
return j+1
if __name__ == '__main__':
s = Solution()
val = 2
nums = [0, 1, 2, 2, 3, 0, 4, 2]
|
def strongest(to_assign, pins_to_match, strength):
def matches(segment):
a,b = segment
return a == pins_to_match or b == pins_to_match
compatible_segments = [s for s in to_assign if matches(s)]
if(len(compatible_segments) == 0):
return strength
def next(segment):
a,b = segment
left_to_assign = [s for s in to_assign if s != segment]
next_pin = a if a != pins_to_match else b
return strongest(left_to_assign, next_pin, strength + a + b)
return max(map(next, compatible_segments))
def longest(to_assign, pins_to_match, strength, length):
def matches(segment):
a,b = segment
return a == pins_to_match or b == pins_to_match
compatible_segments = [s for s in to_assign if matches(s)]
if(len(compatible_segments) == 0):
return (strength, length)
def next(segment):
a,b = segment
left_to_assign = [s for s in to_assign if s != segment]
next_pin = a if a != pins_to_match else b
return longest(left_to_assign, next_pin, strength + a + b, length + 1)
max_strenght = 0
max_length = 0
for s, l in map(next, compatible_segments):
if l > max_length:
max_length = l
max_strenght = s
elif l == max_length:
max_strenght = max(max_strenght, s)
return (max_strenght, max_length)
def parse(line):
tokens = line.split("/")
return (int(tokens[0]), int(tokens[1]))
with open("input.txt") as f:
input = list(map(parse, f.readlines()))
print(strongest(input, 0, 0))
print(longest(input, 0, 0, 0))
|
# API messages
MATCH_DOES_NOT_EXIST_ERROR = "Match does not exist"
MATCH_WAS_NOT_FOUND_ERROR = "Match was not found"
MORE_THAN_ONE_MATCH_FOUND_ERROR = "More than one match was found to be similar. Try to increase similarity threshold"
BET_DOES_NOT_EXIST_ERROR = "Bet does not exist" |
all_attentions_list = []
for model_name, attentions4players in best_attentions_dict.items():
for player_id, attentions4player in attentions4players.items():
all_attentions_list = all_attentions_list + [attentions4player]#.reshape(15, 1)
# mean_att = np.mean(attention_sum_list_dict['30_300_16_32_2_1_3_prefinal'], axis=0)
mean_att = np.mean(all_attentions_list[::], axis=0)
index_order = np.argsort(mean_att)
mean_att = np.median(all_attentions_list[::], axis=0)
index_order = np.argsort(mean_att)
color_att = 'olivedrab'
color_att = 'olive'
color_att = 'darkslategrey'
color_att = 'darkcyan'
margin = 0.018
fontsize = 14
plt.close()
plt.figure(figsize=(8, 5))
y_ticks = list(range(len(index_order)))
plt.barh(y_ticks, mean_att[index_order], color=color_att)
plt.xlim((mean_att.min() - margin, mean_att.max() + margin * 0.7))
plt.yticks(y_ticks, np.array(features_pretty)[index_order], fontsize=fontsize)
plt.xlabel('Mean Attention', fontsize=fontsize+3)
plt.title('Feature Importance', fontsize=fontsize+6)
plt.tight_layout()
plt.savefig('pic/attention_importance_v0.png')
plt.interactive(True)
plt.barh(mean_att[index_order], np.array(features_pretty)[index_order])
# for time_step in [5, 10, 20, 30, 40, 60, 120]:
# command = f'python TimeseriesFinalPreprocessing.py --TIMESTEP {time_step}'
# os.system(command)
# print('Done')
#
|
class VggFaceDetector(object):
"""
preform prediction
"""
def __init__(self, model):
super().__init__()
self.model = model
def make_prediction(self, data):
image = data['image']
bbox = self.model.detect_faces(image)
data.update({'predictions': bbox})
return data
|
def mult(x, y):
result_mult = 0
i = 0
while i < y: # Here I choose 'y' (witch is the base) to show how many times 'x' going to be sum with itself.
i += 1
result_mult += x
return result_mult
def expo():
base = int(input("Type a base: "))
expo = int(input("Type an exponent: "))
if base < 0 or 0 > expo:
print("Don't type any negative value, please try again.")
else:
result_expo = 1
if expo == 0: # If the exponent is equal 0 the result number going to be '1'.
print(f"{base} ^ {expo} = {result_expo}".format(base,expo,result_expo))
else:
i = 0
while i < expo:
i += 1
result_expo = mult(result_expo, base) # result_expo is being multiplied by the base, it's the same thing as ( result_expo * base )
print(f"{base} ^ {expo} = {result_expo}".format(base,expo,result_expo))
expo()
|
#8 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 = int(input("Quanto você ganha por hora?: "));
Horas = int(input("Quantas horas você trabalha no mês?: "));
SalarioMensal = Salario * Horas;
print("Seu salario mensal é {}".format(SalarioMensal)); |
# -*- coding: utf-8 -*-
class JsonerException(Exception):
"""
Base Exception class
"""
pass
class JsonEncodingError(JsonerException):
"""
This error occurs if *Jsoner* cannot encode your object to json.
"""
|
"""
以下列出了 Python 网络编程的一些重要模块:
协议 功能用处 端口号 Python 模块
HTTP 网页访问 80 httplib, urllib, xmlrpclib
NNTP 阅读和张贴新闻文章,俗称为"帖子" 119 nntplib
FTP 文件传输 20 ftplib, urllib
SMTP 发送邮件 25 smtplib
POP3 接收邮件 110 poplib
IMAP4 获取邮件 143 imaplib
Telnet 命令行 23 telnetlib
Gopher 信息查找 70 gopherlib, urllib
""" |
# -*- coding: utf-8 -*-
'''
File name: code\linear_combinations_of_semiprimes\sol_278.py
Author: Vaidic Joshi
Date created: Oct 20, 2018
Python Version: 3.x
'''
# Solution to Project Euler Problem #278 :: Linear Combinations of Semiprimes
#
# For more information see:
# https://projecteuler.net/problem=278
# Problem Statement
'''
Given the values of integers 1 < a1 < a2 <... < an, consider the linear combinationq1a1 + q2a2 + ... + qnan = b, using only integer values qk ≥ 0.
Note that for a given set of ak, it may be that not all values of b are possible.
For instance, if a1 = 5 and a2 = 7, there are no q1 ≥ 0 and q2 ≥ 0 such that b could be
1, 2, 3, 4, 6, 8, 9, 11, 13, 16, 18 or 23.
In fact, 23 is the largest impossible value of b for a1 = 5 and a2 = 7. We therefore call f(5, 7) = 23. Similarly, it can be shown that f(6, 10, 15)=29 and f(14, 22, 77) = 195.
Find ∑ f(p*q,p*r,q*r), where p, q and r are prime numbers and p < q < r < 5000.
'''
# Solution
# Solution Approach
'''
'''
|
def magicalWell(a, b, n):
total = 0
for i in range(n):
total += a * b
a += 1
b += 1
return total
|
#!/usr/bin/env python
# -- Content-Encoding: UTF-8 --
"""
COHORTE Repositories of bundles and component factories
:author: Thomas Calmant
:license: Apache Software License 2.0
..
Copyright 2014 isandlaTech
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 writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
"""
# Documentation strings format
__docformat__ = "restructuredtext en"
# ------------------------------------------------------------------------------
SERVICE_REPOSITORY_ARTIFACTS = "cohorte.repositories.artifacts"
""" Specification of a repository of artifacts """
SERVICE_REPOSITORY_FACTORIES = "cohorte.repositories.factories"
""" Specification of a repository of component factories """
PROP_REPOSITORY_LANGUAGE = "cohorte.repository.language"
""" Language of implementation of the artifacts handled by the repository """
PROP_FACTORY_MODEL = "cohorte.repository.factory.model"
""" Name of the component model handling the factories """
|
"""
This Bazel extension contains the set of rule definitions to deal with generic IO.
"""
def _print_files_impl(ctx):
"""
An executable rule to print to the terminal the files passed via the 'srcs' property.
"""
executable = ctx.actions.declare_file(ctx.attr.name)
contents = "cat {}".format(" ".join([src.short_path for src in ctx.files.srcs]))
ctx.actions.write(executable, contents, is_executable = True)
return [DefaultInfo(
executable = executable,
runfiles = ctx.runfiles(files = ctx.files.srcs),
)]
print_files = rule(
implementation = _print_files_impl,
attrs = {
"srcs": attr.label_list(
allow_files = True,
doc = "The list of files to be printed to the terminal",
),
},
executable = True,
)
|
# n is not required in this program
# to meet the requirements of STDIN of hackerrank we are using n variable
def soln(a, scores):
scores = sorted(list(dict.fromkeys(scores)))
print(scores[-2])
if __name__ == "__main__":
n = int(input())
arr = map(int, input().split())
soln(n, arr)
|
# Copyright (c) 2020. Brendan Johnson. All Rights Reserved.
#import connect
#import config
class ReportTemplates:
def __init__(self, config, connection):
self._config=config
self._connection = connection
##EventBasedTasks
def list(self):
return self._connection.get(url='/reporttemplates')
def search(self, payload):
return self._connection.post(url='/reporttemplates/search', data=payload)
def describe(self, reportID):
return self._connection.get(url='/reporttemplates/{reportTemplateID}'.format(reportTemplateID=reportID))
|
frase = input('Informe uma frase para ver se é palíndromo: ').strip().lower()
frasejunta = frase.split()
frasejunta = ''.join(frasejunta)
novafrase = frasejunta[::-1]
print(f'O inverso de {frasejunta} é {novafrase}')
if frasejunta == novafrase:
print(f'A frase informada é um palíndromo.')
else:
print(f'A frase informada não é um palindromo.')
|
print ('GERADOR DE PA')
print ('-='*20)
n = int(input ('DIGITE UM NUMERO: '))
p = int(input ('DIGITE A RAZÃO DA PA: '))
c = 1
t = n
mais = 10
total = 0
while mais != 0:
total = total + mais
while c <= total:
c = c + 1
t = t + p
print ('{} - '.format (t), end = '')
print ('PAUSA')
mais = int (input ('QUANTOS TERMOS VOCÊ QUER A MAIS? '))
print ('TOTAL FINALIZADA COM {} TERMOS MOSTRADOS'.format (total)) |
#!/usr/bin/env python
def clamp(low, x, high):
return low if x < low else high if x > high else x
def unwrap(txt):
return ' '.join(( s.strip() for s in txt.strip().splitlines() ))
|
class Package:
"""
Data structure for repo packages.
Attributes:
name (str): The name of the package.
version (str): Version number of the package.
size (int): Size of the package.
depends (list): List of dependent package identifiers (conjunct of disjuncts).
conflicts (list): List of conflicting package identifers (conjuncts).
id (str): The ID of the package.
"""
def __init__(self, name, version, size, depends, conflicts):
self.name = name
self.version = version
self.size = size
self.depends = depends
self.conflicts = conflicts
self.id = "{}={}".format(name, version)
def __str__(self):
return self.__repr__()
def __repr__(self):
res = "Package(name={}, version={}, size={}, depends={}, conflicts={})".format(
self.name,
self.version,
self.size,
self.depends,
self.conflicts
)
return res
def within_range(self, op, version_id):
"""Given a version identifier and comparison operation returns True if own version
is within the given range otherwise False."""
if op == None or version_id == None:
return True
elif op == "<=":
if self.compare_version(version_id) in [0, -1]:
return True
elif op == ">=":
if self.compare_version(version_id) in [1, 0]:
return True
elif op == "<":
if self.compare_version(version_id) == -1:
return True
elif op == ">":
if self.compare_version(version_id) == 1:
return True
elif op == "=":
if self.compare_version(version_id) == 0:
return True
return False
def compare_version(self, comparison):
"""Compares own version against paramater provided.
If own version is greater returns '1', if versions are the same '0' and '-1' if lower."""
# Split the two versions into integer lists
# of equal length.
v = [int(item) for item in self.version.split('.')]
c = [int(item) for item in comparison.split('.')]
length = len(v) if len(v) > len(c) else len(c)
v = (v + length * [0])[:length]
c = (c + length * [0])[:length]
# Iterate over lists comparing values.
for i in range(length):
if v[i] == c[i]:
continue
elif v[i] < c[i]:
return -1
elif v[i] > c[i]:
return 1
return 0 |
"""
Ejercicio 1
- Crear dos variables: pais y continente
- Mostrar el valor por pantalla
- Poner comentario indicando tipo de dato
"""
pais = "España" # string
continente = "Europa" # String
print(f"La variable pais contiene: {pais} y es del tipo: ", type(pais ))
print(f"La variable continente contiene: {continente} y es del tipo: ", type(continente )) |
# Zbór zadań A - zadanie 3
# Napisz program liczący silnie rekurencyjnie
# autor : Rafał D.
def silnia(n):
if n > 1:
return n*silnia(n-1)
else:
return 1
print('Program zwraca silnie podanej liczby rekurencyjnie \n')
print('Podaj liczbę dla której chcesz obliczyć silnie: ')
liczba = int(input())
wynik = silnia(liczba)
print(wynik) |
def get_detail(param: str, field: str, message: str, err: str):
detail = [
{
'loc': [
f'{param}', # ex. body
f'{field}' # ex. title
],
"msg": message, # ex. field required, not found
"type": f"{err}.missing" # ex. value_error
}
]
return detail
class InternalException(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message
class NoSuchElementException(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message
class InvalidArgumentException(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message
class RequestConflictException(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message
class ForbiddenException(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message
class RequestInvalidException(Exception):
def __init__(self, message: str):
self.message = message
def __str__(self):
return self.message |
""" Day 07 of the 2021 Advent of Code
https://adventofcode.com/2021/day/7
https://adventofcode.com/2021/day/7/input """
def load_data(path):
data_list = []
with open(path, "r") as file:
for line in file:
data_list = data_list + [int(value.strip()) for value in line.split(",")]
return data_list
def calculate_crab_fuel_needs(data, fuelcomsumption_increases=False):
solution = -1
for target in range(max(data)):
local_score = 0
for start in data:
steps = abs(target - start)
if not fuelcomsumption_increases:
# part 1
local_score = local_score + steps
else:
# part 2
local_score = local_score + sum(list(range(steps + 1)))
# early skip if local score is escalating the pan out
# saves 35s on excecutiontime when solving part 2
if local_score > solution and solution != -1:
break
if local_score < solution or solution == -1:
solution = local_score
return solution
def main():
data = load_data("..//Data//Prod.txt")
data_test = load_data("..//Data//Test.txt")
assert calculate_crab_fuel_needs(data_test, False) == 37
assert calculate_crab_fuel_needs(data, False) == 357353
assert calculate_crab_fuel_needs(data_test, True) == 168
assert calculate_crab_fuel_needs(data, True) == 104822130
if __name__ == "__main__":
main()
|
#!/bin/python3
def poisonousPlants(p):
# Complete this function
survives = list()
survives.append(p[0])
dies = list()
num_plants = len(p)
p_killed = [0]*num_plants
killed_day = [0]*num_plants
for i in range(1,num_plants):
if(p[i] > p[i - 1]):
if(p_killed[i - 1] == 1):
if(survives[-1] < p[i] and dies[-1] < p[i]):
killed_day[i] = killed_day[i-1]
elif(survives[-1] < p[i] and dies[-1] > p[i]):
killed_day[i] = 1 + killed_day[i-1]
dies.append(p[i])
p_killed[i] = 1
else:
#survives.append(p[i])
dies.append(p[i])
p_killed[i] = 1
killed_day[i] = 1
elif(p[i] < p[i - 1]):
if(p_killed[i-1] == 1 and (p[i] > survives[-1] or p[i] > dies[-1])):
killed_day[i] = 1 + killed_day[i-1]
dies.append(p[i])
p_killed[i] = 1
else:
survives.append(p[i])
else:
if(p_killed[i-1] == 1):
p_killed[i] = 1
killed_day = killed_day[i-1]
dies.append(p[i])
else:
survives.append(p[i])
days = max(killed_day)
return days
if __name__ == "__main__":
n = int(input().strip())
p = list(map(int, input().strip().split(' ')))
result = poisonousPlants(p)
print(result) |
class FailureDefinitionAccessor(object, IDisposable):
""" A class that provides access to the details of a FailureDefinition after the definition has been defined. """
def Dispose(self):
""" Dispose(self: FailureDefinitionAccessor) """
pass
def GetApplicableResolutionTypes(self):
"""
GetApplicableResolutionTypes(self: FailureDefinitionAccessor) -> IList[FailureResolutionType]
Retrieves a list of resolution types applicable to the failure.
Returns: The list of resolution types applicable to the failure.
"""
pass
def GetDefaultResolutionType(self):
"""
GetDefaultResolutionType(self: FailureDefinitionAccessor) -> FailureResolutionType
Retrieves the default resolution type for the failure.
Returns: The default resolution type for the failure.
"""
pass
def GetDescriptionText(self):
"""
GetDescriptionText(self: FailureDefinitionAccessor) -> str
Retrieves the description text of the failure.
Returns: The description text.
"""
pass
def GetId(self):
"""
GetId(self: FailureDefinitionAccessor) -> FailureDefinitionId
Retrieves the unique identifier of the FailureDefinition.
Returns: The unique identifier of the FailureDefinition.
"""
pass
def GetResolutionCaption(self, type):
"""
GetResolutionCaption(self: FailureDefinitionAccessor,type: FailureResolutionType) -> str
Retrieves the caption for a specific resolution type.
type: The resolution type.
Returns: The caption of the resolution.
"""
pass
def GetSeverity(self):
"""
GetSeverity(self: FailureDefinitionAccessor) -> FailureSeverity
Retrieves severity of the failure.
Returns: The severity of the failure.
"""
pass
def HasResolutions(self):
"""
HasResolutions(self: FailureDefinitionAccessor) -> bool
Checks if the FailureDefinition has at least one resolution.
Returns: True if at least one resolution is defined in the FailureDefinition.
"""
pass
def IsResolutionApplicable(self, type):
"""
IsResolutionApplicable(self: FailureDefinitionAccessor,type: FailureResolutionType) -> bool
Checks if the given resolution type is applicable to the failure.
type: The resolution type to check.
Returns: True if the given resolution type is applicable to the failure,false otherwise.
"""
pass
def ReleaseUnmanagedResources(self, *args):
""" ReleaseUnmanagedResources(self: FailureDefinitionAccessor,disposing: bool) """
pass
def SetDefaultResolutionType(self, type):
"""
SetDefaultResolutionType(self: FailureDefinitionAccessor,type: FailureResolutionType)
Sets the default resolution type for the failure.
type: The type of resolution to be used as default.
"""
pass
def __enter__(self, *args):
""" __enter__(self: IDisposable) -> object """
pass
def __exit__(self, *args):
""" __exit__(self: IDisposable,exc_type: object,exc_value: object,exc_back: object) """
pass
def __init__(self, *args):
""" x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """
pass
def __repr__(self, *args):
""" __repr__(self: object) -> str """
pass
IsValidObject = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""Specifies whether the .NET object represents a valid Revit entity.
Get: IsValidObject(self: FailureDefinitionAccessor) -> bool
"""
|
def least_rotation(s):
s += s
i, ans = 0, 0
while 2*i < len(s):
ans = i
j, k = i + 1, i
while (2*j < len(s)) and (s[k] <= s[j]):
if s[k] < s[j]:
k = i
else:
k += 1
j += 1
while i <= k:
i += j - k
return s[ans:ans + (len(s) // 2)]
|
'''
Title : Check Strict Superset
Subdomain : Sets
Domain : Python
Author : codeperfectplus
Created : 17 January 2020
'''
a = set(map(int, input().split()))
f = 0
for i in range(int(input())):
b = set(map(int, input().split()))
if len(b.difference(a)) != 0:
f = 1
else:
if len(b) == len(a):
f =1
if f == 0:
print('True')
else:
print('False') |
def fizzbuzz(x):
if x%3==0:
if x%5!=0:
return("Fizz")
elif x%5==0:
return("FizzBuzz")
elif x%5==0:
if x%3!=0:
return("Buzz")
else:
return(x)
a= int(input(" Digite um número: "))
w=fizzbuzz(a)
print(w) |
'''
Methods for parsing chromosomic data
'''
def load_breaks(file_location, only_tra=False):
"""
Reads a file, storing the breaks in a dictionary.
Input:
file_location: full path to file, containing breaks in a genome
Output:
breaks_by_chromosome: dictionary {str:[int]}, where keys are chromosome ids
and the corresponding non-empty list contains the breaks in that chromosome (sorted).
list_of_pairs: list[((str,int),(str,int))]. List of breaks, each entry contains
first chromosome and position within, second chromosome and position within.
"""
breaks_by_chromosome = {}
list_of_pairs = []
# Process file by file
with open(file_location) as f:
# Skip the first line, which is a descriptor of fields
f.next()
# Read break by break
for l in f:
if len(l.split('\t')) != 5:
raise Exception("Wrong number of fields (i.e., not 5) in line", l)
chromosome1, chromosome1_pos, chromosome2, chromosome2_pos, break_type = l.split('\t')
if only_tra:
if 'TRA' in break_type:
chromosome1_pos = int(chromosome1_pos)
chromosome2_pos = int(chromosome2_pos)
# If its the first break found in this chromosome, initialize the chromosome list
if chromosome1 not in breaks_by_chromosome.keys():
breaks_by_chromosome[chromosome1] = [chromosome1_pos]
# Otherwise add it to the end
else:
breaks_by_chromosome[chromosome1].append(chromosome1_pos)
# The same for the second chromosome
if chromosome2 not in breaks_by_chromosome.keys():
breaks_by_chromosome[chromosome2] = [chromosome2_pos]
else:
breaks_by_chromosome[chromosome2].append(chromosome2_pos)
# Also update the list of pairs
list_of_pairs.append(((chromosome1, chromosome1_pos),
(chromosome2, chromosome2_pos)))
else:
chromosome1_pos = int(chromosome1_pos)
chromosome2_pos = int(chromosome2_pos)
# If its the first break found in this chromosome, initialize the chromosome list
if chromosome1 not in breaks_by_chromosome.keys():
breaks_by_chromosome[chromosome1] = [chromosome1_pos]
# Otherwise add it to the end
else:
breaks_by_chromosome[chromosome1].append(chromosome1_pos)
# The same for the second chromosome
if chromosome2 not in breaks_by_chromosome.keys():
breaks_by_chromosome[chromosome2] = [chromosome2_pos]
else:
breaks_by_chromosome[chromosome2].append(chromosome2_pos)
# Also update the list of pairs
list_of_pairs.append(((chromosome1, chromosome1_pos),
(chromosome2, chromosome2_pos)))
# Sort the lists
for k in breaks_by_chromosome.keys():
breaks_by_chromosome[k] = sorted(breaks_by_chromosome[k], key=int)
return breaks_by_chromosome, list_of_pairs
|
# change when building to switch the app to another language
SELECTED_LANG = "jp"
LANGS:list = [
"en", # english
"tr", # turkish
"jp", # japanese
]
LANG_DB:dict = {
"en":[
"6-Digit Code",
"Save Directory",
"Change Directory",
"Fetching...",
"Downloading...",
"Finished!",
"Idling...",
"DL",
"ERROR"
],
"tr":[
"6-Digit kod",
"kayıt dosyası",
"dosyayı değiştir",
"Data alınıyor",
"Indiriyor",
"Biti",
"rölanti",
"DL",
"Hatta",
"Kurmayı başlatın"
],
"jp":[
"コード/六桁コード",
"SAVE FOLDER",
"CHANGE FOLDER",
"フェッチ",
"ダウンロード",
"終了",
"アイドル",
"DL",
"エラー"
],
}
|
# -*- coding: UTF-8 -*-
class Solution:
def findMedianSortedArrays(self, nums1, nums2):
"""
:type nums1: list
:type nums2: list
:rtype : float
"""
# may be wrong
new_nums = sorted(nums1 + nums2)
new_nums_len = len(new_nums)
if new_nums_len % 2 == 0:
return (new_nums[new_nums_len//2-1] + new_nums[new_nums_len//2]) / 2
else:
return new_nums[(new_nums_len)//2]
def main():
nums1 = [1, 3]
nums2 = [2]
result = Solution().findMedianSortedArrays(nums1, nums2)
print(str("%.1f" % result))
if __name__ == '__main__':
main() |
print("I will now count my chickens:") #presents the question
print("Hens", 25 + 30 / 6) #counts the Hens
print("Roosters", 100 - 25 * 3 % 4) #counts the Roosters
print("Now I will count the eggs:") #presents another question
print(3 + 2 + 1 - 5 + 4 % 2 - 1 / 4 + 6) #counts the eggs
print("Is it true that 3 + 2 < 5 - 7?") #shows False bevcause this is False
print(3 + 2 < 5 - 7) #counts
print("What is 3 + 2?", 3 + 2) #counts
print("What is 5 - 7?", 5 - 7) #counts
print("Oh, that's why it's False.") #explains why false
print("How about some more.") #presents more
print("Is it greater?", 5 > -2) #shows true because this is true
print("Is it greater or equal?", 5 >= -2) #shows true because this is true
print("Is it less or equal?", 5 <= -2) #shows false because this is false
|
# -*- coding=utf-8 -*-
'''
'''
class Solution(object):
def dailyTemperatures(self, temperatures):
"""
:type temperatures: List[int]
:rtype: List[int]
"""
length=len(temperatures)
result=[i for i in range(0,length)]
for i in range(0,length):
i=length-i-1
if i==length-1:
result[i]=0
continue
return result
temperatures=[73, 74, 75, 71, 69, 72, 76, 73]
A=Solution()
A.dailyTemperatures(temperatures) |
n_lines = int(input("How many lines? "))
counter = 1
while n_lines >= counter:
print("This is line " + str(counter))
counter += 1
# print("This is line " + str(counter))
print()
input("Press return to continue ...")
|
'''
Token class that will hold each encountered lexeme, its associated token type (e.g. TokenType.PLUS), the line number in the file where it was found as well as the actual literal value.
Note that the "literal" argument in most cases when we're creating Tokens will be empty. The only times we will care about the "literal" argument is when we need to extract the actual numeric or string value of our lexeme
'''
class Token:
def __init__(self, token_type, lexeme: str, line : int, literal=""):
self.token_type = token_type
self.lexeme = lexeme
self.line = line
self.literal = literal
def __str__(self):
return str(self.token_type.name + " " + self.lexeme + " " + str(self.literal))
|
def lonelyinteger(nums):
for i in range(len(nums)):
if nums.count(nums[i]) == 1:
return nums[i]
if __name__ == '__main__':
a = input()
nums = map(int, raw_input().strip().split(" "))
print(lonelyinteger(nums))
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
@author: Pieter Huycke
email: pieter.huycke@ugent.be
GitHub: phuycke
"""
#%%
def mirror(pair):
if type(pair) != list and \
type(pair) != str and \
type(pair) != tuple:
raise ValueError("Wrong type.\nPlease provide a str, list or set.")
assert len(pair) >= 2
return pair[0], pair[-1]
#%%
print(mirror("test"))
print(mirror((1, 2, 3, 5)))
print(mirror(5)) |
#%%
"""
- Text Justification
- https://leetcode.com/problems/text-justification/
- Hard
"""
#%%
|
bins_met_px = {"in": "MET_px", "out": "met_px", "bins": dict(nbins=10, low=0, high=100)}
bins_py = {"in": "Jet_Py", "out": "py_leadJet", "bins": dict(edges=[0, 20., 100.], overflow=True), "index": 0}
bins_nmuon = {"in": "NMuon", "out": "nmuon"}
weight_list = ["EventWeight"]
weight_dict = dict(weighted="EventWeight")
|
mystr = 'TutorialsTeacher'
nums = [1,2,3,4,5,6,7,8,9,10]
portion1 = slice(9)
portion2 = slice(0, -2, None)
print('slice: ', portion1)
print('String value: ', mystr[portion1])
print('List value: ', nums[portion1])
print('slice: ', portion2)
print('String value: ', mystr[portion2])
print('List value: ', nums[portion2])
nums = [1,2,3,4,5,6,7,8,9,10]
odd_portion = slice(0, 10, 2)
print(nums[odd_portion])
even_portion = slice(1, 10, 2)
print(nums[even_portion]) |
"""
@created_at 2017-08-12
@author Exequiel Fuentes Lettura <efulet@gmail.com>
"""
|
inp = "inH.txt"
oup = "outH.txt"
spl = []
with open(inp, "r") as f:
spl = f.readlines()
with open(oup, "w") as f:
for s in spl:
text = "<tr>\n\t<td>\n"
text += "\t\t{0}\n".format(s[:4])
text += "\t</td>\n\t<td>\n"
text += "\t\t{0}\n".format(s[13:])
text += "\t</td>\n</tr>\n"
f.write(text)
"""
<tr>\n
\t<td>\n
\t\ttext\n
\t</td>\n
\t<td>\n
\t\ttext1\n
\t</td>\n
</tr>\n
""" |
class Guardian:
@staticmethod
def adjust_difficulty(original_difficulty: int, block_height: int):
return original_difficulty // 1000
# TODO: decide on the parameters for mainnet
# if block_height < 1000:
# return original_difficulty // 1000
# if block_height < 10000:
# return original_difficulty // 100
# if block_height < 100000:
# return original_difficulty // 10
# return original_difficulty
|
class RepresentMixin:
def __repr__(self):
return repr(self.to_dict())
def to_dict(self):
return {f: getattr(self, f) for f in self.non_empty_fields}
|
class Profile:
def __init__(self, name, age, xp, time_on_calls):
self.__name = name
self.__age = age
self.__xp = xp
self.__time_on_calls = time_on_calls
@property
def name(self):
return self.__name
@property
def age(self):
return self.__age
@property
def xp(self):
return self.__xp
@property
def level(self):
return self.__xp/1000
@property
def time_on_calls(self):
return self.__time_on_calls
|
larg = float(input('Digite a largura da parede: '))
alt = float(input('Digite a altura da parede: '))
area = (larg*alt)
tinta = area/2
print('Sua parede tem a dimensão de {}x{} e sua area é {}m²'.format(larg, alt, area))
print('Para pintar esta parede será necessário {}l de tinta'. format(tinta))
|
class Solution:
def memLeak(self, memory1: int, memory2: int):
count = 1
while count <= memory1 or count <= memory2:
if memory1 < memory2:
memory2 -= count
else:
memory1 -= count
count += 1
return [count, memory1, memory2]
if __name__ == '__main__':
s = Solution()
r = s.memLeak(8,10)
print(r) |
def main():
# input
N, M = map(int, input().split())
As = list(map(int, input().split()))
Bs = list(map(int, input().split()))
# compute
numbers = [0] * (10**3+5)
for i in As:
numbers[i] += 1
for i in Bs:
numbers[i] += 1
anss = []
for i, figure in enumerate(numbers):
if figure == 1:
anss.append(i)
# output
print(*anss)
if __name__ == '__main__':
main()
|
# ELEVSTRS
for i in range(int(input())):
n,v1,v2=map(int,input().split())
time=[]
ele=2*n/v2
st=n*(2**(1/2))/v1
if(ele>st):print("Stairs")
else:print("Elevator") |
# The MIT License (MIT)
# Copyright (c) 2015 Brian Wray (brian@wrocket.org)
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.
# This script generates the square/piece score tables. Basically, tables that
# describe the "goodness" of a particular piece being on a particular square.
def write_row(scores):
return '\t' + ', '.join([str(x).rjust(4) for x in scores]) + ','
def add_row_border(ordered_rows):
border = [0] * 12
side = [0] * 2
result = [border, border]
for r in ordered_rows:
result.append(side + r + side)
result.append(border)
result.append(border)
return result
def make_12x12(white_version_map, perspective='white'):
result = []
key_list = list(white_version_map.keys())
if perspective == 'black':
key_list = reversed(key_list)
for k in key_list:
result.append(white_version_map[k])
result = add_row_border(result)
return result
def write_array(name, whiteVersion):
white_name = 'SQ_SCORE_%s_WHITE' % name.upper()
black_name = 'SQ_SCORE_%s_BLACK' % name.upper()
lines = []
lines.append('const int %s[144] = {' % white_name)
for row in make_12x12(whiteVersion, perspective='white'):
lines.append(write_row(row))
lines.append('};')
lines.append('')
lines.append('const int %s[144] = {' % black_name)
for row in make_12x12(whiteVersion, perspective='black'):
lines.append(write_row(row))
lines.append('};')
print('\n'.join(lines))
white_pawn_opening_scores = {
8: [0, 0, 0, 0, 0, 0, 0, 0],
7: [0, 0, 0, 0, 0, 0, 0, 0],
6: [0, 0, 0, 0, 0, 0, 0, 0],
5: [0, 0, 0, 15, 15, 0, 0, 0],
4: [0, 0, 8, 15, 15, 8, 0, 0],
3: [0, 0, 10, 10, 10, 10, 0, 0],
2: [0, 0, -5, -5, -5, -5, 0, 0],
1: [0, 0, 0, 0, 0, 0, 0, 0]
}
write_array('PAWN_OPENING', white_pawn_opening_scores)
white_knight_opening_scores = {
8: [0, 0, 0, 0, 0, 0, 0, 0],
7: [0, 0, 0, 0, 0, 0, 0, 0],
6: [0, 0, 0, 0, 0, 0, 0, 0],
5: [0, 0, 0, 0, 0, 0, 0, 0],
4: [0, 0, 0, 0, 0, 0, 0, 0],
3: [-10, 0, 10, 0, 0, 10, 0, -10],
2: [-10, 0, 0, 5, 0, 5, 0, -10],
1: [-20, -5, 0, 0, 0, 0, -5, -20]
}
write_array('KNIGHT_OPENING', white_knight_opening_scores)
white_queen_opening_scores = {
8: [-10, -10, -10, -10, -10, -10, -10, -10],
7: [-10, -10, -10, -10, -10, -10, -10, -10],
6: [-10, -10, -10, -10, -10, -10, -10, -10],
5: [-10, -10, -10, -10, -10, -10, -10, -10],
4: [-10, -10, -10, -10, -10, -10, -10, -10],
3: [-10, -10, -10, -10, -10, -10, -10, -10],
2: [0, 0, 0, 0, 0, 0, 0, 0],
1: [0, 0, 0, 0, 0, 0, 0, 0],
}
write_array('QUEEN_OPENING', white_queen_opening_scores)
|
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def swapPairs(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
newHead = None
left_node = None
cur = head
if cur is not None:
next_node = cur.next
while cur is not None and next_node is not None:
if left_node is not None:
left_node.next = next_node
else:
newHead = next_node
cur.next = next_node.next
next_node.next = cur
left_node = cur
cur = cur.next
if cur is not None:
next_node = cur.next
if newHead is None and cur is not None:
newHead = cur
return newHead
def main():
s = Solution()
one = ListNode(1)
two = ListNode(2)
three = ListNode(3)
four = ListNode(4)
one.next = two
two.next = three
three.next = four
new_head = s.swapPairs(one)
cur_node = new_head
while cur_node is not None:
print(cur_node.val)
cur_node = cur_node.next
if __name__ == '__main__':
main()
|
#
# PySNMP MIB module CISCO-DYNAMIC-PORT-VSAN-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-DYNAMIC-PORT-VSAN-MIB
# Produced by pysmi-0.3.4 at Wed May 1 11:56:27 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, 09:23:15)
#
Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "ConstraintsIntersection", "SingleValueConstraint")
CpsmActivateResult, CpsmDiffDb, CpsmDbActivate, CpsmDiffReason = mibBuilder.importSymbols("CISCO-PSM-MIB", "CpsmActivateResult", "CpsmDiffDb", "CpsmDbActivate", "CpsmDiffReason")
ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt")
VsanIndex, FcNameIdOrZero, FcNameId = mibBuilder.importSymbols("CISCO-ST-TC", "VsanIndex", "FcNameIdOrZero", "FcNameId")
ifIndex, = mibBuilder.importSymbols("IF-MIB", "ifIndex")
NotificationGroup, ModuleCompliance, ObjectGroup = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance", "ObjectGroup")
TimeTicks, Counter32, Gauge32, MibIdentifier, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Unsigned32, iso, Counter64, ModuleIdentity, Bits, Integer32, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Counter32", "Gauge32", "MibIdentifier", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Unsigned32", "iso", "Counter64", "ModuleIdentity", "Bits", "Integer32", "NotificationType")
RowStatus, TextualConvention, DisplayString, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TextualConvention", "DisplayString", "TruthValue")
ciscoDpvmMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 421))
ciscoDpvmMIB.setRevisions(('2004-06-22 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: ciscoDpvmMIB.setRevisionsDescriptions(('Initial version of this MIB.',))
if mibBuilder.loadTexts: ciscoDpvmMIB.setLastUpdated('200406220000Z')
if mibBuilder.loadTexts: ciscoDpvmMIB.setOrganization('Cisco Systems Inc.')
if mibBuilder.loadTexts: ciscoDpvmMIB.setContactInfo(' Cisco Systems Customer Service Postal: 170 W Tasman Drive San Jose, CA 95134 USA Tel: +1 800 553-NETS E-mail: cs-san@cisco.com')
if mibBuilder.loadTexts: ciscoDpvmMIB.setDescription('The MIB module for the management of the Dynamic Port Vsan Membership (DPVM) module. DPVM provides the ability to assign (virtual storage area network) VSAN IDs dynamically to switch ports based on the device logging in on the port. The logging-in device can be identified by its port World Wide Name (pWWN) and/or its node World Wide Name (nWWN).')
ciscoDpvmMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 421, 0))
ciscoDpvmMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 421, 1))
ciscoDpvmMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 421, 2))
cdpvmConfiguration = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1))
class CdpvmDevType(TextualConvention, Integer32):
description = 'Represents the type of device. pwwn(1) - Represents the port WWN of the device. nwwn(2) - Represents the node WWN of the device.'
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2))
namedValues = NamedValues(("pwwn", 1), ("nwwn", 2))
cdpvmNextAvailIndex = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 16384))).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmNextAvailIndex.setStatus('current')
if mibBuilder.loadTexts: cdpvmNextAvailIndex.setDescription('This object contains an appropriate value to be used for cdpvmIndex when creating entries in the cdpvmTable. The value 0 indicates that all entries are assigned. A management application should read this object, get the (non-zero) value and use same for creating an entry in the cdpvmTable. After each retrieval and use, the agent should modify the value to the next unassigned index. After a manager retrieves a value the agent will determine through its local policy when this index value will be made available for reuse. A suggested mechanism is to make an index available when the corresponding entry is deleted.')
cdpvmTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2), )
if mibBuilder.loadTexts: cdpvmTable.setStatus('current')
if mibBuilder.loadTexts: cdpvmTable.setDescription("This table contains the set of all valid bindings of devices to VSANs configured on the local device. A valid binding consists of a pWWN/nWWN bound to a VSAN. If a device is bound to a VSAN, then when that device logs in through a port on the local device, that port is assigned the configured VSAN. Such a VSAN is called a 'dynamic' VSAN. The set of valid bindings configured in this table should be activated by means of the cdpvmActivate object. When activated, these bindings are enforced and all subsequent logins will be subject to these bindings.")
cdpvmEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2, 1), ).setIndexNames((0, "CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmIndex"))
if mibBuilder.loadTexts: cdpvmEntry.setStatus('current')
if mibBuilder.loadTexts: cdpvmEntry.setDescription('An entry (conceptual row) in this table. Each entry contains the mapping between a device and its dynamic VSAN.')
cdpvmIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 16384)))
if mibBuilder.loadTexts: cdpvmIndex.setStatus('current')
if mibBuilder.loadTexts: cdpvmIndex.setDescription('Identifies a binding between a device and its dynamic VSAN.')
cdpvmLoginDevType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2, 1, 2), CdpvmDevType().clone('pwwn')).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cdpvmLoginDevType.setStatus('current')
if mibBuilder.loadTexts: cdpvmLoginDevType.setDescription('Specifies the type of the corresponding instance of cdpvmLoginDev object.')
cdpvmLoginDev = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2, 1, 3), FcNameId()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cdpvmLoginDev.setStatus('current')
if mibBuilder.loadTexts: cdpvmLoginDev.setDescription("Represents the logging-in device. If the value of the corresponding instance of cdpvmLoginDevType is 'pwwn', then this object contains a pWWN. If the value of the corresponding instance of cdpvmLoginDevType is 'nwwn', then this object contains a nWWN. This object MUST be set to a valid value before or concurrently with setting the corresponding instance of cdpvmRowStatus to 'active'. The agent should not allow creation of 2 entries in this table with same values for cdpvmLoginDev and cdpvmLoginDevVsan.")
cdpvmLoginDevVsan = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2, 1, 4), VsanIndex().clone(1)).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cdpvmLoginDevVsan.setStatus('current')
if mibBuilder.loadTexts: cdpvmLoginDevVsan.setDescription('Represents the VSAN to be associated to the port on the local device on which the device represented by cdpvmLoginDev logs in.')
cdpvmRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 2, 1, 5), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: cdpvmRowStatus.setStatus('current')
if mibBuilder.loadTexts: cdpvmRowStatus.setDescription("The status of this conceptual row. Before setting this object to 'active', the cdpvmLoginDev object MUST be set to a valid value. Only cdpvmLoginDevVsan object can be modified when the value of this object is 'active'.")
cdpvmActivate = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 3), CpsmDbActivate()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cdpvmActivate.setStatus('current')
if mibBuilder.loadTexts: cdpvmActivate.setDescription("This object helps in activating the set of bindings in the cdpvmTable. Setting this object to 'activate(1)' will result in the valid bindings present in cdpvmTable being activated and copied to the cpdvmEnfTable. By default auto learn will be turned 'on' after activation. Before activation is attempted, it should be turned 'off'. Setting this object to 'forceActivate(3)', will result in forced activation, even if there are errors during activation and the activated bindings will be copied to the cdpvmEnfTable. Setting this object to 'deactivate(5)', will result in deactivation of currently activated valid bindings (if any). Currently active entries (if any), which would have been present in the cdpvmEnfTable, will be removed. Setting this object to 'activateWithAutoLearnOff(2)' and 'forceActivateWithAutoLearnOff(4)' is not allowed. Setting this object to 'noop(6)', results in no action. The value of this object when read is always 'noop(6)'. Activation will not be allowed if auto-learn is enabled.")
cdpvmActivateResult = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 4), CpsmActivateResult()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmActivateResult.setStatus('current')
if mibBuilder.loadTexts: cdpvmActivateResult.setDescription('This object indicates the outcome of the activation.')
cdpvmAutoLearn = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 5), TruthValue()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cdpvmAutoLearn.setStatus('current')
if mibBuilder.loadTexts: cdpvmAutoLearn.setDescription("This object helps to 'learn' the configuration of devices logged into the local device on all its ports and the VSANs to which they are associated. This information will be populated in the the enforced binding table (cdpvmEnfTable). This mechanism of 'learning' the configuration of devices and their VSAN association over a period of time and populating the configuration is a convenience mechanism for users. If this object is set to 'true(1)' all subsequent logins and their VSAN association will be populated in the enforced binding database, provided it is not in conflict with existing enforced bindings. When this object is set to 'false(2)', the mechanism of learning is stopped. The learned entries will however be in the enforced binding database.")
cdpvmCopyEnfToConfig = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("copy", 1), ("noop", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cdpvmCopyEnfToConfig.setStatus('current')
if mibBuilder.loadTexts: cdpvmCopyEnfToConfig.setDescription("This object when set to 'copy(1)', results in the active (enforced) binding database to be copied on to the configuration binding database. Note that the learned entries are also copied. No action is taken if this object is set to 'noop(2)'. The value of this object when read is always 'noop'.")
cdpvmEnfTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7), )
if mibBuilder.loadTexts: cdpvmEnfTable.setStatus('current')
if mibBuilder.loadTexts: cdpvmEnfTable.setDescription('This table contains information on all currently enforced bindings on the local device. The enforced set of bindings is the set of valid bindings copied from the configuration binding database (cdpvmTable) at the time they were activated. These entries cannot be modified. The learnt entries are also a part of this table. Entries can get into this table or be deleted from this table only by means of explicit activation/deactivation. Note that this table will be empty when no valid bindings have been activated.')
cdpvmEnfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7, 1), ).setIndexNames((0, "CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmEnfIndex"))
if mibBuilder.loadTexts: cdpvmEnfEntry.setStatus('current')
if mibBuilder.loadTexts: cdpvmEnfEntry.setDescription('An entry (conceptual row) in this table.')
cdpvmEnfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 16384)))
if mibBuilder.loadTexts: cdpvmEnfIndex.setStatus('current')
if mibBuilder.loadTexts: cdpvmEnfIndex.setDescription('The index of this entry.')
cdpvmEnfLoginDevType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7, 1, 2), CdpvmDevType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmEnfLoginDevType.setStatus('current')
if mibBuilder.loadTexts: cdpvmEnfLoginDevType.setDescription('Specifies the type of the corresponding instance of cdpvmEnfLoginDev.')
cdpvmEnfLoginDev = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7, 1, 3), FcNameId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmEnfLoginDev.setStatus('current')
if mibBuilder.loadTexts: cdpvmEnfLoginDev.setDescription('This object represents the logging in device address. This object was copied from the cdpvmLoginDev object in the cdpvmTable at the time when the currently active bindings were activated.')
cdpvmEnfLoginDevVsan = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7, 1, 4), VsanIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmEnfLoginDevVsan.setStatus('current')
if mibBuilder.loadTexts: cdpvmEnfLoginDevVsan.setDescription("This object represents the VSAN of the port on the local device thru' which the device represented by cdpvmEnfLoginDev logs in. This object was copied from the cdpvmLoginDevVsan object in the cdpvmTable at the time when the currently active bindings were activated")
cdpvmEnfIsLearnt = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 7, 1, 5), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmEnfIsLearnt.setStatus('current')
if mibBuilder.loadTexts: cdpvmEnfIsLearnt.setDescription("This object indicates if this is a learnt entry or not. If the value of this object is 'true', then it is a learnt entry. If the value of this object is 'false', then it is not.")
cdpvmDynPortsTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 8), )
if mibBuilder.loadTexts: cdpvmDynPortsTable.setStatus('current')
if mibBuilder.loadTexts: cdpvmDynPortsTable.setDescription('This table contains the set of all ports that are operating with a dynamic VSAN on the local device.')
cdpvmDynPortsEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 8, 1), ).setIndexNames((0, "IF-MIB", "ifIndex"))
if mibBuilder.loadTexts: cdpvmDynPortsEntry.setStatus('current')
if mibBuilder.loadTexts: cdpvmDynPortsEntry.setDescription('An entry (conceptual row) in this table.')
cdpvmDynPortVsan = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 8, 1, 1), VsanIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmDynPortVsan.setStatus('current')
if mibBuilder.loadTexts: cdpvmDynPortVsan.setDescription("The 'dynamic' VSAN of this port on the local device.")
cdpvmDynPortDevPwwn = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 8, 1, 2), FcNameId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmDynPortDevPwwn.setStatus('current')
if mibBuilder.loadTexts: cdpvmDynPortDevPwwn.setDescription('The pWWN of the device currently logged-in through this port on the local device.')
cdpvmDynPortDevNwwn = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 8, 1, 3), FcNameId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmDynPortDevNwwn.setStatus('current')
if mibBuilder.loadTexts: cdpvmDynPortDevNwwn.setDescription("The nWWN of the device currently logged-in thru' this port on the local device.")
cdpvmDiffConfig = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 9), CpsmDiffDb()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cdpvmDiffConfig.setStatus('current')
if mibBuilder.loadTexts: cdpvmDiffConfig.setDescription("The config database represented by cdpvmTable and the enforced database represented by cdpvmEnfTable can be compared to list out the differences. This object specifies the reference database for the comparison. This object when set to 'configDb(1)', compares the configuration database (cdpvmTable) with respect to the enforced database (cdpvmEnfTable). So, the enforced database will be the reference database and the results of comparison operation will be with respect to the enforced database. This object when set to 'activeDb(2)', compares the enforced database with respect to the configuration database. So, the configured database will be the reference database and the results of comparison operation will be with respect to the configuration database. No action will be taken if this object is set to 'noop(3)'. The value of this object when read is always 'noop(3)'.")
cdpvmDiffTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10), )
if mibBuilder.loadTexts: cdpvmDiffTable.setStatus('current')
if mibBuilder.loadTexts: cdpvmDiffTable.setDescription('This table contains the result of the compare operation configured by means of the cdpvmDiffConfig object.')
cdpvmDiffEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10, 1), ).setIndexNames((0, "CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmDiffIndex"))
if mibBuilder.loadTexts: cdpvmDiffEntry.setStatus('current')
if mibBuilder.loadTexts: cdpvmDiffEntry.setDescription('An entry (conceptual row) in this table.')
cdpvmDiffIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 16384)))
if mibBuilder.loadTexts: cdpvmDiffIndex.setStatus('current')
if mibBuilder.loadTexts: cdpvmDiffIndex.setDescription('The index of this entry.')
cdpvmDiffReason = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10, 1, 2), CpsmDiffReason()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmDiffReason.setStatus('current')
if mibBuilder.loadTexts: cdpvmDiffReason.setDescription('This object indicates the reason for the difference between the databases being compared, for this entry.')
cdpvmDiffLoginDevType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10, 1, 3), CdpvmDevType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmDiffLoginDevType.setStatus('current')
if mibBuilder.loadTexts: cdpvmDiffLoginDevType.setDescription('Specifies the type of the corresponding instance of cdpvmDiffLoginDev object.')
cdpvmDiffLoginDev = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10, 1, 4), FcNameId()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmDiffLoginDev.setStatus('current')
if mibBuilder.loadTexts: cdpvmDiffLoginDev.setDescription('This object represents the logging-in device address. This object was copied from either the cdpvmLoginDev object in the cdpvmTable or from cdpvmEnfLoginDev object in the cdpvmEnfTable at the time when the comparison was done.')
cdpvmDiffLoginDevVsan = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 10, 1, 5), VsanIndex()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmDiffLoginDevVsan.setStatus('current')
if mibBuilder.loadTexts: cdpvmDiffLoginDevVsan.setDescription("This object represents the VSAN of the port on the local device thru' which the device represented by the corresponding instance of cdpvmDiffLoginDev object, logged-in. It was copied from either the cdpvmLoginDevVsan object in the cdpvmTable or from cdpvmEnfLoginDevVsan object in the cdpvmEnfTable at the time when the comparison was done.")
cdpvmClearAutoLearn = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("clear", 1), ("clearOnWwn", 2), ("noop", 3)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cdpvmClearAutoLearn.setStatus('current')
if mibBuilder.loadTexts: cdpvmClearAutoLearn.setDescription("This object assists in clearing the auto-learnt entries. Setting this object to 'clear(1)' will result in all auto-learnt entries being cleared. Setting this object to 'clearOnWwn(2)' will result in a particular entry represented by cdpvmClearAutoLearnWwn object being cleared. Before setting this object to 'clearOnWwn(2)', the cpdvmClearAutoLearnWwn object should be set to the pWWN that is to be cleared. Setting this object to 'noop(3)', will result in no action being taken. The value of this object when read is always 'noop'.")
cdpvmClearAutoLearnWwn = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 12), FcNameIdOrZero().clone(hexValue="")).setMaxAccess("readwrite")
if mibBuilder.loadTexts: cdpvmClearAutoLearnWwn.setStatus('current')
if mibBuilder.loadTexts: cdpvmClearAutoLearnWwn.setDescription('Represents the port WWN (pWWN) to be used for clearing its corresponding auto-learnt entry.')
cdpvmActivationState = MibScalar((1, 3, 6, 1, 4, 1, 9, 9, 421, 1, 1, 13), TruthValue()).setMaxAccess("readonly")
if mibBuilder.loadTexts: cdpvmActivationState.setStatus('current')
if mibBuilder.loadTexts: cdpvmActivationState.setDescription("This object indicates the state of activation. If the value of this object is 'true', then an activation has been attempted as the most recent operation. If the value of this object is 'false', then an activation has not been attempted as the most recent operation.")
ciscoDpvmMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 1))
ciscoDpvmMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 2))
ciscoDpvmMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 1, 1)).setObjects(("CISCO-DYNAMIC-PORT-VSAN-MIB", "ciscoDpvmConfigGroup"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "ciscoDpvmEnforcedGroup"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "ciscoDpvmAutoLearnGroup"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "ciscoDpvmDiffGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoDpvmMIBCompliance = ciscoDpvmMIBCompliance.setStatus('current')
if mibBuilder.loadTexts: ciscoDpvmMIBCompliance.setDescription('The compliance statement for entities which implement the Dynamic Port VSAN Membership Manager.')
ciscoDpvmConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 2, 1)).setObjects(("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmNextAvailIndex"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmLoginDevType"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmLoginDev"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmLoginDevVsan"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmRowStatus"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmActivate"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmActivateResult"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmCopyEnfToConfig"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmDynPortVsan"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmDynPortDevPwwn"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmDynPortDevNwwn"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmActivationState"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoDpvmConfigGroup = ciscoDpvmConfigGroup.setStatus('current')
if mibBuilder.loadTexts: ciscoDpvmConfigGroup.setDescription('A set of objects for configuration of DPVM bindings.')
ciscoDpvmEnforcedGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 2, 2)).setObjects(("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmEnfLoginDevType"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmEnfLoginDev"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmEnfLoginDevVsan"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmEnfIsLearnt"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoDpvmEnforcedGroup = ciscoDpvmEnforcedGroup.setStatus('current')
if mibBuilder.loadTexts: ciscoDpvmEnforcedGroup.setDescription('A set of objects for displaying enforced DPVM bindings.')
ciscoDpvmAutoLearnGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 2, 3)).setObjects(("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmAutoLearn"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmClearAutoLearn"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmClearAutoLearnWwn"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoDpvmAutoLearnGroup = ciscoDpvmAutoLearnGroup.setStatus('current')
if mibBuilder.loadTexts: ciscoDpvmAutoLearnGroup.setDescription('A set of object(s) for configuring auto-learn of DPVM bindings.')
ciscoDpvmDiffGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 421, 2, 2, 4)).setObjects(("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmDiffConfig"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmDiffReason"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmDiffLoginDevType"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmDiffLoginDev"), ("CISCO-DYNAMIC-PORT-VSAN-MIB", "cdpvmDiffLoginDevVsan"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
ciscoDpvmDiffGroup = ciscoDpvmDiffGroup.setStatus('current')
if mibBuilder.loadTexts: ciscoDpvmDiffGroup.setDescription('A set of objects for configuring and displaying database compare operations.')
mibBuilder.exportSymbols("CISCO-DYNAMIC-PORT-VSAN-MIB", cdpvmDynPortDevPwwn=cdpvmDynPortDevPwwn, cdpvmTable=cdpvmTable, ciscoDpvmMIBCompliance=ciscoDpvmMIBCompliance, cdpvmNextAvailIndex=cdpvmNextAvailIndex, cdpvmDynPortsTable=cdpvmDynPortsTable, cdpvmDiffTable=cdpvmDiffTable, ciscoDpvmMIBObjects=ciscoDpvmMIBObjects, cdpvmDiffLoginDev=cdpvmDiffLoginDev, cdpvmLoginDev=cdpvmLoginDev, ciscoDpvmMIBCompliances=ciscoDpvmMIBCompliances, cdpvmDynPortDevNwwn=cdpvmDynPortDevNwwn, cdpvmLoginDevType=cdpvmLoginDevType, cdpvmDiffIndex=cdpvmDiffIndex, cdpvmDiffConfig=cdpvmDiffConfig, ciscoDpvmMIBNotifs=ciscoDpvmMIBNotifs, cdpvmCopyEnfToConfig=cdpvmCopyEnfToConfig, cdpvmActivate=cdpvmActivate, cdpvmActivateResult=cdpvmActivateResult, PYSNMP_MODULE_ID=ciscoDpvmMIB, cdpvmDiffLoginDevType=cdpvmDiffLoginDevType, cdpvmEntry=cdpvmEntry, cdpvmClearAutoLearnWwn=cdpvmClearAutoLearnWwn, cdpvmLoginDevVsan=cdpvmLoginDevVsan, cdpvmEnfEntry=cdpvmEnfEntry, ciscoDpvmMIB=ciscoDpvmMIB, cdpvmEnfLoginDevType=cdpvmEnfLoginDevType, cdpvmAutoLearn=cdpvmAutoLearn, cdpvmEnfLoginDevVsan=cdpvmEnfLoginDevVsan, ciscoDpvmDiffGroup=ciscoDpvmDiffGroup, cdpvmRowStatus=cdpvmRowStatus, cdpvmDiffEntry=cdpvmDiffEntry, cdpvmEnfIsLearnt=cdpvmEnfIsLearnt, ciscoDpvmMIBConform=ciscoDpvmMIBConform, cdpvmDynPortsEntry=cdpvmDynPortsEntry, cdpvmEnfLoginDev=cdpvmEnfLoginDev, cdpvmClearAutoLearn=cdpvmClearAutoLearn, ciscoDpvmEnforcedGroup=ciscoDpvmEnforcedGroup, ciscoDpvmMIBGroups=ciscoDpvmMIBGroups, cdpvmDiffReason=cdpvmDiffReason, cdpvmEnfIndex=cdpvmEnfIndex, cdpvmDiffLoginDevVsan=cdpvmDiffLoginDevVsan, ciscoDpvmAutoLearnGroup=ciscoDpvmAutoLearnGroup, cdpvmConfiguration=cdpvmConfiguration, ciscoDpvmConfigGroup=ciscoDpvmConfigGroup, cdpvmDynPortVsan=cdpvmDynPortVsan, CdpvmDevType=CdpvmDevType, cdpvmActivationState=cdpvmActivationState, cdpvmEnfTable=cdpvmEnfTable, cdpvmIndex=cdpvmIndex)
|
# Title : Print alphabets from mix string
# Author : Kiran Raj R.
# Date : 04:11:2020
string_to_filter = "he712047070l13212l213*(&(ow76968o172830r%*&$d"
def check_alpha(c):
if c.isalpha():
return c
def check_num(c):
if c.isnumeric():
return c
out = "".join(list(filter(check_alpha, string_to_filter)))
print(out)
out = "".join(list(filter(check_num, string_to_filter)))
print(out) |
# Create Allergy check code
# [ ] get input for input_test variable
input_test = input("What have you eaten in the last 24hrs: ")
# [ ] print "True" message if "dairy" is in the input or False message if not
print("Your food intake of",input_test,'contains "dairy" =',"dairy".lower() in input_test.lower())
#test works
# [ ] print True message if "nuts" is in the input or False if not
print("Your food intake of",input_test,'contains "Nuts" =',"Nuts".lower() in input_test.lower())
# [ ] Challenge: Check if "seafood" is in the input - print message
print("Your food intake of",input_test,'contains "seafood" =',"seafood".lower() in input_test.lower())
# [ ] Challenge: Check if "chocolate" is in the input - print message
print("Your food intake of",input_test,'contains "chocolate" =',"chocolate".lower() in input_test.lower()) |
def largestComponent(G):
V, E = G;
vertexDeletedIndex = 0;
largestComponent = 0;
component = 0;
colour = [];
for i in range(len(V)):
Vcopy = V;
del Vcopy[i];
for v in V:
colour[v] = "white";
for v in Vcopy:
if colour[v] == "white":
component = DFS(G, v);
if(component > largestComponent):
largestComponent = component;
vertexDeletedIndex = v;
return vertexDeletedIndex, largestComponent;
def DFS(G, v):
pass;
|
n = int(input())
s = sum(list(map(int, input().split())))
c = 0
for i in range(1, 6):
if (s+i)%(n+1)!=1:
c += 1
print(c)
|
names = ['Christopher', 'Susan']
print(len(names)) # Get the number of items
names.insert(0, 'Bill') # Insert before index
print(names)
|
numBottles=int(input('pleas enter the number of full buttles: '))
numExchange=int(input('pleas enter number of empty bottels to exchange with full bottels: '))
fullbottels=numBottles
result=0
while numBottles>=numExchange or fullbottels>0:
result+=fullbottels
fullbottels=numBottles//numExchange
numBottles%=numExchange
numBottles+=fullbottels
print(result) |
detection_data_path = os.path.join('datasets', 'detection')
# training dataset
detection_train_set = DetectionDataset(detection_data_path, mode='train', transforms=get_transform(True))
# validation dataset
detection_valid_set = DetectionDataset(detection_data_path, mode='valid', transforms=get_transform(True))
#testing dataset
detection_test_set = DetectionDataset(detection_data_path, mode='test', transforms=get_transform(False))
detection_classes = detection_train_set.classes
num_detection_classes = len(detection_classes) |
#######################################
# Accessing Attributes
#######################################
class Employee:
"""Common base class for all employees"""
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print("Name : ", self.name, ", Salary: ", self.salary)
"This would create first object of Employee class"
emp1 = Employee("Zara", 2000)
"This would create second object of Employee class"
emp2 = Employee("Manni", 5000)
emp1.displayEmployee()
emp2.displayEmployee()
print("Total Employee %d" % Employee.empCount)
emp1.age = 7 # Add an 'age' attribute.
emp1.age = 8 # Modify 'age' attribute.
# del emp1.age # Delete 'age' attribute.
hasattr(emp1, 'age') # Returns true if 'age' attribute exists
getattr(emp1, 'age') # Returns value of 'age' attribute
setattr(emp1, 'age', 8) # Set attribute 'age' at 8
delattr(emp1, 'age') # Delete attribute 'age'
#######################################
# Built-In Class Attributes
#######################################
class Employee:
"""Common base class for all employees"""
empCount = 0
def __init__(self, name, salary):
self.name = name
self.salary = salary
Employee.empCount += 1
def displayCount(self):
print("Total Employee %d" % Employee.empCount)
def displayEmployee(self):
print("Name : ", self.name, ", Salary: ", self.salary)
print("Employee.__doc__:", Employee.__doc__)
print("Employee.__name__:", Employee.__name__)
print("Employee.__module__:", Employee.__module__)
print("Employee.__bases__:", Employee.__bases__)
print("Employee.__dict__:", Employee.__dict__)
#######################################
# Destroying Objects (Garbage Collection)
#######################################
a = 40 # Create object <40>
b = a # Increase ref. count of <40>
c = [b] # Increase ref. count of <40>
del a # Decrease ref. count of <40>
b = 100 # Decrease ref. count of <40>
c[0] = -1 # Decrease ref. count of <40>
# class can implement the special method __del__(), called a destructor
class Point:
def __init__(self, x=0, y=0):
self.x = x
self.y = y
def __del__(self):
class_name = self.__class__.__name__
print(class_name, "destroyed")
pt1 = Point()
pt2 = pt1
pt3 = pt1
print(id(pt1), id(pt2), id(pt3)) # prints the ids of the obejcts
del pt1
del pt2
del pt3
#######################################
# Class Inheritance
#######################################
class Parent: # define parent class
parentAttr = 100
def __init__(self):
print("Calling parent constructor")
def parentMethod(self):
print('Calling parent method')
def setAttr(self, attr):
Parent.parentAttr = attr
def getAttr(self):
print("Parent attribute :", Parent.parentAttr)
class Child(Parent): # define child class
def __init__(self):
print("Calling child constructor")
def childMethod(self):
print('Calling child method')
c = Child() # instance of child
c.childMethod() # child calls its method
c.parentMethod() # calls parent's method
c.setAttr(200) # again call parent's method
c.getAttr() # again call parent's method
# Multiple inheritance
class A: # define your class A
"""....."""
class B: # define your class B
"""....."""
class C(A, B): # subclass of A and B
"""....."""
|
"""
j is the index to insert when a number not equal to val.
j will never catch up i, so j will not mess up the check.
"""
class Solution(object):
def removeElement(self, nums, val):
j = 0
for n in nums:
if n!=val:
nums[j] = n
j += 1
return j |
# from pynvim import attach
# nvim = attach('socket', path='/tmp/nvim')
# handle = nvim.request("nvim_create_buf",1,0)
# nvim.request("nvim_open_win",2,True,{'relative':'win','width':50,'height':3,'row':3,'col':3})
# maybe get current window's config and based on it? but resizing will make things weird, like fzf
# src = nvim.new_highlight_source()
buf = nvim.current.buffer
# # for i in range(5):
# # # has async parameter
# # buf.add_highlight("String",i,0,-1,src_id=src)
# # # some time later ...
# # buf.clear_namespace(src)
# nvim.command("silent split")
# nvim.command("silent e FilterJump")
# nvim.command("silent setlocal buftype=nofile")
# nvim.command('silent setlocal filetype=FilterJump')
# nvim.current.window.height = 1
# nvim.command("silent CocDisable")
# nvim.command("startinsert")
|
# Leetcode 323
class Solution:
def countComponents(self, n: int, edges: List[List[int]]) -> int:
visited = [False] * n
adj_list = [None] * n
for vertex in range(n):
adj_list[vertex] = list()
for edge in edges:
adj_list[edge[0]].append(edge[1])
adj_list[edge[1]].append(edge[0])
# 96 ms, faster than 9x%
def bfs(source):
q = []
q.append(source)
visited[source] = True
while q:
node = q.pop(0)
for neighbor in adj_list[node]:
if not visited[neighbor]:
visited[neighbor] = True
q.append(neighbor)
# 116 ms, faster than 67.25%
def dfs(source):
q = []
q.append(source)
visited[source] = True
while q:
node = q.pop()
for neighbor in adj_list[node]:
if not visited[neighbor]:
visited[neighbor] = True
q.append(neighbor)
components = 0
for vertex in range(n):
if not visited[vertex]:
components += 1
dfs(vertex)
return components
|
# търговски комисионни
# Фирма дава следните комисионни на търговците си според града, в който работят и обема на продажбите s:
#
# Напишете програма, която чете име на град (стринг) и обем на продажбите (десетично число) и изчислява размера на
# комисионната. Резултатът да се изведе закръглен с 2 десетични цифри след десетичния знак.
# При невалиден град или обем на продажбите (отрицателно число) да се отпечата "error".
city = input()
sales = float(input())
is_valid = True
if city == 'Sofia':
if 0 <= sales <= 500:
comission = 0.05
elif 500 < sales <= 1000:
comission = 0.07
elif 1000 < sales <= 10000:
comission = 0.08
elif sales > 10000:
comission = 0.12
else:
is_valid = False
elif city == 'Varna':
if 0 <= sales <= 500:
comission = 0.045
elif 500 < sales <= 1000:
comission = 0.075
elif 1000 < sales <= 10000:
comission = 0.1
elif sales > 10000:
comission = 0.13
else:
is_valid = False
elif city == 'Plovdiv':
if 0 <= sales <= 500:
comission = 0.055
elif 500 < sales <= 1000:
comission = 0.08
elif 1000 < sales <= 10000:
comission = 0.12
elif sales > 10000:
comission = 0.145
else:
is_valid = False
else:
is_valid = False
if is_valid == True:
print(f'{sales * comission:.2f}')
elif is_valid == False:
print('error') |
#
# PySNMP MIB module RTBRICK-SYSLOG-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///home/tin/Dev/mibs.snmplabs.com/asn1/RTBRICK-SYSLOG-MIB
# Produced by pysmi-0.3.4 at Fri Jan 31 21:33:01 2020
# On host bier platform Linux version 5.4.0-3-amd64 by user tin
# Using Python version 3.7.6 (default, Jan 19 2020, 22:34:52)
#
Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection")
rtbrickSyslogNotifications, rtbrickTraps, rtbrickModules = mibBuilder.importSymbols("RTBRICK-MIB", "rtbrickSyslogNotifications", "rtbrickTraps", "rtbrickModules")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Bits, NotificationType, Counter32, Counter64, MibIdentifier, IpAddress, TimeTicks, Unsigned32, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, Gauge32, ModuleIdentity, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "Bits", "NotificationType", "Counter32", "Counter64", "MibIdentifier", "IpAddress", "TimeTicks", "Unsigned32", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "Gauge32", "ModuleIdentity", "ObjectIdentity")
TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString")
rtBrickSyslogMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 50058, 104, 2))
rtBrickSyslogMIB.setRevisions(('2019-01-04 00:00',))
if mibBuilder.loadTexts: rtBrickSyslogMIB.setLastUpdated('201804140000Z')
if mibBuilder.loadTexts: rtBrickSyslogMIB.setOrganization('RtBrick')
syslogMessage = MibIdentifier((1, 3, 6, 1, 4, 1, 50058, 104, 2, 1))
class SyslogSeverity(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8))
namedValues = NamedValues(("emergency", 1), ("alert", 2), ("critical", 3), ("error", 4), ("warning", 5), ("notice", 6), ("info", 7), ("debug", 8))
syslogMsgNumber = MibScalar((1, 3, 6, 1, 4, 1, 50058, 104, 2, 1, 1), Unsigned32()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: syslogMsgNumber.setStatus('current')
syslogMsgFacility = MibScalar((1, 3, 6, 1, 4, 1, 50058, 104, 2, 1, 2), DisplayString()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: syslogMsgFacility.setStatus('current')
syslogMsgSeverity = MibScalar((1, 3, 6, 1, 4, 1, 50058, 104, 2, 1, 3), SyslogSeverity()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: syslogMsgSeverity.setStatus('current')
syslogMsgText = MibScalar((1, 3, 6, 1, 4, 1, 50058, 104, 2, 1, 4), DisplayString()).setMaxAccess("accessiblefornotify")
if mibBuilder.loadTexts: syslogMsgText.setStatus('current')
rtbrickSyslogNotificationPrefix = ObjectIdentity((1, 3, 6, 1, 4, 1, 50058, 103, 1, 0))
if mibBuilder.loadTexts: rtbrickSyslogNotificationPrefix.setStatus('current')
rtbrickSyslogTrap = NotificationType((1, 3, 6, 1, 4, 1, 50058, 103, 1, 0, 1))
if mibBuilder.loadTexts: rtbrickSyslogTrap.setStatus('current')
mibBuilder.exportSymbols("RTBRICK-SYSLOG-MIB", SyslogSeverity=SyslogSeverity, rtbrickSyslogNotificationPrefix=rtbrickSyslogNotificationPrefix, rtbrickSyslogTrap=rtbrickSyslogTrap, syslogMsgFacility=syslogMsgFacility, rtBrickSyslogMIB=rtBrickSyslogMIB, PYSNMP_MODULE_ID=rtBrickSyslogMIB, syslogMsgText=syslogMsgText, syslogMsgSeverity=syslogMsgSeverity, syslogMsgNumber=syslogMsgNumber, syslogMessage=syslogMessage)
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
if __name__ == '__main__':
with open("file.txt", 'r') as f:
content = f.read();
print(content)
|
#!/usr/bin/python
# -*- coding: utf-8 -*-
def read_line_in_str(line, number_of_loci):
"""
read str data in each line and check the format and data type (float);
return information and STR-data separately.
"""
col = line.strip().split("\t")
# check the column number
if len(col) != (number_of_loci + 6):
print("\tTermination!Can not read the file because it has wrong column number at some line.")
return
# check if the str is numeric
info_part = col[:6]
str_part = []
for i in col[6:]:
try:
str_part.append(float(i))
except ValueError:
print("\tTermination!There is a non-numeric value in the STR data.")
return
return info_part, str_part
|
class Solution(object):
def numIslands(self, grid):
if not grid:
return 0
count = 0
for i in range(len(grid)):
for j in range(len(grid[0])):
if grid[i][j] == '1':
self.dfs(grid, i, j)
count += 1
return count
def dfs(self, grid, i, j):
if i < 0 or i >= len(grid) \
or j < 0 or j >= len(grid[0]) or grid[i][j] != '1':
return
grid[i][j] = '#'
self.dfs(grid, i + 1, j)
self.dfs(grid, i - 1, j)
self.dfs(grid, i, j + 1)
self.dfs(grid, i, j - 1)
def test_num_islands():
s = Solution()
assert 1 == s.numIslands([['1', '1', '1', '1', '0'],
['1', '1', '0', '1', '0'],
['1', '1', '0', '0', '0'],
['0', '0', '0', '0', '0']])
assert 3 == s.numIslands([['1', '1', '0', '0', '0'],
['1', '1', '0', '0', '0'],
['0', '0', '1', '0', '0'],
['0', '0', '0', '1', '1']])
|
class Empty:
""" An empty element. Serves the same function as None, except that it can be used to indicate that JSGNull
and AnyType attributes (which both can legitimately have None values) have not been assigned
"""
def __new__(cls):
return cls |
print('Insert first string')
string1 = input()
print('Insert second string')
string2 = input()
print(string1 + ' - ' + string2 + ' are anagrams?', sorted(string1) == sorted(string2))
'''
Check whether the strings in input are anagrams or not.
Two strings, a and b, are called anagrams if they contain all the same characters in the same frequencies.
For example, the anagrams of CAT are CAT, ACT, TAC, TCA, ATC, and CTA.
Sample Input:
string1=CAT
string2=ACT
Sample Output:
true
Time complexity : O(N log N)
Space complexity: O(1)
'''
|
class Scaler1D:
def __init__(self) -> None:
self.max_num: float = None
self.min_num: float = None
def transform(self, num_list: list) -> list:
if self.max_num is None:
self.max_num = max(num_list)
if self.min_num is None:
self.min_num = min(num_list)
return [(x - self.min_num) / (self.max_num - self.min_num) for x in num_list]
def inverse_transform(self, num_list: list) -> list:
return [x * (self.max_num - self.min_num) + self.min_num for x in num_list]
class Scaler2D:
def __init__(self) -> None:
self.max_num: float = None
self.min_num: float = None
def transform(self, num_list: list) -> list:
if self.max_num is None:
self.max_num = max([max(x[0], x[1]) for x in num_list])
if self.min_num is None:
self.min_num = min([min(x[0], x[1]) for x in num_list])
return [[(x[0] - self.min_num) / (self.max_num - self.min_num),
(x[1] - self.min_num) / (self.max_num - self.min_num)]
for x in num_list]
def inverse_transform(self, num_list: list) -> list:
return [[x[0] * (self.max_num - self.min_num) + self.min_num,
x[1] * (self.max_num - self.min_num) + self.min_num]
for x in num_list]
|
# 选择排序-简单选择排序
"""
在要排序的一组数中,选出最小(或者最大)的一个数与第1个位置的数交换;
然后在剩下的数当中再找最小(或者最大)的与第2个位置的数交换,依次类推,直到第n-1个元素(倒数第二个数)和第n个元素(最后一个数)比较为止。
简单选择排序的改进——二元选择排序
简单选择排序,每趟循环只能确定一个元素排序后的定位。
我们可以考虑改进为每趟循环确定两个元素(当前趟最大和最小记录)的位置,从而减少排序所需的循环次数。改进后对n个数据进行排序,最多只需进行[n/2]趟循环即可
"""
# 简单选择排序
def selectSort(numbers):
for i in range(len(numbers)-1):
min = i
for j in range(i+1, len(numbers)):
if numbers[min] > numbers[j]:
min = j
if min != i:
numbers[i], numbers[min] = numbers[min], numbers[i]
# 二元选择排序
def selectSort2(numbers):
count = len(numbers)
for i in range(1, int(count/2)):
# 做不超过n/2趟选择排序
# 分别记录最大和最小关键字记录位置
min = i
max = i
for j in range(i+1, count-i):
if numbers[j] > numbers[max]:
max = j
continue
elif numbers[j] < numbers[min]:
min = j
# 该交换操作还可分情况讨论以提高效率
tmp = numbers[i-1]
numbers[i-1] = numbers[min]
numbers[min] = tmp
tmp = numbers[count-i]
numbers[count-i] = numbers[max]
numbers[max] = tmp
MyList = [3, 1, 5, 7, 2, 4, 9, 6]
# selectSort(MyList)
selectSort2(MyList)
print(MyList)
|
"""This module defines Debian Buster dependencies."""
load("@rules_deb_packages//:deb_packages.bzl", "deb_packages")
def debian_buster_amd64():
deb_packages(
name = "debian_buster_amd64_macro",
arch = "amd64",
urls = [
"http://deb.debian.org/debian/$(package_path)",
"http://deb.debian.org/debian-security/$(package_path)",
"https://snapshot.debian.org/archive/debian/$(timestamp)/$(package_path)", # Needed in case of superseded archive no more available on the mirrors
"https://snapshot.debian.org/archive/debian-security/$(timestamp)/$(package_path)", # Needed in case of superseded archive no more available on the mirrors
],
packages = {
"base-files": "pool/main/b/base-files/base-files_10.3+deb10u8_amd64.deb",
"busybox": "pool/main/b/busybox/busybox_1.30.1-4_amd64.deb",
"ca-certificates": "pool/main/c/ca-certificates/ca-certificates_20200601~deb10u2_all.deb",
"libc6": "pool/main/g/glibc/libc6_2.28-10_amd64.deb",
"libssl1.1": "pool/updates/main/o/openssl/libssl1.1_1.1.1d-0+deb10u5_amd64.deb",
"netbase": "pool/main/n/netbase/netbase_5.6_all.deb",
"openssl": "pool/updates/main/o/openssl/openssl_1.1.1d-0+deb10u5_amd64.deb",
"tzdata": "pool/main/t/tzdata/tzdata_2021a-0+deb10u1_all.deb",
},
packages_sha256 = {
"base-files": "eda9ec7196cae25adfa1cb91be0c9071b26904540fc90bab8529b2a93ece62b1",
"busybox": "1e32ea742bddec4ed5a530ee2f423cdfc297c6280bfbb45c97bf12eecf5c3ec1",
"ca-certificates": "a9e267a24088c793a9cf782455fd344db5fdced714f112a8857c5bfd07179387",
"libc6": "6f703e27185f594f8633159d00180ea1df12d84f152261b6e88af75667195a79",
"libssl1.1": "1741ec08b10caa4d3c8a165768323a14946278a7e6fb9cd56ae59cf4fe1ef970",
"netbase": "baf0872964df0ccb10e464b47d995acbba5a0d12a97afe2646d9a6bb97e8d79d",
"openssl": "f4c32a3f851adeb0145edafb8ea271aed8330ee864de23f155f4141a81dc6e10",
"tzdata": "00da63f221b9afa6bc766742807e398cf183565faba339649bafa3f93375fbcb",
},
sources = [
"http://deb.debian.org/debian buster main",
"http://deb.debian.org/debian buster-updates main",
"http://deb.debian.org/debian-security buster/updates main",
],
timestamp = "20210306T084946Z",
)
|
# SWAPPING THE NUMBERS
a=5
b=2
print(a,b)
a,b=b,a
print(a,b) |
BASE_URL = "https://api.labs.cognitive.microsoft.com/academic/v1.0/evaluate?expr"
PAPER_ATTRIBUTES = "AA.DAuN,DN,D,ECC,DFN,J.JN,PB,Y"
AUTHOR_ATTRIBUTES = "Id,DAuN,ECC,LKA.AfN,PC"
STUDY_FIELD_ATTRIBUTES = "Id,PC,FP.FN,ECC,DFN,FC.FN"
PAPER = 'paper'
AUTHOR = 'author'
AFFILIATION = 'affiliation'
STUDY_FIELD = 'study field' |
class Solution:
def gameOfLife(self, board: List[List[int]]) -> None:
"""
Do not return anything, modify board in-place instead.
"""
row=len(board)
col = len(board[0])
copy = [[0 for i in range(col)]for j in range(row)]
for i in range(row):
for j in range(col):
copy[i][j]=board[i][j]
neighbors=[(-1,-1),(-1,0),(-1,1),(0,1),(0,-1),(1,1),(1,0),(1,-1)]
for i in range(row):
for j in range(col):
live_nei = 0
for nei in neighbors:
r = (i+nei[0])
c = (j+nei[1])
if (r<row and r>=0) and (c<col and c>=0)and(copy[r][c]==1):
live_nei+=1
if copy[i][j]==1 and(live_nei<2 or live_nei>3):
board[i][j]=0
if copy[i][j]==0 and live_nei==3:
board[i][j]=1
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.