content
stringlengths 7
1.05M
|
---|
#!/usr/bin/env python
# AUTHOR OF MODULE NAME
AUTHOR="Mauricio Velazco (@mvelazco)"
# DESCRIPTION OF THE MODULE
DESCRIPTION="This module simulates an adversary leveraging a compromised host to perform password spray attacks."
LONGDESCRIPTION="This scenario can occur if an adversary has obtained control of a domain joined computer through a --spear phishing attack or any other kind of client side attack.--Spray_empire leverages the Powershell Empire framework and its API to instruct Empire agents--to perform password spray attacks by using Invoke-SMBLogin (https://github.com/mvelazc0/Invoke-SMBLogin).--The module will connect to the Empire server and leverage existing agents. If no agents are found,--it will use impackets wmiexec to execute an Empire stager on a remote host defined on the settings."
# TODO
OPTIONS="""{"Dc": {"Description": "Domain Controller Ip address", "Required": "True", "Value": ""}, "Domain": {"Description": "Root domain name ( org.com )", "Required": "True", "Value": ""}, "Username": {"Description": "Domain user for ldap queries", "Required": "True", "Value": ""}, "Password": {"Description": "Domain user password for ldap queries", "Required": "True", "Value": ""}, "DomainUsers": {"Description": "Use domain users to spray. If False, random usernames will be used", "Required": "True", "Value": "True"}, "Nusers": {"Description": "Number of domain users to spray", "Required": "True", "Value": "10"}, "Type": {"Description": "Type of simulation", "Required": "True", "Value": "0"}, "UseKerberos": {"Description": "Kerberos or NTLM", "Required": "True", "Value": "True"}, "SprayPassword": {"Description": "Password used to spray", "Required": "True", "Value": "Winter2019"}}"""
ADVANCED_OPTIONS="""{ "EmpireHost": {"Description": "Ip address of the Empire Server ", "Required": "True", "Value": ""}, "EmpirePort": {"Description": "Rest API port number", "Required": "True", "Value": "1337"}, "EmpirePassword": {"Description": "Empire Rest API Password", "Required": "True", "Value": ""} ,"SimulationHost": {"Description": "Ip address of the simulation host", "Required": "False", "Value": ""}, "SimulationUser": {"Description": "Used against the simulation host. Requires admin privs", "Required": "False", "Value": ""} , "SimulationPass": {"Description": "Used against the simulation hos", "Required": "False", "Value": ""}, "Sleep": {"Description": "Time to sleep between each authentication attempt", "Required": "True", "Value": "0"} }"""
TYPES="""{"0": {"Description": "Perform the spray against a randomly picked domain controller"},"1": {"Description": "Perform the spray against a randomly picked domain computer "} , "2": {"Description": "Perform the spray against randomly picked domain computers. One auth per computer"}}""" |
"""
for a string with '(' find the count of complete '()' ones, '(()))" does not count, if does not have full brackets, return -1
time & space: O(n), n = length of S
"""
def count_brackets(S):
# initializations
cs,stack,cnt = S[:],[],0
# iterate through char array of S
for c in cs:
# if it is '(', push this to stack
if c == '(':
stack.append(c)
# if it is ')', pop element from the stack
elif c == ')':
# check if stack is empty
if len(stack) == 0:
#invalid
return -1
el = stack.pop()
# check if element is '('
if el == '(':
# increments the count
cnt += 1
return cnt
test = "(())()"
print(count_brackets(test))
|
# 18. Write a language program to get the volume of a sphere with radius 6
radius=6
volume=(4/3)*3.14*(radius**3)
print("Volume of sphere with radius 6= ",volume)
|
# I usually do not hard-code urls here,
# but there is not much need for complex configuration
BASEURL = 'https://simple-chat-asapp.herokuapp.com/'
login_button_text = 'Login'
sign_in_message = 'Sign in to Chat'
who_are_you = 'Who are you?'
who_are_you_talking_to = 'Who are you talking to?'
chatting_text = 'Chatting'
chatting_with_text = 'You\'re {0}, and you\'re chatting with {1}'
say_something_text = 'Say something...'
send_button_text = 'Send'
# If these need to remain a secret, I normally create a separate file
# for secret data and exclude it in .gitignore
username_1 = 'nicole 1'
username_2 = 'nicole 2'
username_3 = 'nicole 3'
long_username = 'hello' * 20
empty_username = ''
# Messages
hello_message = 'Hello chat!'
hello_2_message = 'Hello to you too!'
secret_message = 'We have a secret! Ssh!'
long_message = '1234567890' * 100
comma_message = 'Hello, I have a comma!'
|
# code to run in IPython shell to test whether clustering info in spikes struct array and in
# the neurons dict is consistent:
for nid in sorted(self.sort.neurons):
print(nid, (self.sort.neurons[nid].sids == np.where(self.sort.spikes['nid'] == nid)[0]).all())
|
def sum67(nums):
count = 0
blocked = False
for n in nums:
if n == 6:
blocked = True
continue
if n == 7 and blocked:
blocked = False
continue
if not blocked:
count += n
return count
|
# author : @akash kumar
# problem link:
# https://prepinsta.com/tcs-coding-question-1/
x,y,d,t=0,0,10,1
for n in range(int(input())):
if t==1:
x+=d
t=2
d+=10
elif t==2:
y+=d
t=3
d+=10
elif t==3:
x-=d
t=4
d+=10
elif t==4:
y-=d
t=5
d+=10
else:
x+=d
t=1
d+=10
print(x,y)
#Time complexity T(n)=O(n)
|
#!/usr/bin/env python3
#encoding=utf-8
#--------------------------------------------
# Usage: python3 3-calltracer_descr-for-method.py
# Description: make descriptor class as decorator to decorate class method
#--------------------------------------------
class Tracer: # a decorator + descriptor
def __init__(self, func): # on @ decorator
print('in property descriptor __init__')
self.calls = 0
self.func = func
def __call__(self, *args, **kwargs): # on call to original func
print('in property descriptor __call__')
self.calls += 1
print('call %s to %s' % (self.calls, self.func.__name__))
return self.func(*args, **kwargs)
def __get__(self, instance, owner): # on method attribute fetch
print('in property descriptor __get__')
def wrapper(*args, **kwargs): # retain state information in both instance
print('in enclosing method wrapper')
return self(instance, *args, **kwargs) # runs __call__
return wrapper
# apply to normal function
@Tracer
def spam(a, b, c):
print('in original function spam')
print('<', a + b + c, '>')
@Tracer
def eggs(x, y):
print('in original function eggs')
print('<', x ** y, '>')
# apply to class method
class Person:
def __init__(self, name, pay):
print('in original class Person __init__')
self.name = name
self.pay = pay
@Tracer
def giveRaise(self, percent):
print('in decorated class giveRaise method')
self.pay *= (1.0 + percent)
@Tracer
def lastName(self):
print('in decorated class lastName method')
return self.name.split()[-1]
if __name__ == '__main__':
print('\n\033[1;36mEntrance\033[0m\n')
print('\n\033[1;37mApply to simple function\033[0m\n')
spam(1, 2, 3)
spam(a=4, b=5, c=6)
print('\n\033[1;37mApply to class method\033[0m\n')
bob = Person('Bob Smith', 50000)
sue = Person('Sue Jones', 100000)
print('<', bob.name, sue.name, '>')
sue.giveRaise(.10)
print(int(sue.pay))
print('<', bob.lastName(), sue.lastName(), '>')
'''
Execution results:
Chapter39.Decorators]# python3 3-calltracer_descr-for-method-1.py
in property descriptor __init__
in property descriptor __init__
in property descriptor __init__
in property descriptor __init__
[1;36mEntrance[0m
[1;37mApply to simple function[0m
in property descriptor __call__
call 1 to spam
in original function spam
< 6 >
in property descriptor __call__
call 2 to spam
in original function spam
< 15 >
[1;37mApply to class method[0m
in original class Person __init__
in original class Person __init__
< Bob Smith Sue Jones >
in property descriptor __get__
in enclosing method wrapper
in property descriptor __call__
call 1 to giveRaise
in decorated class giveRaise method
110000
in property descriptor __get__
in enclosing method wrapper
in property descriptor __call__
call 1 to lastName
in decorated class lastName method
in property descriptor __get__
in enclosing method wrapper
in property descriptor __call__
call 2 to lastName
in decorated class lastName method
< Smith Jones >
'''
|
def bytes2int(data: bytes) -> int:
return int.from_bytes(data, byteorder="big", signed=True)
def int2bytes(x: int) -> bytes:
return int.to_bytes(x, length=4, byteorder="big", signed=True)
|
#!/usr/bin/python3.4
tableData = [['apples','oranges','cherries','bananas'],
['Alice','Bob','Carol','David'],
['dogs','cats','moose','goose']]
# Per the hint
colWidth = [0] * len(tableData)
# Who knew you had to transpose this list of lists
def matrixTranspose( matrix ):
if not matrix: return []
return [ [ row[ i ] for row in matrix ] for i in range( len( matrix[ 0 ] ) ) ]
def printTable(argData):
# Copy of transpose
argDataTrans = matrixTranspose(argData)
# Get longest string in each
for sub in range(len(argData)):
for i in argData[sub]:
if(len(i)>colWidth[sub]):
colWidth[sub] = len(i)
# Get max column width
maxCol = max(colWidth)
# Now print it using the transposed array
for j in range(len(argDataTrans)):
for k in range(len(argDataTrans[j])):
print(argDataTrans[j][k].rjust(maxCol),end='')
print()
if __name__ == '__main__':
printTable(tableData) |
class Niark:
def __init__(self):
self.statements = []
def addStatement(self, statement):
self.statements.insert(0,statement)
def printObject(self, tabs):
for x in range (0, len(self.statements)):
self.statements[x].printObject(tabs)
#############################################################
# Begin simple instruction section
#############################################################
class VariableAssignation:
id = 'VARIABLE ASSIGNATION'
def __init__(self, name, value):
self.name = name
self.value = value
def printObject(self, tabs):
print(tabs,self.id,self.name,self.value)
class ArrayAssignation:
id = 'ARRAY ASSIGNATION'
def __init__(self, name, index, value):
self.name = name
self.index = index
self.value = value
def printObject(self, tabs) :
if type(self.index)is Arithmetic:
print(tabs, self.id, self.name)
self.index.printObject(tabs)
print(tabs, self.value)
else:
print(tabs,self.id,self.name, self.index, self.value)
class VariableDeclaration:
id = 'VARIABLE DECLARATION'
def __init__(self, variable):
self.variable = variable
def printObject(self,tabs):
print(tabs,self.id,self.variable.printObject(tabs))
class ArrayDeclaration:
id = 'ARRAY DECLARATION'
def __init__(self, array):
self.array = array
def printObject(self, tabs):
print(tabs,self.id,self.array.printObject(tabs))
class Instruction:
def __init__(self, id, value):
self.id = id
self.value = value
def printObject(self, tabs):
if type(self.value) is Arithmetic:
print (tabs, self.id)
self.value.printObject(tabs)
else:
print(tabs,self.id, self.value)
class FunctionCall:
id = 'FUNCTION CALL'
def __init__(self, name, parameters):
self.name = name
self.parameters = parameters
def printObject(self,tabs):
if type(self.parameters) is Arithmetic:
print(tabs,self.id, self.name)
self.parameters.printObject(tabs)
else:
print(tabs,self.id, self.name, self.parameters)
class IncDec:
id = 'INCDEC'
def __init__(self, operator, variable):
self.operator = operator
self.variable = variable
def printObject(self,tabs):
print(tabs,self.id,self.operator,self.variable)
#############################################################
# End simple instruction section
#############################################################
#############################################################
# Begin conditions, arithmetics and incdec
#############################################################
class Condition:
id = 'CONDITION'
def __init__(self, term1, operator, term2):
self.term1 = term1
self.term2 = term2
self.operator = operator
def printObject(self,tabs):
if type(self.term1) is Arithmetic:
print(tabs,self.id,)
self.term1.printObject(tabs)
print(tabs,self.operator ,self.term2)
else:
if type(self.term2) is Arithmetic:
print(tabs,self.id, self.term1, self.operator)
self.term2.printObject(tabs)
else:
if type(self.term2) is FunctionCall:
self.term2.printObject(tabs)
else:
print(tabs,self.id,self.term1, self.operator, self.term2)
class Arithmetic:
id = 'ARITHMETIC'
def __init__(self, term1, operator, term2):
self.term1 = term1
self.term2 = term2
self.operator = operator
def printObject(self,tabs):
if type(self.term1) is FunctionCall and type(self.term2) is FunctionCall:
print (tabs, self.id )
self.term1.printObject(tabs)
print (tabs,self.operator)
self.term2.printObject(tabs)
else:
print(tabs,self.id,self.term1, self.operator, self.term2)
#############################################################
# End parameters, conditions and arithmetics
#############################################################
#############################################################
# Begin complex instruction section
#############################################################
class If:
id = 'IF'
def __init__(self, conditions,instructionList):
self.conditions = conditions
self.instructions = instructionList.instructions
def addInstruction(self, instruction):
self.instructions.insert(0,instruction)
def printObject(self,tabs):
print(tabs,self.id)
if(self.conditions != None):
self.conditions.printObject(tabs+" ")
if(self.instructions != None):
for x in range (len(self.instructions)):
if (self.instructions[x] != None):
self.instructions[x].printObject(tabs+" ")
else:
print('No instructions in the IF section')
class IfAndElse:
id = 'IFANDELSE'
id1 = 'IF'
id2 = 'ELSE'
def __init__(self,conditions,instructionListIf,instructionListElse):
self.conditions = conditions
self.instructionsIf = instructionListIf.instructions
self.instructionsElse = instructionListElse.instructions
def printObject(self,tabs):
print(tabs, self.id1)
if (self.conditions != None):
self.conditions.printObject(tabs)
if (self.instructionsIf != None):
for x in range(len(self.instructionsIf)):
if (self.instructionsIf[x] != None):
self.instructionsIf[x].printObject(tabs+" ")
else:
print('No instructions in the IF section')
print(tabs, self.id2)
if (self.instructionsElse != None):
for x in range(len(self.instructionsElse)):
if (self.instructionsElse[x] != None):
self.instructionsElse[x].printObject(tabs+" ")
else:
print('No instructions in the ELSE section')
class For:
id = 'FOR'
def __init__(self,declaration,conditions,incdec,instructionList):
self.declaration = declaration
self.conditions = conditions
self.incdec = incdec
self.instructions = []
# self.instructions.insert(0,declaration) //Asignamos como atributo la declaración para que no sea parte del ciclo.
self.instructions.extend(instructionList.instructions)
def printObject(self,tabs):
print(tabs,self.id)
self.conditions.printObject(tabs)
self.incdec.printObject(tabs)
if (self.instructions != None):
for x in range(len(self.instructions)):
if (self.instructions[x] != None):
self.instructions[x].printObject(tabs+" ")
#############################################################
# End complex instruction section
#############################################################
class Method:
id = 'METHOD'
def __init__(self, functionDomain, returnType, name, parameter,instructionList):
self.functionDomain = functionDomain
self.returnType = returnType
self.name = name
self.parameter = parameter
self.instructions = instructionList.instructions
def printObject(self,tabs):
print(self.id,self.functionDomain,self.returnType,self.name,self.parameter)
if (self.instructions != None):
for x in range(len(self.instructions)):
self.instructions[x].printObject(tabs+" ")
#############################################################
# Begin variables section
#############################################################
class Variable:
id = 'VARIABLE'
def __init__(self, name,value):
self.name = name
self.value = value
def printObject(self,tabs):
print(tabs,self.id, self.name, self.value)
class Array:
id = 'ARRAY'
def __init__(self, name, size):
self.name = name
self.size = size
def printObject(self,tabs):
print(tabs,self.id, self.name, self.size)
class InstructionList:
id = 'INSTRUCTION LIST'
def __init__(self,instruction,instructionList):
self.instructions = []
self.instructions.insert(0,instruction)
if (instructionList is not None):
self.instructions.extend(instructionList.instructions)
def printObject(self,tabs):
if (self.instructions != None):
for x in range(len(self.instructions)):
self.instructions[x].printObject(tabs)
#############################################################
# End variables section
#############################################################
|
#!/usr/bin/env python3
"""
ATTOM API
https://api.developer.attomdata.com
"""
HINSDALE = "HINSDALE, IL"
MADISON_HINSDALE = {}
HOMES = {
"216 S MADISON ST": HINSDALE,
"607 S ADAMS ST": HINSDALE,
"428 MINNEOLA ST": HINSDALE,
"600 S BRUNER ST": HINSDALE,
"637 S BRUNER ST": HINSDALE,
"142 S STOUGH ST": HINSDALE,
"106 S BRUNER ST": HINSDALE,
"37 S STOUGH ST": HINSDALE,
"840 S ADAMS ST": HINSDALE,
"618 S QUINCY ST": HINSDALE,
"904 S STOUGH ST": HINSDALE,
"222 CENTER ST": HINSDALE,
"602 S ADAMS ST": HINSDALE,
"18 E NORTH ST": HINSDALE,
"818 S MADISON ST": HINSDALE,
"427 N MADISON ST": HINSDALE,
"317 E CHICAGO AVE": HINSDALE,
"2 S BRUNER ST": HINSDALE,
"133 S QUINCY ST": HINSDALE,
"410 S MADISON ST": HINSDALE,
"113 MAUMELL ST": HINSDALE,
"138 E MAPLE ST": HINSDALE,
"819 W 8TH ST": HINSDALE,
"519 E 1ST ST": HINSDALE,
"733 N ELM ST": HINSDALE,
"603 JEFFERSON ST": HINSDALE,
"729 JEFFERSON ST": HINSDALE,
"731 TOWN PL": HINSDALE,
"233 S QUINCY ST": HINSDALE,
"238 S MADISON ST": HINSDALE,
"718 W 4TH ST": HINSDALE,
"209 S MADISON ST": HINSDALE,
"415 N COUNTY LINE RD": HINSDALE,
"111 S STOUGH ST": HINSDALE,
"818 W HINSDALE AVE": HINSDALE,
"712 S STOUGH ST": HINSDALE,
"650 S THURLOW ST": HINSDALE,
"134 MAUMELL ST": HINSDALE,
"508 HIGHLAND RD": HINSDALE,
"411 S STOUGH ST": HINSDALE,
"431 S QUINCY ST": HINSDALE,
"442 S QUINCY ST": HINSDALE,
}
|
folder_nm='end_to_end'
coref_path="/home/raj/"+folder_nm+"/output/coreferent_pairs/output2.txt"
chains_path="/home/raj/"+folder_nm+"/output/chains/chains.txt"
f1=open(chains_path,"w+")
def linear_search(obj, item, start=0):
for l in range(start, len(obj)):
if obj[l] == item:
return l
return -1
with open(coref_path, 'r') as f6:
i=0
key=[]
value=[]
words,start,start_end,concept=[],[],[],[]
for num,line in enumerate(f6,1):
#from the coreferent pairs file separate the words and their positions in file
items_nnp = line.rstrip("\n\r").split("|")
word_1,start_1,end_1,word_2,start_2,end_2,concept_type = items_nnp[0], items_nnp[1],items_nnp[2],items_nnp[3],items_nnp[4],items_nnp[5],items_nnp[6]
#get all words in a list and also their positions in another list at corresponding positions
if linear_search(start,start_1)==-1:
words.append(word_1)
start.append(start_1)
start_end.append(start_1+" "+end_1)
concept.append(concept_type)
if linear_search(start,start_2)==-1:
words.append(word_2)
start.append(start_2)
start_end.append(start_2+" "+end_2)
concept.append(concept_type)
#1st row will be marked as 1st pair and so on
key.append(num)
value.append(start_1)
key.append(num)
value.append(start_2)
def formchain(i,Chains):
#if the element is not present in the chain then add it
if linear_search(Chains,value[i])==-1:
Chains.append(value[i])
#store the key and value temporarily
temp_k=key[i]
temp_v=value[i]
#if there is only one element in the list delete it
if i==(len(key)-1):
key[len(key)-1]=""
value[len(value)-1]=""
else:
#delete the element by shifting the following elements by 1 position to left
for j in range (i,len(key)-1):
key[j]=key[j+1]
value[j]=value[j+1]
#mark the last position as ""
key[len(key)-1]=""
value[len(value)-1]=""
# call the method again for the another mention of the pair which shares same key
if linear_search(key,temp_k)!=-1:
formchain(linear_search(key,temp_k),Chains)
# call the method for another pair which has same mention which has already been included
if linear_search(value,temp_v)!=-1:
formchain(linear_search(value,temp_v),Chains)
#As positions are being shifted left, 0th element will never be zero unless the entire array is empty
while(key[0]!=""):
Chains=[]
#start with first element of the list
formchain(0,Chains)
for i in range(len(Chains)-1):
j=linear_search(start,Chains[i])
f1.write(words[j]+"|"+start_end[j]+"|")
j=linear_search(start,Chains[len(Chains)-1])
f1.write(words[j]+"|"+start_end[j]+"|"+concept[j]+"\n")
f1.close()
|
SCOUTOATH = '''
On my honor, I will do my best
to do my duty to God and my country
to obey the Scout Law
to help other people at all times
to keep myself physically strong, mentally awake and morally straight.
'''
SCOUTLAW = '''
A scout is:
Trustworthy
Loyal
Helpful
Friendly
Courteous
Kind
Obedient
Cheerful
Thrifty
Brave
Clean
and Reverent
'''
OUTDOORCODE = '''
As an American, I will do my best:
To be clean in my outdoor manner
To be careful with fire
To be considerate in the outdoors
And to be conservation-minded
'''
PLEDGE = '''
I pledge allegiance
to the flag
of the United States of America
and to the republic
for which it stands:
one nation under God
with liberty
and justice for all
'''
|
# Colors
BLACK = (0, 0, 0)
WHITE = (255, 255, 255)
GREY = (140, 140, 140)
CYAN = (0, 255, 255)
DARK_CYAN = (0, 150, 150)
ORANGE = (255, 165, 0)
RED = (255, 0, 0)
GREEN = (0, 255, 0)
|
data = (
'kka', # 0x00
'kk', # 0x01
'nu', # 0x02
'no', # 0x03
'ne', # 0x04
'nee', # 0x05
'ni', # 0x06
'na', # 0x07
'mu', # 0x08
'mo', # 0x09
'me', # 0x0a
'mee', # 0x0b
'mi', # 0x0c
'ma', # 0x0d
'yu', # 0x0e
'yo', # 0x0f
'ye', # 0x10
'yee', # 0x11
'yi', # 0x12
'ya', # 0x13
'ju', # 0x14
'ju', # 0x15
'jo', # 0x16
'je', # 0x17
'jee', # 0x18
'ji', # 0x19
'ji', # 0x1a
'ja', # 0x1b
'jju', # 0x1c
'jjo', # 0x1d
'jje', # 0x1e
'jjee', # 0x1f
'jji', # 0x20
'jja', # 0x21
'lu', # 0x22
'lo', # 0x23
'le', # 0x24
'lee', # 0x25
'li', # 0x26
'la', # 0x27
'dlu', # 0x28
'dlo', # 0x29
'dle', # 0x2a
'dlee', # 0x2b
'dli', # 0x2c
'dla', # 0x2d
'lhu', # 0x2e
'lho', # 0x2f
'lhe', # 0x30
'lhee', # 0x31
'lhi', # 0x32
'lha', # 0x33
'tlhu', # 0x34
'tlho', # 0x35
'tlhe', # 0x36
'tlhee', # 0x37
'tlhi', # 0x38
'tlha', # 0x39
'tlu', # 0x3a
'tlo', # 0x3b
'tle', # 0x3c
'tlee', # 0x3d
'tli', # 0x3e
'tla', # 0x3f
'zu', # 0x40
'zo', # 0x41
'ze', # 0x42
'zee', # 0x43
'zi', # 0x44
'za', # 0x45
'z', # 0x46
'z', # 0x47
'dzu', # 0x48
'dzo', # 0x49
'dze', # 0x4a
'dzee', # 0x4b
'dzi', # 0x4c
'dza', # 0x4d
'su', # 0x4e
'so', # 0x4f
'se', # 0x50
'see', # 0x51
'si', # 0x52
'sa', # 0x53
'shu', # 0x54
'sho', # 0x55
'she', # 0x56
'shee', # 0x57
'shi', # 0x58
'sha', # 0x59
'sh', # 0x5a
'tsu', # 0x5b
'tso', # 0x5c
'tse', # 0x5d
'tsee', # 0x5e
'tsi', # 0x5f
'tsa', # 0x60
'chu', # 0x61
'cho', # 0x62
'che', # 0x63
'chee', # 0x64
'chi', # 0x65
'cha', # 0x66
'ttsu', # 0x67
'ttso', # 0x68
'ttse', # 0x69
'ttsee', # 0x6a
'ttsi', # 0x6b
'ttsa', # 0x6c
'X', # 0x6d
'.', # 0x6e
'qai', # 0x6f
'ngai', # 0x70
'nngi', # 0x71
'nngii', # 0x72
'nngo', # 0x73
'nngoo', # 0x74
'nnga', # 0x75
'nngaa', # 0x76
'[?]', # 0x77
'[?]', # 0x78
'[?]', # 0x79
'[?]', # 0x7a
'[?]', # 0x7b
'[?]', # 0x7c
'[?]', # 0x7d
'[?]', # 0x7e
'[?]', # 0x7f
' ', # 0x80
'b', # 0x81
'l', # 0x82
'f', # 0x83
's', # 0x84
'n', # 0x85
'h', # 0x86
'd', # 0x87
't', # 0x88
'c', # 0x89
'q', # 0x8a
'm', # 0x8b
'g', # 0x8c
'ng', # 0x8d
'z', # 0x8e
'r', # 0x8f
'a', # 0x90
'o', # 0x91
'u', # 0x92
'e', # 0x93
'i', # 0x94
'ch', # 0x95
'th', # 0x96
'ph', # 0x97
'p', # 0x98
'x', # 0x99
'p', # 0x9a
'<', # 0x9b
'>', # 0x9c
'[?]', # 0x9d
'[?]', # 0x9e
'[?]', # 0x9f
'f', # 0xa0
'v', # 0xa1
'u', # 0xa2
'yr', # 0xa3
'y', # 0xa4
'w', # 0xa5
'th', # 0xa6
'th', # 0xa7
'a', # 0xa8
'o', # 0xa9
'ac', # 0xaa
'ae', # 0xab
'o', # 0xac
'o', # 0xad
'o', # 0xae
'oe', # 0xaf
'on', # 0xb0
'r', # 0xb1
'k', # 0xb2
'c', # 0xb3
'k', # 0xb4
'g', # 0xb5
'ng', # 0xb6
'g', # 0xb7
'g', # 0xb8
'w', # 0xb9
'h', # 0xba
'h', # 0xbb
'h', # 0xbc
'h', # 0xbd
'n', # 0xbe
'n', # 0xbf
'n', # 0xc0
'i', # 0xc1
'e', # 0xc2
'j', # 0xc3
'g', # 0xc4
'ae', # 0xc5
'a', # 0xc6
'eo', # 0xc7
'p', # 0xc8
'z', # 0xc9
's', # 0xca
's', # 0xcb
's', # 0xcc
'c', # 0xcd
'z', # 0xce
't', # 0xcf
't', # 0xd0
'd', # 0xd1
'b', # 0xd2
'b', # 0xd3
'p', # 0xd4
'p', # 0xd5
'e', # 0xd6
'm', # 0xd7
'm', # 0xd8
'm', # 0xd9
'l', # 0xda
'l', # 0xdb
'ng', # 0xdc
'ng', # 0xdd
'd', # 0xde
'o', # 0xdf
'ear', # 0xe0
'ior', # 0xe1
'qu', # 0xe2
'qu', # 0xe3
'qu', # 0xe4
's', # 0xe5
'yr', # 0xe6
'yr', # 0xe7
'yr', # 0xe8
'q', # 0xe9
'x', # 0xea
'.', # 0xeb
':', # 0xec
'+', # 0xed
'17', # 0xee
'18', # 0xef
'19', # 0xf0
'[?]', # 0xf1
'[?]', # 0xf2
'[?]', # 0xf3
'[?]', # 0xf4
'[?]', # 0xf5
'[?]', # 0xf6
'[?]', # 0xf7
'[?]', # 0xf8
'[?]', # 0xf9
'[?]', # 0xfa
'[?]', # 0xfb
'[?]', # 0xfc
'[?]', # 0xfd
'[?]', # 0xfe
)
|
# -*- Python -*-
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
# Alex Dementsov
# California Institute of Technology
# (C) 2010 All Rights Reserved
#
# {LicenseText}
#
# ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
#
testtext = """
/*******************************************************************************
*
*
*
* McStas, neutron ray-tracing package
* Copyright 1997-2002, All rights reserved
* Risoe National Laboratory, Roskilde, Denmark
* Institut Laue Langevin, Grenoble, France
*
* Component: E_monitor
*
* %I
* Written by: Kristian Nielsen and Kim Lefmann
* Date: April 20, 1998
* Version: $Revision: 438 $
* Origin: Risoe
* Release: McStas 1.6
*
* Energy-sensitive monitor.
*
* %D
* A square single monitor that measures the energy of the incoming neutrons.
*
* Example: E_monitor(xmin=-0.1, xmax=0.1, ymin=-0.1, ymax=0.1,
* Emin=1, Emax=50, nchan=20, filename="Output.nrj")
*
* %P
* INPUT PARAMETERS:
*
* xmin: Lower x bound of detector opening (m)
* xmax: Upper x bound of detector opening (m)
* ymin: Lower y bound of detector opening (m)
* ymax: Upper y bound of detector opening (m)
* Emin: Minimum energy to detect (meV)
* Emax: Maximum energy to detect (meV)
* nchan: Number of energy channels (1)
* filename: Name of file in which to store the detector image (text)
*
* OUTPUT PARAMETERS:
*
* E_N: Array of neutron counts
* E_p: Array of neutron weight counts
* E_p2: Array of second moments
*
* %E
*******************************************************************************/
the rest of text
"""
snstext = """
DEFINE COMPONENT SNS_source
DEFINITION PARAMETERS ()
SETTING PARAMETERS (char *S_filename="SNS_moderator_data_file",width=0.1, height=0.12, dist=2.5, xw=0.1, yh=0.12, Emin=50, Emax=70)
OUTPUT PARAMETERS (hdiv,vdiv,p_in)
STATE PARAMETERS (x,y,z,vx,vy,vz,t,s1,s2,p)
"""
# XXX: Check if split by lines for definitions is legal
psd_tew = """
DEFINE COMPONENT PSD_TEW_monitor
DEFINITION PARAMETERS (nxchan=20, nychan=20, nbchan=20, string type="time", string filename, string format="table")
SETTING PARAMETERS (xwidth=0, yheight=0, bmin=0, bmax=0, deltab=0,
restore_neutron=0)
OUTPUT PARAMETERS (TOF_N, TOF_p, TOF_p2, b_min, b_max, delta_b, x_min, x_max, delta_x, y_min, y_max, delta_y)
STATE PARAMETERS (x,y,z,vx,vy,vz,t,s1,s2,p)
POLARISATION PARAMETERS (sx,sy,sz)
"""
iqetext = """
DEFINE COMPONENT IQE_monitor
DEFINITION PARAMETERS ()
SETTING PARAMETERS (Ei=60, Qmin=0, Qmax=10, Emin=-45, Emax=45, int nQ=100,
int nE=90, max_angle_in_plane = 120, min_angle_in_plane = 0,
max_angle_out_of_plane = 30, min_angle_out_of_plane = -30, char *filename = "iqe_monitor.dat")
OUTPUT PARAMETERS () //(IQE_N, IQE_p, IQE_p2)
STATE PARAMETERS (x,y,z,vx,vy,vz,t,s1,s2,p)
"""
sourcegen = """
DEFINE COMPONENT Source_gen
DEFINITION PARAMETERS (string flux_file=0, string xdiv_file=0, string ydiv_file=0)
SETTING PARAMETERS (radius=0.0, dist=0, xw=0, yh=0, E0=0, dE=0, Lambda0=0, dLambda=0, I1=0,
h=0, w=0, verbose=0, T1=0,
flux_file_perAA=0, flux_file_log=0,
Lmin=0,Lmax=0,Emin=0,Emax=0,T2=0,I2=0,T3=0,I3=0,length=0)
OUTPUT PARAMETERS (p_in, lambda0, lambda02, L2P, lambda0b, lambda02b, L2Pb,lambda0c, lambda02c, L2Pc, pTable, pTable_x, pTable_y,pTable_xmin, pTable_xmax, pTable_xsum, pTable_ymin, pTable_ymax, pTable_ysum, pTable_dxmin, pTable_dxmax, pTable_dymin, pTable_dymax)
STATE PARAMETERS (x,y,z,vx,vy,vz,t,s1,s2,p)
"""
__date__ = "$Sep 15, 2010 3:17:26 PM$"
|
def extractSharramycatsTranslations(item):
"""
'Sharramycats Translations'
"""
vol, chp, frag, postfix = extractVolChapterFragmentPostfix(item['title'])
if not (chp or vol or frag) or 'preview' in item['title'].lower():
return None
tagmap = [
('11 Ways to Forget Your Ex-Boyfriend', '11 Ways to Forget Your Ex-Boyfriend', 'translated'),
('The Monster Inside Of My Bed', 'The Monster Inside Of My Bed', 'translated'),
('The Peculiars\' Tale', 'The Peculiars\' Tale', 'translated'),
('ARG', 'A. R. G.', 'translated'),
('Legend of Gemini', 'Legend of Gemini', 'translated'),
('Kaliskis', 'Kaliskis', 'translated'),
('She Died', 'She Died', 'translated'),
('Ice Goddess', 'Ice Goddess', 'translated'),
('The Friendly Wedding', 'The Friendly Wedding', 'translated'),
('Forlorn Madness', 'Forlorn Madness', 'translated'),
('Hidden Inside The Academy', 'Hidden Inside The Academy', 'translated'),
('The Señorita', 'The Señorita', 'translated'),
('School Of Myths', 'School of Myths', 'translated'),
('The Guys Inside of My Bed', 'The Guys Inside of My Bed', 'translated'),
('The Guy Inside Of My Bed', 'The Guys Inside of My Bed', 'translated'),
('Titan Academy Of Special Abilities', 'Titan Academy Of Special Abilities', 'oel'),
]
for tagname, name, tl_type in tagmap:
if tagname in item['tags']:
return buildReleaseMessageWithType(item, name, vol, chp, frag=frag, postfix=postfix, tl_type=tl_type)
return False |
class RangeQuery:
def __init__(self, data, func=min):
self.func = func
self._data = _data = [list(data)]
i, n = 1, len(_data[0])
while 2 * i <= n:
prev = _data[-1]
_data.append([func(prev[j], prev[j + i]) for j in range(n - 2 * i + 1)])
i <<= 1
def query(self, begin, end):
depth = (end - begin).bit_length() - 1
return self.func(
self._data[depth][begin], self._data[depth][end - (1 << depth)]
)
class LCA:
def __init__(self, root, graph):
"""Assumes the graph is zero-indexed"""
self.first = [-1] * len(graph)
self.path = [-1] * len(graph)
parents = [-1] * len(graph)
h = -1
dfs = [root]
# This is just routine-standard DFS traversal
while dfs:
print("The dfs is:", dfs)
node = dfs.pop()
print("The node popped is:", node)
self.path[h] = parents[node]
self.first[node] = h = h + 1
for nei in graph[node]:
if self.first[nei] == -1:
parents[nei] = node
dfs.append(nei)
print("The parents array is:", parents)
print("The first array:", self.first)
print("The path is:", self.path)
print("****************************************************************")
heights = [self.first[node] for node in self.path]
print("The heights are:", heights)
# Instantiating the rangeQuery class with heights
self.rmq = RangeQuery(heights)
def __call__(self, left, right):
if left == right:
return left
# The first array is storing the heights
left = self.first[left]
right = self.first[right]
# If left is greater than right
if left > right:
left, right = right, left
return self.path[self.rmq.query(left, right)]
if __name__ == "__main__":
g = {0: [1], 1: [2, 3, 4], 2: [5, 6], 3: [1], 4: [1, 7], 5: [2], 6: [2], 7: [4]}
print("The graph is:", g)
lca = LCA(1, g)
result = lca(5, 6)
print("The lowest common ancestor is:", result)
|
"""
Main python file for the sssdevops example
"""
def mean(num_list):
"""
Calculate the mean of a list of numbers
Parameters
----------
num_list: list of int or float
Returns
-------
float of the mean of the list
Examples
--------
>>> mean([1, 2, 3, 4, 5])
3.0
"""
return sum(num_list) / len(num_list)
|
class SymbolTableItem:
def __init__(self, type, name, customId, value):
self.type = type
self.name = name
self.value = value
# if type == 'int' or type == 'bool':
# self.value = 0
# elif type == 'string':
# self.value = ' '
# else:
# self.value = None
self.id = 'id_{}'.format(customId)
def __str__(self):
return '{}, {}, {}, {}'.format(self.type, self.name, self.value, self.id)
|
#Desafio14
#Escreva um programa que converta uma temperatura digitando em
#graus Celsius e converta para graus Fahrenheit
temp=int(input('Digite a temperatura °C: '))
f=9*temp/5+32
print('A temperatura de {}°C corresponde a {}°F!'.format(temp,f))
|
# Define the fileName as a variable
fileToWrite = 'outputFile.txt'
fileHandle = open(fileToWrite, 'w')
i = 0
while i < 10:
fileHandle.write("This is line Number " + str(i) + "\n")
i += 1
fileHandle.close()
|
NOTES = """
(c) 2017 JUSTYN CHAYKOWSKI
PROVIDED UNDER MIT LICENSE
SCHOOLOGY.COM
ACCESS CODE: GNH9N-KZ2C2
RIC 115 <-- OFFICE HOURS:
M 4-6 PM
W 12-6 PM
##########################################
# RICE LAB
#
# TEXT BOOK = ARDX ARDUINO EXPERIMENTER'S KIT - OOMLOUT
#
# CLASS PROJECT --MUST-- BUILD OFF OF WORK ALREADY DONE BY OTHER PEOPLE
#
# CTECH MAKER SPACE UNDER RIDDELL !!!!
##########################################
'FIRST FINAL EXAM QUESTION':
- SEE THE TOPICS MAP PROVIDED "TOPIC_MAP_EXAMQ_1_2.JPG"
HACKER:
A MORE LEGITIMATE DEFINITION: "SOMEONE WHO MAKES A DEVICE DO SOMETHING OTHER
THAN IT WAS ORIGINALLY INTENDED TO DO."
SOCIETY DEFINITION (DO NOT USE): "SOMEONE WHO BREAKS INTO COMPUTERS FOR MALICIOUS
PURPOSES."
RICHARD STALLMAN'S DEFINITION: "SOMEONE WHO ENJOYS PLAYFUL CLEVERNESS"
"MAKER MOVEMENT"
'MAKING' BECOMES MAINSTREAM THANKS TO NEW TECHNOLOGIES ENTERING PUB. DOMAIN:
1. FUSED DEPOSITION MOULDING
2. ARDUINO
THE ARDUINO
- ORIGINALLY CALLED 'WIRING'
-
"""
if __name__ == ('__main__'):
print(NOTES)
print('Done.')
if __name__ != ('__main__'):
print('first-day-notes.py successfully imported.')
print('first-day-notes.NOTES the class notes.')
|
a = source()
if True:
b = a + 3 * sanitizer2(y)
else:
b = sanitizer(a)
sink(b) |
#
# This file contains the Python code from Program 10.10 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm10_10.txt
#
class AVLTree(BinarySearchTree):
def balance(self):
self.adjustHeight()
if self.balanceFactor > 1:
if self._left.balanceFactor > 0:
self.doLLRotation()
else:
self.doLRRotation()
elif self.balanceFactor < -1:
if self._right.balanceFactor < 0:
self.doRRRotation()
else:
self.doRLRotation()
# ...
|
# Python program to print Even Numbers in given range
start, end = 4, 19
# iterating each number in list
for num in range(start, end + 1):
# checking condition
if num % 2 == 0:
print(num, end = " ")
|
x = input()
y = input()
z = input()
flag = z % (1 + 1) == 0 and (1 < x and x < 123) or (1 > y and y > x and x > y and y < 123)
def identity(var):
return var
if x ^ y == 1 or (
x % 2 == 0 and (3 > x and x <= 3 and 3 <= y and y > z and z >= 5) or (
identity(-1) + hash('hello') < 10 + 120 and 10 + 120 < hash('world') - 1)):
print(x, y, z)
|
def main():
class student:
std = []
def __init__(self,name,id,cgpa):
self.name = name
self.id = id
self.cgpa = cgpa
def showId(self):
return self.id
def result(self):
if(self.cgpa > 8.5):
print("Great score")
elif(self.cgpa > 7 and self.cgpa < 8.5):
print("Keep it up")
else:
print("Not gonna pass")
def details(self):
print(f'STUDENT ID: {self.id}\nSTUDENT NAME: {self.name}\nCGPA: {self.cgpa}\nPROGRESS REPORT:',end='')+self.result()
def insert():
if 1:
x = input('Enter the name of the student: ')
y = input('Enter the id of the student: ')
z = input('Enter the cgpa of the student: ')
while not(z.isdigit() and int(z)<10):
z = input('Enter a correct cgpa')
if float(z)<5:
print(f'Hey {x}, You better work on your studies')
data = student(x,y,float(z))
student.std.append(data.__dict__)
print(f'id no {y} has been added')
def search():
found = 0
try:
x= input('Enter your id: ')
for data in student.std:
if x == data['id']:
print('NAME: '+ data['name'])
print('CGPA: '+ str(data['cgpa']))
found=1
# print(data['id'])
if found ==0:
print('Data not found')
except:
print('Ooops!Error')
def decision(x):
try:
return{
'1':insert(),
'2':search(),
'3':delete(),
'4': exit()
}[x]
except:
print('Invalid input')
while True:
y = input('Press 1 if you want to insert data\nPress 2 if you want to search data\nPress 3 if you want to delete a data\npress 4 if you want to exit\n')
if y in ['1','2','3']:
if y is '1':
insert()
print(student.std)
continue
elif y is '2':
search()
continue
else:
search()
continue
else:
x1=input('INVALID OPTION.PRESS * TO CONTINUE OR ELSE TO EXIT :')
if int(ord(x1))==42:
continue
else:
break
if __name__=='__main__':
main()
|
def valid(a):
a = str(a)
num = set()
for char in a:
num.add(char)
return len(a) == len(num)
n = int(input())
n += 1
while True:
if valid(n):
print(n)
break
else:
n += 1
|
class QtConnectionError(Exception):
pass
class QtRestApiError(Exception):
""" Problem with authentification"""
pass
class QtFileTypeError(Exception):
"""Invalid type of file"""
pass
class QtArgumentError(Exception):
pass
class QtVocabularyError(Exception):
pass
class QtModelError(Exception):
pass
class QtJobError(Exception):
pass |
class PeculiarBalance:
"""
Can we save them? Beta Rabbit is trying to break into a lab that contains the only known zombie cure - but there's
an obstacle. The door will only open if a challenge is solved correctly. The future of the zombified rabbit
population is at stake, so Beta reads the challenge: There is a scale with an object on the left-hand side, whose
mass is given in some number of units. Predictably, the task is to balance the two sides. But there is a catch:
You only have this peculiar weight set, having masses 1, 3, 9, 27, ... units. That is, one for each power of 3.
Being a brilliant mathematician, Beta Rabbit quickly discovers that any number of units of mass can be balanced
exactly using this set.
To help Beta get into the room, write a method called answer(x), which outputs a list of strings representing where
the weights should be placed, in order for the two sides to be balanced, assuming that weight on the left has mass
x units.
The first element of the output list should correspond to the 1-unit weight, the second element to the 3-unit
weight, and so on. Each string is one of:
"L" : put weight on left-hand side
"R" : put weight on right-hand side
"-" : do not use weight
To ensure that the output is the smallest possible, the last element of the list must not be "-".
x will always be a positive integer, no larger than 1000000000.
"""
@staticmethod
def answer(x):
"""
Peculiar Balance.
Parameters
----------
x : int
Returns
-------
ret : list
Examples
--------
>>> PeculiarBalance().answer(2)
['L', 'R']
>>> PeculiarBalance().answer(8)
['L', '-', 'R']
>>> PeculiarBalance().answer(345)
['-', 'R', 'L', 'R', 'R', 'R']
"""
def _to_rev_ternary(q):
"""
Converts `q` to ternary equivalent in reversed order.
Parameters
----------
q : int
Returns
-------
d2t : list
Examples
--------
>>> _to_rev_ternary(345)
[0, 1, 2, 0, 1, 1]
"""
d2t = []
if q == 0:
d2t.append(0)
while q > 0:
d2t.append(q % 3)
q = q // 3
return d2t
def _to_rev_balanced_ternary(s_q):
"""
Converts `s_q` into balanced ternary.
Parameters
----------
s_q : list
Returns
-------
t2bt : list
Examples
--------
>>> _to_rev_balanced_ternary([0, 1, 2, 0, 1, 1])
[0, 1, 'T', 1, 1, 1]
"""
t2bt = []
carry = 0
for trit in s_q:
if (trit == 2) or (trit + carry == 2):
trit = trit + carry + 1
if trit == 3:
t2bt.append('T')
carry = 1
elif trit == 4:
t2bt.append(0)
carry = 1
else:
t2bt.append(trit + carry)
carry = 0
if carry > 0:
t2bt.append(carry)
return t2bt
# Unbalanced ternary
_t = _to_rev_ternary(x)
# print("""Ternary: {}""".format(_t[::-1]))
# Balanced ternary
_bt = _to_rev_balanced_ternary(_t)
# print("""Balanced Ternary: {}""".format(_bt[::-1]))
return [('L' if (str(t)) == 'T' else ('R' if t == 1 else '-')) for t in _bt]
|
P, A, B = map(int, input().split())
if P >= A+B:
print(P)
elif B > P:
print(-1)
else:
print(A+B)
|
PASSWORD = "PASSW0RD2019"
TO = ["[email protected]",
"[email protected]"]
FROM = "[email protected]"
|
# --------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
#
# Code generated by Microsoft (R) AutoRest Code Generator.
# Changes may cause incorrect behavior and will be lost if the code is
# regenerated.
# --------------------------------------------------------------------------
# pylint: disable=too-many-lines
def edgeorder_order_show(client,
name,
resource_group_name,
location):
return client.get_order_by_name(order_name=name,
resource_group_name=resource_group_name,
location=location)
def edgeorder_list_config(client,
configuration_filters,
skip_token=None,
registered_features=None,
location_placement_id=None,
quota_id=None):
configurations_request = {}
configurations_request['configuration_filters'] = configuration_filters
configurations_request['customer_subscription_details'] = {}
if registered_features is not None:
configurations_request['customer_subscription_details']['registered_features'] = registered_features
if location_placement_id is not None:
configurations_request['customer_subscription_details']['location_placement_id'] = location_placement_id
if quota_id is not None:
configurations_request['customer_subscription_details']['quota_id'] = quota_id
if len(configurations_request['customer_subscription_details']) == 0:
del configurations_request['customer_subscription_details']
return client.list_configurations(skip_token=skip_token,
configurations_request=configurations_request)
def edgeorder_list_family(client,
filterable_properties,
expand=None,
skip_token=None,
registered_features=None,
location_placement_id=None,
quota_id=None):
product_families_request = {}
product_families_request['filterable_properties'] = filterable_properties
product_families_request['customer_subscription_details'] = {}
if registered_features is not None:
product_families_request['customer_subscription_details']['registered_features'] = registered_features
if location_placement_id is not None:
product_families_request['customer_subscription_details']['location_placement_id'] = location_placement_id
if quota_id is not None:
product_families_request['customer_subscription_details']['quota_id'] = quota_id
if len(product_families_request['customer_subscription_details']) == 0:
del product_families_request['customer_subscription_details']
return client.list_product_families(expand=expand,
skip_token=skip_token,
product_families_request=product_families_request)
def edgeorder_list_metadata(client,
skip_token=None):
return client.list_product_families_metadata(skip_token=skip_token)
def edgeorder_list_operation(client):
return client.list_operations()
def edgeorder_address_list(client,
resource_group_name=None,
filter_=None,
skip_token=None):
if resource_group_name:
return client.list_by_group(resource_group_name=resource_group_name,
filter=filter_,
skip_token=skip_token)
return client.list(filter=filter_,
skip_token=skip_token)
def edgeorder_address_show(client,
address_name,
resource_group_name):
return client.get_address_by_name(address_name=address_name,
resource_group_name=resource_group_name)
def edgeorder_address_create(client,
address_name,
resource_group_name,
location,
contact_details,
tags=None,
shipping_address=None):
address_resource = {}
if tags is not None:
address_resource['tags'] = tags
address_resource['location'] = location
if shipping_address is not None:
address_resource['shipping_address'] = shipping_address
address_resource['contact_details'] = contact_details
return client.begin_create_address(address_name=address_name,
resource_group_name=resource_group_name,
address_resource=address_resource)
def edgeorder_address_update(client,
address_name,
resource_group_name,
if_match=None,
tags=None,
shipping_address=None,
contact_details=None):
address_update_parameter = {}
if tags is not None:
address_update_parameter['tags'] = tags
if shipping_address is not None:
address_update_parameter['shipping_address'] = shipping_address
if contact_details is not None:
address_update_parameter['contact_details'] = contact_details
return client.begin_update_address(address_name=address_name,
resource_group_name=resource_group_name,
if_match=if_match,
address_update_parameter=address_update_parameter)
def edgeorder_address_delete(client,
address_name,
resource_group_name):
return client.begin_delete_address_by_name(address_name=address_name,
resource_group_name=resource_group_name)
def edgeorder_order_list(client,
resource_group_name=None,
skip_token=None):
if resource_group_name:
return client.list_by_group(resource_group_name=resource_group_name,
skip_token=skip_token)
return client.list(skip_token=skip_token)
def edgeorder_order_item_list(client,
resource_group_name=None,
filter_=None,
expand=None,
skip_token=None):
if resource_group_name:
return client.list_by_group(resource_group_name=resource_group_name,
filter=filter_,
expand=expand,
skip_token=skip_token)
return client.list(filter=filter_,
expand=expand,
skip_token=skip_token)
def edgeorder_order_item_show(client,
order_item_name,
resource_group_name,
expand=None):
return client.get_order_item_by_name(order_item_name=order_item_name,
resource_group_name=resource_group_name,
expand=expand)
def edgeorder_order_item_create(client,
order_item_name,
resource_group_name,
order_item_resource):
return client.begin_create_order_item(order_item_name=order_item_name,
resource_group_name=resource_group_name,
order_item_resource=order_item_resource)
def edgeorder_order_item_update(client,
order_item_name,
resource_group_name,
if_match=None,
tags=None,
notification_email_list=None,
notification_preferences=None,
transport_preferences=None,
encryption_preferences=None,
management_resource_preferences=None,
shipping_address=None,
contact_details=None):
order_item_update_parameter = {}
if tags is not None:
order_item_update_parameter['tags'] = tags
if notification_email_list is not None:
order_item_update_parameter['notification_email_list'] = notification_email_list
order_item_update_parameter['preferences'] = {}
if notification_preferences is not None:
order_item_update_parameter['preferences']['notification_preferences'] = notification_preferences
if transport_preferences is not None:
order_item_update_parameter['preferences']['transport_preferences'] = transport_preferences
if encryption_preferences is not None:
order_item_update_parameter['preferences']['encryption_preferences'] = encryption_preferences
if management_resource_preferences is not None:
order_item_update_parameter['preferences']['management_resource_preferences'] = management_resource_preferences
if len(order_item_update_parameter['preferences']) == 0:
del order_item_update_parameter['preferences']
order_item_update_parameter['forward_address'] = {}
if shipping_address is not None:
order_item_update_parameter['forward_address']['shipping_address'] = shipping_address
if contact_details is not None:
order_item_update_parameter['forward_address']['contact_details'] = contact_details
if len(order_item_update_parameter['forward_address']) == 0:
del order_item_update_parameter['forward_address']
return client.begin_update_order_item(order_item_name=order_item_name,
resource_group_name=resource_group_name,
if_match=if_match,
order_item_update_parameter=order_item_update_parameter)
def edgeorder_order_item_delete(client,
order_item_name,
resource_group_name):
return client.begin_delete_order_item_by_name(order_item_name=order_item_name,
resource_group_name=resource_group_name)
def edgeorder_order_item_cancel(client,
order_item_name,
resource_group_name,
reason):
cancellation_reason = {}
cancellation_reason['reason'] = reason
return client.cancel_order_item(order_item_name=order_item_name,
resource_group_name=resource_group_name,
cancellation_reason=cancellation_reason)
def edgeorder_order_item_return(client,
order_item_name,
resource_group_name,
return_reason,
service_tag=None,
shipping_box_required=None,
shipping_address=None,
contact_details=None):
return_order_item_details = {}
return_order_item_details['return_reason'] = return_reason
if service_tag is not None:
return_order_item_details['service_tag'] = service_tag
if shipping_box_required is not None:
return_order_item_details['shipping_box_required'] = shipping_box_required
else:
return_order_item_details['shipping_box_required'] = False
return_order_item_details['return_address'] = {}
if shipping_address is not None:
return_order_item_details['return_address']['shipping_address'] = shipping_address
if contact_details is not None:
return_order_item_details['return_address']['contact_details'] = contact_details
if len(return_order_item_details['return_address']) == 0:
del return_order_item_details['return_address']
return client.begin_return_order_item(order_item_name=order_item_name,
resource_group_name=resource_group_name,
return_order_item_details=return_order_item_details)
|
class Config(object):
ORG_NAME = 'footprints'
ORG_DOMAIN = 'footprints.devel'
APP_NAME = 'Footprints'
APP_VERSION = '0.4.0'
|
class Solution:
def minSubArrayLen(self, s: int, nums: List[int]) -> int:
left, sum, count = 0, 0, float('inf')
for right in range(len(nums)):
sum += nums[right]
while sum >= s:
count = min(count, right - left + 1)
sum -= nums[left]
left += 1
return count if count != float('inf') else 0 |
def line(y1, x1, y2, x2):
"""
Yield integer coordinates for a line from (y1, x1) to (y2, x2).
"""
dy = abs(y2 - y1)
dx = abs(x2 - x1)
if dy == 0: # Horizontal
for x in range(x1, x2 + 1):
yield y1, x
elif dx == 0: # Vertical
for y in range(y1, y2 + 1):
yield y, x1
elif dy < dx: # Low-sloped lines
dx = x2 - x1
dy, yi = (2 * (y2 - y1), 1) if y2 >= y1 else (2 * (y1 - y2), -1)
dif = dy - 2 * dx
delta = dy - dx
y = y1
for x in range(x1, x2 + 1):
yield y, x
if delta > 0:
y += yi
delta += dif
else:
delta += dy
else: # High-sloped lines
dx, xi = (2 * (x2 - x1), 1) if x2 >= x1 else (2 * (x1 - x2), -1)
dy = y2 - y1
dif = dx - 2 * dy
delta = dx - dy
x = x1
for y in range(y1, y2 + 1):
yield y, x
if delta > 0:
x += xi
delta += dif
else:
delta += dx
|
"""
TESTS TO WRITE:
* API contract tests for notify/email provider, github, trello
"""
|
def pisano(m):
prev,curr=0,1
for i in range(0,m*m):
prev,curr=curr,(prev+curr)%m
if prev==0 and curr == 1 :
return i+1
def fib(n,m):
seq=pisano(m)
n%=seq
if n<2:
return n
f=[0]*(n+1)
f[1]=1
for i in range(2,n+1):
f[i]=f[i-1]+f[i-2]
return f[n]
# Print Fn % m where n and m are 2 inputs, and Fn => nth Fibonacci Term
inp=list(map(int,input().split()))
print(fib(inp[0],inp[1])%inp[1]) |
### Malha de repetição (loop) - While
'''
O while é bastante parecido com um 'if': ele possui uma expressão,
e é executado caso ela seja verdadeira.
Mas o if é executado apenas uma vez e depois o código segue adiante.
O while não: ao final de sua execução, ele torna a testar a expressão,
e caso ela seja verdadeira, ele repete sua execução.
'''
'''
Uma utilidade interessante do while é obrigar o usuário a
digitar apenas entradas válidas.
'''
# o exemplo abaixo não aceita um salário menor do que o mínimo atual:
salario = 0.0
while salario < 998.0:
salario = float(input('Digite o seu salário: '))
print('Você ganha ', salario)
'''
Todo tipo de código que deve se repetir várias vezes pode ser feito
com o while, como somar vários valores, gerar uma sequência etc.
Nestes casos, é normal utilizar um contador:
'''
numero = int(input('Digite quantas provas você fez: '))
contador = 1
soma = 0
while contador <= numero:
nota = float(input('Digite a nota da prova ' + str(contador) + ':'))
soma = soma + nota
contador = contador + 1
media = soma/numero
print('Você fechou com média:', media)
'''
Um jeito de forçar um loop a ser interrompido é utilizando o comando 'break'.
O loop abaixo em tese seria infinito, mas se a condição do if for verificada,
o break é executado e conseguimos escapar do loop:
'''
while True:
resposta = input('Digite SAIR para sair: ')
if resposta == 'SAIR':
break
else:
print('E lá vamos nós de novo...')
|
#
# PySNMP MIB module TRAPEZE-NETWORKS-RF-BLACKLIST-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRAPEZE-NETWORKS-RF-BLACKLIST-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:27:23 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, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint")
ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup")
TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, Unsigned32, Counter32, ObjectIdentity, iso, Gauge32, Counter64, NotificationType, Bits, IpAddress, ModuleIdentity, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "Unsigned32", "Counter32", "ObjectIdentity", "iso", "Gauge32", "Counter64", "NotificationType", "Bits", "IpAddress", "ModuleIdentity", "Integer32")
DisplayString, TextualConvention, MacAddress = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention", "MacAddress")
trpzMibs, = mibBuilder.importSymbols("TRAPEZE-NETWORKS-ROOT-MIB", "trpzMibs")
trpzRFBlacklistMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 14525, 4, 18))
trpzRFBlacklistMib.setRevisions(('2011-02-24 00:14',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: trpzRFBlacklistMib.setRevisionsDescriptions(('v1.0.4: Initial version, for 7.5 release',))
if mibBuilder.loadTexts: trpzRFBlacklistMib.setLastUpdated('201102240014Z')
if mibBuilder.loadTexts: trpzRFBlacklistMib.setOrganization('Trapeze Networks')
if mibBuilder.loadTexts: trpzRFBlacklistMib.setContactInfo('Trapeze Networks Technical Support www.trapezenetworks.com US: 866.TRPZ.TAC International: 925.474.2400 [email protected]')
if mibBuilder.loadTexts: trpzRFBlacklistMib.setDescription("RF Blacklist objects for Trapeze Networks wireless switches. Copyright (c) 2009-2011 by Trapeze Networks, Inc. All rights reserved. This Trapeze Networks SNMP Management Information Base Specification (Specification) embodies Trapeze Networks' confidential and proprietary intellectual property. Trapeze Networks retains all title and ownership in the Specification, including any revisions. This Specification is supplied 'AS IS' and Trapeze Networks makes no warranty, either express or implied, as to the use, operation, condition, or performance of the Specification.")
class TrpzRFBlacklistedEntryType(TextualConvention, Integer32):
description = 'Enumeration to indicate the Type of a Blacklisted Entry: configuredPermanent: The MAC address has been permanently blacklisted by administrative action; configuredDynamic: The MAC address has been temporarily blacklisted by administrative action; assocReqFlood, reassocReqFlood, disassocReqFlood, unknownDynamic: The MAC address has been automatically blacklisted by RF Detection.'
status = 'current'
subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7))
namedValues = NamedValues(("other", 1), ("unknownDynamic", 2), ("configuredPermanent", 3), ("configuredDynamic", 4), ("assocReqFlood", 5), ("reassocReqFlood", 6), ("disassocReqFlood", 7))
trpzRFBlacklistMibObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 4, 18, 1))
trpzRFBlacklistXmtrTable = MibTable((1, 3, 6, 1, 4, 1, 14525, 4, 18, 1, 2), )
if mibBuilder.loadTexts: trpzRFBlacklistXmtrTable.setStatus('current')
if mibBuilder.loadTexts: trpzRFBlacklistXmtrTable.setDescription('A table containing transmitters blacklisted by RF Detection.')
trpzRFBlacklistXmtrEntry = MibTableRow((1, 3, 6, 1, 4, 1, 14525, 4, 18, 1, 2, 1), ).setIndexNames((0, "TRAPEZE-NETWORKS-RF-BLACKLIST-MIB", "trpzRFBlacklistXmtrMacAddress"))
if mibBuilder.loadTexts: trpzRFBlacklistXmtrEntry.setStatus('current')
if mibBuilder.loadTexts: trpzRFBlacklistXmtrEntry.setDescription('Information about a particular blacklisted transmitter.')
trpzRFBlacklistXmtrMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 14525, 4, 18, 1, 2, 1, 1), MacAddress())
if mibBuilder.loadTexts: trpzRFBlacklistXmtrMacAddress.setStatus('current')
if mibBuilder.loadTexts: trpzRFBlacklistXmtrMacAddress.setDescription('The MAC Address of this Blacklisted Transmitter.')
trpzRFBlacklistXmtrType = MibTableColumn((1, 3, 6, 1, 4, 1, 14525, 4, 18, 1, 2, 1, 2), TrpzRFBlacklistedEntryType()).setMaxAccess("readonly")
if mibBuilder.loadTexts: trpzRFBlacklistXmtrType.setStatus('current')
if mibBuilder.loadTexts: trpzRFBlacklistXmtrType.setDescription('The Type of this Blacklisted Transmitter.')
trpzRFBlacklistXmtrTimeToLive = MibTableColumn((1, 3, 6, 1, 4, 1, 14525, 4, 18, 1, 2, 1, 3), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: trpzRFBlacklistXmtrTimeToLive.setStatus('current')
if mibBuilder.loadTexts: trpzRFBlacklistXmtrTimeToLive.setDescription('The remaining time in seconds until this Transmitter is removed from the RF Blacklist. For permanent entries, the value will be always zero.')
trpzRFBlacklistConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 4, 18, 2))
trpzRFBlacklistCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 4, 18, 2, 1))
trpzRFBlacklistGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 4, 18, 2, 2))
trpzRFBlacklistCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 14525, 4, 18, 2, 1, 1)).setObjects(("TRAPEZE-NETWORKS-RF-BLACKLIST-MIB", "trpzRFBlacklistXmtrGroup"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
trpzRFBlacklistCompliance = trpzRFBlacklistCompliance.setStatus('current')
if mibBuilder.loadTexts: trpzRFBlacklistCompliance.setDescription('The compliance statement for devices that implement RF Blacklist MIB. This compliance statement is for releases 7.5 and greater of AC (wireless switch) software.')
trpzRFBlacklistXmtrGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 14525, 4, 18, 2, 2, 1)).setObjects(("TRAPEZE-NETWORKS-RF-BLACKLIST-MIB", "trpzRFBlacklistXmtrType"), ("TRAPEZE-NETWORKS-RF-BLACKLIST-MIB", "trpzRFBlacklistXmtrTimeToLive"))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
trpzRFBlacklistXmtrGroup = trpzRFBlacklistXmtrGroup.setStatus('current')
if mibBuilder.loadTexts: trpzRFBlacklistXmtrGroup.setDescription('Group of columnar objects implemented to provide Blacklisted Transmitter info in releases 7.5 and greater.')
mibBuilder.exportSymbols("TRAPEZE-NETWORKS-RF-BLACKLIST-MIB", trpzRFBlacklistXmtrEntry=trpzRFBlacklistXmtrEntry, TrpzRFBlacklistedEntryType=TrpzRFBlacklistedEntryType, trpzRFBlacklistXmtrType=trpzRFBlacklistXmtrType, trpzRFBlacklistCompliances=trpzRFBlacklistCompliances, trpzRFBlacklistMib=trpzRFBlacklistMib, trpzRFBlacklistMibObjects=trpzRFBlacklistMibObjects, trpzRFBlacklistGroups=trpzRFBlacklistGroups, trpzRFBlacklistXmtrMacAddress=trpzRFBlacklistXmtrMacAddress, trpzRFBlacklistXmtrTimeToLive=trpzRFBlacklistXmtrTimeToLive, trpzRFBlacklistXmtrGroup=trpzRFBlacklistXmtrGroup, trpzRFBlacklistXmtrTable=trpzRFBlacklistXmtrTable, trpzRFBlacklistCompliance=trpzRFBlacklistCompliance, trpzRFBlacklistConformance=trpzRFBlacklistConformance, PYSNMP_MODULE_ID=trpzRFBlacklistMib)
|
T = int(input())
for i in range(T):
try:
a, b = map(str, input().split())
print(int(int(a)//int(b)))
except Exception as e:
print("Error Code:", e)
|
def sortNums(nums):
# constant space solution
i = 0
j = len(nums) - 1
index = 0
while index <= j:
if nums[index] == 1:
nums[index], nums[i] = nums[i], nums[index]
index += 1
i += 1
if nums[index] == 2:
index += 1
if nums[index] == 3:
nums[index], nums[j] = nums[j], nums[index]
j -= 1
return nums
print(sortNums([2, 3, 2, 2, 3, 2, 3, 1, 1, 2, 1, 3]))
|
#!/usr/bin/env python
def num_digits(k):
c = 0
while k > 0:
c += 1
k /= 10
return c
def is_kaprekar(k):
k2 = pow(k, 2)
p10ndk = pow(10, num_digits(k))
if k == (k2 // p10ndk) + (k2 % p10ndk):
return True
else:
return False
if __name__ == '__main__':
for k in range(1, 1001):
if is_kaprekar(k): print(k)
|
def citerator(data: list, x: int, y: int, layer = False) -> list:
"""Bi-dimensional matrix iterator starting from any point (i, j),
iterating layer by layer around the starting coordinates.
Args:
data (list): Data set to iterate over.
x (int): X starting coordinate.
y (int): Y starting coordinate.
Optional args:
layered (bool): Yield value by value or entire layer.
Yields:
value: Layer value.
list: Matrix layer.
"""
if layer:
yield [data[x][y]]
else:
yield data[x][y]
for depth in range(len(data)):
l = []
# top row
wpos = x - depth - 1
for i in range(y - depth - 1, y + depth + 1):
if (not (i < 0
or wpos < 0
or i >= len(data)
or wpos >= len(data))
and not (wpos >= len(data)
or i >= len(data[wpos]))):
l.append(data[wpos][i])
# right column
hpos = y + depth + 1
for i in range(x - depth - 1, x + depth + 1):
if (not (i < 0
or hpos < 0
or i >= len(data)
or hpos >= len(data))
and not (hpos >= len(data)
or hpos >= len(data[i]))):
l.append(data[i][hpos])
# bottom row
wpos = x + depth + 1
for i in reversed(range(y - depth, y + depth + 2)):
if (not (i < 0
or wpos < 0
or i >= len(data)
or wpos >= len(data))
and not (wpos >= len(data)
or i >= len(data[wpos]))):
l.append(data[wpos][i])
# left column
hpos = y - depth - 1
for i in reversed(range(x - depth, x + depth + 2)):
if (not (i < 0
or hpos < 0
or i >= len(data)
or hpos >= len(data))
and not (hpos >= len(data)
or hpos >= len(data[i]))):
l.append(data[i][hpos])
if l:
if layer:
yield l
else:
for v in l:
yield v
else:
break
|
def decorating_fun(func):
def wrapping_function():
print("this is wrapping function and get func start")
func()
print("func end")
return wrapping_function
@decorating_fun
def decorated_func():
print("i`m decoraed")
decorated_func() |
class CannotAssignValueFromParentCategory(Exception):
def __init__(self):
super().__init__("422 Cannot assign value from parent category")
|
# read file
f=open("funny.txt","r")
for line in f:
print(line)
f.close()
# readlines()
f=open("funny.txt","r")
lines = f.readlines()
print(lines)
# write file
f=open("love.txt","w")
f.write("I love python")
f.close()
# same file when you write i love javascript the previous line goes away
f=open("love.txt","w")
f.write("I love javascript")
f.close()
# You can use append mode to stop having previous lines overwritten
f=open("love.txt","a")
f.write("I love javascript")
f.close()
# show a picture of file open modes (12:12 in old video)
# writelines
f=open("love.txt","w")
f.writelines(["I love C++\n","I love scala"])
f.close()
# with statement
with open("funny.txt","r") as f:
for line in f:
print(line)
# https://www.cricketworldcup.com/teams/india/players/107
player_scores = {}
with open("scores.csv","r") as f:
for line in f:
tokens = line.split(',')
player = tokens[0]
score = int(tokens[1])
if player in player_scores:
player_scores[player].append(score)
else:
player_scores[player] = [score]
print(player_scores)
for player, score_list in player_scores.items():
min_score=min(score_list)
max_score=max(score_list)
avg_score=sum(score_list)/len(score_list)
print(f"{player}==>Min:{min_score}, Max:{max_score}, Avg:{avg_score}")
|
class NoKeywordsException(Exception):
"""Website does not contains any keywords in <meta> tag"""
pass
class BadURLException(Exception):
"""Website does not exists in a given URL"""
pass
|
# -*- coding: utf-8 -*-
"""
This software is licensed under the License (MIT) located at
https://github.com/ephreal/rollbot/Licence
Please see the license for any restrictions or rights granted to you by the
License.
"""
# A mock guild object for testing
class MockGuild():
def __init__(self, name=None, text_channels=None, users=None):
self.name = name
self.text_channels = text_channels
self.users = users
|
"""
Programa que leia duas notas de um aluno e calcule sua média,
mostrando uma mensagem no final, de acordo com a média atingida.
- media abaixo de 5.0:
reprovado
- media entre 5.0 e 6.9:
recuperação
- media 7.0 ou superior:
aprovado
"""
nota1 = float(input('Informe a primeira nota: '))
nota2 = float(input('Informe a segunda nota: '))
media = (nota1 + nota2) / 2
if media < 5.0:
print(f'Sua média foi {media}. Por isso, você está REPROVADO')
elif media <= 6.9:
print(f'Sua média foi {media}. Você ficou em RECUPERAÇÃO')
else:
print(f'Sua média foi {media}. Você está APROVADO')
|
def get_first_matching_attr(obj, *attrs, default=None):
for attr in attrs:
if hasattr(obj, attr):
return getattr(obj, attr)
return default
def get_error_message(exc) -> str:
if hasattr(exc, 'message_dict'):
return exc.message_dict
error_msg = get_first_matching_attr(exc, 'message', 'messages')
if isinstance(error_msg, list):
error_msg = ', '.join(error_msg)
if error_msg is None:
error_msg = str(exc)
return error_msg |
class Batcher(object):
"""
Batcher enables developers to batch multiple retrieval requests.
Example usage #1::
from pycacher import Cacher
cacher = Cacher()
batcher = cacher.create_batcher()
batcher.add('testkey')
batcher.add('testkey1')
batcher.add('testkey2')
values = batcher.batch()
It is possible to use batcher as context manager. Inside the context manager,
developers can call the `.register` method of cached functions
to register its keys to the currently active batcher for later batching. Then,
when the actual cached functions that were registered earlier inside the
context manager were actually called, it will seek its value from the batcher
context.
Example usage #2::
from pycacher import Cacher
cacher = Cacher()
batcher = cacher.create_batcher()
with batcher:
cached_func.register(1, 2)
cached_func_2.register(1, 2)
cached_func_3.register(3, 5)
batcher.batch()
#Later..
with batcher:
cached_func(1, 2) #will look for its value from the batcher
cached_func_2(1, 2)
cached_func(3, 5)
#You can also do this:
batcher.register(cached_func, 1, 2)
batcher.register(cached_func_2, 1, 2)
"""
def __init__(self, cacher=None):
self.cacher = cacher
self._keys = set()
self._last_batched_values = None
self._autobatch_flag = False
self._hooks = {'register':[], 'call':[]}
def add(self, key):
if isinstance(key, list):
for k in key:
self._keys.add(k)
else:
self._keys.add(key)
def reset(self):
self._keys = set()
def batch(self):
self._last_batched_values = self.cacher.backend.multi_get(self._keys)
return self._last_batched_values
def has_batched(self):
return self._last_batched_values is not None
def register(self, decorated_func, *args):
cache_key = decorated_func.build_cache_key(*args)
self.add(cache_key)
#run the hooks on the batcher first
self.trigger_hooks('register', cache_key, self)
self.cacher.trigger_hooks('register', cache_key, self)
def register_list(self, decorated_list_func, *args, **kwargs):
"""Registers a cached list function.
"""
skip = kwargs['skip']
limit = kwargs['limit']
#add the ranged cache keys to the actual internal key batch list.
for ranged_cache_key in decorated_list_func.get_ranged_cache_keys(skip=skip, limit=limit, *args):
self.add(ranged_cache_key)
#Build the "root" cache key to be passed to the hook functions.
#Note that we do not pass the ranged cache key to the hook functions,
#it's completely for internal use.
cache_key = decorated_list_func.build_cache_key(*args)
#run the hooks on the batcher first
self.trigger_hooks('register', cache_key, self)
self.cacher.trigger_hooks('register', cache_key, self)
def get_last_batched_values(self):
return self._last_batched_values
def get_values(self):
return self.get_last_batched_values()
def get_keys(self):
return self._keys
def get(self, key):
if self._last_batched_values:
return self._last_batched_values.get(key)
return None
def is_batched(self, key):
"""Checks whether a key is included in the latest batch.
Example:
self.batcher.add('test-1')
self.batcher.batch()
self.batcher.is_batched('test-1')
>> True
"""
if self._last_batched_values:
return key in self._last_batched_values
return False
def autobatch(self):
"""autobatch enables the batcher to automatically batch the batcher keys
in the end of the context manager call.
Example Usage::
with batcher.autobatch():
expensive_function.register(1, 2)
#is similar to:
with batcher:
expensive_function.register(1, 2)
batcher.batch()
"""
self._autobatch_flag = True
return self
def __enter__(self):
""" On context manager enter step, we're basically pushing this Batcher instance
to the parent cacher's batcher context, so when the there are decorated
functions that are registering, they know to which batcher to register to."""
self.cacher.push_batcher(self)
def __exit__(self, type, value, traceback):
""" On exit, pop the batcher. """
if self._autobatch_flag:
self.batch()
self._autobatch_flag = False
self.cacher.pop_batcher()
def add_hook(self, event, fn):
""" Add hook function to be executed on event.
Example usage::
def on_cacher_invalidate(key):
pass
cacher.add_hook('invalidate', on_cacher_invalidate)
"""
if event not in ('invalidate', 'call', 'register'):
raise InvalidHookEventException(\
"Hook event must be 'invalidate', 'call', or 'register'")
self._hooks[event].append(fn)
def trigger_hooks(self, event, *args, **kwargs):
if event not in ('invalidate', 'call', 'register'):
raise InvalidHookEventException(\
"Hook event must be 'invalidate', 'call', or 'register'")
for fn in self._hooks[event]:
fn(*args, **kwargs)
def remove_all_hooks(self, event):
if event not in ('invalidate', 'call', 'register'):
raise InvalidHookEventException(\
"Hook event must be 'invalidate', 'call', or 'register'")
#reset
self._hooks[event] = []
|
matriz = []
valor = []
somaPar = somaColuna3 = maiorLinha2 = 0
#Gerador de matriz 3x3
for i in range(0, 3):
for j in range(0, 3):
valor.append(int(input(f'Digite um valor para [{i}, {j}]: ')))
matriz.append(valor[:])
valor.clear()
print('-='*30)
for i in range(0, 3):
for j in range(0, 3):
print(f'[{matriz[i][j]:^5}]', end='') #Imprime a matriz 3x3
if matriz[i][j] % 2 == 0: #Análise soma dos pares
somaPar += matriz[i][j]
if j == 2: #Análise soma terceira coluna
somaColuna3 += matriz[i][j]
if i == 1: #Análise maior valor linha 2
if maiorLinha2 <= matriz[i][j]:
maiorLinha2 = matriz[i][j]
print()
print('-='*30)
print(f'Soma de todos os valores pares é {somaPar}.')
print(f'Soma dos valores da terceira coluna é {somaColuna3}.')
print(f'O maior valor da segunda linha é {maiorLinha2}.')
|
'''
Implement the BSTIterator class that represents an iterator over the in-order traversal of a binary search tree (BST):
BSTIterator(TreeNode root) Initializes an object of the BSTIterator class. The root of the BST is given as part of the constructor. The pointer should be initialized to a non-existent number smaller than any element in the BST.
boolean hasNext() Returns true if there exists a number in the traversal to the right of the pointer, otherwise returns false.
int next() Moves the pointer to the right, then returns the number at the pointer.
Notice that by initializing the pointer to a non-existent smallest number, the first call to next() will return the smallest element in the BST.
You may assume that next() calls will always be valid. That is, there will be at least a next number in the in-order traversal when next() is called.
'''
# Definition for a binary tree node.
# class TreeNode(object):
# def __init__(self, val=0, left=None, right=None):
# self.val = val
# self.left = left
# self.right = right
class BSTIterator(object):
def __init__(self, root):
"""
:type root: TreeNode
"""
self.stack = [root]
self.size = 1
def next(self):
"""
:rtype: int
"""
while self.stack:
node = self.stack.pop()
if not node:
node = self.stack.pop()
self.size = len(self.stack)
return node.val
if node.right:
self.stack.append(node.right)
self.stack.append(node)
self.stack.append(None)
if node.left:
self.stack.append(node.left)
return None
def hasNext(self):
"""
:rtype: bool
"""
return self.size > 0
# Your BSTIterator object will be instantiated and called as such:
# obj = BSTIterator(root)
# param_1 = obj.next()
# param_2 = obj.hasNext() |
c = input().strip()
fr = input().split()
n = 0
for i in fr:
if c in i: n += 1
print('{:.1f}'.format(n*100/len(fr)))
|
#Задача N3. Вариант 8
#Напишите программу, которая выводит имя "Борис Николаевич Бугаев", и
#запрашивает его псевдоним. Программа должна сцеплять две эти строки и
#выводить полученную строку, разделяя имя и псевдоним с помощью тире.
#Будашов Андрей
#03.03.2016
print("Герой нашей сегодняшней программы-Борис Николаевич Бугаев")
psev=input("Под каким же псевдонимом он известен? Ваш ответ:")
if(psev)==("Андрей Белый"):
print("Все верно Борис Николаевич Бугаев -" + psev)
else:
print("Вы ошиблись, это не его псевдоним(")
input ("Press Enter to close")
|
# -*- coding: utf-8 -*-
# @Author: TD21forever
# @Date: 2019-05-25 00:18:44
# @Last Modified by: TD21forever
# @Last Modified time: 2019-05-26 11:36:12
'''
保证差距最远的两个磁道的概率最小
'''
def solution(k,alist):
sumRate = sum(alist)
rate = [i/sumRate for i in alist]
rate.sort()
j = 0
k = 0
result = 0
tmp = rate.copy()
for i in range(len(rate)):
if i %2 == 0:
tmp[0+j] = rate[i]
j += 1
else:
tmp[-1-k] = rate[i]
k += 1
for i in range(len(tmp)):
for j in range(i+1,len(tmp)):
result += tmp[i]*tmp[j]*(j-i)
return result
if __name__ == '__main__':
rate = [33, 55, 22, 11, 9]
k = 5
res = solution(k,rate)
print(res) |
# Copyright 2021 Huawei Technologies Co., Ltd
#
# 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.
_base_ = [
'../_base_/models/mask_rcnn_r50_fpn.py',
'../_base_/datasets/coco_instance.py',
'../_base_/schedules/schedule_1x.py', '../_base_/default_runtime.py'
]
model = dict(
rpn_head=dict(
anchor_generator=dict(type='LegacyAnchorGenerator', center_offset=0.5),
bbox_coder=dict(type='LegacyDeltaXYWHBBoxCoder'),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0 / 9.0, loss_weight=1.0)),
roi_head=dict(
bbox_roi_extractor=dict(
type='SingleRoIExtractor',
roi_layer=dict(
type='RoIAlign',
output_size=7,
sampling_ratio=2,
aligned=False)),
mask_roi_extractor=dict(
type='SingleRoIExtractor',
roi_layer=dict(
type='RoIAlign',
output_size=14,
sampling_ratio=2,
aligned=False)),
bbox_head=dict(
bbox_coder=dict(type='LegacyDeltaXYWHBBoxCoder'),
loss_bbox=dict(type='SmoothL1Loss', beta=1.0, loss_weight=1.0))))
# model training and testing settings
train_cfg = dict(
rpn_proposal=dict(nms_post=2000, max_num=2000),
rcnn=dict(assigner=dict(match_low_quality=True)))
|
raw_data = [
b'\x1cT#01 61.01,\r\nT#03 88.07,90.78,90.17,29.48,14.41\r\n \r\n \xae$\xe2\x02\xe0D\x143P\x02\xe0',
b'T#01 56.92,\r\nT#03 88.10,90.62,90.42,29.68,14.39\r\n \r\n C \xfc',
b'T#01 63.51,\r\nT#03 87.98,90.36,90.15,29.30,14.41\r\n \r\n \x03\x82\x01\x80$\x9f\xd8\xbc\x0f\x08',
b'T#01 56.05,\r\nT#03 87.99,90.66,90.52,29.00,14.40\r\n \r\n \x080"',
b'T#01 59.20,\r\nT#03 88.17,91.09,90.62,28.79,14.41\r\n \r\n \x803\x06\x18\xf8',
b'T#01 52.21,\r\nT#03 87.93,90.57,90.56,28.65,14.40\r\n \r\n \xf83\x0b\x1c',
b'T#01 49.17,\r\nT#03 87.75,90.50,90.40,28.24,14.41\r\n \r\n :\x02@\x8c\x06',
b'T#01 45.93,\r\nT#03 87.86,91.08,90.75,27.81,14.42\r\n \r\n \x01\x80\xa1s\x86\xe7\x03\xfc',
b'T#01 50.86,\r\nT#03 87.79,90.61,90.53,27.23,14.43\r\n \r\n \x86\x16 \x80\xf0\xc7\xf2\xc0',
b'\x1e\x80\xf8T#01 47.12,\r\nT#03 87.54,90.59,90.41,26.66,14.42\r\n \r\n \xf1\x17a\x80\x02\xfe',
b'T#01 50.26,\r\nT#03 87.60,90.97,90.42,26.95,14.40\r\n \r\n \xc0\xf3[\xd3\x81\xfc9\xf5\xb8\x06\x80\xfe',
b'T#01 57.21,\r\nT#03 87.64,90.55,90.13,25.40,14.42\r\n \r\n \x04\x08\x93\x98\xd9\xfc',
b'T#01 54.55,\r\nT#03 87.86,90.88,90.43,25.55,14.40\r\n \r\n \x01\x80\t\x18\xc6!`\xfe',
b'#01 53.39,\r\nT#03 87.89,90.84,90.12,25.71,14.41\r\n \r\n \x01(\x12 \xfe',
b'T#01 52.59,\r\nT#03 88.06,90.75,90.29,26.29,14.40\r\n \r\n \xf2\x83l\x1e<\x90\x04',
b'\xfeT#01 54.47,\r\nT#03 87.93,90.83,90.04,26.48,14.41\r\n \r\n k|^y\xfe',
b'T#01 55.85,\r\nT#03 87.83,90.89,90.51,26.45,14.42\r\n \r\n \xc4\xd6>4\xfa',
b'T#01 52.55,\r\nT#03 87.59,90.84,90.53,25.37,14.42\r\n \r\n \x02:\\@\x84G\x01\x84',
b'T#01 54.72,\r\nT#03 87.76,90.86,90.25,25.36,14.40\r\n \r\n \x90\x80B\xc8;\x80\x0e\x80',
b'T#01 54.70,\r\nT#03 87.78,90.64,90.08,25.54,14.40\r\n \r\n \x88P\xc2\x06',
b'T#01 55.10,\r\nT#03 87.96,90.90,90.54,26.46,14.41\r\n \r\n @\xf0kT\xfc',
b'T#01 53.83,\r\nT#03 87.90,90.91,90.32,25.77,14.42\r\n \r\n \x12\x0e"\xf2 \xbb\x0f\x80',
b'T#01 54.64,\r\nT#03 87.99,90.50,90.26,26.15,14.43\r\n \r\n ',
b'T#01 53.13,\r\nT#03 87.85,91.07,90.40,25.94,14.43\r\n \r\n \x80\xf8',
b'T#01 60.26,\r\nT#03 87.62,91.09,90.31,25.16,14.42\r\n \r\n \x18A\x04',
b'T#01 56.29,\r\nT#03 87.71,91.03,90.17,24.70,14.40\r\n \r\n "\xc8H\xc0',
b'T#01 66.20,\r\nT#03 87.77,91.03,90.26,24.44,14.40\r\n \r\n ',
b'T#01 57.08,\r\nT#03 87.82,91.13,90.22,24.22,14.40\r\n \r\n \x01\x02\x80@\x04',
b'T#01 61.81,\r\nT#03 87.69,91.07,90.28,24.03,14.40\r\n \r\n \xf3',
b'T#01 59.01,\r\nT#03 87.73,90.70,90.07,23.99,14.42\r\n \r\n @\xfc',
b'T#01 56.05,\r\nT#03 87.69,91.02,90.36,24.32,14.40\r\n \r\n \xa0\x8f\x0b\x07\x01',
b'T#01 63.64,\r\nT#03 87.72,90.99,90.34,24.45,14.41\r\nT#01 64.58,\r\n \r\n \xfe',
b'\xfcT#01 67.45,\r\nT#03 87.80,90.83,90.22,24.52,14.42\r\n \r\n \x02\x04\xfe ,@\xa3\x03',
b'T#01 60.04,\r\nT#03 87.69,90.80,90.57,24.98,14.41\r\n \r\n \xe0\x01\x14',
b'T#01 59.57,\r\nT#03 87.72,90.96,90.57,25.91,14.42\r\n \r\n \x01\xe4s\xe10D\x03\xe0',
b'T#01 61.67,\r\nT#03 87.73,91.05,90.40,26.04,14.42\r\n \r\n \xe0\xfa\xe2\xc8\x84\x1e',
b'\x12\xf8T#01 85.78,\r\nT#03 87.71,91.21,90.41,25.67,14.39\r\n \r\n 2\x011\x95\x89\x80\r\xf0',
b'T#01 69.74,\r\nT#03 87.91,90.97,90.49,25.24,14.42\r\n \r\n \xf0',
b'T#01 65.01,\r\nT#03 87.93,90.61,90.60,25.28,14.41\r\n \r\n \x01\xf3HB',
b'T#01 63.63,\r\nT#03 87.97,90.90,90.92,26.12,14.40\r\n \r\n \xfe',
b'T#01 61.84,\r\nT#03 88.17,91.13,90.78,26.92,14.42\r\n \r\n \x80H\xf0',
b'T#01 65.72,\r\nT#03 87.72,90.93,90.51,26.14,14.40\r\n \r\n \xfe1\x8e',
b'T#01 61.01,\r\nT#03 87.61,90.94,90.65,25.93,14.40\r\n \r\n \x02\x1cH\xe0',
b'T#01 60.10,\r\nT#03 87.62,90.97,90.60,25.87,14.39\r\n \r\n \xf1',
b'T#01 61.83,\r\nT#03 87.83,91.03,90.29,25.60,14.43\r\n \r\n \xf8\xe8',
b'T#01 65.53,\r\nT#03 88.13,90.71,90.49,25.44,14.42\r\n \r\n \xc7a"\x12\x04',
b'T#01 67.88,\r\nT#03 87.83,91.02,90.20,25.28,14.42\r\n \r\n 0\x07@\x12D',
b'T#01 77.61,\r\nT#03 87.68,91.06,90.27,24.85,14.42\r\n \r\n \x800\xfb\x02\xdc\x03\x01\x1e',
b'T#01 67.28,\r\nT#03 87.94,91.08,90.61,24.95,14.40\r\n \r\n \xc0|\xdb\xe8g<',
b'T#01 63.90,\r\nT#03 87.86,90.98,90.53,24.97,14.43\r\n \r\n \xc7\x02\x80',
b'T#01 60.11,\r\nT#03 87.76,90.91,90.52,25.06,14.40\r\n \r\n ',
b'T#01 66.12,\r\nT#03 87.65,90.85,90.69,25.25,14.42\r\n \r\n \xe0\x02\x80X\t\x04@',
b'T#01 71.97,\r\nT#03 87.81,90.91,90.32,25.65,14.42\r\n \r\n \xc8\x06\x047',
b'T#01 66.58,\r\nT#03 87.79,91.06,90.35,25.46,14.43\r\n \r\n `\x80\x88\xa4\xfc',
b'T#01 58.96,\r\nT#03 87.32,90.92,90.27,25.17,14.39\r\n \r\n \x08\xfa',
b'T#01 58.30,\r\nT#03 87.23,90.91,90.43,24.80,14.41\r\n \r\n ',
b'T#01 56.55,\r\nT#03 87.35,90.98,90.50,24.71,14.39\r\n \r\n \xf8<-\x0c',
b'T#01 58.05,\r\nT#03 87.40,90.91,90.18,24.76,14.41\r\n \r\n \x05',
b'T#01 76.65,\r\nT#03 87.64,91.03,90.22,24.38,14.42\r\n \r\n `\x81\xc2\xc0#\x0c\x1c',
b'T#01 65.58,\r\nT#03 87.69,90.56,90.21,24.26,14.40\r\n \r\n \xc8',
b'T#01 62.54,\r\nT#03 87.65,90.73,90.48,24.64,14.42\r\n \r\n \x0e7\x124\r\xfe',
b'T#01 62.07,\r\nT#03 87.48,90.98,90.17,25.01,14.42\r\n \r\n \x80\xfea\x92\xc4\xae',
b'T#01 63.46,\r\nT#03 87.52,91.04,90.37,24.83,14.40\r\n \r\n \x80\xc0',
b'T#01 60.82,\r\nT#03 87.18,90.87,90.26,24.67,14.39\r\n \r\n \x03?h\x04\xb1\x98\t\x80\x0f\x81\x01\x80',
b'T#01 54.87,\r\nT#03 87.27,90.85,90.50,24.82,14.41\r\n \r\n \xfc(\x04B\x1c\xf0',
b'T#01 73.36,\r\nT#03 87.56,90\xfc\x04\x01\x12\x12\xf5\x1e0\x01\x80',
b'T#01 71.44,\r\nT#03 87.76,91.00,90.31,24.82,14.14\r\n \r\n \xc0t',
b'T#01 64.59,\r\nT#03 87.24,91.05,90.08,24.17,14.42\r\n \r\n \x02\xe0',
b'T#01 72.30,\r\nT#03 87.32,91.08,90.14,23.47,14.42\r\n \r\n @H\x80\x01\xa0\x19\x15\x03',
b'T#01 65.38,\r\nT#03 87.48,90.94,90.24,23.25,14.44\r\n \r\n \x03\x10\x06\x85l0\x18',
b'T#01 64.02,\r\nT#03 87.45,90.98,90.18,22.97,14.42\r\n \r\n \x80\xfe\x1b',
b'\x01\xf9T#01 87.72,\r\nT#03 87.60,91.12,90.06,22.60,14.27\r\n \r\n \x80\xf8\x8c\x10\x8b',
b'T#01 80.09,\r\nT#03 87.47,91.07,89.97,22.08,14.09\r\nT#01 86.17,\r\nT#03 87.47,91.09,90.05,21.94,14.04\r\n \r\n \xfcM\x06D\x06',
b'T#01 67.42,\r\nT#03 87.45,91.03,90.00,21.38,14.42\r\n \r\n \xfd9P\x0c\\\x04',
b'T#01 72.79,\r\nT#03 87.40,91.07,90.09,20.90,14.13\r\n \r\n \xc1\x03',
b'T#01 72.22,\r\nT#03 87.66,91.27,90.00,20.44,13.91\r\n \r\n \x10\x10\x80\x0c\xd0t\xc4\x17\x0c\x80',
b'T#01 71.30,\r\nT#03 87.56,91.18,90.11,20.04,13.76\r\n \r\n \x01\xea',
b'T#01 83.55,\r\nT#03 87.52,90.96,89.86,19.28,13.64\r\n \r\n \xf4',
b'T#01 77.06,\r\nT#03 87.75,91.30,90.21,18.97,13.49\r\n \r\n \xa0\x8a&\x02',
b'T#01 79.01,\r\nT#03 87.55,91.02,90.12,18.57,13.39\r\n \r\n \x0c\x03\x03\xc0\xe1\x80 \xfc',
b'T#01 91.21,\r\nT#03 87.67,91.03,90.01,18.39,13.28\r\n \r\n \xe6\x19\xd0\x01\xd0',
b'T#01 89.87,\r\nT#03 88.16,91.20,90.12,18.07,13.16\r\n \r\n \xe0\xc4\x90\xc2\x03\xf0',
b'T#01 89.64,\r\nT#03 87.91,90.82,89.80,17.45,13.08\r\n \r\n \x02\x02\x13\xc0c\xc8\x19\xfc',
b'T#01 88.11,\r\nT#03 87.94,90.98,89.85,17.33,13.01\r\n \r\n \x80\r\x18\xfe',
b'T#01 89.66,\r\nT#03 87.88,91.42,89.75,17.03,12.96\r\n \r\n \xc0x\x80\x08\xbd\x0f',
b'T#01 92.55,\r\nT#03 87.94,90.80,89.64,16.70,12.93\r\n \r\n \xfev\xa9\x04',
b'T#01 88.17,\r\nT#03 87.94,91.15,89.74,16.60,12.93\r\n \r\n \x050\x89\xc1\x81\xe7V\x06&',
b'T#01 92.07,\r\nT#03 87.76,90.92,89.62,16.64,12.93\r\n \r\n \xfc\x01<\xe0\x08\x04',
b'T#01 89.57,\r\nT#03 87.67,90.97,89.57,16.57,12.93\r\n \r\n \x01"\x80\x04\xfe',
b'T#01 88.74,\r\nT#03 88.18,91.11,90.09,16.61,12.93\r\n \r\n \x03\x060\xfe\x8f\x97\x0e\x170\x01\xc0',
b'T#01 88.81,\r\nT#03 87.98,90.89,89.86,16.19,12.95\r\n \r\n \xf0\x85\x0e8\xe8\x03',
b'T#01 95.93,\r\nT#03 87.88,90.96,90.01,16.06,12.96\r\n \r\n \xfa',
b'\xf8T#01 92.55,\r\nT#03 87.87,90.92,90.17,15.88,12.96\r\n \r\n \xc9\x08,',
b'T#01 93.25,\r\nT#03 87.74,90.88,89.86,15.81,12.96\r\n \r\n \xfe%m\x03\x91\x0f',
b'\x0c\xc0T#01 94.89,\r\nT#03 87.81,91.07,89.78,15.67,12.96\r\n \r\n \x01\xfa0\x08',
b'T#01 92.07,\r\nT#03 87.87,90.94,89.96,15.63,12.96\r\n \r\n \xfe\x0b\xe0\xc3',
b'T#01 97.30,\r\nT#03 87.75,91.06,90.04,15.38,12.96\r\n \r\n \x02@',
b'T#01 95.69,\r\nT#03 87.68,91.04,89.88,15.24,12.96\r\n \r\n \x900\xe4',
b'T#01 95.21,\r\nT#03 87.78,90.99,89.73,15.18,12.96\r\n \r\n C\xfe\x1cD\n\x89\x81',
b'T#01 91.75,\r\nT#03 87.90,90.96,89.65,15.18,12.96\r\n \r\n @\xf2,A',
]
clean_data = [
[['61.01', ], ],
[['56.92', ], ],
[['63.51', ], ],
[['56.05', ], ],
[['59.20', ], ],
[['52.21', ], ],
[['49.17', ], ],
[['45.93', ], ],
[['50.86', ], ],
[['47.12', ], ],
[['50.26', ], ],
[['57.21', ], ],
[['54.55', ], ],
[['53.39', ], ],
[['52.59', ], ],
[['54.47', ], ],
[['55.85', ], ],
[['52.55', ], ],
[['54.72', ], ],
[['54.70', ], ],
[['55.10', ], ],
[['53.83', ], ],
[['54.64', ], ],
[['53.13', ], ],
[['60.26', ], ],
[['56.29', ], ],
[['66.20', ], ],
[['57.08', ], ],
[['61.81', ], ],
[['59.01', ], ],
[['56.05', ], ],
[['63.64', ], ['64.58', ], ],
[['67.45', ], ],
[['60.04', ], ],
[['59.57', ], ],
[['61.67', ], ],
[['85.78', ], ],
[['69.74', ], ],
[['65.01', ], ],
[['63.63', ], ],
[['61.84', ], ],
[['65.72', ], ],
[['61.01', ], ],
[['60.10', ], ],
[['61.83', ], ],
[['65.53', ], ],
[['67.88', ], ],
[['77.61', ], ],
[['67.28', ], ],
[['63.90', ], ],
[['60.11', ], ],
[['66.12', ], ],
[['71.97', ], ],
[['66.58', ], ],
[['58.96', ], ],
[['58.30', ], ],
[['56.55', ], ],
[['58.05', ], ],
[['76.65', ], ],
[['65.58', ], ],
[['62.54', ], ],
[['62.07', ], ],
[['63.46', ], ],
[['60.82', ], ],
[['54.87', ], ],
[['73.36', ], ],
[['71.44', ], ],
[['64.59', ], ],
[['72.30', ], ],
[['65.38', ], ],
[['64.02', ], ],
[['87.72', ], ],
[['80.09', ], ['86.17', ], ],
[['67.42', ], ],
[['72.79', ], ],
[['72.22', ], ],
[['71.30', ], ],
[['83.55', ], ],
[['77.06', ], ],
[['79.01', ], ],
[['91.21', ], ],
[['89.87', ], ],
[['89.64', ], ],
[['88.11', ], ],
[['89.66', ], ],
[['92.55', ], ],
[['88.17', ], ],
[['92.07', ], ],
[['89.57', ], ],
[['88.74', ], ],
[['88.81', ], ],
[['95.93', ], ],
[['92.55', ], ],
[['93.25', ], ],
[['94.89', ], ],
[['92.07', ], ],
[['97.30', ], ],
[['95.69', ], ],
[['95.21', ], ],
[['91.75', ], ],
]
|
# -*- coding: utf-8 -*-
#
# Unless explicitly stated otherwise all files in this repository are licensed
# under the Apache 2 License.
#
# This product includes software developed at Datadog
# (https://www.datadoghq.com/).
#
# Copyright 2018 Datadog, Inc.
#
"""crud_service.py
Service-helpers for creating and updating data.
"""
class CRUDService(object):
"""CRUD persistent storage service.
An abstract class for creating and mutating data.
"""
def create(self):
"""Creates and persists a new record to the database."""
pass
def update(self):
"""Updates a persisted record."""
pass
def delete(self):
"""Deletes a persisted record."""
pass
|
#
# @lc app=leetcode id=1299 lang=python3
#
# [1299] Replace Elements with Greatest Element on Right Side
#
# @lc code=start
class Solution:
def replaceElements(self, arr: List[int]) -> List[int]:
index = 0
result = []
for i,v in enumerate(arr):
if i+1 == len(arr):
result.append(-1)
break
result.append(max(arr[i+1:len(arr)]))
index = index + 1
return result
# @lc code=end
|
class Solution:
def findNumberOfLIS(self, nums):
"""
:type nums: List[int]
:rtype: int
"""
if not nums:
return 0
dp = [1 for i in range(len(nums))]
c = [1 for i in range(len(nums))]
for i in range(1, len(nums)):
for j in range(i):
if nums[j] < nums[i]:
#dp[i] = max(dp[j]+1, dp[i])
if dp[i] < dp[j] + 1:
dp[i] = dp[j] + 1
c[i] = c[j]
elif dp[i] == dp[j] + 1:
c[i] += c[j]
print(c)
print(dp)
m = max(dp)
res = 0
for i in range(len(dp)):
if dp[i] == m:
res += c[i]
return res
|
# REFAZENDO O DESAFIO 51
# mostra os 10 primeiros termos de uma PA
print('GERADOR DE PA')
a1 = int(input('Digite o primeiro termo da PA: '))
r = int(input('Digite a razão da PA: '))
print('Dez primeiros termos da PA:')
termo = a1
i = 1
while i <= 10:
print('{} '.format(termo), end='')
termo += r
i += 1
print('\nFIM')
|
def rotate(cur_direction, rotation_command):
# Assumes there are only R/L 90/180/270
invert_rl = {
"R": "L",
"L": "R",
}
if int(rotation_command[1:]) == 270:
rotation_command = f"{invert_rl[rotation_command[0]]}90"
elif int(rotation_command[1:]) == 180:
flip = {
"N": "S",
"E": "W",
"S": "N",
"W": "E",
}
return flip[cur_direction]
lookup = {
"L90" : {
"N": "W",
"E": "N",
"S": "E",
"W": "S",
},
"R90" : {
"N": "E",
"E": "S",
"S": "W",
"W": "N",
},
}
return lookup[rotation_command][cur_direction]
def rotate_waypoint(x, y, rotation_command):
# Assumes there are only R/L 90/180/270
invert_rl = {
"R": "L",
"L": "R",
}
if int(rotation_command[1:]) == 270:
rotation_command = f"{invert_rl[rotation_command[0]]}90"
elif int(rotation_command[1:]) == 180:
return -1 * x, -1 * y
if rotation_command == "L90":
return -1 * y, x
elif rotation_command == "R90":
return y, -1 * x
else:
print(f"Invalid command: {rotation_command}")
exit(-1)
def shift_coords(curx, cury, command):
n = int(command[1:])
offsets = {
"N": (0, 1),
"S": (0, -1),
"W": (-1, 0),
"E": (1, 0),
}
offx, offy = offsets[command[0]]
return n * offx + curx, n * offy + cury
class Ship:
def __init__(self):
self.direction = "E"
self.x = 0
self.y = 0
def run_command(self, command):
if "L" in command or "R" in command:
self.direction = rotate(self.direction, command)
else:
command = command.replace("F", self.direction)
self.x, self.y = shift_coords(self.x, self.y, command)
def manhattan_dist(self):
return abs(self.x) + abs(self.y)
class ShipWithWaypoint:
def __init__(self):
self.x = 0
self.y = 0
self.waypoint_x = 10
self.waypoint_y = 1
def run_command(self, command):
if "L" in command or "R" in command:
self.waypoint_x, self.waypoint_y = rotate_waypoint(self.waypoint_x, self.waypoint_y, command)
elif "F" in command:
n = int(command[1:])
self.x += self.waypoint_x * n
self.y += self.waypoint_y * n
else:
self.waypoint_x, self.waypoint_y = shift_coords(self.waypoint_x, self.waypoint_y, command)
def manhattan_dist(self):
return abs(self.x) + abs(self.y)
|
#-------------------------------------------------------------------------------
# Name: module2
# Purpose:
#
# Author: user
#
# Created: 28/03/2019
# Copyright: (c) user 2019
# Licence: <your licence>
#-------------------------------------------------------------------------------
print("LISTS")
print("Working with LISTS")
print('''
lists=[], this is an epty list
''')
list=["kevin", 5, 7.9, True]
# list values are indexed
friend=["kevin", "KAren", "Jim", "Toddy", "Frog"]
# 0 1 2 3 4
print('''
list=["kevin", 5, 7.9, True]
# list values are indexed
friend=["kevin", "KAren", "Jim", "Toddy", "Frog"]
# 0 1 2 3 4
''')
print(''' print(friend[0])
=''')
print(friend[0])
print('''
print(friend[-1])
''')
print(friend[-1])
print('''
print(friend[-3])
''')
print(friend[-3])
print('''
print(friend[1:2])
''')
print(friend[1:2])
print('''
print(friend[1:3])
''')
print(friend[1:3])
print('''
print(friend[1:4])
=''')
print(friend[1:4])
print('''
update or modify list values
friend[0]= "000"
print(friend[0])
=''')
friend[0]= "000"
print(friend[0])
print(''' update or modify list values
friend[0:1]= ["000", "ttt"]
print(friend[0:2])
=''')
friend[0:1]= ["000", "ttt"]
print(friend[0:2])
print('''
List Functions
print('
List Functions
')
''')
print('''
Items=["car", "chair", "table", "mat"]
num=[8.8, 7.7,9.9,5.5,25,34,35,43,45,50,52,53,55,61,70,71,77,91,92,93,99,105,115,
122,125,133,151,155,160,170,171,177,181,192,205,250,322,331]
numbers=[4,8,15,16,23,42]
FRINDS=["kevin", "KAren", "Jim", "Toddy", "Frog", "Todd", "Jorge", "Lang"]
# 0 1 2 3 4 5 7 8
''')
Items=["car", "chair", "table", "mat"]
num=[8.8, 7.7,9.9,5.5,25,34,35,43,45,50,52,53,55,61,70,71,77,91,92,93,99,105,115,
122,125,133,151,155,160,170,171,177,181,192,205,250,322,331]
numbers=[4,8,15,16,23,42]
FRINDS=["kevin", "KAren", "Jim", "Toddy", "Frog", "Todd", "Jorge", "Lang"]
# 0 1 2 3 4 5 7 8
print('''
FRINDS.extend(numbers)
print(FRINDS)
=''')
FRINDS.extend(numbers)
print(FRINDS)
print('''
FRINDS.append(num)
print(FRINDS)
=''')
FRINDS.append(num)
print(FRINDS)
print('''
FRINDS.extend(Items)
FRINDS.extend("77777777777")
print(FRINDS)
=''')
FRINDS.extend(Items)
FRINDS.extend("77777777777")
print(FRINDS)
print('''
FRINDS.append(Items)
FRINDS.append("55555555555")
print(FRINDS)
=''')
FRINDS.append(Items)
FRINDS.append("55555555555")
print(FRINDS)
print('''
FRINDS.insert(1,"00000000000000")
# index 1, replace with
print(FRINDS)
=''')
FRINDS.insert(1,"00000000000000")
# index 1, replace with this
print(FRINDS)
print('''
=''')
print('''
FRINDS.insert(7,Items*3)
print(FRINDS)
=''')
FRINDS.insert(7,Items*3)
print(FRINDS)
print(''' remove one item
FRINDS.remove("00000000000000")
print(FRINDS)
=''')
FRINDS.remove("00000000000000" )
print(FRINDS)
print(''' clear or remove last element\item of the list
FRINDS.pop()
print(FRINDS)
=''')
FRINDS.pop()
print(FRINDS)
print(''' find element\item of the list
FRINDS.index('Toddy')
FRINDS.index("car")
print(FRINDS.index("car"))
=''')
print(''' count number of a value
print(FRINDS.count("car"))
print(FRINDS.count("7"))
=''')
print(FRINDS.index("car"))
print(FRINDS.index('Toddy'))
print(FRINDS.count("car"))
print(FRINDS.count("7"))
print(''' clear all items
FRINDS.clear()
print(FRINDS)
=''')
FRINDS.clear()
print(FRINDS)
FRINDS=["You","HE", "he", "WE", "we","We", "wE"]
math=[3, 33, 4.4, 9.0, 9, .1, 0.1, 0, 0.0, .0, .00, 00, 00.00, 00.000, 0000]
print(''' sort/arrange all items alphabetically in assending order
FRINDS=["You","HE", "he", "WE", "we","We", "wE"]
math=[3, 33, 4.4, 9.0, 9, .1, 0.1, 0, 0.0, .0, .00, 00, 00.00, 00.000, 0000]
FRINDS.sort()
math.sort()
print(FRINDS)
print(math)
=''')
FRINDS.sort()
math.sort()
print(FRINDS)
print(math)
print(""" reverse the list items
FRINDS.reverse()
math.reverse()
print(FRINDS)
print(math)
""")
FRINDS.reverse()
math.reverse()
print(FRINDS)
print(math)
print(""" copy the list items to another list
FRINDS3=math
FRINDS2=math.copy()
FRINDS3=math
print(FRINDS2)
print(FRINDS3)
""")
FRINDS3=math
FRINDS2=math.copy()
FRINDS3=math
print(FRINDS2)
print(FRINDS3)
#-------------------------------------------------------------------------------
# Name: Print Book pages module1
# Purpose: Get printed missing pages / numbers
#
# Author: user/shyed
#
# Created: 27/03/2019
# Copyright: (c) user 2019
# Licence: <your licence>
#-------------------------------------------------------------------------------
a=225 # start at 225
b=226 # start at 226
l=599 # stop at 599
list1=[] # initialize an empty list
for i in range(a,l+1,4): list1.append(i)
for j in range(b,l, 4): list1.append(j)
list1.sort()
print(list1)
print('''
a=225
b=226
l=599
list1=[]
for i in range(a,l+1,4): list1.append(i)
for j in range(b,l, 4): list1.append(j)
list1.sort()
print(list1)
''')
print(""" That code will result this list,
[225, 226, 229, 230, 233, 234, 237, 238, 241, 242, 245, 246,
249, 250, 253, 254, 257, 258, 261, 262, 265, 266, 269, 270, 273, 274,
277, 278, 281, 282, 285, 286, 289, 290, 293, 294, 297, 298, 301, 302,
305, 306, 309, 310, 313, 314, 317, 318, 321, 322, 325, 326, 329,
330, 333, 334, 337, 338, 341, 342, 345, 346, 349, 350, 353, 354,
357, 358, 361, 362, 365, 366, 369, 370, 373, 374, 377, 378, 381,
382, 385, 386, 389, 390, 393, 394, 397, 398, 401, 402, 405, 406,
409, 410, 413, 414, 417, 418, 421, 422, 425, 426, 429, 430, 433,
434, 437, 438, 441, 442, 445, 446, 449, 450, 453, 454, 457, 458,
461, 462, 465, 466, 469, 470, 473, 474, 477, 478, 481, 482, 485,
486, 489, 490, 493, 494, 497, 498, 501, 502, 505, 506, 509, 510,
513, 514, 517, 518, 521, 522, 525, 526, 529, 530, 533, 534,
537, 538, 541, 542, 545, 546, 549, 550, 553, 554, 557, 558,
561, 562, 565, 566, 569, 570, 573, 574, 577, 578, 581, 582,
585, 586, 589, 590, 593, 594, 597, 598]""")
|
# https://codeforces.com/problemsets/acmsguru/problem/99999/100
A, B = map(int, input().split())
print(A+B)
|
"""
Check if items are in list
"""
def has_invalid_fields(fields):
for field in fields:
if field not in ['foo', 'bar']:
return True
return False
def has_invalid_fields2(fields):
return bool(set(fields) - set(['foo', 'bar']))
""" set eliminates duplicates """
""" Code is valid but it will a variation of the example
many times """
def add_animal_in_family(species, animal, family):
if family not in species:
species[family] = set()
species[family].add(animal)
species = {}
add_animal_in_family(species, 'cat', 'felidea')
# import collections
def add_animal_in_family2(species, animal, family):
species[family].add(animal)
species = collections.defaultdict(set)
add_animal_in_family2(species, 'cat', 'felidea')
""" Each time you try try to access a nonexistent item from
your dict the defaultdict will use the function that was
passed as argument to its constructor to build a new
value instead of raising a KeyError. In this case the
set() function is used to build a new set each time we
need it.
"""
# Ordered list and bisect
""" Sorted lists use a bisecting algorithm for lookup
to achieve a retrieve time of O(logn). The idea is to split
the list in half and look on which side, left or right, the
item must appear in and so which side should be searched next.
We need to import bisect
"""
farm = sorted(['haystack', 'needle', 'cow', 'pig'])
bisect.bisect(farm, 'needle')
""" bisect.bisect() returns the position where an element
should be inserted to keep the list sorted. Only works if
the list is properly sorted to begin with.
Using bisect module you could also create a special SortedList
class inheriting from list to create a list that is always
sorted,"""
class SortedList(list):
def __init__(self, iterable):
super(SortedList, self).__init__(sorted(iterable))
def insort(self, item):
bisect.insort(self, item)
def extend(self, other):
for item in other:
self.insort(item)
@staticmethod
def append(o):
raise RuntimeError("Cannot append to a sorted list")
def index(self, value, start=None, stop=None):
place = bisect.bisect_left(self[start:stop], value)
if start:
place += start
end = stop or len(self)
if place < end and self[place] == value:
return place
raise ValueError(f'{value} is not in list')
""" In python regular objects store all of their attributes inside
a dictionary and this dictionary is itself store in the __dict__
attribute """
class Point(object):
def __init__(self, x, y):
self.x = x
self.y = y
p = Point(1, 2)
p.__dict__
""" {'y': 2, 'x': 1}
Instead we can use __slots__ that will turn this dictionary into
list, the idea is that dictionaries are expensive for memory but
lists are less, only works for classes that inherit from object,
or when we have large number of simple objects
"""
class Foobar(object):
__slots__ = ('x',)
def __init__(self, x):
self.x = x
""" However this limits us to them being immutable. Rather than
having to reference them by index, namedtuple provides the ability to
retrieve tuple elements by referencing a named attribute.
import collections
Foobar = collections.namedtuple('Foodbar', [x])
Foobar(42)
Foobar(42).x
42
Its a little bit less efficient than __slots__ but gives
the ability to inde by name
"""
# Memoization
""" Its an optimization technique used to speed up function
calls by caching their results. The results of a function
can be cached only if the function is pure.
functools module provides a least recently used LRU cache
decorator. This provides the same functionality as memoization
but with the benefit that it limits the number of entries in the cache
removing the least recently used one when the cache reaches its
maximum size. Also provides statistics.>>> import functools
>>> import math
>>> @functools.lru_cache(maxsize=2)
... def memoized_sin(x):
... return math.sin(x)
...
>>> memoized_sin(2)
0.9092974268256817
>>> memoized_sin.cache_info()
CacheInfo(hits=0, misses=1, maxsize=2, currsize=1)
>>> memoized_sin(2)
0.9092974268256817
>>> memoized_sin.cache_info()
CacheInfo(hits=1, misses=1, maxsize=2, currsize=1)
>>> memoized_sin(3)
0.1411200080598672
>>> memoized_sin.cache_info()
CacheInfo(hits=1, misses=2, maxsize=2, currsize=2)
>>> memoized_sin(4)
-0.7568024953079282
>>> memoized_sin.cache_info()
"""
|
# Hand decompiled day 19 part 2
a,b,c,d,e,f = 1,0,0,0,0,0
c += 2
c *= c
c *= 209
b += 2
b *= 22
b += 7
c += b
if a == 1:
b = 27
b *= 28
b += 29
b *= 30
b *= 14
b *= 32
c += b
a = 0
for d in range(1, c+1):
if c % d == 0:
a += d
print(a) |
'''Faça um programa que tenha uma função chamada área(), que receba as dimensões de um terreno retangular (largura e comprimento) e mostre a área do terreno.'''
def linha():
print('=' * 30)
def area():
resultado = l * c
print('=' * 50)
print(f'A área total do terreno {l}X{c}é {resultado} metros.')
linha()
print(' CONTROLE DE TERRENOS')
linha()
l = float(input('Largura (M): '))
c = float(input('Comprimento (M): '))
area()
|
class test_result():
"""Log the performance on the test set"""
def __init__(self, autonet, X_test, Y_test):
self.autonet = autonet
self.X_test = X_test
self.Y_test = Y_test
def __call__(self, model, epochs):
if self.Y_test is None or self.X_test is None:
return float("nan")
return self.autonet.score(self.X_test, self.Y_test)
class gradient_norm():
"""Log the norm of the gradients"""
def __init_(self):
pass
def __call__(self, network, epoch):
total_gradient = 0
n_params = 0
for p in list(filter(lambda p: p.grad is not None, network.parameters())):
total_gradient += p.grad.data.norm(2).item()
n_params += 1
# Prevent division through 0
if total_gradient==0:
n_params = 1
return total_gradient/n_params
|
'''Crow/AAP Alarm IP Module Feedback Class for alarm state'''
class StatusState:
# Zone State
@staticmethod
def get_initial_zone_state(maxZones):
"""Builds the proper zone state collection."""
_zoneState = {}
for i in range (1, maxZones+1):
_zoneState[i] = {'status': {'open': False, 'bypass': False, 'alarm': False, 'tamper': False},
'last_fault': 0}
return _zoneState
# Area State
@staticmethod
def get_initial_area_state(maxAreas):
"""Builds the proper alarm state collection."""
_areaState = {}
for i in range(1, maxAreas+1):
_areaState[i] = {'status': {'alarm': False, 'armed': False, 'stay_armed': False,
'disarmed': False,'exit_delay': False, 'stay_exit_delay': False,
'alarm_zone': '', 'last_disarmed_by_user': '',
'last_armed_by_user': '' }}
return _areaState
# Output State
@staticmethod
def get_initial_output_state(maxOutputs):
_outputState = {}
for i in range (1, maxOutputs+1):
_outputState[i] = {'status': {'open': False}}
return _outputState
# System Status State
@staticmethod
def get_initial_system_state():
_systemState = {'status':{'mains': True, 'battery': True,'tamper': False, 'line': True,
'dialler': True,'ready': True, 'fuse': True, 'zonebattery': True,
'pendantbattery': True, 'codetamper': False}}
return _systemState
|
def go(o, a, b):
if o == '+':
return a + b
return a * b
def main():
a, o, b = int(input()), input(), int(input())
return go(o, a, b)
if __name__ == '__main__':
print(main())
|
"""Migration for a given Submitty course database."""
def up(config, database, semester, course):
if not database.table_has_column('teams', 'last_viewed_time'):
database.execute('ALTER TABLE teams ADD COLUMN last_viewed_time timestamp with time zone')
def down(config, database, semester, course):
pass
|
def cube(a):
"""Cube the number a.
Args:
a (float): The number to be squared.
"""
return a**3
|
#
# This file contains the Python code from Program 14.14 of
# "Data Structures and Algorithms
# with Object-Oriented Design Patterns in Python"
# by Bruno R. Preiss.
#
# Copyright (c) 2003 by Bruno R. Preiss, P.Eng. All rights reserved.
#
# http://www.brpreiss.com/books/opus7/programs/pgm14_14.txt
#
class SimpleRV(RandomVariable):
def getNext(self):
return RandomNumberGenerator.next
|
def test_list(client, seeder, utils):
user_id, admin_unit_id = seeder.setup_base()
seeder.create_event(admin_unit_id)
url = utils.get_url("planing")
utils.get_ok(url)
url = utils.get_url("planing", keyword="name")
utils.get_ok(url)
|
class Solution:
def to_hex(self, num: int) -> str:
if num == 0:
return "0"
prefix, ans = "0123456789abcdef", ""
num = 2 ** 32 + num if num < 0 else num
while num:
item = num & 15 # num % 16
ans = prefix[item] + ans
num >>= 4 # num //= 4
return ans
|
classifiers = """
License :: OSI Approved :: BSD License
Operating System :: POSIX
Intended Audience :: Developers
Intended Audience :: Science/Research
Programming Language :: C
Programming Language :: C++
Programming Language :: Cython
Programming Language :: Python
Programming Language :: Python :: 2
Programming Language :: Python :: 3
Topic :: Scientific/Engineering
Topic :: Software Development :: Libraries :: Python Modules
"""
keywords = """
scientific computing
parallel computing
"""
metadata = {
'author' : 'Lisandro Dalcin',
'author_email' : '[email protected]',
'classifiers' : [c for c in classifiers.split('\n') if c],
'keywords' : [k for k in keywords.split('\n') if k],
'license' : 'BSD',
'platforms' : ['POSIX'],
'maintainer' : 'Lisandro Dalcin',
'maintainer_email' : '[email protected]',
}
|
def partTwo(instr: str) -> int:
# This is the parsing section
service_list = instr.strip().split("\n")[-1].split(",")
eqns = []
for i, svc in enumerate(service_list):
if svc == "x":
continue
svc = int(svc)
v = 0
if i != 0:
v = svc - i # This is the only maths stuff in the parsing
eqns.append((v, svc))
# This is the maths section
n = 1
for (_, v) in eqns:
n *= v
sigma_x = 0
for (bi, ni) in eqns:
# this type cast could potentially cause a problem.
# int required for pow function and the division *should* produce a whole number anyway
Ni = int(n / ni)
yi = pow(Ni, -1, ni) # https://stackoverflow.com/a/9758173
sigma_x += bi * Ni * yi
return sigma_x % n
|
'''
Motion Event Provider
=====================
Abstract class for the implemention of a
:class:`~kivy.input.motionevent.MotionEvent`
provider. The implementation must support the
:meth:`~MotionEventProvider.start`, :meth:`~MotionEventProvider.stop` and
:meth:`~MotionEventProvider.update` methods.
'''
__all__ = ('MotionEventProvider', )
class MotionEventProvider(object):
'''Base class for a provider.
'''
def __init__(self, device, args):
self.device = device
if self.__class__ == MotionEventProvider:
raise NotImplementedError('class MotionEventProvider is abstract')
def start(self):
'''Start the provider. This method is automatically called when the
application is started and if the configuration uses the current
provider.
'''
pass
def stop(self):
'''Stop the provider.
'''
pass
def update(self, dispatch_fn):
'''Update the provider and dispatch all the new touch events though the
`dispatch_fn` argument.
'''
pass
|
class Model(object):
def __init__(self, xml):
self.raw_data = xml
def __str__(self):
return self.raw_data.toprettyxml( )
def _get_attribute(self, attr):
val = self.raw_data.getAttribute(attr)
if val == '':
return None
return val
def _get_element(self, name):
nodes = self.raw_data.getElementsByTagName(name)
if len(nodes) == 0:
return None
if len(nodes) > 1:
raise AttributeError("Too many elements with name %s" % name)
return nodes[0]
def _get_childNodes(self, name):
return self._get_element(name).childNodes if self._get_element(name) else []
def _get_nodeValue(self, node):
if isinstance(node, str):
nodes = self._get_childNodes(node)
elif hasattr(node, 'childNodes'):
nodes = node.childNodes
else:
return None
if len(nodes) == 0:
return None
if len(nodes) > 1:
raise AttributeError("Unable to parse value from node with name %s" % name)
return nodes[0].nodeValue
class Book(Model):
@property
def book_id(self):
return self._get_attribute('book_id')
@property
def isbn(self):
return self._get_attribute('isbn')
@property
def isbn13(self):
return self._get_attribute('isbn13')
@property
def title(self):
return self._get_nodeValue('Title')
@property
def title_long(self):
return self._get_nodeValue('TitleLong')
@property
def authors_text(self):
return self._get_nodeValue('AuthorsText')
@property
def authors(self):
for node in self._get_childNodes('Authors'):
if node.nodeType == node.ELEMENT_NODE:
aid = node.getAttribute('person_id')
name = self._get_nodeValue(node)
yield {
'person_id': aid,
'person_text': name,
}
@property
def publisher_id(self):
pelem = self._get_element('PublisherText')
if pelem is not None:
val = pelem.getAttribute('publisher_id')
if val != '':
return val
return None
@property
def publisher_text(self):
return self._get_nodeValue('PublisherText')
@property
def details(self):
delem = self._get_element('Details')
if delem is not None:
return dict(delem.attributes.items())
return None
@property
def summary(self):
return self._get_nodeValue('Summary')
@property
def notes(self):
return self._get_nodeValue('Notes')
@property
def urls_text(self):
return self._get_nodeValue('UrlsText')
@property
def awards_text(self):
return self._get_nodeValue('AwardsText')
@property
def prices(self):
for node in self._get_childNodes('Prices'):
if node.nodeType == node.ELEMENT_NODE:
yield dict(node.attributes.items())
@property
def subjects(self):
for node in self._get_childNodes('Subjects'):
if node.nodeType == node.ELEMENT_NODE:
sid = node.getAttribute('subject_id')
text = self._get_nodeValue(node)
yield {
'subject_id': sid,
'subject_text': text,
}
@property
def marc_records(self):
for node in self._get_childNodes('MARCRecords'):
if node.nodeType == node.ELEMENT_NODE:
yield dict(node.attributes.items())
class Subject(Model):
@property
def subject_id(self):
return self._get_attribute('subject_id')
@property
def book_count(self):
return self._get_attribute('book_count')
@property
def marc_field(self):
return self._get_attribute('marc_field')
@property
def marc_indicators(self):
return (self._get_attribute('marc_indicator_1'),
self._get_attribute('marc_indicator_2'))
@property
def name(self):
return self._get_nodeValue('Name')
@property
def categories(self):
for node in self._get_childNodes('Categories'):
if node.nodeType == node.ELEMENT_NODE:
cid = node.getAttribute('category_id')
text = self._get_nodeValue(node)
yield {
'category_id': cid,
'category_text': text,
}
@property
def structure(self):
for node in self._get_childNodes('SubjectStructure'):
if node.nodeType == node.ELEMENT_NODE:
yield dict(node.attributes.items())
class Category(Model):
@property
def category_id(self):
return self._get_attribute('category_id')
@property
def parent_id(self):
return self._get_attribute('parent_id')
@property
def name(self):
return self._get_nodeValue('Name')
@property
def details(self):
delem = self._get_element('Details')
if delem:
return dict(delem.attributes.items())
return {}
@property
def subcategories(self):
for node in self._get_childNodes('SubCategories'):
if node.nodeType == node.ELEMENT_NODE:
yield dict(node.attributes.items())
class Author(Model):
@property
def author_id(self):
return self._get_attribute('person_id')
@property
def name(self):
return self._get_nodeValue('Name')
@property
def details(self):
delem = self._get_element('Details')
if delem:
return dict(delem.attributes.items())
return None
@property
def categories(self):
for node in self._get_childNodes('Categories'):
if node.nodeType == node.ELEMENT_NODE:
cid = node.getAttribute('category_id')
text = self._get_nodeValue(node)
yield {
'category_id': cid,
'category_text': text,
}
@property
def subjects(self):
for node in self._get_childNodes('Subjects'):
if node.nodeType == node.ELEMENT_NODE:
sid = node.getAttribute('subject_id')
count = node.getAttribute('book_count')
text = self._get_nodeValue(node)
yield {
'subject_id': sid,
'book_count': count,
'subject_text': text,
}
class Publisher(Model):
@property
def publisher_id(self):
return self._get_attribute('publisher_id')
@property
def name(self):
return self._get_nodeValue('Name')
@property
def details(self):
delem = self._get_element('Details')
if delem:
return dict(delem.attributes.items())
return None
@property
def categories(self):
for node in self._get_childNodes('Categories'):
if node.nodeType == node.ELEMENT_NODE:
cid = node.getAttribute('category_id')
text = self._get_nodeValue(node)
yield {
'category_id': cid,
'category_text': text,
}
|
# cook your dish here
a=int(input())
b=int(input())
while(1):
if a%b==0:
print(a)
break
else:
a-=1
|
"""
Operadores relacionais
== Igual
!= Diferente
> Maior
< Menor
>= Maior ou igual
<= Menor ou igual
Operadores Lógicos
Operador Operação
AND → Duas condições sejam verdadeiras
OR → Pelo menos uma condição seja verdadeira
NOT → Inverte o valor
"""
"""
x = 2
y = 3
"""
"""
x = 3
y = 3
z = 3
"""
x = 3
y = 3
z = 4
#soma = x + y
print(x == y and x == z)
print(x == y or x == z and z == y) |
# Exercício Python 086:
# Crie um programa que declare uma matriz de dimensão 3x3 e preencha com valores lidos pelo teclado.
# No final, mostre a matriz na tela, com a formatação correta.
matriz = list()
for contador in range(0, 10):
if 1 <= contador <= 3:
valor = int(input(f"Digite o valor da elemento [1, {contador}]: "))
matriz.append(valor)
elif 4 <= contador <= 6:
valor = int(input(f"Digite o valor da elemento [2, {contador-3}]: "))
matriz.append(valor)
elif 7 <= contador <= 9:
valor = int(input(f"Digite o valor da elemento [3, {contador-6}]: "))
matriz.append(valor)
print()
print("Gerando Matriz..")
print()
print(f'''[{matriz[0]}] [{matriz[1]}] [{matriz[2]}]\n[{matriz[3]}] [{matriz[4]}] [{matriz[5]}]\n[{matriz[6]}] [{matriz[7]}] [{matriz[8]}]''')
|
"""
1. **kwargs usage
"""
def test(**kwargs):
# Do not use **kwargs
# Print key serials
print(*kwargs)
_dict = kwargs
for k in _dict.keys():
print("Key=", k)
print("Value=", _dict[k])
print()
test(a=1, b=2, c=3)
"""
1. * -> unpack container type
"""
list1 = [1, 2, 3]
tuple1 = (3, 4, 5)
set1 = {5, 6, 7}
dict1= {"aa": 123, "bb": 456, "cc": 789}
str1 = "itcast"
print(*list1)
def test2():
return 3, 4, 5
# uppack container
a, b, c = test2() |
# -*- coding: utf-8 -*-
AUCTIONS = {
'simple': 'openprocurement.auction.esco.auctions.simple',
'multilot': 'openprocurement.auction.esco.auctions.multilot',
}
|
# python3
def max_pairwise_product(numbers):
x = sorted(numbers)
n = len(numbers)
return x[n-1] * x[n-2]
if __name__ == '__main__':
input_n = int(input())
input_numbers = [int(x) for x in input().split()]
print(max_pairwise_product(input_numbers))
|
def topological_sort(inc, out):
# ・ノードIDは、0~N-1とする
# ・以下のデータは既に作られているとする
# inc[n] = nに流入するリンク数(int)
# out[n] = nからの流出先のノード集合(list or set)
# N = 7
# inc = [0] * N
# out = [[] for _ in range(N)]
# inc[0] = 3
# inc[1] = 0
# inc[2] = 0
# inc[3] = 0
# inc[4] = 1
# inc[5] = 1
# inc[6] = 1
#
# out[0] = [4, 5, 6]
# out[1] = [0]
# out[2] = [0]
# out[3]= [0]
# out[4] = []
# out[5] = []
# out[6] = []
# 入次数が0のノード
S = {i for i, c in enumerate(inc) if c == 0}
L = []
while S:
n = S.pop()
L.append(n)
for m in out[n]:
inc[m] -= 1
if inc[m] == 0:
S.add(m)
return L |
#!/usr/bin/env python3
"""
Custom errors for Seisflows
"""
class ParameterError(ValueError):
"""
A new ValueError class which explains the Parameter's that threw the error
"""
def __init__(self, *args):
if len(args) == 0:
msg = "Bad parameter."
super(ParameterError, self).__init__(msg)
elif len(args) == 1:
msg = f"Bad parameter: {args[0]}"
super(ParameterError, self).__init__(msg)
elif args[1] not in args[0]:
msg = f"{args[1]} is not defined."
super(ParameterError, self).__init__(msg)
elif key in obj:
msg = f"{args[0]} has bad value: {args[1].__getattr__(args[0])}"
super(ParameterError, self).__init__(msg)
class CheckError(ValueError):
"""
An error called by the Check functions within each module, that returns the
name of the class that raised the error, as well as the parameter in
question.
"""
def __init__(self, cls, par):
"""
CheckError simply returns a print message
"""
msg = f"{cls.__class__.__name__} requires parameter {par}"
super(CheckError, self).__init__(msg)
|
'''
Homework assignment for the 'Python is easy' course by Pirple.
Written by Ed Yablonsky.
It pprints the numbers from 1 to 100.
But for multiples of three print "Fizz" instead of the number and for the
multiples of five print "Buzz".
For numbers which are multiples of both three and five print "FizzBuzz".
It also adds "prime" to the output when the number is a prime
(divisible only by itself and one).
'''
for number in range(1, 101):
output = "" # collects output for the number
if number % 3 == 0:
output += "Fizz"
if number % 5 == 0:
output += "Buzz"
if output == "":
output = str(number)
isPrime = True # assume the number is a prime by default
for divisor in range(2, number):
if number % divisor == 0:
isPrime = False # mark the number as not a prime
break
if isPrime:
output += " prime"
print(output)
|
"""
1309. Decrypt String from Alphabet to Integer Mapping
Given a string s formed by digits ('0' - '9') and '#' . We want to map s to English lowercase characters as follows:
Characters ('a' to 'i') are represented by ('1' to '9') respectively.
Characters ('j' to 'z') are represented by ('10#' to '26#') respectively.
Return the string formed after mapping.
It's guaranteed that a unique mapping will always exist.
Example 1:
Input: s = "10#11#12"
Output: "jkab"
Explanation: "j" -> "10#" , "k" -> "11#" , "a" -> "1" , "b" -> "2".
Example 2:
Input: s = "1326#"
Output: "acz"
Example 3:
Input: s = "25#"
Output: "y"
Example 4:
Input: s = "12345678910#11#12#13#14#15#16#17#18#19#20#21#22#23#24#25#26#"
Output: "abcdefghijklmnopqrstuvwxyz"
Constraints:
1 <= s.length <= 1000
s[i] only contains digits letters ('0'-'9') and '#' letter.
s will be valid string such that mapping is always possible.
"""
class Solution:
def freqAlphabets(self, s: str):
return s.replace("10#", "j")\
.replace("11#", "k")\
.replace("12#", "l")\
.replace("13#", "m")\
.replace("14#", "n")\
.replace("15#", "o")\
.replace("16#", "p")\
.replace("17#", "q")\
.replace("18#", "r")\
.replace("19#", "s")\
.replace("20#", "t")\
.replace("21#", "u")\
.replace("22#", "v")\
.replace("23#", "w")\
.replace("24#", "x")\
.replace("25#", "y")\
.replace("26#", "z")\
.replace("1", "a")\
.replace("2", "b")\
.replace("3", "c")\
.replace("4", "d")\
.replace("5", "e")\
.replace("6", "f")\
.replace("7", "g")\
.replace("8", "h")\
.replace("9", "i")
class Solution:
def freqAlphabets(self, s: str):
return re.sub(r'\d{2}#|\d', lambda x: chr(int(x.group()[:2])+96), s)
|
a=input()
print(a)
print(a)
print(a)
|
load(
"@io_bazel_rules_dotnet//dotnet/private:providers.bzl",
"DotnetLibrary",
)
def collect_transitive_info(deps):
"""Collects transitive information.
Args:
deps: Dependencies that the DotnetLibrary depends on.
Returns:
A depsets of the references, runfiles and deps. References and deps also include direct dependencies provided by deps.
However, runtfiles do not include direct runfiles.
"""
direct_refs = []
direct_deps = []
transitive_refs = []
transitive_runfiles = []
transitive_deps = []
for dep in deps:
assembly = dep[DotnetLibrary]
if assembly.ref:
direct_refs += assembly.ref.files.to_list()
elif assembly.result:
direct_refs.append(assembly.result)
if assembly.transitive_refs:
transitive_refs.append(assembly.transitive_refs)
transitive_runfiles.append(assembly.runfiles)
direct_deps.append(assembly)
if assembly.transitive:
transitive_deps.append(assembly.transitive)
return (
depset(direct = direct_refs, transitive = transitive_refs),
depset(direct = [], transitive = transitive_runfiles),
depset(direct = direct_deps, transitive = transitive_deps),
)
|
# ================================================================================
# Copyright (c) 2017-2019 AT&T Intellectual Property. All rights reserved.
# ================================================================================
# 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.
# ============LICENSE_END=========================================================
#
"""contants of policy-handler"""
POLICY_ID = 'policy_id'
POLICY_BODY = 'policy_body'
CATCH_UP = "catch_up"
AUTO_CATCH_UP = "auto catch_up"
AUTO_RECONFIGURE = "auto reconfigure"
LATEST_POLICIES = "latest_policies"
REMOVED_POLICIES = "removed_policies"
ERRORED_POLICIES = "errored_policies"
POLICY_FILTER = "policy_filter"
POLICY_FILTERS = "policy_filters"
POLICIES = "policies"
POLICY_VERSIONS = "policy_versions"
POLICY_NAMES = "policy_names"
POLICY_FILTER_MATCHES = "policy_filter_matches"
TARGET_ENTITY = "target_entity"
|
# Fancy-pants method for getting a where clause that groups adjacent image keys
# using "BETWEEN X AND Y" ... unfortunately this usually takes far more
# characters than using "ImageNumber IN (X,Y,Z...)" since we don't run into
# queries asking for consecutive image numbers very often (except when we do it
# deliberately). It is also slower than the "IN" method unless the ImageNumbers
# come in a smaller list of consecutive groups.
#
# ...still, this may be very useful since it is notably faster when ImageNumbers
# are consecutive.
def get_where_clause_for_images(keys, is_sorted=False):
'''
takes a list of keys and returns a (hopefully) short where clause that
includes those keys.
'''
def in_sequence(k1,k2):
if len(k1)>1:
if k1[:-1] != k2[:-1]:
return False
return k1[-1]==(k2[-1]-1)
def optimize_for_query(keys, is_sorted=False):
if not is_sorted:
keys.sort()
groups = []
in_run = False
for i in range(len(keys)):
if i == len(keys)-1:
if in_run:
groups[-1] += [keys[i]]
else:
groups += [[keys[i]]]
break
if in_run:
if in_sequence(keys[i], keys[i+1]):
continue
else:
groups[-1] += [keys[i]]
in_run = False
else:
if in_sequence(keys[i], keys[i+1]):
in_run = True
groups += [[keys[i]]]
return groups
groups = optimize_for_query(keys)
wheres = []
for k in groups:
if len(k)==1:
wheres += ['%s=%s'%(col,value) for col, value in zip(object_key_columns(), k[0])]
else:
# expect 2 keys: the first and last of a contiguous run
first, last = k
if p.table_id:
wheres += ['(%s=%s AND %s BETWEEN %s and %s)'%
(p.table_id, first[0], p.image_id, first[1], last[1])]
else:
wheres += ['(%s BETWEEN %s and %s)'%
(p.image_id, first[0], last[0])]
return ' OR '.join(wheres) |
# A module for class Restaurant
"""A set of classes that can be used to represent a restaurant."""
class Restaurant():
"""A model of a restaurant."""
def __init__(self, name, cuisine):
"""Initialize name and age attributes."""
self.name = name
self.cuisine = cuisine
def describe_restaurant(self):
"""Simulate a description of restaurant."""
print(self.name.title() + " is the restaurant.")
print(self.cuisine.title() + " is the type of cuisine.")
def open_restaurant(self):
"""Simulate a message alerting that the restaurant is open."""
print(self.name.title() + " is open.")
class IceCreamStand(Restaurant):
"""Represent aspects of a restaurant, specific to ice cream stands."""
def __init__(self, name, cuisine):
"""Initialize attributes of parent class; then initialize attributes
specific to an ice cream stand."""
super().__init__(name, cuisine)
flavors = "vanilla, chocolate, strawberry, and rocky road."
self.flavors = flavors
def describe_ice_cream_flavors(self):
"""Print a statement describing the ice cream flavors offered."""
print("This ice cream stand has the following flavors: " + self.flavors)
|
g = int(input().strip())
for _ in range(g):
n = int(input().strip())
s = [int(x) for x in input().strip().split(' ')]
x = 0
for i in s:
x ^= i
if len(set(s))==1 and 1 in s:
#here x=0 or 1
if x:#odd no. of ones
print("Second")
else:#even no. of ones
print("First")
else:
if x:
print("First")
else:
print("Second")
|
class SerializerNotFound(Exception):
"""
Serializer not found
"""
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.