content stringlengths 7 1.05M |
|---|
class StoreDoesNotExist(Exception):
def __init__(self):
super(StoreDoesNotExist, self).__init__("Store with the given query does not exist")
|
class Blend(GenericForm, IDisposable):
""" A blend solid or void form. """
def Dispose(self):
""" Dispose(self: Element,A_0: bool) """
pass
def getBoundingBox(self, *args):
""" getBoundingBox(self: Element,view: View) -> BoundingBoxXYZ """
pass
def GetVertexConnectionMap(self):
"""
GetVertexConnectionMap(self: Blend) -> VertexIndexPairArray
Gets the mapping between the vertices in the top and bottom profiles.
"""
pass
def ReleaseUnmanagedResources(self, *args):
""" ReleaseUnmanagedResources(self: Element,disposing: bool) """
pass
def setElementType(self, *args):
""" setElementType(self: Element,type: ElementType,incompatibleExceptionMessage: str) """
pass
def SetVertexConnectionMap(self, vertexMap):
"""
SetVertexConnectionMap(self: Blend,vertexMap: VertexIndexPairArray)
Sets the mapping between the vertices in the top and bottom profiles.
"""
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
BottomOffset = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""The offset of the bottom end of the blend relative to the sketch plane.
Get: BottomOffset(self: Blend) -> float
Set: BottomOffset(self: Blend)=value
"""
BottomProfile = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""The curves which make up the bottom profile of the sketch.
Get: BottomProfile(self: Blend) -> CurveArrArray
"""
BottomSketch = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""Returns the Bottom Sketch of the Blend.
Get: BottomSketch(self: Blend) -> Sketch
"""
TopOffset = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""The offset of the top end of the blend relative to the sketch plane.
Get: TopOffset(self: Blend) -> float
Set: TopOffset(self: Blend)=value
"""
TopProfile = property(
lambda self: object(), lambda self, v: None, lambda self: None
)
"""The curves which make up the top profile of the sketch.
Get: TopProfile(self: Blend) -> CurveArrArray
"""
TopSketch = property(lambda self: object(), lambda self, v: None, lambda self: None)
"""Returns the Top Sketch of the Blend.
Get: TopSketch(self: Blend) -> Sketch
"""
|
class LexerFileWriter():
def __init__(self, tokens: dict, lexical_errors: dict, symbol_table: dict, token_filename="tokens.txt",
lexical_error_filename="lexical_errors.txt", symbol_table_filename="symbol_table.txt"):
self.tokens = tokens
self.lexical_errors = lexical_errors
self.symbol_table = symbol_table
self.token_filename = token_filename
self.lexical_error_filename = lexical_error_filename
self.symbol_table_filename = symbol_table_filename
def write_token_file(self):
output_string = ""
with open(self.token_filename, 'w') as f:
for k in sorted(self.tokens.keys()):
output_string += f"{k}.\t{self.tokens[k]}\n"
f.write(output_string)
def write_lexical_errors_file(self):
output_string = ""
with open(self.lexical_error_filename, 'w') as f:
if self.lexical_errors:
for k in sorted(self.lexical_errors.keys()):
output_string += f"{k}.\t{self.lexical_errors[k]}\n"
else:
output_string = "There is no lexical error."
f.write(output_string)
def write_symbol_table_file(self):
output_string = ""
with open(self.symbol_table_filename, 'w') as f:
for k in sorted(self.symbol_table.keys()):
output_string += f"{k}.\t{self.symbol_table[k]}\n"
f.write(output_string)
|
classes = {
# layout = ["name", [attacks],[item_drops], [changes]]
0: ["soldier", [0], [2, 4, 5, 11], ["h+10", "d+2"]],
1: ["mage", [0, 2], [3, 7], ["m+40"]],
2: ["tank", [0], [1, 2, 6, 11], ["h*2", "d*0.7"]],
3: ["archer", [0, 1], [0, 3, 4, 11], ["a+10"]],
100: ["boss", [], [], ["h*1.3", "d*1.5", "a*2", "m*2"]],
101: ["basic", [0], [], []]
}
def get_all_classes(name_only=False):
'''
Gets all of the classes stored in classes.
If name_only is true returns only the names
'''
all_classes = []
if name_only:
for i in classes.values():
all_classes.append(i[0])
return(all_classes)
else:
for i in classes.values():
all_classes.append(i)
return(all_classes)
def get_assignable_classes(as_list=False):
'''
Gets all of the classes that can be either chosen or assigned.
'''
assignable_classes = classes.copy()
assignable_classes.pop(100)
assignable_classes.pop(101)
if as_list:
assignable_classes_li = []
for i in assignable_classes.values():
assignable_classes_li.append(i)
return assignable_classes_li
else:
return assignable_classes
def is_class_valid(classe=""):
for classes in get_assignable_classes(True):
if classe.lower() in classes:
return True
return False
|
def common_settings(args, plt):
# Common options
if args['--title']:
plt.title(args['--title'])
plt.ylabel(args['--ylabel'])
plt.xlabel(args['--xlabel'])
if args['--xlog']:
plt.xscale('log')
if args['--ylog']:
plt.yscale('log')
|
#This assignment will allow you to practice writing
#Python Generator functions and a small GUI using tkinter
#Title: Generator Function of Powers of Two
#Author: Anthony Narlock
#Prof: Lisa Minogue
#Class: CSCI 2061
#Date: Nov 14, 2020
#Powers of two is a gen function that can take multiple parameters, 1 or 2, gives error for anything else
def powers_of_twos(*args):
number_of_parameters = len(args)
if(number_of_parameters == 1):
starting_pow = 1
num_of_pow = args[0]
elif(number_of_parameters == 2):
starting_pow = args[0]
num_of_pow = args[1]
else:
raise TypeError("Expected either one or two parameters")
for i in range(num_of_pow):
yield 2 ** starting_pow
starting_pow += 1
#main function for testing
def main():
print("Printing the powers of two that yield from powers_of_two(5):")
single_example = powers_of_twos(5)
for powers in powers_of_twos(5):
print(powers)
print("\nPrinting the powers of two that yield from powers_of_two(3,5):")
for powers in powers_of_twos(3,5):
print(powers)
#print("\n Showing error by typing powers_of_twos(1,2,3)")
#for powers in powers_of_twos(1,2,3):
# print(powers)
print("\n Showing error by typing powers_of_twos(0)")
for powers in powers_of_twos():
print(powers)
if __name__ == '__main__':
main()
|
# -*- coding: utf-8 -*-
# 入力値を任意の刻み幅に変換
def Tick_int(num:int, tick):
mod = num % 10 # 入力値の最小桁
times = int(mod / tick) # 最小桁はtick何個分か?
result = tick * times # 最小桁 = tick刻みでの最大値
change = num - num % 10 + result # 最小桁をtick刻みに変換
return change
|
class FileNames(object):
'''standardize and handle all file names/types encountered by pipeline'''
def __init__(self, name):
'''do everything upon instantiation'''
# determine root file name
self.root = name
self.root = self.root.replace('_c.fit','')
self.root = self.root.replace('_sobj.fit','')
self.root = self.root.replace('_cobj.fit','')
self.root = self.root.replace('_cnew.fit','')
self.root = self.root.replace('_cwcs.fit','' )
self.root = self.root.replace('_ctwp.fit','' )
self.root = self.root.replace('_cfwp.fit','' )
self.root = self.root.replace('_ctcv.fit','' )
self.root = self.root.replace('_cfcv.fit','' )
self.root = self.root.replace('_ctsb.fit','' )
self.root = self.root.replace('_cfsb.fit','' )
self.root = self.root.replace('_cph.fit','' )
self.root = self.root.replace('_ctph.fit','' )
self.root = self.root.replace('_sbph.fit','' )
self.root = self.root.replace('_cand.fit','' )
self.root = self.root.replace('_fwhm.txt','' )
self.root = self.root.replace('_obj.txt','' )
self.root = self.root.replace('_psfstar.txt','' )
self.root = self.root.replace('_apt.txt','' )
self.root = self.root.replace('_apt.dat','' )
self.root = self.root.replace('_psf.txt','' )
self.root = self.root.replace('_standrd.txt','')
self.root = self.root.replace('_standxy.txt','')
self.root = self.root.replace('_objectrd.txt','')
self.root = self.root.replace('_objectxy.txt','')
self.root = self.root.replace('_sky.txt','')
self.root = self.root.replace('_apass.dat','')
self.root = self.root.replace('_zero.txt','')
self.root = self.root.replace('.fit','')
self.root = self.root.replace('.fts','')
# generate all filenames from root
self.cimg = self.root + '_c.fit'
self.sobj = self.root + '_sobj.fit'
self.cobj = self.root + '_cobj.fit'
self.cnew = self.root + '_cnew.fit'
self.cwcs = self.root + '_cwcs.fit'
self.ctwp = self.root + '_ctwp.fit'
self.cfwp = self.root + '_cfwp.fit'
self.ctcv = self.root + '_ctcv.fit'
self.cfcv = self.root + '_cfcv.fit'
self.ctsb = self.root + '_ctsb.fit'
self.cfsb = self.root + '_cfsb.fit'
self.cph = self.root + '_cph.fit'
self.ctph = self.root + '_ctph.fit'
self.sbph = self.root + '_sbph.fit'
self.cand = self.root + '_cand.fit'
self.fwhm_fl = self.root + '_fwhm.txt'
self.obj = self.root + '_obj.txt'
self.psfstar = self.root + '_psfstar.txt'
self.apt = self.root + '_apt.txt'
self.aptdat = self.root + '_apt.dat'
self.psf = self.root + '_psf.txt'
self.psfsub = self.root + '_psfsub.txt'
self.psffitarr = self.root + '_psffitarr.fit'
self.psfdat = self.root + '_psf.dat'
self.psfsubdat = self.root + '_psfsub.dat'
self.standrd = self.root + '_standrd.txt'
self.standxy = self.root + '_standxy.txt'
self.objectrd = self.root + '_objectrd.txt'
self.objectxy = self.root + '_objectxy.txt'
self.skytxt = self.root + '_sky.txt'
self.skyfit = self.root + '_sky.fit'
self.apass = self.root + '_apass.dat'
self.zerotxt = self.root + '_zero.txt'
|
# -*- coding: utf-8 -*-
class Hero(object):
def __init__(self, forename, surname, hero):
self.forename = forename
self.surname = surname
self.heroname = hero
def __repr__(self):
return 'Hero({0}, {1}, {2})'.format(
self.forename, self.surname, self.heroname)
|
result = []
with open(FILE, mode='r') as file:
reader = csv.reader(file, lineterminator='\n')
for *features, label in reader:
label = SPECIES[int(label)]
row = tuple(features) + (label,)
result.append(row)
|
def spec(x, y, color="run ID"):
def subfigure(params, x_kwargs, y_kwargs):
return {
"height": 400,
"width": 600,
"encoding": {
"x": {"type": "quantitative", "field": x, **x_kwargs},
"y": {"type": "quantitative", "field": y, **y_kwargs},
"color": {"type": "nominal", "field": color},
"opacity": {
"value": 0.1,
"condition": {
"test": {
"and": [
{"param": "legend_selection"},
{"param": "hover"},
]
},
"value": 1,
},
},
},
"layer": [
{
"mark": "line",
"params": params,
}
],
}
params = [
{
"bind": "legend",
"name": "legend_selection",
"select": {
"on": "mouseover",
"type": "point",
"fields": ["run ID"],
},
},
{
"bind": "legend",
"name": "hover",
"select": {
"on": "mouseover",
"type": "point",
"fields": ["run ID"],
},
},
]
return {
"$schema": "https://vega.github.io/schema/vega-lite/v5.json",
"data": {"name": "data"},
"hconcat": [
subfigure(
params=[*params, {"name": "selection", "select": "interval"}],
x_kwargs={},
y_kwargs={},
),
subfigure(
params=params,
x_kwargs={"scale": {"domain": {"param": "selection", "encoding": "x"}}},
y_kwargs={"scale": {"domain": {"param": "selection", "encoding": "y"}}},
),
],
}
|
"""Faça um programa para uma loja de tintas. O programa deverá pedir o tamanho em metros quadrados
da área a ser pintada.
Considere que a cobertura da tinta é de 1 litro para cada 3 metros quadrados
e que a tinta é vendida em latas de 18 litros, que custam R$ 80,00.
Informe ao usuário a quantidades de latas de tinta a serem compradas e o preço total.
"""
area = float(input('Informe o tamanho da área (metros) a ser pintada: '))
cobertura = area / 3
latas = cobertura / 18
if cobertura % 18 != 0:
latas += 1
print(f'Quantidade de latas de tinta: {latas}')
print(f'Preço total: R${latas * 80}')
|
# Option for variable 'simulation_type':
# 1: cylindrical roller bearing
# 2:
# 3: cylindrical roller thrust bearing
# 4: ball on disk (currently not fully supported)
# 5: pin on disk
# 6: 4 ball
# 7: ball on three plates
# 8: ring on ring
# global simulation setup
simulation_type = 8 # one of the above type numbers
simulation_name = 'RingOnRing'
auto_print = True # True or False
auto_plot = False
auto_report = False
# global test setup / bearing information
tribo_system_name = 'bla'
number_planets = 2
# Sun (CB1)
e_cb1 = 210000 # young's modulus in MPa
ny_cb1 = 0.3 # poisson number in MPa
diameter_cb1 = 37.5 # in mm
length_cb1 = 10 # in mm
type_profile_cb1 = 'ISO' # 'None', 'ISO', 'Circle', 'File'
path_profile_cb1 = 'tribology/p3can/BearingProfiles/NU206-RE-1.txt' # path to profile.txt file required if TypeProfile == 'File'
profile_radius_cb1 = 6.35 # input required if TypeProfile == 'Circle'
# Planet (CB2)
e_cb2 = 210000 # young's modulus in MPa
ny_cb2 = 0.3 # poisson number in MPa
diameter_cb2 = 9 # in mm
type_profile_cb2 = 'ISO' # 'None', 'File'
profile_radius_cb2 = 20
length_cb2 = 10
path_profile_cb2 = "tribology/p3can/BearingProfiles/NU206-IR-2.txt" # path to profile.txt file required if TypeProfile == 'File'
# Loads
global_force = 300 # in N
rot_velocity1 = 300 # in rpm
rot_velocity2 = 2 # in rpm
# Mesh
res_x = 33 # data points along roller length
res_y = 31 # data points along roller width
|
class TestAuth:
"""
Test all functions relating to authentication in api.py. Logout is designed always to return success (even if user
not logged in), since its job is to clear session data.
"""
def test_1(self, auth): # login and logout: correct input and method
res = auth.login(uname="U1", password="111")
assert res.headers.get("Set-Cookie") is not None
assert res.json()["status"] == 1
# logout to clear session
res = auth.logout()
assert "session=; Expires=Thu, 01-Jan-1970 00:00:00 GMT; Max-Age=0;" in res.headers.get("Set-Cookie")
assert res.json()["status"] == 1
def test_2(self, client): # login: wrong method
res = client.get("/api/auth/login", data={"uname": "U1", "password": "111"})
assert res.status_code == 404
def test_3(self, auth): # login: non-existent username
res = auth.login(uname="0.30000000000000004", password="111")
assert b"Username does not exist." in res.content
def test_4(self, auth): # login: wrong password
res = auth.login(uname="U1", password="000")
assert b"Incorrect password." in res.content
def test_5(self, auth): # login: empty input
res = auth.login(uname=None, password=None)
assert b"Invalid input." in res.content
def test_6(self, auth): # register: correct
res = auth.register(uname="foobar", password="@123456a", nickname="Hook")
assert res.json()["status"] == 1
auth.logout() # clear session
res = auth.login(uname="foobar", password="@123456a")
assert res.headers.get("Set-Cookie") is not None
assert res.json()["status"] == 1
auth.logout()
def test_7(self, auth): # register: invalid uname/password/nickname
res = auth.register(uname="foo", password="@123456a", nickname="Hook")
assert b"Username must be of length 5 ~ 20." in res.content
res = auth.register(uname="foo123", password="12345678", nickname="Hook")
assert b"Invalid password." in res.content
res = auth.register(uname="foo123", password="@123456a", nickname="H" * 21)
assert b"Invalid nickname." in res.content
|
e={'Eid':100120,'name':'vijay','age':21}
e1={'Eid':100121,'name':'vijay','age':21}
e3={'Eid':100122,'name':'vijay','age':21}
print(e)
print(e.get('name'))
e['age']=22;
for i in e.keys():
print(e[i])
for i,j in e.items():
print(i,j)
|
class Solution(object):
def islandPerimeter(self, grid):
"""
:type grid: List[List[int]]
:rtype: int
"""
island_num = neighbor_num = 0
for i in range(len(grid)):
for j in range(len(grid[i])):
if grid[i][j] == 1:
island_num += 1
if i < len(grid) - 1 and grid[i + 1][j] == 1:
neighbor_num += 1
if j < len(grid[i]) - 1 and grid[i][j + 1] == 1:
neighbor_num += 1
return island_num * 4 - neighbor_num * 2
|
def all_doe_stake_transactions():
data = {
'module': 'account',
'action': 'txlist',
'address':'0x60C6b5DC066E33801F2D9F2830595490A3086B4e',
'startblock':'13554136',
'endblock':'99999999',
# 'page': '1',
# 'offset': '5',
'sort': 'asc',
'apikey': hidden_details.etherscan_key,
}
return requests.get("https://api.etherscan.io/api", data=data).json()['result']
def dump_all_stakers():
addresses = []
dump = all_doe_stake_transactions()
for tx in dump:
addr = tx['from']
if addr not in addresses:
addresses.append(addr) |
'''
Created on 2018年1月31日
@author: lenovo
'''
if __name__ == '__main__':
opposite = {'(': ')', '[': ']', '{': '}'}
print(opposite) |
#Crie um pgm q tenha a função leiaint(), que vai funcionar de forma semelhante à função input() do Python, só q fazendo a validação para aceitar apenas um valor numérico.
#n=leiaint('Digite um n')
def leiaint(msg):
num = input(msg)
while num.isnumeric() is False:
print(f'ERRO! {num} não é um número inteiro válido.')
num = input(msg)
num = int(num)
return num
n=leiaint('Digite um número: ')
print(f'Você acabou de digitar o número {n}')
|
# -*- coding: utf-8 -*-
"""
Spyderエディタ
これは一時的なスクリプトファイルです
"""
print('hello world')
print('I like 6.00.1x!')
a = 0
b = 1
if a < b:
print ("True")
else:
print ("false") |
n = int(input('Digite um numero! '))
m = n-1
s = n+1
print('O numero escolhido é {} seu antecessor é {} e seu sucessor é {}!' .format(n, m, s))
|
# -*- coding: utf-8 -*-
class Solution(object):
def removeDuplicates(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
last = 0
for i in range(1, len(nums)):
if nums[i] != nums[last]:
last += 1
nums[last] = nums[i]
return last + 1
print(Solution().removeDuplicates([1,1,2])) |
"""
53. How to get the last n rows of a dataframe with row sum > 100?
"""
"""
Difficulty Level: L2
"""
"""
Get the last two rows of df whose row sum is greater than 100.
"""
"""
df = pd.DataFrame(np.random.randint(10, 40, 60).reshape(-1, 4))
"""
|
class Thinker:
def __init__(self):
self.velocity = 0
def viewDistance(self):
return 20
def step(self, deltaTime):
self.velocity = 30
def getVelocity(self):
return self.velocity |
__author__ = 'fernando'
class BaseAuth(object):
def has_data(self):
raise NotImplementedError()
def get_username(self):
raise NotImplementedError()
def get_password(self):
raise NotImplementedError() |
# -*- coding: utf-8 -*-
def test_readuntil(monkey):
pass
|
class dotRebarSpacing_t(object):
# no doc
EndOffset = None
EndOffsetIsAutomatic = None
EndOffsetIsFixed = None
NumberSpacingZones = None
StartOffset = None
StartOffsetIsAutomatic = None
StartOffsetIsFixed = None
Zones = None
|
# from (Book) OpenCV-Python으로 배우는 영상 처리 및 응용
'''# 01.variable.py - 변수의 자료형'''
variable1 = 100 # 정수 변수 선언
variable2 = 3.14 # 실수 변수 선언
variable3 = -200 # 정수 변수 선언
variable4 = 1.2 + 3.4j # 복소수 변수 선언
variable5 = 'This is Python' # 문자열 변수 선언
variable6 = True # bool 변수 선언
variable7 = float(variable1) # 자료형 변경
variable8 = int(variable2) # 자료형 변경
print('variable1 =' , variable1, type(variable1)) # 변수의 값과 자료형 출력
print('variable2 =' , variable2, type(variable2))
print('variable3 =' , variable3, type(variable3))
print('variable4 =' , variable4, type(variable4))
print('variable5 =' , variable5, type(variable5))
print('variable6 =' , variable6, type(variable6))
print('variable7 =' , variable7, type(variable7)) # 실수로 변경되어 소수점 표시됨
print('variable8 =' , variable8, type(variable8)) # 정수로 변경되어 소수점이하 소실 |
# You can create a generator using a generator expression like a lambda function.
# This function does not need or use a yield keyword.
# Syntax : Y = ([ Expression ])
y = [1,2,3,4,5]
print([x**2 for x in y])
print("\nDoing this without using the generator expressions :")
length = len(y)
print((x**2 for x in y).__next__())
input("Press any key to exit ")
|
# Mock out starturls for ../spiders.py file
class MockGenerator(object):
def __init__(self, *args, **kwargs):
pass
def __call__(self, *args, **kwargs):
return []
class FeedGenerator(MockGenerator):
pass
class FragmentGenerator(MockGenerator):
pass
|
class Time:
def gettime(self):
self.hour=int(input("Enter hour: "))
self.minute=int(input("Enter minute: "))
self.second=int(input("Enter seconds: "))
def display(self):
print(f"Time is {self.hour}:{self.minute}:{self.second}\n")
def __add__(self,other):
sum=Time()
sum.hour=self.hour+other.hour
sum.minute=self.minute+other.minute
if sum.minute>=60:
sum.hour+=1
sum.minute-=60
sum.second=self.second+other.second
if sum.second>=60:
sum.minute+=1
sum.second-=60
return sum
a=Time()
a.gettime()
a.display()
b=Time()
b.gettime()
b.display()
c=a+b
c.display() |
n = int(input())
for i in range(n):
a = input()
set1 = set(input().split())
b = input()
set2 = set(input().split())
print(set1.issubset(set2))
|
def estimator(data):
reportedCases=data['reportedCases']
totalHospitalBeds=data['totalHospitalBeds']
output={"data": {},"impact": {},"severeImpact":{}}
output['impact']['currentlyInfected']=reportedCases * 10
output['severeImpact']['currentlyInfected']=reportedCases * 50
days=28
if days:
factor=int(days/3)
estimate_impact=output['impact']['currentlyInfected'] *pow(2,factor)
output['impact']['infectionsByRequestedTime']=estimate_impact
estimate_severeimpact=output['severeImpact']['currentlyInfected']* pow(2,factor)
output['severeImpact']['infectionsByRequestedTime']=estimate_severeimpact
impact_=output['impact']['infectionsByRequestedTime'] *0.15
severimpact_=output['severeImpact']['infectionsByRequestedTime']*0.15
output['impact']['severeCasesByRequestedTime']=impact_
output['severeImpact']['severeCasesByRequestedTime']=severimpact_
beds_available =round(totalHospitalBeds*0.35,0)
available_hospital_beds_impact=beds_available - output['impact']['severeCasesByRequestedTime']
available_hospital_beds_severeImpact= beds_available - output['severeImpact']['severeCasesByRequestedTime']
output['impact']['hospitalBedsByRequestedTime']=available_hospital_beds_impact
output['severeImpact']['hospitalBedsByRequestedTime']=available_hospital_beds_severeImpact
output['data']=data
impact_icu=output['impact']['infectionsByRequestedTime'] *0.05
severimpact_icu=output['severeImpact']['infectionsByRequestedTime']*0.05
output['impact']['casesForICUByRequestedTime']=impact_icu
output['severeImpact']['casesForICUByRequestedTime']=severimpact_icu
impact_vetilator=output['impact']['infectionsByRequestedTime'] *0.02
severimpact_vetilator=output['severeImpact']['infectionsByRequestedTime']*0.02
output['impact']['casesForVentilatorsByRequestedTime']=impact_vetilator
output['severeImpact']['casesForVentilatorsByRequestedTime']=severimpact_vetilator
dollarsInFlight_1=output['impact']['infectionsByRequestedTime']
dollarsInFlight_2=output['severeImpact']['infectionsByRequestedTime']
estimated_money=dollarsInFlight_1*0.85*5*30
estimated_money1=dollarsInFlight_2*0.85*5*30
output['impact']['dollarsInFlight']=estimated_money
output['severeImpact']['dollarsInFlight']=estimated_money1
final_output={"data":{}, "estimate":{}}
final_output['data']=data
final_output['estimate']["impact"]=output["impact"]
final_output['estimate']["severeImpact"]=output["severeImpact"]
return final_output
elif data['weeks']:
days=data['weeks']*7
factor=round(days/3,0)
estimate_impact=output['impact']['currentlyInfected'] *pow(2,factor)
output['impact']['infectionsByRequestedTime']=estimate_impact
estimate_severeimpact=output['severeImpact']['currentlyInfected']* pow(2,factor)
output['severeImpact']['infectionsByRequestedTime']=estimate_severeimpact
impact_=output['impact']['infectionsByRequestedTime'] *0.15
severimpact_=output['severeImpact']['infectionsByRequestedTime']*0.15
output['impact']['severeCasesByRequestedTime']=impact_
output['severeImpact']['severeCasesByRequestedTime']=severimpact_
beds_available =round(totalHospitalBeds*0.35,0)
available_hospital_beds_impact=beds_available - output['impact']['severeCasesByRequestedTime']
available_hospital_beds_severeImpact= beds_available - output['severeImpact']['severeCasesByRequestedTime']
output['impact']['hospitalBedsByRequestedTime']=available_hospital_beds_impact
output['severeImpact']['hospitalBedsByRequestedTime']=available_hospital_beds_severeImpact
output['data']=data
impact_icu=output['impact']['infectionsByRequestedTime'] *0.05
severimpact_icu=output['severeImpact']['infectionsByRequestedTime']*0.05
output['impact']['casesForICUByRequestedTime']=impact_icu
output['severeImpact']['casesForICUByRequestedTime']=severimpact_icu
impact_vetilator=output['impact']['infectionsByRequestedTime'] *0.02
severimpact_vetilator=output['severeImpact']['infectionsByRequestedTime']*0.02
output['impact']['casesForVentilatorsByRequestedTime']=impact_vetilator
output['severeImpact']['casesForVentilatorsByRequestedTime']=severimpact_vetilator
dollarsInFlight_1=output['impact']['infectionsByRequestedTime']
dollarsInFlight_2=output['severeImpact']['infectionsByRequestedTime']
estimated_money=dollarsInFlight_1*0.85*5*30
estimated_money1=dollarsInFlight_2*0.85*5*30
output['impact']['dollarsInFlight']=estimated_money
output['severeImpact']['dollarsInFlight']=estimated_money1
return output
elif data['months']:
days= data['months']*30
factor=round(days/3,0)
estimate_impact=output['impact']['currentlyInfected'] *pow(2,factor)
output['impact']['infectionsByRequestedTime']=estimate_impact
estimate_severeimpact=output['severeImpact']['currentlyInfected']* pow(2,factor)
output['severeImpact']['infectionsByRequestedTime']=estimate_severeimpact
impact_=output['impact']['infectionsByRequestedTime'] *0.15
severimpact_=output['severeImpact']['infectionsByRequestedTime']*0.15
output['impact']['severeCasesByRequestedTime']=impact_
output['severeImpact']['severeCasesByRequestedTime']=severimpact_
beds_available =round(totalHospitalBeds*0.35,0)
available_hospital_beds_impact=beds_available - output['impact']['severeCasesByRequestedTime']
available_hospital_beds_severeImpact= beds_available - output['severeImpact']['severeCasesByRequestedTime']
output['impact']['hospitalBedsByRequestedTime']=available_hospital_beds_impact
output['severeImpact']['hospitalBedsByRequestedTime']=available_hospital_beds_severeImpact
output['data']=data
impact_icu=output['impact']['infectionsByRequestedTime'] *0.05
severimpact_icu=output['severeImpact']['infectionsByRequestedTime']*0.05
output['impact']['casesForICUByRequestedTime']=impact_icu
output['severeImpact']['casesForICUByRequestedTime']=severimpact_icu
impact_vetilator=output['impact']['infectionsByRequestedTime'] *0.02
severimpact_vetilator=output['severeImpact']['infectionsByRequestedTime']*0.02
output['impact']['casesForVentilatorsByRequestedTime']=impact_vetilator
output['severeImpact']['casesForVentilatorsByRequestedTime']=severimpact_vetilator
dollarsInFlight_1=output['impact']['infectionsByRequestedTime']
dollarsInFlight_2=output['severeImpact']['infectionsByRequestedTime']
estimated_money=dollarsInFlight_1*0.85*5*30
estimated_money1=dollarsInFlight_2*0.85*5*30
output['impact']['dollarsInFlight']=estimated_money
output['severeImpact']['dollarsInFlight']=estimated_money1
return output
else:
return{'error':"no data "}
|
class Location(object):
"""
Represents a Location where an Action could be taken.
"""
def __init__(self, location_id: str):
"""
Create a new Location.
:param location_id: The id of the Location.
"""
self._location_id: str = location_id
@property
def location_id(self) -> str:
"""
Return the id of the Location.
"""
return self._location_id
def __repr__(self) -> str:
return 'Location({})'.format(self._location_id)
def __gt__(self, other: 'Location') -> bool:
return self._location_id > other._location_id
def __lt__(self, other: 'Location') -> bool:
return self._location_id < other._location_id
|
# The base class for all widgets
class Widget:
def __init__(self, name):
self.name = name
pass
def press_on(self, key):
"""Called with the argument `key`"""
pass
def release_on(self, k):
pass
# Text related methods
def start_text_on(self, k):
pass
def update_text_on(self, k):
pass
def end_text_on(self, k):
pass
def refresh(self):
if self.window:
self.window.noutrefresh()
|
"""
Space : O(n)
Time : O(n)
Hackerrank competition
"""
def getMinimumUniqueSum(arr):
ans = 0
dp = [0] * 7000
for i in arr:
dp[i] += 1
n = len(dp)
for i in range(n-1):
if dp[i] > 1:
dp[i+1] += dp[i] - 1
dp[i] = 1
for j in range(n):
if dp[j] > 0:
ans += j
return ans
|
num1=int(input('Enter the first number:'))
num2=int(input('Enter the second number:'))
sum=lambda num1,num2:num1+num2
diff=lambda num1,num2:num1-num2
mul=lambda num1,num2:num1*num2
div=lambda num1,num2:num1//num2
print("Sum is:",sum(num1,num2))
print("Difference is:",diff(num1,num2))
print("Multiply is",mul(num1,num2))
print("Division is:",div(num1,num2))
|
"""
command line function stuff
@author: matt milunski
"""
def check_refresh(input):
if input >= 1:
return input
else:
return 1
def check_currency(input):
assert len(input) > 0, "you forgot to specify the crypto to track"
return input |
SECRET_KEY='development-key'
MYSQL_DATABASE_USER='root'
MYSQL_DATABASE_PASSWORD='classroom'
MYSQL_DATABASE_DB='Ascott_InvMgmt'
MYSQL_DATABASE_HOST='dogfood.coxb3venarbl.ap-southeast-1.rds.amazonaws.com'
UPLOADS_DEFAULT_DEST = 'static/img/items/'
UPLOADS_DEFAULT_URL = 'http://localhost:5000/static/img/items/'
UPLOADED_IMAGES_DEST = 'static/img/items/'
UPLOADED_IMAGES_URL = 'http://localhost:5000/static/img/items/'
BABEL_LOCALES = ('en', 'zh', 'ms', 'ta')
BABEL_DEFAULT_LOCALE = "en"
# Property-specific info
# Timezone string follows TZ format (see https://en.wikipedia.org/wiki/List_of_tz_database_time_zones)
TIMEZONE = "Asia/Singapore"
PROP_NAME = "Capstone Room"
|
class ThreadModule(object):
'''docstring for ThreadModule'''
def __init__(self, ):
super().__init__() |
# Copyright (c) 2014, MapR Technologies
#
# 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.
OOZIE = 'Oozie'
HIVE = 'Hive'
HIVE_METASTORE = 'HiveMetastore'
HIVE_SERVER2 = 'HiveServer2'
CLDB = 'CLDB'
FILE_SERVER = 'FileServer'
ZOOKEEPER = 'ZooKeeper'
RESOURCE_MANAGER = 'ResourceManager'
HISTORY_SERVER = 'HistoryServer'
IS_M7_ENABLED = 'Enable MapR-DB'
GENERAL = 'general'
JOBTRACKER = 'JobTracker'
NODE_MANAGER = 'NodeManager'
DATANODE = 'Datanode'
TASK_TRACKER = 'TaskTracker'
SECONDARY_NAMENODE = 'SecondaryNamenode'
NFS = 'NFS'
WEB_SERVER = 'Webserver'
WAIT_OOZIE_INTERVAL = 300
WAIT_NODE_ALARM_NO_HEARTBEAT = 360
ecosystem_components = ['Oozie',
'Hive-Metastore',
'HiveServer2',
'HBase-Master',
'HBase-RegionServer',
'HBase-Client',
'Pig']
|
def Analysis(cipherText):
alphabet = dict(zip('ABCDEFGHIJKLMNOPQRSTUVWXYZ', [0] * 27))
for letter in cipherText:
if letter.isalpha():
alphabet[letter] += 1
for key, value in alphabet.items():
alphabet[key] = value * (value - 1)
IC = sum(alphabet.values()) / (len(cipherText) * len(cipherText) - 1)
key_len = abs(((0.027 * len(cipherText)) / (len(cipherText) - 1) * IC - 0.038 * len(cipherText) + 0.065))
IC = "%.6f" % IC
key_len = "%.2f" % key_len
return float(IC), key_len |
# find nth fibonacci number using recursion.
# sample output:
# 21
def findnthfibnumber(n, map={1: 0, 2: 1}):
if n in map:
return map[n]
else:
map[n] = findnthfibnumber(n-1, map) + findnthfibnumber(n-2, map)
return map[n]
print (findnthfibnumber(9))
|
class Solution:
def countElements(self, arr: List[int]) -> int:
d = {}
count = 0
for i in arr:
d[i] = 1
for x in arr:
if x+1 in d.keys():
count += 1
return count
|
def part_1() -> None:
h_pos: int = 0
v_pos: int = 0
with open("../data/day2.txt", "r") as dFile:
for row in dFile.readlines():
value: int = int(row.split(" ")[1])
match row.split(" ")[0]:
case "forward":
h_pos += value
case "down":
v_pos += value
case "up":
v_pos -= value
case _:
raise ValueError(f"Unsupported command {row.split(' ')[0]}")
print("Day: 2 | Part: 1 | Result:", h_pos * v_pos)
def part_2() -> None:
h_pos: int = 0
v_pos: int = 0
aim : int = 0
with open("../data/day2.txt", "r") as dFile:
for row in dFile.readlines():
value: int = int(row.split(" ")[1])
match row.split(" ")[0]:
case "forward":
h_pos += value
v_pos += value * aim
case "down":
aim += value
case "up":
aim -= value
case _:
raise ValueError(f"Unsupported command {row.split(' ')[0]}")
print("Day: 2 | Part: 2 | Result:", h_pos * v_pos)
if __name__ == "__main__":
part_1()
part_2()
|
pkgname = "libffi8"
pkgver = "3.4.2"
pkgrel = 0
build_style = "gnu_configure"
configure_args = [
"--includedir=/usr/include", "--disable-multi-os-directory", "--with-pic"
]
hostmakedepends = ["pkgconf"]
# actually only on x86 and arm (tramp.c code) but it does not hurt
makedepends = ["linux-headers"]
checkdepends = ["dejagnu"]
pkgdesc = "Library supporting Foreign Function Interfaces"
maintainer = "q66 <q66@chimera-linux.org>"
license = "MIT"
url = "http://sourceware.org/libffi"
source = f"https://github.com/libffi/libffi/releases/download/v{pkgver}/libffi-{pkgver}.tar.gz"
sha256 = "540fb721619a6aba3bdeef7d940d8e9e0e6d2c193595bc243241b77ff9e93620"
# missing checkdepends for now
options = ["!check"]
def post_install(self):
self.install_license("LICENSE")
@subpackage("libffi-devel")
def _devel(self):
return self.default_devel(man = True, extra = ["usr/share/info"])
|
#
# PySNMP MIB module HPN-ICF-L2VPN-PWE3-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/HPN-ICF-L2VPN-PWE3-MIB
# Produced by pysmi-0.3.4 at Mon Apr 29 19:27:17 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)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ValueRangeConstraint, ValueSizeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection")
hpnicfCommon, = mibBuilder.importSymbols("HPN-ICF-OID-MIB", "hpnicfCommon")
ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup")
Gauge32, Bits, MibIdentifier, Counter64, ModuleIdentity, Counter32, Unsigned32, ObjectIdentity, IpAddress, NotificationType, iso, TimeTicks, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "Gauge32", "Bits", "MibIdentifier", "Counter64", "ModuleIdentity", "Counter32", "Unsigned32", "ObjectIdentity", "IpAddress", "NotificationType", "iso", "TimeTicks", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn")
DisplayString, RowStatus, TextualConvention, TruthValue = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "RowStatus", "TextualConvention", "TruthValue")
hpnicfL2VpnPwe3 = ModuleIdentity((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78))
if mibBuilder.loadTexts: hpnicfL2VpnPwe3.setLastUpdated('200703310000Z')
if mibBuilder.loadTexts: hpnicfL2VpnPwe3.setOrganization('')
class HpnicfL2VpnVcEncapsType(TextualConvention, Integer32):
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 64, 255))
namedValues = NamedValues(("frameRelayDlciMartini", 1), ("atmAal5SduVccTransport", 2), ("atmTransparentCellTransport", 3), ("ethernetTagged", 4), ("ethernet", 5), ("hdlc", 6), ("ppp", 7), ("cem", 8), ("atmN2OneVccCellTransport", 9), ("atmN2OneVpcCellTransport", 10), ("ipLayer2Transport", 11), ("atmOne2OneVccCellMode", 12), ("atmOne2OneVpcCellMode", 13), ("atmAal5PduVccTransport", 14), ("frameRelayPortMode", 15), ("cep", 16), ("saE1oP", 17), ("saT1oP", 18), ("saE3oP", 19), ("saT3oP", 20), ("cESoPsnBasicMode", 21), ("tDMoIPbasicMode", 22), ("l2VpnCESoPSNTDMwithCAS", 23), ("l2VpnTDMoIPTDMwithCAS", 24), ("frameRelayDlci", 25), ("ipInterworking", 64), ("unknown", 255))
hpnicfL2VpnPwe3ScalarGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 1))
hpnicfPwVcTrapOpen = MibScalar((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite")
if mibBuilder.loadTexts: hpnicfPwVcTrapOpen.setStatus('current')
hpnicfL2VpnPwe3Table = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2))
hpnicfPwVcTable = MibTable((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1), )
if mibBuilder.loadTexts: hpnicfPwVcTable.setStatus('current')
hpnicfPwVcEntry = MibTableRow((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1), ).setIndexNames((0, "HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcIndex"))
if mibBuilder.loadTexts: hpnicfPwVcEntry.setStatus('current')
hpnicfPwVcIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 1), Integer32())
if mibBuilder.loadTexts: hpnicfPwVcIndex.setStatus('current')
hpnicfPwVcID = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 2), Unsigned32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hpnicfPwVcID.setStatus('current')
hpnicfPwVcType = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 3), HpnicfL2VpnVcEncapsType()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hpnicfPwVcType.setStatus('current')
hpnicfPwVcPeerAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 4), IpAddress()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hpnicfPwVcPeerAddr.setStatus('current')
hpnicfPwVcMtu = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 5), Unsigned32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hpnicfPwVcMtu.setStatus('current')
hpnicfPwVcCfgType = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("primary", 1), ("backup", 2), ("multiPort", 3)))).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hpnicfPwVcCfgType.setStatus('current')
hpnicfPwVcInboundLabel = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 7), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfPwVcInboundLabel.setStatus('current')
hpnicfPwVcOutboundLabel = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 8), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfPwVcOutboundLabel.setStatus('current')
hpnicfPwVcIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 9), Unsigned32()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hpnicfPwVcIfIndex.setStatus('current')
hpnicfPwVcAcStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("down", 1), ("up", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfPwVcAcStatus.setStatus('current')
hpnicfPwVcStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("down", 1), ("up", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: hpnicfPwVcStatus.setStatus('current')
hpnicfPwVcRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 2, 1, 1, 12), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: hpnicfPwVcRowStatus.setStatus('current')
hpnicfL2VpnPwe3Notifications = MibIdentifier((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3))
hpnicfPwVcSwitchWtoP = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 1)).setObjects(("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr"))
if mibBuilder.loadTexts: hpnicfPwVcSwitchWtoP.setStatus('current')
hpnicfPwVcSwitchPtoW = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 2)).setObjects(("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr"))
if mibBuilder.loadTexts: hpnicfPwVcSwitchPtoW.setStatus('current')
hpnicfPwVcDown = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 3)).setObjects(("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr"))
if mibBuilder.loadTexts: hpnicfPwVcDown.setStatus('current')
hpnicfPwVcUp = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 4)).setObjects(("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr"))
if mibBuilder.loadTexts: hpnicfPwVcUp.setStatus('current')
hpnicfPwVcDeleted = NotificationType((1, 3, 6, 1, 4, 1, 11, 2, 14, 11, 15, 2, 78, 3, 5)).setObjects(("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcID"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcType"), ("HPN-ICF-L2VPN-PWE3-MIB", "hpnicfPwVcPeerAddr"))
if mibBuilder.loadTexts: hpnicfPwVcDeleted.setStatus('current')
mibBuilder.exportSymbols("HPN-ICF-L2VPN-PWE3-MIB", hpnicfPwVcEntry=hpnicfPwVcEntry, hpnicfPwVcOutboundLabel=hpnicfPwVcOutboundLabel, hpnicfPwVcID=hpnicfPwVcID, hpnicfL2VpnPwe3Table=hpnicfL2VpnPwe3Table, hpnicfL2VpnPwe3=hpnicfL2VpnPwe3, hpnicfPwVcTable=hpnicfPwVcTable, hpnicfPwVcSwitchPtoW=hpnicfPwVcSwitchPtoW, PYSNMP_MODULE_ID=hpnicfL2VpnPwe3, hpnicfPwVcAcStatus=hpnicfPwVcAcStatus, hpnicfPwVcDeleted=hpnicfPwVcDeleted, hpnicfPwVcStatus=hpnicfPwVcStatus, hpnicfL2VpnPwe3Notifications=hpnicfL2VpnPwe3Notifications, hpnicfPwVcMtu=hpnicfPwVcMtu, hpnicfPwVcSwitchWtoP=hpnicfPwVcSwitchWtoP, hpnicfPwVcIndex=hpnicfPwVcIndex, hpnicfPwVcUp=hpnicfPwVcUp, hpnicfPwVcDown=hpnicfPwVcDown, hpnicfPwVcIfIndex=hpnicfPwVcIfIndex, hpnicfPwVcType=hpnicfPwVcType, hpnicfPwVcCfgType=hpnicfPwVcCfgType, hpnicfPwVcInboundLabel=hpnicfPwVcInboundLabel, HpnicfL2VpnVcEncapsType=HpnicfL2VpnVcEncapsType, hpnicfPwVcRowStatus=hpnicfPwVcRowStatus, hpnicfL2VpnPwe3ScalarGroup=hpnicfL2VpnPwe3ScalarGroup, hpnicfPwVcTrapOpen=hpnicfPwVcTrapOpen, hpnicfPwVcPeerAddr=hpnicfPwVcPeerAddr)
|
"""
This file contains misc functions that are used throughout the project...
"""
def print_dict(d, level=0):
# Prints a dictionary
for k, v in d.items():
if isinstance(v, dict):
print(level * '\t', k, ':')
print_dict(v, level + 1)
else:
print(level * '\t', k, '-', v)
|
{
"targets": [
{
"target_name": "gameLauncher",
"conditions": [
["OS==\"win\"", {
"sources": [
"srcs/windows/GameLauncher.cpp"
]
}],
["OS==\"linux\"", {
"sources": [
"srcs/linux/GameLauncher.cpp"
]
}]
]
}
]
}
|
# pylint: disable=undefined-variable
## Whether to include output from clients other than this one sharing the same
# kernel.
# Required for jupyter-vim, see:
# https://github.com/jupyter-vim/jupyter-vim#jupyter-configuration
c.ZMQTerminalInteractiveShell.include_other_output = True
## Text to display before the first prompt. Will be formatted with variables
# {version} and {kernel_banner}.
c.ZMQTerminalInteractiveShell.banner = 'Jupyter console {version}'
## Shortcut style to use at the prompt. 'vi' or 'emacs'.
#c.ZMQTerminalInteractiveShell.editing_mode = 'emacs'
## The name of a Pygments style to use for syntax highlighting
c.ZMQTerminalInteractiveShell.highlighting_style = 'solarized-dark'
## How many history items to load into memory
c.ZMQTerminalInteractiveShell.history_load_length = 1000
## Use 24bit colors instead of 256 colors in prompt highlighting. If your
# terminal supports true color, the following command should print 'TRUECOLOR'
# in orange: printf "\x1b[38;2;255;100;0mTRUECOLOR\x1b[0m\n"
c.ZMQTerminalInteractiveShell.true_color = True
|
# Function to count number of substrings
# with exactly k unique characters
def countkDist(str1, k):
n = len(str1)
# Initialize result
res = 0
# Consider all substrings beginning
# with str[i]
for i in range(0, n):
dist_count = 0
# Initializing array with 0
cnt = [0] * 27
# Consider all substrings between str[i..j]
for j in range(i, n):
# If this is a new character for this
# substring, increment dist_count.
if(cnt[ord(str1[j]) - 97] == 0):
dist_count += 1
# Increment count of current character
cnt[ord(str1[j]) - 97] += 1
# If distinct character count becomes k,
# then increment result.
if(dist_count == k):
res += 1
if(dist_count > k):
break
return res
|
# -*- coding: utf-8 -*-
@bot.message_handler(commands=['qrcode', 'Qrcode'])
def qr_image(message):
userlang = redisserver.get("settings:user:language:" + str(message.from_user.id))
userid = message.from_user.id
banlist = redisserver.sismember('zigzag_banlist', '{}'.format(userid))
if banlist:
return
if len(message.text.replace("◻️ QR Code", "", 1).split()) < 2:
bot.reply_to(message, language[userlang]["QRCODE_NEA_MSG"], parse_mode="Markdown")
return
argus = message.text.replace("/qrcode ","").replace(" ", "%20")
bot.reply_to(message, "Processing..")
urllib.urlretrieve("http://api.qrserver.com/v1/create-qr-code/?data={}&size=600x600".format(argus), 'qrcode.png')
# print("http://apimeme.com/meme?meme={}&top={}&bottom={}".format(args[0], args[1], args[2]))
bot.send_photo(message.chat.id, open('qrcode.png'), caption=" QR Code by @TheZigZagBot")
|
def check_order(scale_list):
ascending_list = sorted(scale_list)
descending_list = sorted(scale_list, reverse=True)
if scale_list == ascending_list:
return "ascending"
elif scale_list == descending_list:
return "descending"
else:
return "mixed"
def main():
scale_list = input().split()
result_value = check_order(scale_list)
print(result_value)
if __name__ == "__main__":
main()
|
#! /usr/bin/env python3
# -*- coding: UTF-8 -*-
#------------------------------------------------------------------------------
def asSeparator () :
return "//" + ("-" * 78) + "\n"
#------------------------------------------------------------------------------
def generateInterruptSection (interruptSectionName) :
sCode = asSeparator ()
sCode += "// INTERRUPT - SECTION: " + interruptSectionName + "\n"
sCode += asSeparator () + "\n"
sCode += " .section .text.interrupt." + interruptSectionName + ", \"ax\", %progbits\n\n"
sCode += " .align 1\n"
sCode += " .global interrupt." + interruptSectionName + "\n"
sCode += " .type interrupt." + interruptSectionName + ", %function\n\n"
sCode += "interrupt." + interruptSectionName + ":\n"
sCode += "//----------------------------------------- R2 <- CPU INDEX\n"
sCode += " ldr r3, = 0xD0000000 + 0x000 // Address of SIO CPUID control register\n"
sCode += " ldr r2, [r3] // R2 <- 0 for CPU0, 1 for CPU 1\n"
sCode += "//----------------------------------------- Activity led On\n"
sCode += " MACRO_ACTIVITY_LED_0_OR_1_ON // R2 should contain CPU index\n"
sCode += "//--- Save registers\n"
sCode += " push {r4, lr}\n"
sCode += "//--- R4 <- Address of SPINLOCK 0 (rp2040 datasheet, 2.3.1.7, page 42)\n"
sCode += " ldr r4, = 0xD0000000 + 0x100\n"
sCode += "//--- Read: attempt to claim the lock. Read value is nonzero if the lock was\n"
sCode += "// successfully claimed, or zero if the lock had already been claimed\n"
sCode += "// by a previous read (rp2040 datasheet, section 2.3.1.3 page 30).\n"
sCode += interruptSectionName +".spinlock.busy.wait:\n"
sCode += " ldr r0, [r4]\n"
sCode += " cmp r0, #0\n"
sCode += " beq " + interruptSectionName +".spinlock.busy.wait\n"
sCode += "//--- Call section, interrupts disabled, spinlock successfully claimed\n"
sCode += " bl interrupt.section." + interruptSectionName + "\n"
sCode += "//--- Write (any value): release the lock (rp2040 datasheet, section 2.3.1.3 page 30).\n"
sCode += "// The next attempt to claim the lock will be successful.\n"
sCode += " str r0, [r4]\n"
sCode += "//--- Return\n"
sCode += " pop {r4, pc}\n\n"
return ("", sCode)
#------------------------------------------------------------------------------
# ENTRY POINT
#------------------------------------------------------------------------------
def buildSectionInterruptCode (interruptSectionList):
#------------------------------ Destination file strings
cppFile = ""
sFile = ""
#------------------------------ Iterate on section sectionList
for interruptSectionName in interruptSectionList :
(cppCode, sCode) = generateInterruptSection (interruptSectionName)
cppFile += cppCode
sFile += sCode
#------------------------------ Return
return (cppFile, sFile)
#------------------------------------------------------------------------------
|
class Solution(object):
# Empty list + join (Accepted + Top Voted), O(n) space and time
def restoreString(self, s, indices):
"""
:type s: str
:type indices: List[int]
:rtype: str
"""
ret = [None] * len(s)
for i in range(len(s)):
ret[indices[i]] = s[i]
return "".join(ret)
|
'''
File name: jr_utils.py
Author: Tyche Analytics Co.
Note: truncated file, suitable for model inference, but not development
'''
"""Collect various utility functions for JR model"""
def mean(xs):
if hasattr(xs,"__len__"):
return sum(xs)/float(len(xs))
else:
acc = 0
n = 0
for x in xs:
acc += x
n += 1
return acc/float(n)
def variance(xs,correct=True):
n = len(xs)
correction = n/float(n-1) if correct else 1
mu = mean(xs)
return correction * mean([(x-mu)**2 for x in xs])
def se(xs,correct=True):
return sd(xs,correct)/sqrt(len(xs))
|
def two_fer(name="you"):
"""Returns a string in the two-fer format."""
return "One for " + name + ", one for me."
|
"""
© https://sudipghimire.com.np
Sets Exercises
Please read the note carefully and try to solve the problem below:
"""
"""
1. Write a program to create two different set of countries
i. rich: {'USA', 'China', 'Japan', 'Germany', 'France', 'Australia', 'Italy'}
ii. europe: {'Germany', 'France', 'England', 'Switzerland', 'Italy', 'Portugal', 'Sweden'}
Use the Set methods to find out:
a. countries that are rich but not in Europe
b. countries that are in Europe but not rich
c. countries that are both rich and are in Europe
d. countries that are either rich or in Europe, but not both
e. all the countries in either of the sets. (Names must be unique)
f. see if two sets are disjoint or not
g. now remove the common countries from the `rich` set and check if two sets are disjoint or not.
- hint: use `difference_update()` method. for more, please refer to python documentation
"""
# answer 1.
# a
# b
# c
# d
# e
# f
# g
"""
2. Create two more sets
i. `asian_rich` and add {'China', 'Japan'} to it.
ii. `american_rich` and add {'USA', 'Canada'} to it.
and check whether:
a. `asian_rich` is a subset of `rich` or not
b. `rich` is a superset of `asian_rich` or not
c. `american_rich` is a subset of `rich` or not
"""
# answer 2
# a
# b
# c
|
in_str = list(str(input()))
str_len = len(in_str)
# letters set
set_letters = set(in_str)
set_len = len(set_letters)
if str_len == set_len:
print("Unique")
else:
print("Deja Vu") |
# Copyright (c) 2015 The WebRTC project authors. All Rights Reserved.
#
# Use of this source code is governed by a BSD-style license
# that can be found in the LICENSE file in the root of the source
# tree. An additional intellectual property rights grant can be found
# in the file PATENTS. All contributing project authors may
# be found in the AUTHORS file in the root of the source tree.
{
'includes': [ '../build/common.gypi', ],
'targets': [
{
'target_name': 'peerconnection_unittests',
'type': '<(gtest_target_type)',
'dependencies': [
'<(DEPTH)/testing/gmock.gyp:gmock',
'<(webrtc_root)/api/api.gyp:libjingle_peerconnection',
'<(webrtc_root)/base/base_tests.gyp:rtc_base_tests_utils',
'<(webrtc_root)/common.gyp:webrtc_common',
'<(webrtc_root)/media/media.gyp:rtc_unittest_main',
'<(webrtc_root)/pc/pc.gyp:rtc_pc',
],
'direct_dependent_settings': {
'include_dirs': [
'<(DEPTH)/testing/gmock/include',
],
},
'defines': [
# Feature selection.
'HAVE_SCTP',
],
'sources': [
'datachannel_unittest.cc',
'dtlsidentitystore_unittest.cc',
'dtmfsender_unittest.cc',
'fakemetricsobserver.cc',
'fakemetricsobserver.h',
'jsepsessiondescription_unittest.cc',
'localaudiosource_unittest.cc',
'mediaconstraintsinterface_unittest.cc',
'mediastream_unittest.cc',
'peerconnection_unittest.cc',
'peerconnectionendtoend_unittest.cc',
'peerconnectionfactory_unittest.cc',
'peerconnectioninterface_unittest.cc',
'proxy_unittest.cc',
'rtpsenderreceiver_unittest.cc',
'statscollector_unittest.cc',
'test/fakeaudiocapturemodule.cc',
'test/fakeaudiocapturemodule.h',
'test/fakeaudiocapturemodule_unittest.cc',
'test/fakeconstraints.h',
'test/fakedatachannelprovider.h',
'test/fakedtlsidentitystore.h',
'test/fakeperiodicvideocapturer.h',
'test/fakevideotrackrenderer.h',
'test/mockpeerconnectionobservers.h',
'test/peerconnectiontestwrapper.h',
'test/peerconnectiontestwrapper.cc',
'test/testsdpstrings.h',
'videocapturertracksource_unittest.cc',
'videotrack_unittest.cc',
'webrtcsdp_unittest.cc',
'webrtcsession_unittest.cc',
],
# TODO(kjellander): Make the code compile without disabling these flags.
# See https://bugs.chromium.org/p/webrtc/issues/detail?id=3307
'cflags': [
'-Wno-sign-compare',
],
'cflags!': [
'-Wextra',
],
'cflags_cc!': [
'-Woverloaded-virtual',
],
'msvs_disabled_warnings': [
4245, # conversion from 'int' to 'size_t', signed/unsigned mismatch.
4267, # conversion from 'size_t' to 'int', possible loss of data.
4389, # signed/unsigned mismatch.
],
'conditions': [
['clang==1', {
# TODO(kjellander): Make the code compile without disabling these flags.
# See https://bugs.chromium.org/p/webrtc/issues/detail?id=3307
'cflags!': [
'-Wextra',
],
'xcode_settings': {
'WARNING_CFLAGS!': ['-Wextra'],
},
}],
['OS=="android"', {
'sources': [
'test/androidtestinitializer.cc',
'test/androidtestinitializer.h',
],
'dependencies': [
'<(DEPTH)/testing/android/native_test.gyp:native_test_native_code',
'<(webrtc_root)/api/api.gyp:libjingle_peerconnection_jni',
],
}],
['OS=="win" and clang==1', {
'msvs_settings': {
'VCCLCompilerTool': {
'AdditionalOptions': [
# Disable warnings failing when compiling with Clang on Windows.
# https://bugs.chromium.org/p/webrtc/issues/detail?id=5366
'-Wno-sign-compare',
'-Wno-unused-function',
],
},
},
}],
['use_quic==1', {
'dependencies': [
'<(DEPTH)/third_party/libquic/libquic.gyp:libquic',
],
'sources': [
'quicdatachannel_unittest.cc',
'quicdatatransport_unittest.cc',
],
'export_dependent_settings': [
'<(DEPTH)/third_party/libquic/libquic.gyp:libquic',
],
}],
], # conditions
}, # target peerconnection_unittests
], # targets
'conditions': [
['OS=="android"', {
'targets': [
{
'target_name': 'libjingle_peerconnection_android_unittest',
'type': 'none',
'dependencies': [
'<(webrtc_root)/api/api.gyp:libjingle_peerconnection_java',
],
'variables': {
'apk_name': 'libjingle_peerconnection_android_unittest',
'java_in_dir': 'androidtests',
'resource_dir': 'androidtests/res',
'native_lib_target': 'libjingle_peerconnection_so',
'is_test_apk': 1,
'test_type': 'instrumentation',
'tested_apk_path': '',
'never_lint': 1,
},
'includes': [
'../../build/java_apk.gypi',
'../../build/android/test_runner.gypi',
],
},
], # targets
}], # OS=="android"
['OS=="android"', {
'targets': [
{
'target_name': 'peerconnection_unittests_apk_target',
'type': 'none',
'dependencies': [
'<(apk_tests_path):peerconnection_unittests_apk',
],
},
],
'conditions': [
['test_isolation_mode != "noop"',
{
'targets': [
{
'target_name': 'peerconnection_unittests_apk_run',
'type': 'none',
'dependencies': [
'<(apk_tests_path):peerconnection_unittests_apk',
],
'includes': [
'../build/isolate.gypi',
],
'sources': [
'peerconnection_unittests_apk.isolate',
],
},
]
}
],
],
}], # OS=="android"
['test_isolation_mode != "noop"', {
'targets': [
{
'target_name': 'peerconnection_unittests_run',
'type': 'none',
'dependencies': [
'peerconnection_unittests',
],
'includes': [
'../build/isolate.gypi',
],
'sources': [
'peerconnection_unittests.isolate',
],
},
], # targets
}], # test_isolation_mode != "noop"
], # conditions
}
|
txtFile=open("/Users/chenchaoyang/Desktop/python/Python/content/content.txt","r")
while True:
line=txtFile.readline()
if not line:
break
else:
print(line)
txtFile.close() |
class DatabaseException(Exception):
"""Base exception for this package."""
pass
class NoDataFoundException(DatabaseException):
"""Should be used when no data has been found."""
pass
class BadDataException(DatabaseException):
"""Should be used when incorrect data is being submitted."""
pass
|
def beautify_parameter_name(s: str) -> str:
"""Make a parameter name look better.
Good for parameter names that have words separated by _ .
1. change _ by spaces.
2. First letter is uppercased.
"""
new_s = " ".join(s.split("_"))
return new_s.capitalize()
|
# Extra parsing for markdown (Highlighting and alert boxes)
def parse(rtxt, look, control):
txtl = rtxt.split(look)
i, j = 0, 0
ret_text = ""
while i < len(txtl):
if j == 0:
# This is the start before the specified tag, add it normally
ret_text += control.start(txtl[i])
j+=1
elif j == 1:
# This is the text we actually want to parse
ret_text += control.inner(txtl[i])
j+=1
else:
ret_text += control.end(txtl[i])
j = 1
i+=1
return ret_text
class Control():
def start(self, s):
return s
def inner(self, s):
return s
def end(self, s):
return s
class HighlightControl(Control):
def inner(self, s):
return "<span class='highlight'>" + s + "</span>"
class BoxControl(Control):
def inner(self, s):
style = s.split("\n")[0].strip().replace("<br />", "") # This controls info, alert, danger, warning, error etc...
if style == "info": # info box
return "<div class='alert-info white' style='color: white !important;'><i class='fa fa-info-circle i-m3' aria-hidden='true'></i><span class='bold'>Info</span>" + s.replace("info", "", 1) + "</div>"
return s
# This adds the == highlighter and ::: boxes
def emd(txt: str) -> str:
# == highlighting
ret_text = parse(txt, "==", HighlightControl())
# ::: boxes
ret_text = parse(ret_text, ":::", BoxControl())
return ret_text
# Test cases
#emd.emd("Hi ==Highlight== We love you == meow == What about you? == mew == ::: info\nHellow world:::")
|
# Copyright 2021, Google LLC
# 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.
# returns fullfillment response for dialogflow detect_intent call
# [START dialogflow_webhook]
# TODO: change the default Entry Point text to handleWebhook
def handleWebhook(request):
req = request.get_json()
responseText = ""
intent = req["queryResult"]["intent"]["displayName"]
if intent == "Default Welcome Intent":
responseText = "Hello from a GCF Webhook"
elif intent == "get-agent-name":
responseText = "My name is Flowhook"
else:
responseText = f"There are no fulfillment responses defined for Intent {intent}"
# You can also use the google.cloud.dialogflowcx_v3.types.WebhookRequest protos instead of manually writing the json object
res = {"fulfillmentMessages": [{"text": {"text": [responseText]}}]}
return res
# [END dialogflow_webhook]
|
class TxtReader:
def __init__(self, f):
self.f = f
def parse(self):
file = open(self.f)
line = file.readline()
while line:
print(line)
line = file.readline()
file.close
#t = TxtReader('sample.txt')
#t.parse()
|
sal = float(input('Digite o valor do seu salário: R$'))
if(sal > 1250):
print('Seu salário agora é R${:.2f}'.format(sal + (sal * 0.10)))
else:
print('Seu salário agora é R${:.2f}'.format(sal + (sal * 0.15)))
|
#!/usr/bin/env python
# encoding: utf-8
"""
search_in_2d_matrix.py
Created by Shengwei on 2014-07-24.
"""
# https://oj.leetcode.com/problems/search-a-2d-matrix/
# tags: easy / medium, matrix, search, edge cases
"""
Write an efficient algorithm that searches for a value in an m x n matrix. This matrix has the following properties:
Integers in each row are sorted from left to right.
The first integer of each row is greater than the last integer of the previous row.
For example,
Consider the following matrix:
[
[1, 3, 5, 7],
[10, 11, 16, 20],
[23, 30, 34, 50]
]
Given target = 3, return true.
"""
# https://oj.leetcode.com/discuss/6201/compare-some-of-solutions-witch-is-most-effective
class Solution:
# @param matrix, a list of lists of integers
# @param target, an integer
# @return a boolean
def searchMatrix(self, matrix, target):
# look for the row where target locates
up, down = 0, len(matrix)
while up < down:
mid = (up + down) / 2
if matrix[mid][0] == target:
return True
if matrix[mid][0] > target:
down = mid
else:
up = mid + 1
# up == down == i+1 where target is in
# row i if it exists; i.e.,
# matrix[up][0] > target > matrix[up-1][0]
if up == 0:
return False
row = up - 1
# search in the row
left, right = 0, len(matrix[row])
while left < right:
mid = (left + right) / 2
if matrix[row][mid] == target:
return True
if matrix[row][mid] > target:
right = mid
else:
left = mid + 1
return False
|
# -*- coding: utf-8 -*-
def greet(name):
i =0
# while True:
# i +=1
first_name, surname = name.split(' ')
return 'Hello {0}, {1}'.format(surname, first_name)
def suggest_travel(distance):
if distance > 5:
return 'You should take the train.'
elif distance > 2:
return 'You should cycle.'
else:
return 'Stop being lazy and walk!'
def fizz_buzz(n):
if n%3==0 and n%5==0:
return 'FizzBuzz'
elif n%3==0:
return 'Fizz'
elif n%5==0:
return 'Buzz'
else:
return n
def sum_odd_numbers(n):
my_sum=0
for i in range(1,n):
if i%2!=0:
my_sum = my_sum + i
return my_sum
def double_char(word):
double_word = "" # initialise double_word as an empty string
for character in word:
double_word = double_word + character*2
return double_word
def sum_div3_numbers(n):
my_sum=0
for i in range(1,n):
if i%3==0:
my_sum = my_sum + i
return my_sum
def sum_numbers(n):
my_sum=0
for i in range(1,n):
my_sum = my_sum + i
return my_sum |
# Para criar uma lista com 5 elementos '_'
# ex. ['_', '_', '_', '_', '_']
print("Lista com elementos iguais")
lista = []
for i in range(5):
lista.append('_')
print("Lista: ", lista)
# Alternativa
lista_alternativa = ['_' for i in range(5)]
print("Modo Alternativdo de criar lista: ", lista_alternativa)
# Para criar uma lista com 6 numeros
# ex. [0, 1, 2, 3, 4, 5]
print("Lista com numeros na sequencia")
lista = []
for i in range(6):
lista.append(i)
print("Lista: ", lista)
# Alternativa
lista_alternativa = [i for i in range(6)]
print("Modo Alternativdo de criar lista: ", lista_alternativa)
# Para criar uma lista com 6 numeros pares
# ex. [0, 2, 4, 6, 8, 10]
print("Lista com 6 numeros pares na sequencia")
lista = []
for i in range(6):
lista.append(i * 2)
print("Lista: ", lista)
# Alternativa
lista_alternativa = [i * 2 for i in range(6)]
print("Modo Alternativdo de criar lista: ", lista_alternativa)
# Para criar uma matriz com elementos repetidos
# ex. [ ['_', '_', '_'],
# ['_', '_', '_'],
# ['_', '_', '_']
# ]
print("Matriz 3x3 com elementos repetidos")
matriz = []
for l in range(3):
linha = []
for c in range(6):
linha.append('_')
matriz.append(linha)
print("Matriz: ", matriz)
# Alternativa
matriz_alternativa = [['_' for c in range(3)] for l in range(3)]
print("Modo Alternativdo de criar matriz: ", matriz_alternativa) |
#hack RSA, caluclate the p,q,d in order by given t,n,e
def finitePrimeHack(t, n, e):
res_list = []
# find p & q
for i in range(2, t):
if n % i == 0:
p = i
q = n//p
res_list.append(p)
res_list.append(q)
#sort the list as p <= q
res_list.sort()
# find the d which is modular inverse of e
d = 0
y = 1
far = (p-1)*(q-1)
while (((far * y) + 1) % e) != 0:
y += 1
d = (far * y + 1) // e
res_list.append(d)
# print(res_list)
return res_list
def blockSizeHack(blocks, n, e):
SYMBOLS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890 !?.'
string = []
p = 0
q = 0
for i in range(2, n):
if n % i == 0:
p = i
q = n//p
break
x = (p-1)*(q-1)
y = 1
d = 0
while (((x * y) + 1) % e) != 0:
y += 1
d = (x * y + 1) // e
for i in range(len(blocks)):
blockInt = pow(blocks[i], d, n)
if blockInt < len(SYMBOLS)**i and blockInt != 0:
blockInt = blockInt % (len(SYMBOLS)**i)
else:
blockInt = blockInt // (len(SYMBOLS)**i)
string.append(SYMBOLS[blockInt])
return ''.join(string)
def main():
# # question1
t = 100
n = 493
e = 5
print(finitePrimeHack(t, n, e))
# question3
blocks = [2361958428825, 564784031984, 693733403745, 693733403745,
2246930915779, 1969885380643]
n = 3328101456763
e = 1827871
print(blockSizeHack(blocks, n, e))
if __name__ == "__main__":
main()
|
d1 = {0:1, 1:1, 2:2, 3:3}
pent_nums = []
for i in range(1, 100):
val1 = ((3*(i**2))-i)/2
val2 = ((3*((-i)**2))+i)/2
pent_nums.append(val1)
pent_nums.append(val2)
for n in range(4, 101):
ite = 0
p_t = d1[n-pent_nums[ite]]
step = 1
stop = False
rolling_sum = 0
while not stop:
if step == 1 or step == 2:
rolling_sum += p_t
step += 1
elif step==3:
rolling_sum -= p_t
step += 1
else:
rolling_sum -= p_t
step = 1
ite += 1
try:
if d1[n-pent_nums[ite]] > 0:
p_t = d1[n-pent_nums[ite]]
except:
stop = True
d1[n] = rolling_sum
print(d1[100]-1) # 190569291
"""
Using a recurrence relation for the partitions of n
based on generalized pentagonal numbers...
""" |
n1 = int(input())
n2 = int(input())
n3 = int(input())
if n1 > n2 > n3:
print(n3)
print(n2)
print(n1)
elif n2 > n1 > n3:
print(n3)
print(n1)
print(n2)
elif n1 > n3 > n2:
print(n2)
print(n3)
print(n1)
elif n2 > n3 > n1:
print(n1)
print(n3)
print(n2)
elif n3 > n2 > n1:
print(n1)
print(n2)
print(n3)
elif n3 > n1 > n2:
print(n2)
print(n1)
print(n3) |
RBNF = r"""
NEWLINE := ''
ENDMARKER := ''
NAME := ''
INDENT := ''
DEDENT := ''
NUMBER := ''
STRING := ''
single_input ::= it=NEWLINE | seq=simple_stmt | it=compound_stmt NEWLINE
file_input ::= (NEWLINE | seqs<<stmt)* [ENDMARKER] -> mod=Module(sum(seqs or [], [])); fix_missing_locations(mod); return mod
eval_input ::= it=testlist NEWLINE* ENDMARKER -> Expression(it)
# the restrictions of decorator syntax are released here for the sake of convenience.
decorator ::= '@' exp=test NEWLINE -> exp
decorated ::= decorators=decorator+ it=(classdef | funcdef | async_funcdef) -> it.decorator_list = list(decorators); return it
async_funcdef ::= mark='async'
'def' name=NAME args=parameters ['->' ret=test] ':' body=suite -> def_rewrite(mark, name, args, ret, body, is_async=True)
funcdef ::= mark='def' name=NAME args=parameters ['->' ret=test] ':' body=suite -> def_rewrite(mark, name, args, ret, body)
parameters ::= '(' [args=typedargslist] ')' -> args if args else arguments([], None, [], [], None, [])
lam_args ::= [args=varargslist] -> args if args else arguments([], None, [], [], None, [])
default_fp ::= '=' expr=test -> expr
kw_default_fp ::= ['=' expr=test] -> expr
tfpdef ::= name=NAME [':' annotation=test] -> arg(name.value, annotation, **loc @ name)
vfpdef ::= name=NAME -> arg(name.value, None, **loc @ name)
typedargslist ::= args << tfpdef [defaults<<default_fp] (',' args<<tfpdef [defaults<<default_fp])* [',' [
'*' [vararg=tfpdef] (',' kwonlyargs<<tfpdef kw_defaults<<kw_default_fp)* [',' ['**' kwarg=tfpdef [',']]]
| '**' kwarg=tfpdef [',']]]
| '*' [vararg=tfpdef] (',' kwonlyargs<<tfpdef kw_defaults<<kw_default_fp)* [',' ['**' kwarg=tfpdef [',']]]
| '**' kwarg=tfpdef [',']
-> arguments(args or [], vararg, kwonlyargs or [], kw_defaults or [], kwarg, defaults or [])
varargslist ::= args << vfpdef [defaults<<default_fp] (',' args<<vfpdef [defaults<<default_fp])* [',' [
'*' [vararg=vfpdef] (',' kwonlyargs<<vfpdef kw_defaults<<kw_default_fp)* [',' ['**' kwarg=vfpdef [',']]]
| '**' kwarg=vfpdef [',']]]
| '*' [vararg=vfpdef] (','kwonlyargs<<vfpdef kw_defaults<<kw_default_fp)* [',' ['**' kwargs=vfpdef [',']]]
| '**' kwargs=vfpdef [',']
-> arguments(args or [], vararg, kwonlyargs or [], kw_defaults or [], kwarg, defaults or [])
stmt ::= seq=simple_stmt | it=compound_stmt -> [it] if it else seq
simple_stmt ::= seq<<small_stmt (';' seq<<small_stmt)* [';'] NEWLINE -> seq
small_stmt ::= it=(expr_stmt | del_stmt | pass_stmt | flow_stmt | # ------------------------------
import_stmt | global_stmt | nonlocal_stmt | assert_stmt) -> it
expr_stmt ::= lhs=testlist_star_expr (ann=annassign | aug=augassign aug_exp=(yield_expr|testlist) | # ------------------------------
('=' rhs<<(yield_expr|testlist_star_expr))*) -> expr_stmt_rewrite(lhs, ann, aug, aug_exp, rhs)
annassign ::= ':' anno=test ['=' value=test] -> (anno, value)
testlist_star_expr ::= seq<<(test|star_expr) (',' seq<<(test|star_expr))* [force_tuple=','] -> Tuple(seq, Load()) if len(seq) > 1 or force_tuple else seq[0]
augassign ::= it=('+=' | '-=' | '*=' | '@=' | '/=' | '%=' | '&=' | '|=' | '^=' | # ------------------------------
'<<=' | '>>=' | '**=' | '//=') -> augassign_rewrite(it)
# For normal and annotated assignments, additional restrictions enforced by the interpreter -------------------------------
del_stmt ::= mark='del' lst=exprlist -> Delete([as_del(lst)], **loc @ mark)
pass_stmt ::= mark='pass' -> Pass(**loc @ mark)
flow_stmt ::= it=(break_stmt | continue_stmt | return_stmt | raise_stmt | yield_stmt) -> it
break_stmt ::= mark='break' -> Break(**loc @ mark)
continue_stmt ::= mark='continue' -> Continue(**loc @ mark)
return_stmt ::= mark='return' [value=testlist_star_expr] -> Return(value, **loc @ mark)
yield_stmt ::= exp=yield_expr -> Expr(exp)
raise_stmt ::= mark='raise' [exc=test ['from' cause=test]] -> Raise(exc, cause, **loc @ mark)
import_stmt ::= it=(import_name | import_from) -> it
import_name ::= mark='import' names=dotted_as_names -> Import(names, **loc @ mark)
# note below::= the ('.' | '...') is necessary because '...' is tokenized as ELLIPSIS --------------------------------
import_level::= (_1='.' | '...') -> 1 if _1 else 3
wild ::= '*' -> [alias(name='*', asname=None)]
import_from ::= (mark='from' (levels=import_level* module=dotted_name | levels=import_level+) # ------------------------------
'import' (wild=wild | '(' names=import_as_names ')' | names=import_as_names)) -> ImportFrom(module or '', wild or names, sum(levels or []), **loc @ mark)
NAMESTR ::= n=NAME -> n.value
import_as_name ::= name=NAMESTR ['as' asname=NAMESTR] -> alias(name, asname)
dotted_as_name ::= name=dotted_name ['as' asname=NAMESTR] -> alias(name, asname)
import_as_names::= seq<<import_as_name (',' seq<<import_as_name)* [','] -> seq
dotted_as_names::= seq<<dotted_as_name (',' seq<<dotted_as_name)* -> seq
dotted_name ::= xs=(NAME ('.' NAME)*) -> ''.join(c.value for c in xs)
global_stmt ::= mark='global' names<<NAMESTR (',' name<<NAMESTR)* -> Global(names, **loc @ mark)
nonlocal_stmt ::= mark='nonlocal' names<<NAMESTR (',' name<<NAMESTR)* -> Nonlocal(names, **loc @ mark)
assert_stmt ::= mark='assert' test=test [',' msg=test] -> Assert(test, msg, **loc @ mark)
compound_stmt ::= it=(if_stmt | while_stmt | for_stmt | try_stmt | with_stmt | funcdef | classdef | decorated # ------------------------------
| async_stmt) -> it
async_stmt ::= it=(async_funcdef | async_with_stmt | async_for_stmt) -> it
if_stmt ::= marks<<'if' tests<<test ':' # ------------------------------
bodies<<suite # ------------------------------
(marks<<'elif' tests<<test ':' bodies<<suite)* # ------------------------------
['else' ':' orelse=suite] -> if_stmt_rewrite(marks, tests, bodies, orelse)
while_stmt ::= 'while' test=test ':' body=suite ['else' ':' orelse=suite] -> while_stmt_rewrite(test, body, orelse)
async_for_stmt ::= 'async' 'for' target=exprlist 'in' iter=testlist ':' body=suite ['else' ':' orelse=suite] -> for_stmt_rewrite(target, iter, body, orelse, is_async=True)
for_stmt ::= 'for' target=exprlist 'in' iter=testlist ':' body=suite ['else' ':' orelse=suite] -> for_stmt_rewrite(target, iter, body, orelse)
try_stmt ::= (mark='try' ':' # ---------------------------
body=suite # ---------------------------
((excs<<except_clause ':' rescues<<suite)+ # ---------------------------
['else' ':' orelse=suite] # ---------------------------
['finally' ':' final=suite] | # ---------------------------
'finally' ':' final=suite)) -> try_stmt_rewrite(mark, body, excs, rescues, orelse, final)
async_with_stmt::= mark='async' 'with' items<<with_item (',' items<<with_item)* ':' body=suite -> with_stmt_rewrite(mark, items, body, is_async=True)
with_stmt ::= mark='with' items<<with_item (',' items<<with_item)* ':' body=suite -> with_stmt_rewrite(mark, items, body)
with_item ::= context_expr=test ['as' optional_vars=expr] -> withitem(context_expr, as_store(optional_vars))
except_clause ::= 'except' [type=test ['as' name=NAMESTR]] -> (type, name)
suite ::= seqs<<simple_stmt | NEWLINE INDENT (seqs<<stmt)+ DEDENT -> sum(seqs, [])
test ::= it=(ifexp| lambdef) -> it
ifexp ::= body=or_test ['if' test=or_test 'else' orelse=test] -> IfExp(test, body, orelse) if orelse else body
test_nocond ::= it=(or_test | lambdef_nocond) -> it
lambdef ::= m='lambda' args=lam_args ':' body=test -> Lambda(args, body)
lambdef_nocond ::= m='lambda' args=lam_args ':' body=test_nocond -> Lambda(args, body)
or_test ::= head=and_test ('or' tail<<and_test)* -> BoolOp(Or(), [head, *tail]) if tail else head
and_test ::= head=not_test ('and' tail<<not_test)* -> BoolOp(And(), [head, *tail]) if tail else head
not_test ::= mark='not' expr=not_test | comp=comparison -> UnaryOp(Not(), expr, **loc @ mark) if mark else comp
comparison ::= left=expr (ops<<comp_op comparators<<expr)* -> Compare(left, ops, comparators) if ops else left
comp_op ::= op=('<'|'>'|'=='|'>='|'<='|'<>'|'!='
|'in'|'not' 'in'|'is'|'is' 'not') -> comp_op_rewrite(op)
star_expr ::= mark='*' expr=expr -> Starred(expr, Load(), **loc @ mark)
expr_tr ::= op='|' expr=xor_expr -> (op, expr)
expr ::= head=xor_expr tail=expr_tr* -> expr_rewrite(head, tail)
xor_expr_tr ::= op='^' expr=and_expr -> (op, expr)
xor_expr ::= head=and_expr tail=xor_expr_tr* -> xor_expr_rewrite(head, tail)
and_expr_tr ::= op = '&' expr=shift_expr -> (op, expr)
and_expr ::= head=shift_expr tail=and_expr_tr* -> and_expr_rewrite(head, tail)
shift_expr_tr ::= op=('<<'|'>>') expr=arith_expr -> (op, expr)
shift_expr ::= head=arith_expr tail=shift_expr_tr* -> shift_expr_rewrite(head, tail)
arith_expr_tr ::= op=('+'|'-') expr=term -> (op, expr)
arith_expr ::= head=term tail=arith_expr_tr* -> arith_expr_rewrite(head, tail)
term_tr ::= op=('*'|'@'|'/'|'%'|'//') expr=factor -> (op, expr)
term ::= head=factor tail=term_tr* -> term_rewrite(head, tail)
factor ::= mark=('+'|'-'|'~') factor=factor | power=power -> factor_rewrite(mark, factor, power)
power ::= atom_expr=atom_expr ['**' factor=factor] -> BinOp(atom_expr, Pow(), factor) if factor else atom_expr
atom_expr ::= [a='await'] atom=atom trailers=trailer* -> atom_expr_rewrite(a, atom, trailers)
atom ::= (is_gen ='(' [yield_expr=yield_expr|comp=testlist_comp] ')' |
is_list='[' [comp=testlist_comp] ']' |
head='{' [dict=dictorsetmaker] is_dict='}' |
name=NAME |
number=NUMBER |
strs=STRING+ |
ellipsis='...' |
namedc='None' |
namedc='True' |
namedc='False')
-> atom_rewrite(loc, name, number, strs, namedc, ellipsis, dict, is_dict, is_gen, is_list, comp, yield_expr)
testlist_comp ::= values<<(test|star_expr) ( comp=comp_for | (',' values<<(test|star_expr))* [force_tuple=','] )
->
def app(is_tuple=None, is_list=None):
if is_list and comp:
return ListComp(*values, comp)
elif is_list:
return List(values, Load())
elif comp:
return GeneratorExp(*values, comp)
else:
return values[0] if len(values) is 1 and not force_tuple else Tuple(values, Load())
app
# `ExtSlice` is ignored here. We don't need this optimization for this project.
trailer ::= arglist=arglist | mark='[' subscr=subscriptlist ']' | mark='.' attr=NAMESTR
-> (lambda value: Subscript(value, subscr, Load(), **loc @ mark)) if subscr is not None else\
(lambda value: Call(value, *split_args_helper(arglist))) if arglist is not None else\
(lambda value: Attribute(value, attr, Load(), **loc @ mark))
# `Index` will be deprecated in Python3.8.
# See https://github.com/python/cpython/pull/9605#issuecomment-425381990
subscriptlist ::= head=subscript (',' tail << subscript)* [',']
-> Index(head if not tail else Tuple([head, *tail], Load()))
subscript3 ::= [lower=test] subscr=[':' [upper=test] [':' [step=test]]] -> Slice(lower, upper, step) if subscr else lower
subscript ::= it=(subscript3 | test) -> it
exprlist ::= seq << (expr|star_expr) (',' seq << (expr|star_expr))* [force_tuple=','] -> Tuple(seq, Load()) if force_tuple or len(seq) > 1 else seq[0]
testlist ::= seq << test (',' seq << test)* [force_tuple=','] -> Tuple(seq, Load()) if force_tuple or len(seq) > 1 else seq[0]
dict_unpack_s ::= '**' -> None
dictorsetmaker ::= (((keys<<test ':' values<<test | keys<<dict_unpack_s values<<expr)
(comp=comp_for | (',' (keys<<test ':' values<<test | keys<<dict_unpack_s values<<expr))* [','])) |
(values<<(test | star_expr)
(comp=comp_for | (',' values<<(test | star_expr))* [','])) )
-> if not comp: return ExDict(keys, values, Load()) if keys else Set(values)
DictComp(*keys, *values, comp) if keys else SetComp(*values, comp)
classdef ::= mark='class' name=NAME [arglist=arglist]':' suite=suite
-> ClassDef(name.value, *split_args_helper(arglist or []), suite, [], **loc @ mark)
arglist ::= mark='(' [seq<<argument (',' seq<<argument)* [',']] ')' -> check_call_args(loc @ mark, seq or [])
argument ::= (
key=NAME '=' value=test |
arg=test [comp=comp_for] |
mark='**' kwargs=test |
mark='*' args=test )
->
Starred(**(loc @ mark), value=args, ctx=Load()) if args else \
keyword(**(loc @ mark), arg=None, value=kwargs) if kwargs else\
keyword(**(loc @ key), arg=key.value, value=value) if key else \
GeneratorExp(arg, comp) if comp else \
arg
comp_for_item ::= [is_async='async'] 'for' target=exprlist 'in' iter=or_test ('if' ifs<<test_nocond)*
-> comprehension(as_store(target), iter, ifs, bool(is_async))
comp_for ::= generators=comp_for_item+ -> list(generators)
encoding_decl ::= NAME
yield_expr ::= mark='yield' [is_yield_from='from' expr=test | expr=testlist_star_expr]
-> YieldFrom(**(loc @ mark), value=expr) if is_yield_from else Yield(**(loc @ mark), value=expr)
"""
|
# https://codeforces.com/problemset/problem/959/A
n = int(input())
print('Mahmoud' if n%2 == 0 else 'Ehab') |
#
# Copyright (c) 2017-2018 Joy Diamond. All rights reserved.
#
@gem('Sapphire.Parse1Atom')
def gem():
show = 7
@share
def parse1_map_element():
if qk() is not none:
#my_line('qk: %r', qk())
raise_unknown_line()
token = parse1_atom()
if token.is_right_brace:
return token
if token.is_special_operator:
raise_unknown_line()
operator = qk()
if operator is none:
if qn() is not none:
raise_unknown_line()
operator = tokenize_operator()
else:
wk(none)
if not operator.is_colon:
token = parse1_ternary_expression__X__any_expression(token, operator)
operator = qk()
if operator is none:
raise_unknown_line()
wk(none)
if not operator.is_colon:
raise_unknown_line()
return conjure_map_element(token, operator, parse1_ternary_expression())
@share
def parse1_map__left_brace(left_brace):
#
# 1
#
left = parse1_map_element()
if left.is_right_brace:
return conjure_empty_map(left_brace, left)
operator = qk()
if operator is none:
operator = tokenize_operator()
else:
wk(none)
if operator.is_keyword_for:
left = parse1_comprehension_expression__X__any_expression(left, operator)
operator = qk()
if operator is none:
operator = tokenize_operator()
else:
wk(none)
if operator.is_right_brace:
return conjure_map_expression_1(left_brace, left, operator)
if not operator.is_comma:
raise_unknown_line()
token = parse1_map_element()
if token.is_right_brace:
return conjure_map_expression_1(left_brace, left, conjure__comma__right_brace(operator, token))
many = [left, token]
many_frill = [operator]
while 7 is 7:
operator = qk()
if operator is none:
raise_unknown_line()
wk(none)
if operator.is_right_brace:
return conjure_map_expression_many(left_brace, many, many_frill, operator)
if not operator.is_comma:
raise_unknown_line()
token = parse1_map_element()
if token.is_right_brace:
return conjure_map_expression_many(
left_brace,
many,
many_frill,
conjure__comma__right_brace(operator, token),
)
many_frill.append(operator)
many.append(token)
@share
def parse1__parenthesized_expression__left_parenthesis(left_parenthesis):
#
# 1
#
#
# TODO:
# Replace this with 'parse1__parenthesis__first_atom' & handle a right-parenthesis as an empty tuple
#
middle_1 = parse1_atom()
if middle_1.is_right_parenthesis:
return conjure_empty_tuple(left_parenthesis, middle_1)
if middle_1.is_special_operator:
raise_unknown_line()
operator_1 = qk()
if operator_1 is none:
operator_1 = tokenize_operator()
else:
wk(none)
#my_line('operator_1: %r', operator_1)
if not operator_1.is_end_of_ternary_expression:
middle_1 = parse1_ternary_expression__X__any_expression(middle_1, operator_1)
operator_1 = qk()
wk(none)
if operator_1.is_right_parenthesis:
return conjure_parenthesized_expression(left_parenthesis, middle_1, operator_1)
if operator_1.is_comma__right_parenthesis:
return conjure_parenthesized_tuple_expression_1(left_parenthesis, middle_1, operator_1)
if not operator_1.is_comma:
raise_unknown_line()
#
# 2
#
middle_2 = parse1_atom()
if middle_2.is_right_parenthesis:
return conjure_parenthesized_tuple_expression_1(
left_parenthesis,
middle_1,
conjure_comma__right_parenthesis(operator_1, middle_2),
)
if middle_2.is_special_operator:
raise_unknown_line()
operator_2 = tokenize_operator()
if not operator_2.is_end_of_ternary_expression:
middle_2 = parse1_ternary_expression__X__any_expression(middle_2, operator_2)
operator_2 = qk()
wk(none)
if operator_2.is__optional_comma__right_parenthesis:
return conjure_tuple_expression_2(left_parenthesis, middle_1, operator_1, middle_2, operator_2)
if not operator_2.is_comma:
raise_unknown_line()
#
# 3
#
middle_3 = parse1_atom()
if middle_3.is_right_parenthesis:
return conjure_tuple_expression_2(
left_parenthesis,
middle_1,
operator_1,
middle_2,
conjure_comma__right_parenthesis(operator_2, middle_3),
)
if middle_3.is_special_operator:
raise_unknown_line()
many = [middle_1, middle_2]
many_frill = [operator_1, operator_2]
while 7 is 7:
operator_7 = tokenize_operator()
if not operator_7.is_end_of_ternary_expression:
middle_3 = parse1_ternary_expression__X__any_expression(middle_3, operator_7)
operator_7 = qk()
wk(none)
many.append(middle_3)
if operator_7.is__optional_comma__right_parenthesis:
return conjure_tuple_expression_many(left_parenthesis, many, many_frill, operator_7)
if not operator_7.is_comma:
raise_unknown_line()
middle_3 = parse1_atom()
if middle_3.is_right_parenthesis:
return conjure_tuple_expression_many(
left_parenthesis,
many,
many_frill,
conjure_comma__right_parenthesis(operator_7, middle_3),
)
if middle_3.is_special_operator:
raise_unknown_line()
many_frill.append(operator_7)
@share
def parse1__list_expression__left_square_bracket(left_square_bracket):
#
# 1
#
middle_1 = parse1_atom()
if middle_1.is_right_square_bracket:
return conjure_empty_list(left_square_bracket, middle_1)
if middle_1.is_special_operator:
raise_unknown_line()
operator_1 = tokenize_operator()
if not operator_1.is_end_of_comprehension_expression:
middle_1 = parse1_comprehension_expression__X__any_expression(middle_1, operator_1)
operator_1 = qk()
wk(none)
if operator_1.is__optional_comma__right_square_bracket:
return conjure_list_expression_1(left_square_bracket, middle_1, operator_1)
if not operator_1.is_comma:
#my_line('line: %d; middle_1: %r; operator_1: %r', ql(), middle_1, operator_1)
raise_unknown_line()
#
# 2
#
middle_2 = parse1_atom()
if middle_2.is_right_square_bracket:
return conjure_list_expression_1(
left_square_bracket,
middle_1,
conjure_comma__right_square_bracket(operator_1, middle_2),
)
if middle_2.is_special_operator:
raise_unknown_line()
operator_2 = tokenize_operator()
if not operator_2.is_end_of_ternary_expression:
middle_2 = parse1_ternary_expression__X__any_expression(middle_2, operator_2)
operator_2 = qk()
wk(none)
if operator_2.is__optional_comma__right_square_bracket:
return conjure_list_expression_2(left_square_bracket, middle_1, operator_1, middle_2, operator_2)
if not operator_2.is_comma:
raise_unknown_line()
#
# 3
#
middle_3 = parse1_atom()
if middle_3.is_right_square_bracket:
return conjure_list_expression_2(
left_square_bracket,
middle_1,
operator_1,
middle_2,
conjure_comma__right_square_bracket(operator_2, middle_3),
)
if middle_3.is_special_operator:
raise_unknown_line()
many = [middle_1, middle_2]
many_frill = [operator_1, operator_2]
while 7 is 7:
operator_7 = tokenize_operator()
if not operator_7.is_end_of_ternary_expression:
middle_3 = parse1_ternary_expression__X__any_expression(middle_3, operator_7)
operator_7 = qk()
wk(none)
many.append(middle_3)
if operator_7.is__optional_comma__right_square_bracket:
return conjure_list_expression_many(left_square_bracket, many, many_frill, operator_7)
if not operator_7.is_comma:
raise_unknown_line()
middle_3 = parse1_atom()
if middle_3.is_right_square_bracket:
return conjure_list_expression_many(
left_square_bracket,
many,
many_frill,
conjure_comma__right_square_bracket(operator_7, middle_3),
)
if middle_3.is_special_operator:
raise_unknown_line()
many_frill.append(operator_7)
@share
def parse1_atom():
assert qk() is none
assert qn() is none
m = atom_match(qs(), qj())
if m is none:
#my_line('full: %r; s: %r', portray_string(qs()), portray_string(qs()[qj() :]))
raise_unknown_line()
token = analyze_atom(m)
if token.is__atom__or__special_operator:
return token
if token.is_left_parenthesis:
return parse1__parenthesized_expression__left_parenthesis(token)
if token.is_left_square_bracket:
return parse1__list_expression__left_square_bracket(token)
if token.is_left_brace:
return parse1_map__left_brace(token)
if token.is_keyword_not:
return parse1_not_expression__operator(token)
if token.is_minus_sign:
return parse1_negative_expression__operator(token)
if token.is_tilde_sign:
return parse1_twos_complement_expression__operator(token)
if token.is_star_sign:
return conjure_star_argument(token, parse1_ternary_expression())
my_line('token: %r', token)
assert 0
raise_unknown_line()
|
def calculateFuel(weight):
return int(weight / 3)-2
# Part 1
total = 0
with open("/Users/a318196/Code/AdventOfCode2020/20191201/input.txt") as file:
for line in file:
total += calculateFuel(int(line))
print ('Total part 1: ' + str(total))
# Part 2
total = 0
with open("/Users/a318196/Code/AdventOfCode2020/20191201/input.txt") as file:
for line in file:
fuel = calculateFuel(int(line))
additionalFuel = calculateFuel(fuel)
while additionalFuel > 0:
fuel += additionalFuel
additionalFuel = calculateFuel(additionalFuel)
total += fuel
print ('Total part 2: ' + str(total)) |
class FLAG_OPTIONS:
MUTLIPLE_SEGMENTS_EXIST = 0x1
ALL_PROPERLY_ALIGNED = 0x2
SEG_UNMAPPED = 0x4
NEXT_SEG_UNMAPPED = 0x8
SEQ_REV_COMP = 0x10
NEXT_SEQ_REV_COMP = 0x20
FIRST_SEQ_IN_TEMP = 0x40
LAST_SEQ_IN_TEMP = 0x80
SECONDARY_ALG = 0x100
POOR_QUALITY = 0x200
DUPLICATE_READ = 0x400
SUPPLEMENTARY_ALG = 0x800 |
secure_log_path = "/var/log/secure";
secure_log_score_tokens = \
{
"Invalid user": 3,
"User root": 5,
"Failed password": 2
};
secure_log_score_limit = 10;
#firewall-cmd --permanent --ipset=some_set --add-entry=xxx.xxx.xxx.xxx
firewalld_ipset_name = "ips2drop";
#####################################################
# technical section #
#####################################################
# time_stamp_pattern = "";
ip_address_pattern = r"[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}";
abuse_report_mail_pattern = r"abuse@[a-zA-Z]+\.[a-zA-Z]+";
##################################################### |
__doc__ = "Menu class that represents a MenuComponent. It has a list of items, that could be other MenuComponents, or Actions(leafs)"
class Menu:
def __init__(self, label):
self.items = []
self.label = label
self.items.append(GoBackAction())
def execute(self):
i = 0
op = -1
while op != 0:
print("")
print(self.label)
print("---")
for item in self.items:
print("{} - {}".format(i, item.label))
i += 1
op = input("Select an option:")
try:
op = int(op)
self.items[op].execute()
except:
print("")
print ("@#|@~€#~ >> That wasn't a number, you bastard!")
i = 0
def addItem(self, item):
self.items.append(item)
# This action is common for all menus. Good place to define it
class GoBackAction:
def __init__(self):
self.label = "Go Back"
def execute(self):
pass
|
a, b, c, d = map(int, input().split())
s = a + b + c + d
a, b, c, d = map(int, input().split())
t = a + b + c + d
print(max(s, t))
|
"""
# Definition for a Node.
class Node(object):
def __init__(self, val, children):
self.val = val
self.children = children
"""
class Codec:
def serialize(self, root):
"""Encodes a tree to a single string.
:type root: Node
:rtype: str
"""
vals = []
def preorder(node):
if node:
vals.append(str(node.val))
for child in node.children:
preorder(child)
vals.append('#')
preorder(root)
return ' '.join(vals)
def deserialize(self, data):
"""Decodes your encoded data to tree.
:type data: str
:rtype: Node
"""
if not data:
return None
stream = iter(data.split())
val = int(next(stream))
root = Node(val, [])
def build(node):
while True:
val = next(stream)
if val == "#":
break
child = Node(int(val), [])
node.children.append(child)
build(child)
build(root)
return root
# Your Codec object will be instantiated and called as such:
# codec = Codec()
# codec.deserialize(codec.serialize(root))
|
# Copyright (c) Nikita Sychev, 29.04.2017
# Licensed by MIT
a = input()
b = input()
c = input()
n = len(a)
a_new = ""
b_new = ""
c_new = ""
for i in range(n):
unused = chr(ord('A') + ord('B') + ord('C') + ord('?')
- ord(a[i]) - ord(b[i]) - ord(c[i]))
if a[i] == '?':
a_new += unused
else:
a_new += a[i]
if b[i] == '?':
b_new += unused
else:
b_new += b[i]
if c[i] == '?':
c_new += unused
else:
c_new += c[i]
print(a_new)
print(b_new)
print(c_new)
|
def sum(x,y):
print("sum"," =",(x+y))
def subtract(x,y):
print("difference"," =",(x-y))
def divide(x,y):
print("division"," =",(x/y))
def multiply(x,y):
print("multiplication"," =",(x/y))
|
def plug_in(symbol_values):
s = symbol_values['s']
p = len(s.sites) / s.volume
rho = float(s.density)
mbar = rho / p
v_a = 1 / p
return {'p': len(s.sites) / s.volume,
'rho': float(s.density),
'v_a': v_a,
'mbar': mbar}
DESCRIPTION = """
Model calculating the atomic density from the corresponding
structure object of the material
"""
config = {
"name": "density",
"connections": [
{
"inputs": [
"s"
],
"outputs": [
"p",
"rho",
"mbar",
"v_a"
]
}
],
"categories": [
"mechanical"
],
"symbol_property_map": {
"s": "structure",
"p": "atomic_density",
"rho": "density",
"v_a": "volume_per_atom",
"mbar": "mass_per_atom"
},
"description": DESCRIPTION,
"references": [],
"plug_in": plug_in
}
|
# 110. Balanced Binary Tree
# Runtime: 3232 ms, faster than 5.10% of Python3 online submissions for Balanced Binary Tree.
# Memory Usage: 17.6 MB, less than 100.00% of Python3 online submissions for Balanced Binary Tree.
# Definition for a binary tree node.
# class TreeNode:
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class Solution:
# Recursive
def isBalanced(self, root: TreeNode) -> bool:
if not root:
return True
else:
def get_depth(node: TreeNode) -> int:
if not node:
return 0
else:
return max(get_depth(node.left), get_depth(node.right)) + 1
depth_diff = abs(get_depth(root.left) - get_depth(root.right)) <= 1
balance_child = self.isBalanced(root.left) and self.isBalanced(root.right)
return depth_diff and balance_child |
# Link: https://leetcode.com/problems/reverse-substrings-between-each-pair-of-parentheses/
# Time: O(N)
# Space: O(N)
def reverse_parentheses(s):
stack, queue = [], []
for char in s:
if char == ")":
while stack[-1] != "(":
queue.append(stack.pop())
stack.pop() # remove '('
while queue:
stack.append(queue.pop(0))
else:
stack.append(char)
return "".join(stack)
def main():
s = "(ed(et(oc))el)"
print(reverse_parentheses(s))
if __name__ == "__main__":
main()
|
x = input("Enter a string")
y = input("Enter a string")
z = input("Enter a string")
for i in range(10):
print("This is some output from the lab ",i)
print("Your input was " + x)
print("Your input was " + y)
print("Your input was " + z) |
"""Load dependencies needed to compile CLIF as a 3rd-party consumer."""
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_archive")
LLVM_COMMIT = "1f21de535d37997c41b9b1ecb2f7ca0e472e9f77" # 2021-01-15
LLVM_BAZEL_TAG = "llvm-project-%s" % (LLVM_COMMIT,)
LLVM_BAZEL_SHA256 = "f2fd051574fdddae8f8fff81f986d1165b51dc0b62b70d9d47685df9f2d804e1"
LLVM_SHA256 = "3620b7e6efa72e73e2e83420d71dfc7fdf4c81cff1ee692f03e3151600250fe0"
LLVM_URLS = [
"https://storage.googleapis.com/mirror.tensorflow.org/github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
"https://github.com/llvm/llvm-project/archive/{commit}.tar.gz".format(commit = LLVM_COMMIT),
]
def clif_deps():
"""Load common dependencies needed to compile and use CLIF."""
if not native.existing_rule("llvm-project"):
http_archive(
name = "llvm-bazel",
sha256 = LLVM_BAZEL_SHA256,
strip_prefix = "llvm-bazel-{tag}/llvm-bazel".format(tag = LLVM_BAZEL_TAG),
url = "https://github.com/google/llvm-bazel/archive/{tag}.tar.gz".format(tag = LLVM_BAZEL_TAG),
)
http_archive(
name = "llvm-project-raw",
build_file_content = "#empty",
sha256 = LLVM_SHA256,
strip_prefix = "llvm-project-" + LLVM_COMMIT,
urls = LLVM_URLS,
)
if not native.existing_rule("com_google_protobuf"):
http_archive(
name = "com_google_protobuf",
sha256 = "bf0e5070b4b99240183b29df78155eee335885e53a8af8683964579c214ad301",
strip_prefix = "protobuf-3.14.0",
urls = [
"https://storage.googleapis.com/mirror.tensorflow.org/github.com/protocolbuffers/protobuf/archive/v3.14.0.zip",
"https://github.com/protocolbuffers/protobuf/archive/v3.14.0.zip",
],
)
if not native.existing_rule("com_google_absl"):
http_archive(
name = "com_google_absl",
sha256 = "6622893ab117501fc23268a2936e0d46ee6cb0319dcf2275e33a708cd9634ea6",
strip_prefix = "abseil-cpp-20200923.3",
urls = ["https://github.com/abseil/abseil-cpp/archive/20200923.3.zip"],
)
if not native.existing_rule("com_google_googletest"):
http_archive(
name = "com_google_googletest",
sha256 = "9dc9157a9a1551ec7a7e43daea9a694a0bb5fb8bec81235d8a1e6ef64c716dcb",
strip_prefix = "googletest-release-1.10.0",
urls = [
"https://mirror.bazel.build/github.com/google/googletest/archive/release-1.10.0.tar.gz",
"https://github.com/google/googletest/archive/release-1.10.0.tar.gz",
],
)
if not native.existing_rule("com_github_gflags_gflags"):
http_archive(
name = "com_github_gflags_gflags",
sha256 = "34af2f15cf7367513b352bdcd2493ab14ce43692d2dcd9dfc499492966c64dcf",
strip_prefix = "gflags-2.2.2",
urls = ["https://github.com/gflags/gflags/archive/v2.2.2.tar.gz"],
)
if not native.existing_rule("com_github_google_glog"):
http_archive(
name = "com_github_google_glog",
sha256 = "62efeb57ff70db9ea2129a16d0f908941e355d09d6d83c9f7b18557c0a7ab59e",
strip_prefix = "glog-d516278b1cd33cd148e8989aec488b6049a4ca0b",
urls = ["https://github.com/google/glog/archive/d516278b1cd33cd148e8989aec488b6049a4ca0b.zip"],
)
if not native.existing_rule("io_abseil_py"):
http_archive(
name = "io_abseil_py",
sha256 = "ac357a83c27464f5a612fda94704d0cc4fd4be1f2c0667c1819c4037e875f7aa",
strip_prefix = "abseil-py-pypi-v0.11.0",
urls = [
"https://mirror.bazel.build/github.com/abseil/abseil-py/archive/pypi-v0.11.0.zip",
"https://github.com/abseil/abseil-py/archive/pypi-v0.11.0.zip",
],
)
if not native.existing_rule("six_archive"):
http_archive(
name = "six_archive",
build_file = "@com_google_protobuf//:third_party/six.BUILD",
sha256 = "d16a0141ec1a18405cd4ce8b4613101da75da0e9a7aec5bdd4fa804d0e0eba73",
urls = ["https://pypi.python.org/packages/source/s/six/six-1.12.0.tar.gz"],
)
# rules_python 0.1.0 is needed for pip_install. Older versions of
# rules_python might not have pip_install functionalities.
if not native.existing_rule("rules_python"):
http_archive(
name = "rules_python",
sha256 = "b6d46438523a3ec0f3cead544190ee13223a52f6a6765a29eae7b7cc24cc83a0",
url = "https://github.com/bazelbuild/rules_python/releases/download/0.1.0/rules_python-0.1.0.tar.gz",
)
|
class Solution:
def reverseBits(self, n):
result = 0
for i in range(32):
result <<= 1
if n & 1 > 0:
result += 1
n >>= 1
return result
|
i = 1
n = 1
S = int(0)
while i <= 39:
somar = i/n
S = S + somar
n = n*2
i = i + 2
print('%.2f'%S)
|
n = input('Digite um valor:\n')
print(type(n))
print('É um alfanumerico?',n.isalnum())
print('É alfabetico?',n.isalpha())
print('É um numero?', n.isnumeric())
print('Ésta em maiusculo?', n.isupper())
print("Está em minusculo?", n.islower()) |
'''
Class to define a LIFO Stack
'''
class UnderflowException(Exception):
'''
Raised when any element access operation is attempted on
an empty stack.
'''
pass
class Stack(object):
'''
Implements a Stack or a LIFO-style collection of elements.
'''
def __init__(self):
self.stack = []
def push(self, elem):
'''
Push an element to the top of the stack.
'''
self.stack.append(elem)
def pop(self):
'''
Remove and returns the top element of the stack.
'''
if self.stack:
return self.stack.pop()
else:
raise UnderflowException("Stack is empty!!")
def top(self):
'''
Returns the next element of the stack.
'''
if self.stack:
return self.stack[-1]
else:
return None
def isEmpty(self):
'''
Returns True iff stack is empty.
'''
return len(self.stack) == 0
def makeCopy(self):
'''
Returns a new object which is an exact copy of the current stack
'''
newObj = Stack()
newObj.stack = list(self.stack)
return newObj |
#!/usr/bin/env python3
def eval_jumps1(jumps):
cloned = list(jumps)
pc = 0
i = 0
while 0 <= pc < len(cloned):
old_pc = cloned[pc]
cloned[pc] += 1
pc += old_pc
i += 1
return i
def eval_jumps2(jumps):
cloned = list(jumps)
pc = 0
i = 0
while 0 <= pc < len(cloned):
old_pc = cloned[pc]
if cloned[pc] >= 3:
cloned[pc] -= 1
else:
cloned[pc] += 1
pc += old_pc
i += 1
return i
def main():
jumps = []
with open('input.txt') as fh:
for line in fh:
jumps.append(int(line))
print(eval_jumps1(jumps))
print(eval_jumps2(jumps))
if __name__ == '__main__':
main()
|
class Solution:
def solve(self, n, k):
ans = []
for i in range(k):
ans.append(x := max(1,n-26*(k-i-1)))
n -= x
return "".join(chr(ord('a')+x-1) for x in ans)
|
load("@build_bazel_rules_nodejs//:index.bzl", "pkg_web")
load(":tools/ngsw_config.bzl", _ngsw_config = "ngsw_config")
def pkg_pwa(
name,
srcs,
index_html,
ngsw_config,
additional_root_paths = []):
pkg_web(
name = "%s_web" % name,
srcs = srcs + ["@npm//:node_modules/@angular/service-worker/ngsw-worker.js", "@npm//:node_modules/zone.js/dist/zone.min.js"],
additional_root_paths = additional_root_paths + ["npm/node_modules/@angular/service-worker"],
visibility = ["//visibility:private"],
)
_ngsw_config(
name = name,
src = ":%s_web" % name,
config = ngsw_config,
index_html = index_html,
tags = ["app"],
)
|
def rearranjar(l):
return [-l[0],-l[1],l[2]]
def partition(l, p, r):
pivot = l[r] #ultimo elemento da lista
i = p-1#inicio da janelinha
for j in range(p,r): #limite da janelinha
if rearranjar(l[j]) <= rearranjar(pivot):
i +=1 #afasta janelinha para direita
l[i],l[j] = l[j],l[i]
l[i+1],l[r] =l[r],l[i+1] #muda o pivot
return i+1 #retorna indice do pivot
#esq i+1 é menor q ele, e dir de i+1 é maior q ele.
def quicksort(l, p, r):
if p < r:
q = partition(l, p, r)#retorna indice do novo pivot
quicksort(l, p, q-1)#ordena todos q são menor que pivot
quicksort(l, q+1, r)#ordena todos q são maiores q pivot
#entrada-------------------------------------------------------------
def planos(nome,plano, urgencia, l):
if plano == "premium": plano = 10
elif plano == "diamante": plano = 9
elif plano == "ouro": plano = 8
elif plano == "prata": plano = 7
elif plano == "bronze": plano = 6
elif plano == "resto": plano = 5
l.append((plano, (urgencia),(nome)))
return l
qtd = int(input())
lista = []
for x in range(qtd):
paciente = input().split()
nome,plano,urgencia = paciente[0],paciente[1],int(paciente[2])
planos(nome, plano, urgencia,lista)
r = qtd-1
p = 0
quicksort(lista,p,r)
for x in range(qtd):
print(lista[x][2])
|
def calculate_amstrong_numbers_3_digits():
result = []
for item in range(100, 1000):
sum = 0
for number in str(item):
sum += int(number) ** 3
if sum == item:
result.append(item)
return result
print("3-digit Amstrong Numbers:")
print(calculate_amstrong_numbers_3_digits())
|
def int_to_Roman(num):
val = [
1000, 900, 500, 400,
100, 90, 50, 40,
10, 9, 5, 4,
1
]
syb = [
"M", "CM", "D", "CD",
"C", "XC", "L", "XL",
"X", "IX", "V", "IV",
"I"
]
roman_num = ''
i = 0
while num > 0:
for _ in range(num // val[i]):
roman_num += syb[i]
num -= val[i]
i += 1
return roman_num
num = int(input())
if(num>=1 and num<=3999):
while(num>=1 and num<=3999):
roman = str(int_to_Roman(num))
max=ord(roman[0])
for i in range(len(roman)):
if(max<ord(roman[i])):
max = ord(roman[i])
base = max - ord('A') + 11
new_num = 0
for i in range(len(roman)):
r = roman[len(roman)-i-1]
n1 = ord(roman[len(roman)-i-1]) - ord('A') + 10
new_num = new_num + (n1*(base**i))
num = new_num
print(num)
else:
print(num) |
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Sat Oct 5 19:33:09 2019
@author: sodatab
MITx: 6.00.1x
"""
"""
Midterm-03 Closest Power
-------------------------
Implement a function called closest_power that meets the specifications below.
def closest_power(base, num):
'''
base: base of the exponential, integer > 1
num: number you want to be closest to, integer > 0
Find the integer exponent such that base**exponent is closest to num.
Note that the base**exponent may be either greater or smaller than num.
In case of a tie, return the smaller value.
Returns the exponent.
'''
"""
"""Answer Script:"""
def closest_power(base, num):
'''
base: base of the exponential, integer > 1
num: number you want to be closest to, integer > 0
Find the integer exponent such that base**exponent is closest to num.
Note that the base**exponent may be either greater or smaller than num.
In case of a tie, return the smaller value.
Returns the exponent.
'''
assert base > 1
assert num > 0
exponent = 0
while True:
if base**exponent > num:
if abs(num - base**(exponent - 1)) == abs(base**exponent - num):
return exponent - 1
break
else:
return exponent
break
elif base**exponent == num:
return exponent
break
else:
exponent += 1
return exponent
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.