content
stringlengths 7
1.05M
|
---|
YEAR_IN_S = 31557600.
GEV_IN_KEV = 1.e6
C_KMSEC = 299792.458
NUCLEON_MASS = 0.938272 # Nucleon mass in GeV
P_MAGMOM = 2.793 # proton magnetic moment, PDG Live
N_MAGMOM = -1.913 # neutron magnetic moment, PDG Live
NUCLEAR_MASSES = {
'xenon': 122.298654871,
'germanium': 67.663731424,
'argon': 37.2113263068,
'silicon': 26.1614775455,
'sodium': 21.4140502327,
'iodine': 118.206437626,
'fluorine': 17.6969003039,
'he3': 3.,
'helium': 4.,
'nitrogen': 14.,
'neon': 20.,
} # this is target nucleus mass in GeV: mT[GeV] = 0.9314941 * A[AMU]
ELEMENT_INFO = {"xenon":{128:0.0192,129:0.2644,130:0.0408,131:0.2118,132:0.2689,134:0.1044,136:0.0887,'weight':131.1626},"germanium":{70:0.2084,72:0.2754,73:0.0773,74:0.3628,76:0.0761,'weight':72.6905},"iodine":{127:1.,'weight':127.},"sodium":{23:1.,'weight':23.},"silicon":{28:0.922,29:0.047,30:0.031,'weight':28.109},"fluorine":{19:1.,'weight':19.},"argon":{40:1.,'weight':40.},"helium":{4:1.,'weight':4.},"he3":{3:1.,'weight':3.},"nitrogen":{14:1.,'weight':14.},"neon":{20:1.,'weight':20.}}
|
class FrameworkTextComposition(TextComposition):
""" Represents a composition during the text input events of a System.Windows.Controls.TextBox. """
def Complete(self):
"""
Complete(self: FrameworkTextComposition)
Finalizes the composition.
"""
pass
CompositionLength=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the length of the current composition in Unicode symbols.
Get: CompositionLength(self: FrameworkTextComposition) -> int
"""
CompositionOffset=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the position at which the composition text occurs in the System.Windows.Controls.TextBox.
Get: CompositionOffset(self: FrameworkTextComposition) -> int
"""
ResultLength=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the length of the finalized text in Unicode symbols when the System.Windows.Input.TextCompositionManager.TextInput event occurs.
Get: ResultLength(self: FrameworkTextComposition) -> int
"""
ResultOffset=property(lambda self: object(),lambda self,v: None,lambda self: None)
"""Gets the offset of the finalized text when the System.Windows.Input.TextCompositionManager.TextInput event occurs.
Get: ResultOffset(self: FrameworkTextComposition) -> int
"""
|
def get_version(testbed: str):
path = [e for e in testbed.split(" ") if e.find("/") > -1][0]
full_name = path.split("/")[-1]
return full_name.replace(".jar", "")
def parse_engine_name(testbed: str):
return get_version(testbed).split("-")[0]
|
def predict(text, with_neu=True): # requires string input.
start_at = time.time()
x_test = pad_sequences(tokenizer.texts_to_sequences([text]), maxlen=seq_len)
score = model.predict([x_test])[0]
label = decode_sentiment(score, with_neu=with_neu)
score = float(score)
return {print(f"label: {label}, score: {score}, calculation duration: {time.time()-start_at}.")}
print('Welcome!')
print('Script for post toxicity estimation is evaluated. Enter your text below for sentiment estimation and press ENTER.')
post_text = str(input('Your text: '))
print(predict(post_text))
print(f'In terminal type predict(text) and pass string to it for the next prediction. Type file_sanalysis(filepath) to make several predictions. Local time: {datetime.datetime.now().time()}')
def file_sanalysis(filepath):
file = open(filepath, 'rt')
c = 0
n = 0
processed_file = file.readlines()
for text in processed_file:
n += 1
print(n,'', text)
print(predict(text))
c += 1
print(f'\n')
print(f'Total comments analyzed: {c}')
file_sanalysis('../comment.txt')
|
def get_session_attributes(previous_intent = "", previous_intent_attributes = "", requested_value = "", previous_requested_value = "", questions_urls = [], question_now_id = 0, question_name = "", answers_ids = [], answer_now_id = 0, comments_ids = [], comment_now_id = 0, complete_answer = [], complete_code = [], complete_code_now_id = 0):
sessionAttributes = {}
sessionAttributes["questions_urls"] = questions_urls
sessionAttributes["question_now_id"] = question_now_id
sessionAttributes["question_name"] = question_name
sessionAttributes["answers_ids"] = answers_ids
sessionAttributes["answer_now_id"] = answer_now_id
sessionAttributes["comments_ids"] = comments_ids
sessionAttributes["comment_now_id"] = comment_now_id
sessionAttributes["previous_intent"] = previous_intent
sessionAttributes["previous_intent_attributes"] = previous_intent_attributes
sessionAttributes["complete_answer"] = complete_answer
sessionAttributes["complete_code"] = complete_code
sessionAttributes["complete_code_now_id"] = complete_code_now_id
sessionAttributes["requested_value"] = requested_value
sessionAttributes["previous_requested_value"] = previous_requested_value
return sessionAttributes
def get_outputSpeech(outputSpeech_type, outputSpeech_text):
outputSpeech = {}
outputSpeech["type"] = outputSpeech_type
outputSpeech["text"] = outputSpeech_text
return outputSpeech
def get_card(card_type, card_title, card_content, card_text):
card = {}
card["type"] = card_type
card["title"] = card_title
card["content"] = card_content
card["text"] = card_text
return card
def get_repromt(repromt_outputSpeech_type, repromt_outputSpeech_text):
reprompt = {}
reprompt["outputSpeech"] = get_outputSpeech(repromt_outputSpeech_type, repromt_outputSpeech_text)
return reprompt
def get_response(outputSpeech_text, outputSpeech_type = "PlainText", card_type = "Standard", card_title = "", card_content = "", card_text = "", repromt_outputSpeech_type = "PlainText", repromt_outputSpeech_text = "", shouldEndSession = True):
response = {}
response["outputSpeech"] = get_outputSpeech(outputSpeech_type, outputSpeech_text)
if card_title != "":
response["card"] = get_card(card_type, card_title, card_content, card_text)
if repromt_outputSpeech_text != "":
response["reprompt"] = get_repromt(repromt_outputSpeech_type, repromt_outputSpeech_text)
response["shouldEndSession"] = shouldEndSession
return response
def give_response(response, session_attributes = {}):
lambda_response = {}
lambda_response["version"] = "string"
if session_attributes != {}:
lambda_response["sessionAttributes"] = session_attributes
lambda_response["response"] = response
return lambda_response |
# Definición de parámetros de configuración
PeriodoDePoleo = 30000 # Milisegundos entre cada poleo de mediciones
AlmacenamientoLocal = False # Define si los datos se alamacenarán localmente o no
Compresion = False # Define si los datos que se almacenarán localmente serán comprimidos
EnvioAlaNube = True # Define si los datos serán enviados a Internet a traves del protocolo MQTT
TxRxPins = [33, 19] # Los pines donde está conectado el sensor [33, 19] para cancay a1,
LogEnTerminal = False # Habilita el envío de log a la consola repl
# Esta es solo una línea para probar el OTA
# Seguimos probando el OTA
|
def bag_of_words(text):
"""Returns bag-of-words representation of the input text.
Args:
text: A string containing the text.
Returns:
A dictionary of strings to integers.
"""
bag = {}
for word in text.lower().split():
bag[word] = bag.get(word, 0) + 1
return bag
|
STATS = [
{
"num_node_expansions": 0,
"search_time": 0.0929848,
"total_time": 0.206795,
"plan_length": 209,
"plan_cost": 209,
"objects_used": 145,
"objects_total": 253,
"neural_net_time": 0.09392738342285156,
"num_replanning_steps": 0,
"wall_time": 0.9533143043518066
},
{
"num_node_expansions": 0,
"search_time": 0.0644765,
"total_time": 0.15406,
"plan_length": 178,
"plan_cost": 178,
"objects_used": 139,
"objects_total": 253,
"neural_net_time": 0.0441431999206543,
"num_replanning_steps": 0,
"wall_time": 0.7657253742218018
},
{
"num_node_expansions": 0,
"search_time": 0.106279,
"total_time": 0.234601,
"plan_length": 199,
"plan_cost": 199,
"objects_used": 166,
"objects_total": 359,
"neural_net_time": 0.0629584789276123,
"num_replanning_steps": 0,
"wall_time": 1.0160789489746094
},
{
"num_node_expansions": 0,
"search_time": 0.108802,
"total_time": 0.238978,
"plan_length": 242,
"plan_cost": 242,
"objects_used": 167,
"objects_total": 359,
"neural_net_time": 0.06333541870117188,
"num_replanning_steps": 0,
"wall_time": 1.0204391479492188
},
{
"num_node_expansions": 0,
"search_time": 0.0803484,
"total_time": 0.181895,
"plan_length": 181,
"plan_cost": 181,
"objects_used": 141,
"objects_total": 378,
"neural_net_time": 0.06571578979492188,
"num_replanning_steps": 0,
"wall_time": 0.8968064785003662
},
{
"num_node_expansions": 0,
"search_time": 0.142677,
"total_time": 0.253942,
"plan_length": 207,
"plan_cost": 207,
"objects_used": 135,
"objects_total": 378,
"neural_net_time": 0.06601405143737793,
"num_replanning_steps": 0,
"wall_time": 0.9965448379516602
},
{
"num_node_expansions": 0,
"search_time": 0.11895,
"total_time": 0.255997,
"plan_length": 167,
"plan_cost": 167,
"objects_used": 125,
"objects_total": 255,
"neural_net_time": 0.04192996025085449,
"num_replanning_steps": 1,
"wall_time": 1.385655164718628
},
{
"num_node_expansions": 0,
"search_time": 0.157901,
"total_time": 0.30572,
"plan_length": 202,
"plan_cost": 202,
"objects_used": 126,
"objects_total": 255,
"neural_net_time": 0.04552125930786133,
"num_replanning_steps": 0,
"wall_time": 1.1248347759246826
},
{
"num_node_expansions": 0,
"search_time": 0.0805039,
"total_time": 0.176183,
"plan_length": 170,
"plan_cost": 170,
"objects_used": 109,
"objects_total": 175,
"neural_net_time": 0.03158974647521973,
"num_replanning_steps": 5,
"wall_time": 2.148319959640503
},
{
"num_node_expansions": 0,
"search_time": 0.0587677,
"total_time": 0.173702,
"plan_length": 165,
"plan_cost": 165,
"objects_used": 106,
"objects_total": 175,
"neural_net_time": 0.03000664710998535,
"num_replanning_steps": 0,
"wall_time": 0.9106862545013428
},
{
"num_node_expansions": 0,
"search_time": 0.0402155,
"total_time": 0.147669,
"plan_length": 127,
"plan_cost": 127,
"objects_used": 111,
"objects_total": 249,
"neural_net_time": 0.07640314102172852,
"num_replanning_steps": 0,
"wall_time": 0.922156572341919
},
{
"num_node_expansions": 0,
"search_time": 0.101752,
"total_time": 0.19686,
"plan_length": 150,
"plan_cost": 150,
"objects_used": 105,
"objects_total": 249,
"neural_net_time": 0.07982420921325684,
"num_replanning_steps": 0,
"wall_time": 0.9400062561035156
},
{
"num_node_expansions": 0,
"search_time": 0.0719713,
"total_time": 0.137339,
"plan_length": 228,
"plan_cost": 228,
"objects_used": 107,
"objects_total": 197,
"neural_net_time": 0.05859208106994629,
"num_replanning_steps": 0,
"wall_time": 0.7167832851409912
},
{
"num_node_expansions": 0,
"search_time": 0.0929935,
"total_time": 0.190003,
"plan_length": 209,
"plan_cost": 209,
"objects_used": 114,
"objects_total": 197,
"neural_net_time": 0.03446316719055176,
"num_replanning_steps": 0,
"wall_time": 0.8573403358459473
},
{
"num_node_expansions": 0,
"search_time": 0.079714,
"total_time": 0.185505,
"plan_length": 173,
"plan_cost": 173,
"objects_used": 103,
"objects_total": 199,
"neural_net_time": 0.03453779220581055,
"num_replanning_steps": 0,
"wall_time": 0.8996772766113281
},
{
"num_node_expansions": 0,
"search_time": 0.0926601,
"total_time": 0.21608,
"plan_length": 169,
"plan_cost": 169,
"objects_used": 105,
"objects_total": 199,
"neural_net_time": 0.05138850212097168,
"num_replanning_steps": 0,
"wall_time": 0.988412618637085
},
{
"num_node_expansions": 0,
"search_time": 0.153958,
"total_time": 0.230492,
"plan_length": 219,
"plan_cost": 219,
"objects_used": 170,
"objects_total": 264,
"neural_net_time": 0.04536151885986328,
"num_replanning_steps": 0,
"wall_time": 0.8006608486175537
},
{
"num_node_expansions": 0,
"search_time": 0.0818528,
"total_time": 0.188787,
"plan_length": 220,
"plan_cost": 220,
"objects_used": 177,
"objects_total": 264,
"neural_net_time": 0.04852485656738281,
"num_replanning_steps": 0,
"wall_time": 0.8596897125244141
},
{
"num_node_expansions": 0,
"search_time": 0.0492729,
"total_time": 0.125523,
"plan_length": 179,
"plan_cost": 179,
"objects_used": 125,
"objects_total": 226,
"neural_net_time": 0.04153084754943848,
"num_replanning_steps": 2,
"wall_time": 1.2470283508300781
},
{
"num_node_expansions": 0,
"search_time": 0.0572884,
"total_time": 0.12549,
"plan_length": 210,
"plan_cost": 210,
"objects_used": 121,
"objects_total": 226,
"neural_net_time": 0.03936648368835449,
"num_replanning_steps": 0,
"wall_time": 0.6882929801940918
},
{
"num_node_expansions": 0,
"search_time": 0.155052,
"total_time": 0.264927,
"plan_length": 157,
"plan_cost": 157,
"objects_used": 126,
"objects_total": 271,
"neural_net_time": 0.04673433303833008,
"num_replanning_steps": 0,
"wall_time": 0.9777631759643555
},
{
"num_node_expansions": 0,
"search_time": 0.0738639,
"total_time": 0.171292,
"plan_length": 178,
"plan_cost": 178,
"objects_used": 125,
"objects_total": 271,
"neural_net_time": 0.05072212219238281,
"num_replanning_steps": 0,
"wall_time": 0.8584322929382324
},
{
"num_node_expansions": 0,
"search_time": 0.068614,
"total_time": 0.165012,
"plan_length": 178,
"plan_cost": 178,
"objects_used": 117,
"objects_total": 254,
"neural_net_time": 0.046701908111572266,
"num_replanning_steps": 0,
"wall_time": 0.8422744274139404
},
{
"num_node_expansions": 0,
"search_time": 0.0784991,
"total_time": 0.185713,
"plan_length": 189,
"plan_cost": 189,
"objects_used": 118,
"objects_total": 254,
"neural_net_time": 0.045041799545288086,
"num_replanning_steps": 0,
"wall_time": 0.910815954208374
},
{
"num_node_expansions": 0,
"search_time": 0.0377378,
"total_time": 0.0919111,
"plan_length": 155,
"plan_cost": 155,
"objects_used": 108,
"objects_total": 168,
"neural_net_time": 0.02987837791442871,
"num_replanning_steps": 0,
"wall_time": 0.5988538265228271
},
{
"num_node_expansions": 0,
"search_time": 0.05612,
"total_time": 0.117127,
"plan_length": 156,
"plan_cost": 156,
"objects_used": 110,
"objects_total": 168,
"neural_net_time": 0.029909610748291016,
"num_replanning_steps": 0,
"wall_time": 0.6504032611846924
},
{
"num_node_expansions": 0,
"search_time": 0.118899,
"total_time": 0.236672,
"plan_length": 187,
"plan_cost": 187,
"objects_used": 117,
"objects_total": 283,
"neural_net_time": 0.04805254936218262,
"num_replanning_steps": 0,
"wall_time": 1.0010144710540771
},
{
"num_node_expansions": 0,
"search_time": 0.0412124,
"total_time": 0.148293,
"plan_length": 137,
"plan_cost": 137,
"objects_used": 117,
"objects_total": 283,
"neural_net_time": 0.05118083953857422,
"num_replanning_steps": 0,
"wall_time": 0.8539888858795166
},
{
"num_node_expansions": 0,
"search_time": 0.130546,
"total_time": 0.284641,
"plan_length": 208,
"plan_cost": 208,
"objects_used": 152,
"objects_total": 278,
"neural_net_time": 0.051322221755981445,
"num_replanning_steps": 0,
"wall_time": 1.119509220123291
},
{
"num_node_expansions": 0,
"search_time": 0.1676,
"total_time": 0.278637,
"plan_length": 189,
"plan_cost": 189,
"objects_used": 144,
"objects_total": 278,
"neural_net_time": 0.052797555923461914,
"num_replanning_steps": 0,
"wall_time": 0.9699740409851074
},
{
"num_node_expansions": 0,
"search_time": 0.0559687,
"total_time": 0.152069,
"plan_length": 162,
"plan_cost": 162,
"objects_used": 145,
"objects_total": 316,
"neural_net_time": 0.05460691452026367,
"num_replanning_steps": 0,
"wall_time": 0.822706937789917
},
{
"num_node_expansions": 0,
"search_time": 0.0838116,
"total_time": 0.182175,
"plan_length": 186,
"plan_cost": 186,
"objects_used": 144,
"objects_total": 316,
"neural_net_time": 0.05571866035461426,
"num_replanning_steps": 0,
"wall_time": 0.8658485412597656
},
{
"num_node_expansions": 0,
"search_time": 0.0603922,
"total_time": 0.163295,
"plan_length": 165,
"plan_cost": 165,
"objects_used": 117,
"objects_total": 254,
"neural_net_time": 0.04593300819396973,
"num_replanning_steps": 0,
"wall_time": 0.843583345413208
},
{
"num_node_expansions": 0,
"search_time": 0.0459874,
"total_time": 0.13095,
"plan_length": 159,
"plan_cost": 159,
"objects_used": 115,
"objects_total": 254,
"neural_net_time": 0.04458308219909668,
"num_replanning_steps": 0,
"wall_time": 0.7566969394683838
},
{
"num_node_expansions": 0,
"search_time": 0.222052,
"total_time": 0.382279,
"plan_length": 259,
"plan_cost": 259,
"objects_used": 139,
"objects_total": 238,
"neural_net_time": 0.04237771034240723,
"num_replanning_steps": 0,
"wall_time": 1.23612642288208
},
{
"num_node_expansions": 0,
"search_time": 0.19537,
"total_time": 0.32901,
"plan_length": 246,
"plan_cost": 246,
"objects_used": 133,
"objects_total": 238,
"neural_net_time": 0.042508602142333984,
"num_replanning_steps": 0,
"wall_time": 1.1203975677490234
},
{
"num_node_expansions": 0,
"search_time": 0.135153,
"total_time": 0.268125,
"plan_length": 214,
"plan_cost": 214,
"objects_used": 149,
"objects_total": 343,
"neural_net_time": 0.059821367263793945,
"num_replanning_steps": 0,
"wall_time": 1.05523681640625
},
{
"num_node_expansions": 0,
"search_time": 0.103736,
"total_time": 0.220218,
"plan_length": 257,
"plan_cost": 257,
"objects_used": 147,
"objects_total": 343,
"neural_net_time": 0.06213259696960449,
"num_replanning_steps": 0,
"wall_time": 0.9649918079376221
},
{
"num_node_expansions": 0,
"search_time": 0.0568394,
"total_time": 0.159339,
"plan_length": 142,
"plan_cost": 142,
"objects_used": 110,
"objects_total": 222,
"neural_net_time": 0.03833651542663574,
"num_replanning_steps": 0,
"wall_time": 0.8489890098571777
},
{
"num_node_expansions": 0,
"search_time": 0.0806894,
"total_time": 0.189079,
"plan_length": 188,
"plan_cost": 188,
"objects_used": 110,
"objects_total": 222,
"neural_net_time": 0.03789353370666504,
"num_replanning_steps": 0,
"wall_time": 0.9437530040740967
},
{
"num_node_expansions": 0,
"search_time": 0.151005,
"total_time": 0.222475,
"plan_length": 190,
"plan_cost": 190,
"objects_used": 101,
"objects_total": 250,
"neural_net_time": 0.04339957237243652,
"num_replanning_steps": 0,
"wall_time": 0.8491106033325195
},
{
"num_node_expansions": 0,
"search_time": 0.0478454,
"total_time": 0.150686,
"plan_length": 142,
"plan_cost": 142,
"objects_used": 110,
"objects_total": 250,
"neural_net_time": 0.07555818557739258,
"num_replanning_steps": 0,
"wall_time": 0.8761661052703857
},
{
"num_node_expansions": 0,
"search_time": 0.123577,
"total_time": 0.257152,
"plan_length": 204,
"plan_cost": 204,
"objects_used": 130,
"objects_total": 269,
"neural_net_time": 0.04827475547790527,
"num_replanning_steps": 0,
"wall_time": 1.0524470806121826
},
{
"num_node_expansions": 0,
"search_time": 0.0871824,
"total_time": 0.221488,
"plan_length": 210,
"plan_cost": 210,
"objects_used": 129,
"objects_total": 269,
"neural_net_time": 0.04716014862060547,
"num_replanning_steps": 0,
"wall_time": 1.0055983066558838
},
{
"num_node_expansions": 0,
"search_time": 0.0819503,
"total_time": 0.208188,
"plan_length": 159,
"plan_cost": 159,
"objects_used": 146,
"objects_total": 367,
"neural_net_time": 0.06378006935119629,
"num_replanning_steps": 0,
"wall_time": 0.9702720642089844
},
{
"num_node_expansions": 0,
"search_time": 0.268373,
"total_time": 0.452797,
"plan_length": 266,
"plan_cost": 266,
"objects_used": 160,
"objects_total": 367,
"neural_net_time": 0.06560254096984863,
"num_replanning_steps": 5,
"wall_time": 3.011348009109497
},
{
"num_node_expansions": 0,
"search_time": 0.0941831,
"total_time": 0.221279,
"plan_length": 178,
"plan_cost": 178,
"objects_used": 127,
"objects_total": 263,
"neural_net_time": 0.04631924629211426,
"num_replanning_steps": 0,
"wall_time": 1.009706735610962
},
{
"num_node_expansions": 0,
"search_time": 0.0539835,
"total_time": 0.119023,
"plan_length": 171,
"plan_cost": 171,
"objects_used": 116,
"objects_total": 263,
"neural_net_time": 0.04792213439941406,
"num_replanning_steps": 0,
"wall_time": 0.6958885192871094
},
{
"num_node_expansions": 0,
"search_time": 0.138429,
"total_time": 0.26899,
"plan_length": 228,
"plan_cost": 228,
"objects_used": 132,
"objects_total": 307,
"neural_net_time": 0.05261349678039551,
"num_replanning_steps": 0,
"wall_time": 1.0931148529052734
},
{
"num_node_expansions": 0,
"search_time": 0.122325,
"total_time": 0.287355,
"plan_length": 191,
"plan_cost": 191,
"objects_used": 138,
"objects_total": 307,
"neural_net_time": 0.052745819091796875,
"num_replanning_steps": 0,
"wall_time": 1.2211828231811523
},
{
"num_node_expansions": 0,
"search_time": 0.0702098,
"total_time": 0.161979,
"plan_length": 152,
"plan_cost": 152,
"objects_used": 109,
"objects_total": 186,
"neural_net_time": 0.0562443733215332,
"num_replanning_steps": 0,
"wall_time": 0.873492956161499
},
{
"num_node_expansions": 0,
"search_time": 0.0607624,
"total_time": 0.168418,
"plan_length": 133,
"plan_cost": 133,
"objects_used": 111,
"objects_total": 186,
"neural_net_time": 0.0317075252532959,
"num_replanning_steps": 0,
"wall_time": 0.8738946914672852
},
{
"num_node_expansions": 0,
"search_time": 0.105255,
"total_time": 0.232733,
"plan_length": 196,
"plan_cost": 196,
"objects_used": 137,
"objects_total": 425,
"neural_net_time": 0.0749213695526123,
"num_replanning_steps": 0,
"wall_time": 1.0104260444641113
},
{
"num_node_expansions": 0,
"search_time": 0.161776,
"total_time": 0.321529,
"plan_length": 239,
"plan_cost": 239,
"objects_used": 143,
"objects_total": 425,
"neural_net_time": 0.07435131072998047,
"num_replanning_steps": 0,
"wall_time": 1.2037241458892822
},
{
"num_node_expansions": 0,
"search_time": 0.10898,
"total_time": 0.20831,
"plan_length": 231,
"plan_cost": 231,
"objects_used": 161,
"objects_total": 452,
"neural_net_time": 0.08123517036437988,
"num_replanning_steps": 0,
"wall_time": 0.9305424690246582
},
{
"num_node_expansions": 0,
"search_time": 0.0706434,
"total_time": 0.194282,
"plan_length": 205,
"plan_cost": 205,
"objects_used": 162,
"objects_total": 452,
"neural_net_time": 0.08131527900695801,
"num_replanning_steps": 0,
"wall_time": 0.9569718837738037
},
{
"num_node_expansions": 0,
"search_time": 0.0423357,
"total_time": 0.118826,
"plan_length": 167,
"plan_cost": 167,
"objects_used": 120,
"objects_total": 185,
"neural_net_time": 0.03236651420593262,
"num_replanning_steps": 0,
"wall_time": 0.7566854953765869
},
{
"num_node_expansions": 0,
"search_time": 0.0918883,
"total_time": 0.182959,
"plan_length": 186,
"plan_cost": 186,
"objects_used": 123,
"objects_total": 185,
"neural_net_time": 0.032120704650878906,
"num_replanning_steps": 0,
"wall_time": 0.817650556564331
},
{
"num_node_expansions": 0,
"search_time": 0.0979132,
"total_time": 0.224043,
"plan_length": 220,
"plan_cost": 220,
"objects_used": 118,
"objects_total": 294,
"neural_net_time": 0.05071663856506348,
"num_replanning_steps": 0,
"wall_time": 1.0140111446380615
},
{
"num_node_expansions": 0,
"search_time": 0.105051,
"total_time": 0.223332,
"plan_length": 205,
"plan_cost": 205,
"objects_used": 123,
"objects_total": 294,
"neural_net_time": 0.05296945571899414,
"num_replanning_steps": 0,
"wall_time": 1.0141093730926514
},
{
"num_node_expansions": 0,
"search_time": 0.134815,
"total_time": 0.264608,
"plan_length": 179,
"plan_cost": 179,
"objects_used": 134,
"objects_total": 239,
"neural_net_time": 0.04209327697753906,
"num_replanning_steps": 0,
"wall_time": 1.0186936855316162
},
{
"num_node_expansions": 0,
"search_time": 0.0863073,
"total_time": 0.194703,
"plan_length": 216,
"plan_cost": 216,
"objects_used": 128,
"objects_total": 239,
"neural_net_time": 0.04327273368835449,
"num_replanning_steps": 0,
"wall_time": 0.8725950717926025
},
{
"num_node_expansions": 0,
"search_time": 0.0789072,
"total_time": 0.165693,
"plan_length": 192,
"plan_cost": 192,
"objects_used": 137,
"objects_total": 441,
"neural_net_time": 0.08032083511352539,
"num_replanning_steps": 0,
"wall_time": 0.8416461944580078
},
{
"num_node_expansions": 0,
"search_time": 0.125951,
"total_time": 0.252282,
"plan_length": 216,
"plan_cost": 216,
"objects_used": 142,
"objects_total": 441,
"neural_net_time": 0.07857489585876465,
"num_replanning_steps": 0,
"wall_time": 1.0415000915527344
},
{
"num_node_expansions": 0,
"search_time": 0.0625197,
"total_time": 0.144617,
"plan_length": 215,
"plan_cost": 215,
"objects_used": 140,
"objects_total": 322,
"neural_net_time": 0.05614805221557617,
"num_replanning_steps": 0,
"wall_time": 0.7807624340057373
},
{
"num_node_expansions": 0,
"search_time": 0.171375,
"total_time": 0.314981,
"plan_length": 212,
"plan_cost": 212,
"objects_used": 151,
"objects_total": 322,
"neural_net_time": 0.05498790740966797,
"num_replanning_steps": 0,
"wall_time": 1.1263976097106934
},
{
"num_node_expansions": 0,
"search_time": 0.0524852,
"total_time": 0.166942,
"plan_length": 138,
"plan_cost": 138,
"objects_used": 112,
"objects_total": 232,
"neural_net_time": 0.04028916358947754,
"num_replanning_steps": 0,
"wall_time": 0.8710212707519531
},
{
"num_node_expansions": 0,
"search_time": 0.103607,
"total_time": 0.198748,
"plan_length": 169,
"plan_cost": 169,
"objects_used": 106,
"objects_total": 232,
"neural_net_time": 0.039990901947021484,
"num_replanning_steps": 0,
"wall_time": 0.8681793212890625
},
{
"num_node_expansions": 0,
"search_time": 0.0643245,
"total_time": 0.143637,
"plan_length": 165,
"plan_cost": 165,
"objects_used": 117,
"objects_total": 302,
"neural_net_time": 0.051032304763793945,
"num_replanning_steps": 0,
"wall_time": 0.7398231029510498
},
{
"num_node_expansions": 0,
"search_time": 0.0679649,
"total_time": 0.169156,
"plan_length": 179,
"plan_cost": 179,
"objects_used": 121,
"objects_total": 302,
"neural_net_time": 0.050397396087646484,
"num_replanning_steps": 0,
"wall_time": 0.8502187728881836
},
{
"num_node_expansions": 0,
"search_time": 0.0490003,
"total_time": 0.11576,
"plan_length": 159,
"plan_cost": 159,
"objects_used": 119,
"objects_total": 221,
"neural_net_time": 0.039055585861206055,
"num_replanning_steps": 0,
"wall_time": 0.6635472774505615
},
{
"num_node_expansions": 0,
"search_time": 0.131966,
"total_time": 0.200885,
"plan_length": 204,
"plan_cost": 204,
"objects_used": 118,
"objects_total": 221,
"neural_net_time": 0.04007387161254883,
"num_replanning_steps": 0,
"wall_time": 0.7671856880187988
},
{
"num_node_expansions": 0,
"search_time": 0.0901247,
"total_time": 0.188966,
"plan_length": 189,
"plan_cost": 189,
"objects_used": 118,
"objects_total": 263,
"neural_net_time": 0.04721832275390625,
"num_replanning_steps": 0,
"wall_time": 0.9165947437286377
},
{
"num_node_expansions": 0,
"search_time": 0.0420897,
"total_time": 0.138097,
"plan_length": 129,
"plan_cost": 129,
"objects_used": 118,
"objects_total": 263,
"neural_net_time": 0.04863762855529785,
"num_replanning_steps": 0,
"wall_time": 0.8551199436187744
},
{
"num_node_expansions": 0,
"search_time": 0.0570443,
"total_time": 0.116505,
"plan_length": 144,
"plan_cost": 144,
"objects_used": 89,
"objects_total": 110,
"neural_net_time": 0.01940011978149414,
"num_replanning_steps": 0,
"wall_time": 0.6247892379760742
},
{
"num_node_expansions": 0,
"search_time": 0.0458228,
"total_time": 0.118598,
"plan_length": 159,
"plan_cost": 159,
"objects_used": 92,
"objects_total": 110,
"neural_net_time": 0.020870208740234375,
"num_replanning_steps": 0,
"wall_time": 0.6696300506591797
},
{
"num_node_expansions": 0,
"search_time": 0.0455459,
"total_time": 0.170986,
"plan_length": 156,
"plan_cost": 156,
"objects_used": 171,
"objects_total": 398,
"neural_net_time": 0.07069921493530273,
"num_replanning_steps": 0,
"wall_time": 0.9098761081695557
},
{
"num_node_expansions": 0,
"search_time": 0.178719,
"total_time": 0.333981,
"plan_length": 273,
"plan_cost": 273,
"objects_used": 176,
"objects_total": 398,
"neural_net_time": 0.0706338882446289,
"num_replanning_steps": 0,
"wall_time": 1.2203617095947266
},
{
"num_node_expansions": 0,
"search_time": 0.0924526,
"total_time": 0.181018,
"plan_length": 240,
"plan_cost": 240,
"objects_used": 141,
"objects_total": 299,
"neural_net_time": 0.05379128456115723,
"num_replanning_steps": 0,
"wall_time": 0.8276622295379639
},
{
"num_node_expansions": 0,
"search_time": 0.0828678,
"total_time": 0.159347,
"plan_length": 208,
"plan_cost": 208,
"objects_used": 136,
"objects_total": 299,
"neural_net_time": 0.05095386505126953,
"num_replanning_steps": 0,
"wall_time": 0.7490129470825195
},
{
"num_node_expansions": 0,
"search_time": 0.0452422,
"total_time": 0.114662,
"plan_length": 171,
"plan_cost": 171,
"objects_used": 87,
"objects_total": 129,
"neural_net_time": 0.022167205810546875,
"num_replanning_steps": 0,
"wall_time": 0.6578855514526367
},
{
"num_node_expansions": 0,
"search_time": 0.0585229,
"total_time": 0.133924,
"plan_length": 168,
"plan_cost": 168,
"objects_used": 90,
"objects_total": 129,
"neural_net_time": 0.022145986557006836,
"num_replanning_steps": 0,
"wall_time": 0.7226030826568604
},
{
"num_node_expansions": 0,
"search_time": 0.0916457,
"total_time": 0.221311,
"plan_length": 171,
"plan_cost": 171,
"objects_used": 131,
"objects_total": 298,
"neural_net_time": 0.05045294761657715,
"num_replanning_steps": 0,
"wall_time": 1.0133440494537354
},
{
"num_node_expansions": 0,
"search_time": 0.0623154,
"total_time": 0.161016,
"plan_length": 178,
"plan_cost": 178,
"objects_used": 125,
"objects_total": 298,
"neural_net_time": 0.05021095275878906,
"num_replanning_steps": 0,
"wall_time": 0.8984758853912354
},
{
"num_node_expansions": 0,
"search_time": 0.0358807,
"total_time": 0.121069,
"plan_length": 116,
"plan_cost": 116,
"objects_used": 107,
"objects_total": 198,
"neural_net_time": 0.03419780731201172,
"num_replanning_steps": 0,
"wall_time": 0.730410099029541
},
{
"num_node_expansions": 0,
"search_time": 0.0472072,
"total_time": 0.13457,
"plan_length": 143,
"plan_cost": 143,
"objects_used": 103,
"objects_total": 198,
"neural_net_time": 0.03411746025085449,
"num_replanning_steps": 0,
"wall_time": 0.7624046802520752
},
{
"num_node_expansions": 0,
"search_time": 0.052692,
"total_time": 0.180943,
"plan_length": 153,
"plan_cost": 153,
"objects_used": 123,
"objects_total": 249,
"neural_net_time": 0.0444490909576416,
"num_replanning_steps": 0,
"wall_time": 1.0244402885437012
},
{
"num_node_expansions": 0,
"search_time": 0.075898,
"total_time": 0.196162,
"plan_length": 180,
"plan_cost": 180,
"objects_used": 123,
"objects_total": 249,
"neural_net_time": 0.04358696937561035,
"num_replanning_steps": 0,
"wall_time": 0.916325569152832
},
{
"num_node_expansions": 0,
"search_time": 0.109635,
"total_time": 0.25776,
"plan_length": 204,
"plan_cost": 204,
"objects_used": 129,
"objects_total": 242,
"neural_net_time": 0.043290138244628906,
"num_replanning_steps": 0,
"wall_time": 1.0722479820251465
},
{
"num_node_expansions": 0,
"search_time": 0.0918233,
"total_time": 0.190336,
"plan_length": 148,
"plan_cost": 148,
"objects_used": 122,
"objects_total": 242,
"neural_net_time": 0.04327988624572754,
"num_replanning_steps": 0,
"wall_time": 0.8662850856781006
},
{
"num_node_expansions": 0,
"search_time": 0.0500598,
"total_time": 0.130817,
"plan_length": 151,
"plan_cost": 151,
"objects_used": 99,
"objects_total": 181,
"neural_net_time": 0.032167673110961914,
"num_replanning_steps": 0,
"wall_time": 0.7324697971343994
},
{
"num_node_expansions": 0,
"search_time": 0.104269,
"total_time": 0.21618,
"plan_length": 171,
"plan_cost": 171,
"objects_used": 104,
"objects_total": 181,
"neural_net_time": 0.031090497970581055,
"num_replanning_steps": 0,
"wall_time": 0.9418821334838867
},
{
"num_node_expansions": 0,
"search_time": 0.318445,
"total_time": 0.389018,
"plan_length": 180,
"plan_cost": 180,
"objects_used": 97,
"objects_total": 152,
"neural_net_time": 0.02628469467163086,
"num_replanning_steps": 0,
"wall_time": 0.9369549751281738
},
{
"num_node_expansions": 0,
"search_time": 0.0519396,
"total_time": 0.114015,
"plan_length": 148,
"plan_cost": 148,
"objects_used": 94,
"objects_total": 152,
"neural_net_time": 0.026342153549194336,
"num_replanning_steps": 0,
"wall_time": 0.6257641315460205
},
{
"num_node_expansions": 0,
"search_time": 0.0752088,
"total_time": 0.143422,
"plan_length": 192,
"plan_cost": 192,
"objects_used": 126,
"objects_total": 306,
"neural_net_time": 0.05185842514038086,
"num_replanning_steps": 0,
"wall_time": 0.7288417816162109
},
{
"num_node_expansions": 0,
"search_time": 0.034485,
"total_time": 0.106152,
"plan_length": 151,
"plan_cost": 151,
"objects_used": 126,
"objects_total": 306,
"neural_net_time": 0.05185699462890625,
"num_replanning_steps": 0,
"wall_time": 0.6879549026489258
},
{
"num_node_expansions": 0,
"search_time": 0.136146,
"total_time": 0.293922,
"plan_length": 194,
"plan_cost": 194,
"objects_used": 137,
"objects_total": 252,
"neural_net_time": 0.04554438591003418,
"num_replanning_steps": 0,
"wall_time": 1.176285982131958
},
{
"num_node_expansions": 0,
"search_time": 0.110748,
"total_time": 0.231414,
"plan_length": 202,
"plan_cost": 202,
"objects_used": 129,
"objects_total": 252,
"neural_net_time": 0.0443422794342041,
"num_replanning_steps": 0,
"wall_time": 0.9532647132873535
},
{
"num_node_expansions": 0,
"search_time": 0.0635986,
"total_time": 0.207597,
"plan_length": 178,
"plan_cost": 178,
"objects_used": 160,
"objects_total": 590,
"neural_net_time": 0.11240124702453613,
"num_replanning_steps": 0,
"wall_time": 1.0796713829040527
},
{
"num_node_expansions": 0,
"search_time": 0.115994,
"total_time": 0.2062,
"plan_length": 222,
"plan_cost": 222,
"objects_used": 156,
"objects_total": 590,
"neural_net_time": 0.10931205749511719,
"num_replanning_steps": 0,
"wall_time": 0.948901891708374
},
{
"num_node_expansions": 0,
"search_time": 0.0546317,
"total_time": 0.139553,
"plan_length": 127,
"plan_cost": 127,
"objects_used": 98,
"objects_total": 137,
"neural_net_time": 0.024482250213623047,
"num_replanning_steps": 0,
"wall_time": 0.7495617866516113
},
{
"num_node_expansions": 0,
"search_time": 0.04194,
"total_time": 0.126749,
"plan_length": 153,
"plan_cost": 153,
"objects_used": 96,
"objects_total": 137,
"neural_net_time": 0.022912263870239258,
"num_replanning_steps": 0,
"wall_time": 0.7276170253753662
},
{
"num_node_expansions": 0,
"search_time": 0.0657196,
"total_time": 0.151708,
"plan_length": 185,
"plan_cost": 185,
"objects_used": 108,
"objects_total": 194,
"neural_net_time": 0.03308534622192383,
"num_replanning_steps": 0,
"wall_time": 0.7719326019287109
},
{
"num_node_expansions": 0,
"search_time": 0.0385118,
"total_time": 0.112582,
"plan_length": 142,
"plan_cost": 142,
"objects_used": 105,
"objects_total": 194,
"neural_net_time": 0.03346872329711914,
"num_replanning_steps": 0,
"wall_time": 0.6850829124450684
},
{
"num_node_expansions": 0,
"search_time": 0.12478,
"total_time": 0.209107,
"plan_length": 218,
"plan_cost": 218,
"objects_used": 124,
"objects_total": 273,
"neural_net_time": 0.0484766960144043,
"num_replanning_steps": 0,
"wall_time": 0.8329904079437256
},
{
"num_node_expansions": 0,
"search_time": 0.0934944,
"total_time": 0.175708,
"plan_length": 188,
"plan_cost": 188,
"objects_used": 124,
"objects_total": 273,
"neural_net_time": 0.04935503005981445,
"num_replanning_steps": 0,
"wall_time": 0.8079173564910889
},
{
"num_node_expansions": 0,
"search_time": 0.0576064,
"total_time": 0.15922,
"plan_length": 136,
"plan_cost": 136,
"objects_used": 112,
"objects_total": 252,
"neural_net_time": 0.050174713134765625,
"num_replanning_steps": 0,
"wall_time": 0.8631553649902344
},
{
"num_node_expansions": 0,
"search_time": 0.0809324,
"total_time": 0.16812,
"plan_length": 193,
"plan_cost": 193,
"objects_used": 108,
"objects_total": 252,
"neural_net_time": 0.04494309425354004,
"num_replanning_steps": 0,
"wall_time": 0.8042213916778564
},
{
"num_node_expansions": 0,
"search_time": 0.150789,
"total_time": 0.277772,
"plan_length": 193,
"plan_cost": 193,
"objects_used": 130,
"objects_total": 342,
"neural_net_time": 0.05874204635620117,
"num_replanning_steps": 0,
"wall_time": 1.0789546966552734
},
{
"num_node_expansions": 0,
"search_time": 0.137949,
"total_time": 0.286343,
"plan_length": 244,
"plan_cost": 244,
"objects_used": 135,
"objects_total": 342,
"neural_net_time": 0.057566165924072266,
"num_replanning_steps": 1,
"wall_time": 1.4527130126953125
},
{
"num_node_expansions": 0,
"search_time": 0.105657,
"total_time": 0.235481,
"plan_length": 201,
"plan_cost": 201,
"objects_used": 128,
"objects_total": 239,
"neural_net_time": 0.043076276779174805,
"num_replanning_steps": 0,
"wall_time": 0.9969813823699951
},
{
"num_node_expansions": 0,
"search_time": 0.0734793,
"total_time": 0.225471,
"plan_length": 193,
"plan_cost": 193,
"objects_used": 132,
"objects_total": 239,
"neural_net_time": 0.042589426040649414,
"num_replanning_steps": 0,
"wall_time": 1.0482325553894043
},
{
"num_node_expansions": 0,
"search_time": 0.155992,
"total_time": 0.400421,
"plan_length": 238,
"plan_cost": 238,
"objects_used": 191,
"objects_total": 548,
"neural_net_time": 0.10288858413696289,
"num_replanning_steps": 0,
"wall_time": 1.5625355243682861
},
{
"num_node_expansions": 0,
"search_time": 0.334524,
"total_time": 0.505858,
"plan_length": 230,
"plan_cost": 230,
"objects_used": 187,
"objects_total": 548,
"neural_net_time": 0.09901881217956543,
"num_replanning_steps": 0,
"wall_time": 1.4250199794769287
},
{
"num_node_expansions": 0,
"search_time": 0.0619202,
"total_time": 0.131806,
"plan_length": 185,
"plan_cost": 185,
"objects_used": 129,
"objects_total": 285,
"neural_net_time": 0.049799442291259766,
"num_replanning_steps": 0,
"wall_time": 0.7084746360778809
},
{
"num_node_expansions": 0,
"search_time": 0.122541,
"total_time": 0.20295,
"plan_length": 189,
"plan_cost": 189,
"objects_used": 130,
"objects_total": 285,
"neural_net_time": 0.05124354362487793,
"num_replanning_steps": 0,
"wall_time": 0.8297102451324463
},
{
"num_node_expansions": 0,
"search_time": 0.117833,
"total_time": 0.237295,
"plan_length": 222,
"plan_cost": 222,
"objects_used": 165,
"objects_total": 356,
"neural_net_time": 0.06300878524780273,
"num_replanning_steps": 0,
"wall_time": 1.0006396770477295
},
{
"num_node_expansions": 0,
"search_time": 0.132216,
"total_time": 0.252078,
"plan_length": 231,
"plan_cost": 231,
"objects_used": 167,
"objects_total": 356,
"neural_net_time": 0.0627584457397461,
"num_replanning_steps": 0,
"wall_time": 0.9945011138916016
},
{
"num_node_expansions": 0,
"search_time": 0.0590759,
"total_time": 0.149012,
"plan_length": 156,
"plan_cost": 156,
"objects_used": 107,
"objects_total": 204,
"neural_net_time": 0.03542733192443848,
"num_replanning_steps": 0,
"wall_time": 0.8198165893554688
},
{
"num_node_expansions": 0,
"search_time": 0.106132,
"total_time": 0.217121,
"plan_length": 218,
"plan_cost": 218,
"objects_used": 110,
"objects_total": 204,
"neural_net_time": 0.06274199485778809,
"num_replanning_steps": 0,
"wall_time": 1.00437593460083
},
{
"num_node_expansions": 0,
"search_time": 0.0634019,
"total_time": 0.141975,
"plan_length": 176,
"plan_cost": 176,
"objects_used": 94,
"objects_total": 130,
"neural_net_time": 0.02202630043029785,
"num_replanning_steps": 0,
"wall_time": 0.7373795509338379
},
{
"num_node_expansions": 0,
"search_time": 0.0335487,
"total_time": 0.0920351,
"plan_length": 144,
"plan_cost": 144,
"objects_used": 88,
"objects_total": 130,
"neural_net_time": 0.02197718620300293,
"num_replanning_steps": 0,
"wall_time": 0.5983211994171143
},
{
"num_node_expansions": 0,
"search_time": 0.109335,
"total_time": 0.256434,
"plan_length": 171,
"plan_cost": 171,
"objects_used": 135,
"objects_total": 282,
"neural_net_time": 0.04994654655456543,
"num_replanning_steps": 4,
"wall_time": 2.322432518005371
},
{
"num_node_expansions": 0,
"search_time": 0.131862,
"total_time": 0.247472,
"plan_length": 220,
"plan_cost": 220,
"objects_used": 131,
"objects_total": 282,
"neural_net_time": 0.05040121078491211,
"num_replanning_steps": 4,
"wall_time": 2.156909465789795
},
{
"num_node_expansions": 0,
"search_time": 0.137213,
"total_time": 0.24042,
"plan_length": 205,
"plan_cost": 205,
"objects_used": 122,
"objects_total": 241,
"neural_net_time": 0.04193997383117676,
"num_replanning_steps": 0,
"wall_time": 0.9178109169006348
},
{
"num_node_expansions": 0,
"search_time": 0.117394,
"total_time": 0.241386,
"plan_length": 187,
"plan_cost": 187,
"objects_used": 121,
"objects_total": 241,
"neural_net_time": 0.04581952095031738,
"num_replanning_steps": 1,
"wall_time": 1.299536943435669
},
{
"num_node_expansions": 0,
"search_time": 0.116395,
"total_time": 0.211216,
"plan_length": 174,
"plan_cost": 174,
"objects_used": 117,
"objects_total": 303,
"neural_net_time": 0.05017542839050293,
"num_replanning_steps": 0,
"wall_time": 0.8741514682769775
},
{
"num_node_expansions": 0,
"search_time": 0.0966587,
"total_time": 0.211036,
"plan_length": 162,
"plan_cost": 162,
"objects_used": 115,
"objects_total": 303,
"neural_net_time": 0.051862478256225586,
"num_replanning_steps": 0,
"wall_time": 0.8510780334472656
},
{
"num_node_expansions": 0,
"search_time": 0.113647,
"total_time": 0.211338,
"plan_length": 183,
"plan_cost": 183,
"objects_used": 115,
"objects_total": 187,
"neural_net_time": 0.03305411338806152,
"num_replanning_steps": 0,
"wall_time": 0.8724808692932129
},
{
"num_node_expansions": 0,
"search_time": 0.110512,
"total_time": 0.199805,
"plan_length": 211,
"plan_cost": 211,
"objects_used": 113,
"objects_total": 187,
"neural_net_time": 0.03314328193664551,
"num_replanning_steps": 0,
"wall_time": 0.8387811183929443
},
{
"num_node_expansions": 0,
"search_time": 0.0512388,
"total_time": 0.143361,
"plan_length": 166,
"plan_cost": 166,
"objects_used": 122,
"objects_total": 149,
"neural_net_time": 0.026326417922973633,
"num_replanning_steps": 0,
"wall_time": 0.7781620025634766
},
{
"num_node_expansions": 0,
"search_time": 0.0492694,
"total_time": 0.109376,
"plan_length": 190,
"plan_cost": 190,
"objects_used": 115,
"objects_total": 149,
"neural_net_time": 0.026416301727294922,
"num_replanning_steps": 0,
"wall_time": 0.642287015914917
},
{
"num_node_expansions": 0,
"search_time": 0.0489913,
"total_time": 0.132804,
"plan_length": 150,
"plan_cost": 150,
"objects_used": 132,
"objects_total": 270,
"neural_net_time": 0.050424814224243164,
"num_replanning_steps": 0,
"wall_time": 0.7631943225860596
},
{
"num_node_expansions": 0,
"search_time": 0.102728,
"total_time": 0.211444,
"plan_length": 188,
"plan_cost": 188,
"objects_used": 134,
"objects_total": 270,
"neural_net_time": 0.04851222038269043,
"num_replanning_steps": 0,
"wall_time": 0.9128179550170898
},
{
"num_node_expansions": 0,
"search_time": 0.0515611,
"total_time": 0.157182,
"plan_length": 146,
"plan_cost": 146,
"objects_used": 106,
"objects_total": 159,
"neural_net_time": 0.02697467803955078,
"num_replanning_steps": 0,
"wall_time": 0.8290927410125732
},
{
"num_node_expansions": 0,
"search_time": 0.0603945,
"total_time": 0.139822,
"plan_length": 146,
"plan_cost": 146,
"objects_used": 100,
"objects_total": 159,
"neural_net_time": 0.0265805721282959,
"num_replanning_steps": 0,
"wall_time": 0.7267487049102783
},
{
"num_node_expansions": 0,
"search_time": 0.109096,
"total_time": 0.197121,
"plan_length": 184,
"plan_cost": 184,
"objects_used": 122,
"objects_total": 245,
"neural_net_time": 0.0434718132019043,
"num_replanning_steps": 0,
"wall_time": 0.8433651924133301
},
{
"num_node_expansions": 0,
"search_time": 0.0569313,
"total_time": 0.149679,
"plan_length": 157,
"plan_cost": 157,
"objects_used": 122,
"objects_total": 245,
"neural_net_time": 0.04352283477783203,
"num_replanning_steps": 0,
"wall_time": 0.7943651676177979
},
{
"num_node_expansions": 0,
"search_time": 0.0688804,
"total_time": 0.162913,
"plan_length": 166,
"plan_cost": 166,
"objects_used": 105,
"objects_total": 224,
"neural_net_time": 0.03991389274597168,
"num_replanning_steps": 0,
"wall_time": 0.8286600112915039
},
{
"num_node_expansions": 0,
"search_time": 0.087877,
"total_time": 0.205901,
"plan_length": 187,
"plan_cost": 187,
"objects_used": 110,
"objects_total": 224,
"neural_net_time": 0.04076838493347168,
"num_replanning_steps": 0,
"wall_time": 0.9610884189605713
},
{
"num_node_expansions": 0,
"search_time": 0.108875,
"total_time": 0.287741,
"plan_length": 203,
"plan_cost": 203,
"objects_used": 162,
"objects_total": 344,
"neural_net_time": 0.06036639213562012,
"num_replanning_steps": 0,
"wall_time": 1.199660301208496
},
{
"num_node_expansions": 0,
"search_time": 0.140254,
"total_time": 0.301378,
"plan_length": 210,
"plan_cost": 210,
"objects_used": 158,
"objects_total": 344,
"neural_net_time": 0.06137275695800781,
"num_replanning_steps": 0,
"wall_time": 1.1875953674316406
},
{
"num_node_expansions": 0,
"search_time": 0.0948984,
"total_time": 0.225837,
"plan_length": 177,
"plan_cost": 177,
"objects_used": 125,
"objects_total": 461,
"neural_net_time": 0.08402681350708008,
"num_replanning_steps": 0,
"wall_time": 1.1599135398864746
},
{
"num_node_expansions": 0,
"search_time": 0.165758,
"total_time": 0.41311,
"plan_length": 180,
"plan_cost": 180,
"objects_used": 149,
"objects_total": 461,
"neural_net_time": 0.08339810371398926,
"num_replanning_steps": 10,
"wall_time": 5.166301012039185
},
{
"num_node_expansions": 0,
"search_time": 0.053683,
"total_time": 0.141606,
"plan_length": 158,
"plan_cost": 158,
"objects_used": 96,
"objects_total": 213,
"neural_net_time": 0.03530240058898926,
"num_replanning_steps": 0,
"wall_time": 0.7653453350067139
},
{
"num_node_expansions": 0,
"search_time": 0.08182,
"total_time": 0.180951,
"plan_length": 144,
"plan_cost": 144,
"objects_used": 100,
"objects_total": 213,
"neural_net_time": 0.03677558898925781,
"num_replanning_steps": 0,
"wall_time": 0.8767471313476562
},
{
"num_node_expansions": 0,
"search_time": 0.112981,
"total_time": 0.219522,
"plan_length": 172,
"plan_cost": 172,
"objects_used": 120,
"objects_total": 210,
"neural_net_time": 0.03706240653991699,
"num_replanning_steps": 0,
"wall_time": 0.9154744148254395
},
{
"num_node_expansions": 0,
"search_time": 0.0566878,
"total_time": 0.200295,
"plan_length": 158,
"plan_cost": 158,
"objects_used": 126,
"objects_total": 210,
"neural_net_time": 0.038547515869140625,
"num_replanning_steps": 0,
"wall_time": 1.0092735290527344
},
{
"num_node_expansions": 0,
"search_time": 0.0664906,
"total_time": 0.151631,
"plan_length": 163,
"plan_cost": 163,
"objects_used": 97,
"objects_total": 176,
"neural_net_time": 0.029233455657958984,
"num_replanning_steps": 0,
"wall_time": 0.7926013469696045
},
{
"num_node_expansions": 0,
"search_time": 0.0538599,
"total_time": 0.118603,
"plan_length": 145,
"plan_cost": 145,
"objects_used": 90,
"objects_total": 176,
"neural_net_time": 0.02914142608642578,
"num_replanning_steps": 0,
"wall_time": 0.7353930473327637
},
{
"num_node_expansions": 0,
"search_time": 0.066048,
"total_time": 0.157862,
"plan_length": 153,
"plan_cost": 153,
"objects_used": 131,
"objects_total": 173,
"neural_net_time": 0.030073165893554688,
"num_replanning_steps": 0,
"wall_time": 0.7830359935760498
},
{
"num_node_expansions": 0,
"search_time": 0.0921026,
"total_time": 0.175147,
"plan_length": 147,
"plan_cost": 147,
"objects_used": 128,
"objects_total": 173,
"neural_net_time": 0.030555248260498047,
"num_replanning_steps": 0,
"wall_time": 0.7749836444854736
},
{
"num_node_expansions": 0,
"search_time": 0.118463,
"total_time": 0.282047,
"plan_length": 184,
"plan_cost": 184,
"objects_used": 139,
"objects_total": 339,
"neural_net_time": 0.059423208236694336,
"num_replanning_steps": 0,
"wall_time": 1.1752550601959229
},
{
"num_node_expansions": 0,
"search_time": 0.0597391,
"total_time": 0.164878,
"plan_length": 168,
"plan_cost": 168,
"objects_used": 131,
"objects_total": 339,
"neural_net_time": 0.059804677963256836,
"num_replanning_steps": 0,
"wall_time": 0.8735132217407227
},
{
"num_node_expansions": 0,
"search_time": 0.0707919,
"total_time": 0.171617,
"plan_length": 162,
"plan_cost": 162,
"objects_used": 113,
"objects_total": 215,
"neural_net_time": 0.03980255126953125,
"num_replanning_steps": 0,
"wall_time": 0.8347995281219482
},
{
"num_node_expansions": 0,
"search_time": 0.136539,
"total_time": 0.297679,
"plan_length": 193,
"plan_cost": 193,
"objects_used": 125,
"objects_total": 215,
"neural_net_time": 0.03705787658691406,
"num_replanning_steps": 0,
"wall_time": 1.171936273574829
},
{
"num_node_expansions": 0,
"search_time": 0.166099,
"total_time": 0.332001,
"plan_length": 213,
"plan_cost": 213,
"objects_used": 153,
"objects_total": 333,
"neural_net_time": 0.056998491287231445,
"num_replanning_steps": 0,
"wall_time": 1.1840345859527588
},
{
"num_node_expansions": 0,
"search_time": 0.137145,
"total_time": 0.253378,
"plan_length": 191,
"plan_cost": 191,
"objects_used": 145,
"objects_total": 333,
"neural_net_time": 0.057398319244384766,
"num_replanning_steps": 0,
"wall_time": 0.9758951663970947
},
{
"num_node_expansions": 0,
"search_time": 0.0572285,
"total_time": 0.141806,
"plan_length": 168,
"plan_cost": 168,
"objects_used": 117,
"objects_total": 286,
"neural_net_time": 0.05305218696594238,
"num_replanning_steps": 0,
"wall_time": 0.7997596263885498
},
{
"num_node_expansions": 0,
"search_time": 0.0730807,
"total_time": 0.174237,
"plan_length": 178,
"plan_cost": 178,
"objects_used": 119,
"objects_total": 286,
"neural_net_time": 0.05058908462524414,
"num_replanning_steps": 0,
"wall_time": 0.877018928527832
},
{
"num_node_expansions": 0,
"search_time": 0.0436968,
"total_time": 0.113316,
"plan_length": 161,
"plan_cost": 161,
"objects_used": 109,
"objects_total": 200,
"neural_net_time": 0.03450441360473633,
"num_replanning_steps": 0,
"wall_time": 0.6501560211181641
},
{
"num_node_expansions": 0,
"search_time": 0.171478,
"total_time": 0.346798,
"plan_length": 194,
"plan_cost": 194,
"objects_used": 127,
"objects_total": 200,
"neural_net_time": 0.034224510192871094,
"num_replanning_steps": 0,
"wall_time": 1.2174389362335205
},
{
"num_node_expansions": 0,
"search_time": 0.0350258,
"total_time": 0.111698,
"plan_length": 136,
"plan_cost": 136,
"objects_used": 100,
"objects_total": 181,
"neural_net_time": 0.030783414840698242,
"num_replanning_steps": 0,
"wall_time": 0.7171695232391357
},
{
"num_node_expansions": 0,
"search_time": 0.0683696,
"total_time": 0.173089,
"plan_length": 150,
"plan_cost": 150,
"objects_used": 105,
"objects_total": 181,
"neural_net_time": 0.03152823448181152,
"num_replanning_steps": 0,
"wall_time": 0.8520138263702393
},
{
"num_node_expansions": 0,
"search_time": 0.0871958,
"total_time": 0.182047,
"plan_length": 204,
"plan_cost": 204,
"objects_used": 135,
"objects_total": 229,
"neural_net_time": 0.041161537170410156,
"num_replanning_steps": 0,
"wall_time": 0.8202221393585205
},
{
"num_node_expansions": 0,
"search_time": 0.0800008,
"total_time": 0.177595,
"plan_length": 171,
"plan_cost": 171,
"objects_used": 138,
"objects_total": 229,
"neural_net_time": 0.04072093963623047,
"num_replanning_steps": 0,
"wall_time": 0.8345837593078613
},
{
"num_node_expansions": 0,
"search_time": 0.407514,
"total_time": 0.551243,
"plan_length": 231,
"plan_cost": 231,
"objects_used": 153,
"objects_total": 333,
"neural_net_time": 0.059165000915527344,
"num_replanning_steps": 0,
"wall_time": 1.3791015148162842
},
{
"num_node_expansions": 0,
"search_time": 0.112556,
"total_time": 0.249969,
"plan_length": 192,
"plan_cost": 192,
"objects_used": 155,
"objects_total": 333,
"neural_net_time": 0.057951927185058594,
"num_replanning_steps": 0,
"wall_time": 1.1176068782806396
},
{
"num_node_expansions": 0,
"search_time": 0.0470725,
"total_time": 0.0825322,
"plan_length": 146,
"plan_cost": 146,
"objects_used": 81,
"objects_total": 161,
"neural_net_time": 0.02678227424621582,
"num_replanning_steps": 0,
"wall_time": 0.5234506130218506
},
{
"num_node_expansions": 0,
"search_time": 0.0364912,
"total_time": 0.0741524,
"plan_length": 156,
"plan_cost": 156,
"objects_used": 82,
"objects_total": 161,
"neural_net_time": 0.02719879150390625,
"num_replanning_steps": 0,
"wall_time": 0.524160623550415
},
{
"num_node_expansions": 0,
"search_time": 0.0875584,
"total_time": 0.180473,
"plan_length": 196,
"plan_cost": 196,
"objects_used": 145,
"objects_total": 400,
"neural_net_time": 0.0715029239654541,
"num_replanning_steps": 0,
"wall_time": 0.8854470252990723
},
{
"num_node_expansions": 0,
"search_time": 0.0949566,
"total_time": 0.206312,
"plan_length": 225,
"plan_cost": 225,
"objects_used": 147,
"objects_total": 400,
"neural_net_time": 0.07208442687988281,
"num_replanning_steps": 0,
"wall_time": 0.9514024257659912
}
] |
# -*- coding: utf-8 -*-
"""
Created on Sun Sep 17 10:43:46 2017
@author: ASUS
This code snippet finds the given spliced motif within the given DNA sequence
"""
#I put \n manually so that it fits to my solution
fasta_formatted_input = ">Rosalind_4080\nGTTACTGCCGAGTGCAAGCAACTTATTGCTGATTGGTCCGTGTAGGCTGTTAGCAGTTAGAATCTCTTAGCCTCAGCACAGTTTGTTTTCACGAAACAATGCGGAAACTATCTAGAACAACAAAAACATTATTGGAAGTTTGTGCTTCATCAATTATCGTGATAACACACCTACTAGTAGCAGTCGTGGAGCAATCGAGTCTCATGGAATGTAGCTTACGCGGTGGAACAAAATCGCCTATTAGTTGTTTGGTACAACATATTGTGCCAGCCTGCCGTTTCCTTAAAGAGGCCTAGCCACGGTTGGAACCCTCCATTTTTTTCAGAAGGGGGGTGCTGCTGCTCGGTTGTGACGCTAGGCATCTTTAAGCAACACGAATCAAAGAAGGAAATCATAGTCTATATCACACGAGTACCGCAAGCTAACTTGAGACGTCCTGAAGTTCACAGGCGTTCACTACTACCCCCCGCGGCGCTCGGATTTGCAGAAGATCGCGTGTCGTCTGGGAGACACAAAGCTCGCCAGAATAAACTAAGCAATGAGTAGGTAAGCGAAGCAGACCAGGGCCTATGCAGGGTCTATAGCCTCTAGCTAATTGGTAGAATTAACATCTATCTAACGTCATACTGATTGCTCCACGGGAATGGAAGTCCAGTGATGAGTTCATTACTGAAACCTCAGTTCGCGAGGATCACTAAGGACAATCAGTGCACGCTGGGCTCTATGCCATTGTCGATGAAAGGAGGTATTGTAACAATGTGGGATAGGCAAACTCGCGGTTGGCCGATCTTCGCAGATTTCTGAAAAAAATATCAATCACCGTTGCGCCCGTGCTTGCGTACTTTTTCCCTGGCTACGTTTCTCGGTCGACTTCGAAAGAACAG\n>Rosalind_6924\nCACCTTGACTATCCAATCACTACCAGCTAAGTACGTGGGGTTGCACCAGAACATTATGAATTCCGAGCTGATTTAGGGTGCAA"
splitted_input = fasta_formatted_input.split("\n")
#If you look input carefully you will see that
#First index corresponds to DNA itself, wherease third index corresponds to the motif
dna_sequence = splitted_input[1]
motif = splitted_input[3]
indices = ""
dna_index = 0
motif_index = 0
#Iterate through the DNA
for base in dna_sequence:
#If current base is equal to the `current` base in the motif
#By current I mean the latest base we are looking for
if base == motif[motif_index]:
motif_index += 1
#`dna_index + 1` is because question assumes first index is 1
indices += str(dna_index + 1) + " "
#If we are out of motif base then done
if motif_index == len(motif):
break
dna_index += 1
print(indices)
|
"""
Files in nftfw - and a description of what they do
PackageIndex.txt this file
__init__.py amend the Python module lookup
Main nftfw application
----------------------
__main__.py Main application, deals with argument decode
and dispatch
config.py Class Config - supplies default config settings,
reads a config.ini file, supports overriding
the settings from the command line
Sets up logging
the object is passed into all modules
loggermanager.py Manages the Python Logger modules so
output can be controlled to the terminal
and also the terminal
stdargs.py Decodes -q -v and -o arguments
also used by nftfwadm
Utilities
--------
locker.py Provides an overall filesystem lock for the
various applications
sqdb.py Class SqDb - simple interface to sqlite3
fileposdb.py Derived from SqDb, FileposdB is interface to
the sqlite3 filepos table storing last seek positions
for log files
fwdb.py Derived from SqDb, FwDb is interface to sqlite3
providing an interface to the blacklist database
scheduler.py Provides locking and command sequencing for
both background commands run from cron, systemd or
incron and also for commands run from the
command line
stats.py Compute durations and frequencies
Nftfw modules
-------------
'load' function:
fwmanage.py fw_manage manages creation and installation of nftables
rulesreader.py Class RulesReader - reads rules from rules directory
rules translate actions into nft commands
ruleserr.py Exception class for RulesReader
firewallreader.py Class FirewallReader - reads specification files
from the incoming and outgoing directories
firewallprocess.py Class FireWallProcess - generates nft commands from
data read by FirewallReader
listreader.py Class ListReader - reads files from whitelist &
blacklist directories
listprocess.py Class ListProcess - generates nft commands from
the two directories, generates nftable sets
with ip addresses
netreader.py Class NetReader - reads files from blacknets directory
validates entries and creates lists that can be used
in listprocess to output the sets.
nft.py Interface to nftables, calls the nft program
to do its work, tested with Python 3.6
'whitelist' function
whitelist.py Reads information from wtmp looking for
user logins, adds whitelist entries
to the directory when found.
Will automatically remove entries after
a set period
nftfw_utmp.py Interface to libc utmp processing
I got fed up with waiting for the Debian
utmp package to be available for Python3
on Buster
utmpconst.py Constants for the utmp interface
'blacklist' function
blacklist.py Controls blacklisting, reads patterns
from patterns.d to establish files to scan and
how to scan them.
Using this information is maintains the
blacklist sqlite3 database, and writes files in
the blacklist directory
patternreader.py Parses pattern files, establishing log files to
scan and regexes to apply.
logreader.py Uses patternreader output and manages file
scanning
whitelistcheck.py Checks whether addresses found in logs
are actually whitelisted, don't blacklist
whitelist addresses
normaliseaddress.py Validates IP addresses, does checking
to ignore local ones
Separate nftfw programs
-----------------------
nftfwadm.py Front end for the nftfwadm command
'clean','save' & 'restore' functions
fwcmds.py flush action: removes all nftables commands
cleans install directory
clean action: cleans install directory
nftfwls.py Provides a pretty print of the contents of the
blacklist database matching the entries in the
blacklist directory
nftfwedit.py Prints data from the system, integrating
GeoIP2 lookups and DNSBL Lookups
Also provides cmdline interface to add, delete
and blacklist ip addresses
nf_edit_dbfns.py Main editing functions for nftfwedit
nf_edit_print.py Print function for nftfwedit
nf_edit_validate.p User input validate functions
dnsbl.py DNS Blacklist lookup
geoipcountry.py Geolocation interface
"""
|
class Basededados:
def __init__(self):
self._dados = {}
def inserir_cliente(self,id , nome):
if 'clientes' not in self._dados: #Se o cliente não existir nos dados
self._dados['clientes'] = {id:nome} #o ID vai ser o nome
else:
self._dados['clientes'].update({id:nome}) #se já existir, atualiza o nome
def lista_cliente(self):
for id, nome in self._dados['clientes'].items():
print(id, nome)
def apaga_cliente(self,id): #remover um cliente
if 'clientes' in self._dados:
if id in self._dados['clientes']:
del self._dados['clientes'][id]
bd = Basededados()
bd.inserir_cliente(1, 'Joao')
bd.inserir_cliente(2, 'Maria')
bd.inserir_cliente(3, 'Pedro')
bd.apaga_cliente(2)
print(bd._dados)
bd.lista_cliente() |
# Copyright (c) 2020 Trail of Bits, Inc.
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU Affero General Public License as
# published by the Free Software Foundation, either version 3 of the
# License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU Affero General Public License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
class Colors:
class c:
green = '\033[92m'
yellow = '\033[93m'
red = '\033[91m'
magneta = '\033[95m'
bg_yellow = '\033[43m'
orange = '\033[38;5;202m'
RESET = '\033[0m'
def get_result_color(total, success):
if total == 0:
return Colors.c.magneta
if total == success:
return Colors.c.green
if success == 0:
return Colors.c.red
return Colors.c.yellow
def get_bin_result(result):
if result == 1:
return Colors.c.green
if result == 0:
return Colors.c.red
return Colors.c.magneta
def clean():
return Colors.RESET
def c(color, message):
return color + message + clean()
def fail():
return Colors.c.red
def succ():
return Colors.c.green
#TODO: Not sure if it's worth to generate these for each color from attrs dynamically
def green(message):
return c(Colors.c.green, message)
def red(message):
return c(Colors.c.red, message)
def yellow(message):
return c(Colors.c.yellow, message)
def magneta(message):
return c(Colors.c.magneta, message)
def bg_yellow(message):
return c(Colors.c.bg_yellow, message)
def orange(message):
return c(Colors.c.orange, message)
def id(message):
return message
|
# container.py - Creates META-INF/content.xml within the epub file
def create_container(epub_file):
epub_file.writestr('META-INF/container.xml', '''<?xml version="1.0"?>
<container version="1.0" xmlns="urn:oasis:names:tc:opendocument:xmlns:container">
<rootfiles>
<rootfile full-path="OEBPS/content.opf" media-type="application/oebps-package+xml"/>
</rootfiles>
</container>''')
|
APP_MIN_WIDTH = 1024
APP_MIN_HEIGHT = 800
APP_NAME = 'Fractals'
APP_FONT = 12
|
s = input()
ans = []
i=0
while i<len(s):
if s[i]=='.':
ans.append('0')
else:
if s[i+1]=='.':
ans.append('1')
else:
ans.append('2')
i=i+1
i+=1
for j in ans:
print(j,end='') |
def usersagein_Sec():
users_age = int(input("Enter user age in years"))
agein_sec = users_age *12 *365 * 24
print(f"Age in sec is {agein_sec}")
print("Welcome to function project 1 ")
usersagein_Sec()
# Never use same name in anywhere inside a function program. else going to get error.
friends = []
def friend():
friends.append("Ram")
friend()
friend()
friend()
print(friends)
|
def test_non_standard_default_desired_privilege_level(iosxe_conn):
# purpose of this test is to ensure that when a user sets a non-standard default desired priv
# level, that there is nothing in genericdriver/networkdriver that will prevent that from
# actually being set as the default desired priv level
iosxe_conn.close()
iosxe_conn.default_desired_privilege_level = "configuration"
iosxe_conn.open()
current_prompt = iosxe_conn.get_prompt()
assert current_prompt == "csr1000v(config)#"
iosxe_conn.close()
|
class Trader(object):
"""An entity buying and/or selling on the market."""
def __init__(self, name, funds=0, units=0):
self.name = name
self.funds = funds
self.units = units
def __repr__(self):
return "[Trader: name={}, funds={}, units={}]".format(self.name, self.funds, self.units)
NO_TRADER = Trader("No Trader", -1, -1)
|
fruits = {
"orange" :"a sweet,orange citrus fruit",
"apple" :"good for making cider",
"lemon" :"a sour,yellow citrus fruit",
"grape" :"a small, sweet fruit growing in bunches",
"lime" :"a sour,yellow citrus fruit",
}
def simple_operation():
print("To find the details in Fruits dictionary")
print(fruits)
print()
print('To find description for "lemon" in Fruits dictionary')
print(fruits["lemon"])
print()
print('To add a fruit name "pear" in in Fruits dictionary')
fruits["pear"] = "an odd shaped apple"
print(fruits)
print()
print('To change description of fruit "lime" in in Fruits dictionary')
fruits["lime"] = "great with tequilla"
print(fruits)
print()
print('Deleting a Key "Apple" from fruits')
del(fruits["apple"])
print(fruits)
print()
print("Clearing the fruits dictionary")
fruits.clear()
print(fruits)
def find_description():
print("To Find the description of a fruit")
while True:
dict_key = input("Please Enter Fruit name:\n")
if dict_key == "quit":
break
if dict_key in fruits:
description = fruits.get(dict_key)
print(description)
else:
print("The details of {} doesn't exist".format(dict_key))
if __name__ == "__main__":
print("""Select any one the below options
1. To find the description of fruit
2. To Display simple operation""")
choice = input("Enter Your choice here: ")
if choice == "1":
print("*" * 120)
find_description()
elif choice == "2":
print("*" * 120)
simple_operation() |
# Mac address of authentication server
AUTH_SERVER_MAC = "b8:ae:ed:7a:05:3b"
# IP address of authentication server
AUTH_SERVER_IP = "192.168.1.42"
# Switch port authentication server is facing
AUTH_SERVER_PORT = 3
#CTL_REST_IP = "192.168.1.39"
CTL_REST_IP = "10.0.1.8"
CTL_REST_PORT = "8080"
CTL_MAC = "b8:27:eb:b0:1d:6b"
GATEWAY_MAC = "24:09:95:79:31:7e"
GATEWAY_PORT = 1
# L2 src-dst pairs which are whitelisted and does not need to go through auth
WHITELIST = [
(AUTH_SERVER_MAC, CTL_MAC),
(CTL_MAC, AUTH_SERVER_MAC),
(GATEWAY_MAC, "00:1d:a2:80:60:64"),
("00:1d:a2:80:60:64", GATEWAY_MAC)
# (GATEWAY_MAC, "9c:eb:e8:01:6e:db"),
# ("9c:eb:e8:01:6e:db", GATEWAY_MAC)
]
|
print('-=-=-=-= DESAFIO 64 -=-=-=-=')
print()
n = tot = soma = 0
print('Para sair, digite "999".')
while n != 999:
n = int(input('Digite um número: '))
if n != 999:
tot += 1
soma += n
print('Foram digitados {} valores e a soma entre eles vale {}.'.format(tot, soma))
# RESOLUÇÃO do PROF:
# n = int(input('Digite um número [999 para sair]: '))
# while n != 999:
# tot += 1
# soma += n
# n = int(input('Digite um número [999 para sair]: '))
# print('Foram digitados {} valores e a soma entre eles vale {}.'.format(tot, soma))
|
running = True
# Global Options
SIZES = {'small': [7.58, 0], 'medium': [9.69, 1], 'large': [12.09, 2], 'jumbo': [17.99, 3], 'party': [20.29, 4]} # [Price, ID]
TOPPINGS = {'pepperoni': [0, False], 'bacon': [0, True], 'sausage': [0, False], 'mushroom': [1, False], 'black olive': [1, False], 'green pepper': [1, False]} # [Group, Special]
TOPPING_PRICES = [[1.6, 2.05, 2.35, 3.15, 3.30], [1.95, 2.25, 2.65, 3.49, 3.69]] # 0: No Special - 1: Special [Inc size]
def ask(question, options, show = True):
answer = False
o = "" # Choices to show, only if show = true
if show:
o = " (" + ', '.join([str(lst).title() for lst in options]) + ")"
while True:
a = input(question + o + ": ").lower() # User input
if a.isdigit(): # Allow users to pick via number too
a = int(a) - 1 # Set to an int
if a in range(0, len(options)):
a = options[a] # Set to value so next function completes
if a in options: # Is option valid?
answer = a
break
print("Not a valid option, try again!") # Nope
return answer # Return answer
def splitter():
print("---------------------------------------------------")
# Only do while running, used for confirmation.
while running:
PIZZA = {} # Pizza config
DELIVERY = {} # Delivery config
TOTAL = 0
# Start title
print(" MAKAN PIZZA ")
splitter()
# Delivery or pickup?
DELIVERY['type'] = ask("Type of order", ['delivery', 'pickup'])
while True:
DELIVERY['location'] = input("Location of " + DELIVERY['type'] + ": ") # Need a location
# Did they leave it blank?
if DELIVERY['location']:
break
else:
print("Please enter a valid location!")
# If delivery, ask for special instructions
if DELIVERY['type'] == "delivery":
DELIVERY['special_instructions'] = input("Special instructions (Blank for None): ")
# Do they have special instructions?
if not DELIVERY['special_instructions']:
DELIVERY['special_instructions'] = "None"
splitter()
# Size of the pizza
PIZZA['size'] = ask("Select the size", ['small', 'medium', 'large', 'jumbo', 'party'])
# Dough type
PIZZA['dough'] = ask("Select dough type", ['regular', 'whole wheat', 'carbone'])
# Type of sauce
PIZZA['sauce'] = ask("Type of sauce", ['tomato', 'pesto', 'bbq sauce', 'no sauce'])
# Type of primary cheese
PIZZA['cheese'] = ask("Type of cheese", ['mozzarella', 'cheddar', 'dairy-free', 'no cheese'])
splitter()
# Pick your topping section!
print("Pick your Toppings!", end = "")
count = -1 # Category count
for i in TOPPINGS:
start = "" # Used for the comma
# Check category and print to new line if so.
if TOPPINGS[i][0] != count:
count = TOPPINGS[i][0]
print("\n--> ", end = "")
else:
start = ", " # Split toppings
print(start + i.title(), end = "") # Print topping
# Special topping?
if TOPPINGS[i][1]:
print(" (*)", end = "")
print() # New line
# Extra functions
print("--> Typing in list will show current toppings.")
print("--> Retyping in a topping will remove it.")
print("--> Press enter once you're done!")
# Topping selector
PIZZA['toppings'] = []
while True:
top = input("Pick your topping: ") # Get input
if top == "list": # Want a list of toppings.
if not len(PIZZA['toppings']): # Do they have toppings?
print("You have no toppings!")
else:
for i in PIZZA['toppings']: # Go through and print toppings.
print("--> ", i.title())
elif not top: # Done picking.
break
else: # Picked a topping?
if top.endswith('s'): # If it ends with s, remove and check (sausages -> sausage)
top = top[:-1]
if top in TOPPINGS:
if top in PIZZA['toppings']:
print("Topping", top.title(), "has been removed from your order.")
PIZZA['toppings'].remove(top) # Remove topping
else:
print("Topping", top.title(), "has been added to your order.")
PIZZA['toppings'].append(top) # Add topping
else:
print("That topping does not exist!")
splitter()
print(" MAKAN PIZZA ORDER CONFIRMATION ")
splitter()
# Calculate the price of order and print.
print(PIZZA['size'].title() + " Pizza (CAD$" + str(SIZES[PIZZA['size']][0]) + ")")
TOTAL += SIZES[PIZZA['size']][0] # Price of size
# Free Things
print("--> " + PIZZA['dough'].title() + " (FREE)")
print("--> " + PIZZA['sauce'].title() + " (FREE)")
print("--> " + PIZZA['cheese'].title() + " (FREE)")
# Toppings
if PIZZA['toppings']:
print("--> Toppings:") # If they have any toppings, print title
# Go through all the toppings
for i in PIZZA['toppings']:
if TOPPINGS[i][1]:
tpp = TOPPING_PRICES[1][SIZES[PIZZA['size']][1]] # Special pricing
else:
tpp = TOPPING_PRICES[0][SIZES[PIZZA['size']][1]] # Non-Special pricing
print(" --> " + i.title() + " (CAD$" + format(tpp, '.2f') + ")") # Print the topping name and price
TOTAL += tpp # Add price of topping to total
splitter()
print("Sub-Total: CAD$" + format(TOTAL, '.2f')) # total
# Delivery has delivery fee (Fixed $3.50)
if DELIVERY['type'] == "delivery":
print("Delivery Fee: CAD$3.50")
TOTAL += 3.5
# Calculate and add tax
TAX = round(TOTAL * 0.13, 2)
TOTAL += TAX
print("Tax: CAD$" + format(TAX, '.2f'))
print("Total: CAD$" + format(TOTAL, '.2f'))
splitter()
CONFIRM = ask("Do you wish to confirm this order", ['yes', 'no'])
splitter()
# Done?
if CONFIRM == "yes":
break
# Final order print
print("Your order is on the way, we'll be there in 45 minutes or you get a refund!")
if DELIVERY['type'] == "delivery": # Did they get delivery?
print("Delivery to:", DELIVERY['location'], "(Special Instructions:", DELIVERY['special_instructions'] + ")")
else:
print("Pickup at:", DELIVERY['location'])
splitter() |
#
# PySNMP MIB module EdgeSwitch-QOS-AUTOVOIP-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/EdgeSwitch-QOS-AUTOVOIP-MIB
# Produced by pysmi-0.3.4 at Wed May 1 13:10:44 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")
ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint")
fastPathQOS, = mibBuilder.importSymbols("EdgeSwitch-QOS-MIB", "fastPathQOS")
InterfaceIndex, InterfaceIndexOrZero = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex", "InterfaceIndexOrZero")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
NotificationType, TimeTicks, Counter32, ModuleIdentity, iso, Bits, Unsigned32, MibIdentifier, Counter64, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, Gauge32, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "TimeTicks", "Counter32", "ModuleIdentity", "iso", "Bits", "Unsigned32", "MibIdentifier", "Counter64", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "Gauge32", "Integer32")
DisplayString, RowStatus, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "RowStatus", "TextualConvention")
fastPathQOSAUTOVOIP = ModuleIdentity((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4))
fastPathQOSAUTOVOIP.setRevisions(('2012-02-18 00:00', '2011-01-26 00:00', '2007-11-23 00:00', '2007-11-23 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: fastPathQOSAUTOVOIP.setRevisionsDescriptions(('Added OUI based auto VoIP support.', 'Postal address updated.', 'Ubiquiti branding related changes.', 'Initial revision.',))
if mibBuilder.loadTexts: fastPathQOSAUTOVOIP.setLastUpdated('201101260000Z')
if mibBuilder.loadTexts: fastPathQOSAUTOVOIP.setOrganization('Broadcom Inc')
if mibBuilder.loadTexts: fastPathQOSAUTOVOIP.setContactInfo('')
if mibBuilder.loadTexts: fastPathQOSAUTOVOIP.setDescription('The MIB definitions for Quality of Service - VoIP Flex package.')
agentAutoVoIPCfgGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1))
agentAutoVoIPVLAN = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 1), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentAutoVoIPVLAN.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPVLAN.setDescription('The VLAN to which all VoIP traffic is mapped to.')
agentAutoVoIPOUIPriority = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 2), Integer32()).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentAutoVoIPOUIPriority.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPOUIPriority.setDescription('The priority to which all VoIP traffic with known OUI is mapped to.')
agentAutoVoIPProtocolPriScheme = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("trafficClass", 1), ("remark", 2)))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentAutoVoIPProtocolPriScheme.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPProtocolPriScheme.setDescription('The priotization scheme which is used to priritize the voice data. ')
agentAutoVoIPProtocolTcOrRemarkValue = MibScalar((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 4), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 7))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentAutoVoIPProtocolTcOrRemarkValue.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPProtocolTcOrRemarkValue.setDescription("If 'agentAutoVoIPProtocolPriScheme' is traffic class, then the object 'agentAutoVoIPProtocolTcOrRemarkValue' is CoS Queue value to which all VoIP traffic is mapped to. if 'agentAutoVoIPProtocolPriScheme' is remark, then the object 'agentAutoVoIPProtocolTcOrRemarkValue' is 802.1p priority to which all VoIP traffic is remarked at the ingress port. This is used by Protocol based Auto VoIP")
agentAutoVoIPTable = MibTable((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5), )
if mibBuilder.loadTexts: agentAutoVoIPTable.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPTable.setDescription('A table providing configuration of Auto VoIP Profile.')
agentAutoVoIPEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5, 1), ).setIndexNames((0, "EdgeSwitch-QOS-AUTOVOIP-MIB", "agentAutoVoIPIntfIndex"))
if mibBuilder.loadTexts: agentAutoVoIPEntry.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPEntry.setDescription('Auto VoIP Profile configuration for a port.')
agentAutoVoIPIntfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5, 1, 1), InterfaceIndex())
if mibBuilder.loadTexts: agentAutoVoIPIntfIndex.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPIntfIndex.setDescription('This is a unique index for an entry in the agentAutoVoIPTable. A non-zero value indicates the ifIndex for the corresponding interface entry in the ifTable. A value of zero represents global configuration, which in turn causes all interface entries to be updated for a set operation, or reflects the most recent global setting for a get operation.')
agentAutoVoIPProtocolMode = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone(2)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentAutoVoIPProtocolMode.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPProtocolMode.setDescription('Enables / disables AutoVoIP Protocol profile on an interface.')
agentAutoVoIPOUIMode = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone(2)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentAutoVoIPOUIMode.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPOUIMode.setDescription('Enables / disables AutoVoIP OUI profile on an interface.')
agentAutoVoIPProtocolPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentAutoVoIPProtocolPortStatus.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPProtocolPortStatus.setDescription('AutoVoIP protocol profile operational status of an interface.')
agentAutoVoIPOUIPortStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 5, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2)))).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentAutoVoIPOUIPortStatus.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPOUIPortStatus.setDescription('AutoVoIP OUI profile operational status of an interface.')
agentAutoVoIPOUITable = MibTable((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 6), )
if mibBuilder.loadTexts: agentAutoVoIPOUITable.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPOUITable.setDescription('A table providing configuration of Auto VoIP Profile.')
agentAutoVoIPOUIEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 6, 1), ).setIndexNames((0, "EdgeSwitch-QOS-AUTOVOIP-MIB", "agentAutoVoIPOUIIndex"))
if mibBuilder.loadTexts: agentAutoVoIPOUIEntry.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPOUIEntry.setDescription('Auto VoIP Profile OUI configuration.')
agentAutoVoIPOUIIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 6, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 128))).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentAutoVoIPOUIIndex.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPOUIIndex.setDescription('The Auto VoIP OUI table index.')
agentAutoVoIPOUI = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 6, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(3, 3)).setFixedLength(3)).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentAutoVoIPOUI.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPOUI.setDescription('The Organizationally Unique Identifier (OUI), as defined in IEEE std 802-2001, is a 24 bit (three octets) globally unique assigned number referenced by various standards, of the information received from the remote system.')
agentAutoVoIPOUIDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 6, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite")
if mibBuilder.loadTexts: agentAutoVoIPOUIDesc.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPOUIDesc.setDescription('The Description of the Organizationally Unique Identifier (OUI), as defined in IEEE std 802-2001(up to 32 characters)')
agentAutoVoIPOUIRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 6, 1, 4), RowStatus()).setMaxAccess("readcreate")
if mibBuilder.loadTexts: agentAutoVoIPOUIRowStatus.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPOUIRowStatus.setDescription('The row status variable is used according to installation and removal conventions for conceptual rows.')
agentAutoVoIPSessionTable = MibTable((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7), )
if mibBuilder.loadTexts: agentAutoVoIPSessionTable.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPSessionTable.setDescription('A table providing configuration of Auto VoIP Profile.')
agentAutoVoIPSessionEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1), ).setIndexNames((0, "EdgeSwitch-QOS-AUTOVOIP-MIB", "agentAutoVoIPSessionIndex"))
if mibBuilder.loadTexts: agentAutoVoIPSessionEntry.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPSessionEntry.setDescription('Auto VoIP Session Table.')
agentAutoVoIPSessionIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 127))).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentAutoVoIPSessionIndex.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPSessionIndex.setDescription('The Auto VoIP session index.')
agentAutoVoIPSourceIP = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1, 2), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentAutoVoIPSourceIP.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPSourceIP.setDescription('The source IP address of the VoIP session.')
agentAutoVoIPDestinationIP = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1, 3), IpAddress()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentAutoVoIPDestinationIP.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPDestinationIP.setDescription('The destination IP address of the VoIP session.')
agentAutoVoIPSourceL4Port = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1, 4), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentAutoVoIPSourceL4Port.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPSourceL4Port.setDescription('The source L4 Port of the VoIP session.')
agentAutoVoIPDestinationL4Port = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1, 5), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentAutoVoIPDestinationL4Port.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPDestinationL4Port.setDescription('The destination L4 Port of the VoIP session.')
agentAutoVoIPProtocol = MibTableColumn((1, 3, 6, 1, 4, 1, 4413, 1, 1, 3, 4, 1, 7, 1, 6), Integer32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: agentAutoVoIPProtocol.setStatus('current')
if mibBuilder.loadTexts: agentAutoVoIPProtocol.setDescription('The Protocol of the VoIP session.')
mibBuilder.exportSymbols("EdgeSwitch-QOS-AUTOVOIP-MIB", agentAutoVoIPProtocolMode=agentAutoVoIPProtocolMode, agentAutoVoIPOUIMode=agentAutoVoIPOUIMode, agentAutoVoIPProtocol=agentAutoVoIPProtocol, agentAutoVoIPOUIDesc=agentAutoVoIPOUIDesc, agentAutoVoIPDestinationIP=agentAutoVoIPDestinationIP, agentAutoVoIPOUIEntry=agentAutoVoIPOUIEntry, agentAutoVoIPCfgGroup=agentAutoVoIPCfgGroup, agentAutoVoIPEntry=agentAutoVoIPEntry, fastPathQOSAUTOVOIP=fastPathQOSAUTOVOIP, agentAutoVoIPSessionIndex=agentAutoVoIPSessionIndex, agentAutoVoIPSourceL4Port=agentAutoVoIPSourceL4Port, agentAutoVoIPOUIPriority=agentAutoVoIPOUIPriority, agentAutoVoIPOUIIndex=agentAutoVoIPOUIIndex, agentAutoVoIPDestinationL4Port=agentAutoVoIPDestinationL4Port, agentAutoVoIPOUI=agentAutoVoIPOUI, agentAutoVoIPOUIRowStatus=agentAutoVoIPOUIRowStatus, PYSNMP_MODULE_ID=fastPathQOSAUTOVOIP, agentAutoVoIPSessionEntry=agentAutoVoIPSessionEntry, agentAutoVoIPProtocolTcOrRemarkValue=agentAutoVoIPProtocolTcOrRemarkValue, agentAutoVoIPSourceIP=agentAutoVoIPSourceIP, agentAutoVoIPTable=agentAutoVoIPTable, agentAutoVoIPProtocolPriScheme=agentAutoVoIPProtocolPriScheme, agentAutoVoIPSessionTable=agentAutoVoIPSessionTable, agentAutoVoIPOUIPortStatus=agentAutoVoIPOUIPortStatus, agentAutoVoIPOUITable=agentAutoVoIPOUITable, agentAutoVoIPProtocolPortStatus=agentAutoVoIPProtocolPortStatus, agentAutoVoIPIntfIndex=agentAutoVoIPIntfIndex, agentAutoVoIPVLAN=agentAutoVoIPVLAN)
|
# #!/usr/bin/env python
# encoding: utf-8
#
# --------------------------------------------------------------------------------------------------------------------
# Name: amortization.py
# Version: 0.0.1
# Summary: Para que a dívida seja totalmente paga, o tomador deve quitar o montante inicial adicionado aos juros
# acrescidos. A forma como o valor total do saldo devedor será calculado é definida de acordo com o sistema de
# amortização aplicado. Ele caracteriza como a dívida vai ser diminuída até chegar a sua total liquidação.
#
# Author: Alexsander Lopes Camargos
# Author-email: [email protected]
#
# License: MIT
# --------------------------------------------------------------------------------------------------------------------
class Amortization:
def __init__(self):
self.amortization = list()
@staticmethod
def taxa_equivalente(taxa, periodo_da_taxa_atual, periodo_da_taxa_equivalente):
"""Realiza a conversão de uma taxa de juros dada ao ano para taxa de juros ao mês.
1 + taxa equivalente = (1 + taxa de juros)período da taxa equivalente/período da taxa atual
Primeiro você deve transformar esses 2% dividindo o número 2 por 100
para encontrar 0,02 dessa forma: 2% = 2/100 = 0,02. O período da taxa
equivalente que queremos descobrir é 12 meses.
O período da taxa atual que temos é de 1 mês, então utilizaremos 12/1 = 12.
1 + taxa equivalente = (1 + 0,02)12/1
1 + taxa equivalente = 1,0212
1 + taxa equivalente = 1,2682
taxa equivalente = 1,2682 – 1
taxa equivalente = 0,2682
taxa equivalente = 26,82%
A taxa anual de juros equivalente a 2% ao mês é de 26,82%.
"""
taxa /= 100
return ((1 + taxa) ** (periodo_da_taxa_equivalente / periodo_da_taxa_atual)) - 1
def calcular(self):
"""Calcula as parcelas, amortizações, juros e evolução do saldo devedor."""
# Deve ser implementado nas classes filhas.
pass
def show(self):
"""Mostra uma tabela contendo todas as parcelas da operação de financiamento, no padrão:
# Parcelas Amortizações Juros Saldo Devedor
"""
# Realiza o calculo das parcelas a serem pagas durante o financiamento.
self.calcular()
# Totalizando os valores pagos durante a operação de financiamento.
total_parcela = 0
total_amortization = 0
total_juros = 0
print('{:<5}{:<12}{:<16}{:<12}{:<12}'.format('#', 'Parcelas', 'Amortizações', 'Juros', 'Saldo Devedor'))
for pmt, pgto, amortization, juros, saldo_devedor in self.amortization:
print(f'{pmt:<5}R${pgto:<10.2f}R${amortization:<16.2f}R${juros:<10.2f}R${saldo_devedor:<10.2f}')
total_parcela += pgto
total_amortization += amortization
total_juros += juros
print('Parcela = Amortização + Juro')
print(f'\nValor total pago de Parcelas: R${total_parcela:.2f}')
print(f'Valor total pago de Amortizações: R${total_amortization:.2f}')
print(f'Valor total pago de Juros: R${total_juros:.2f}')
class TabelaSAC(Amortization):
"""O Sistema de Amortização Constante (SAC) ou Método Hamburguês consiste na amortização constante da dívida com
base em pagamentos periódicos decrescentes. Ou seja, quanto mais o tempo passa, menores ficam as parcelas de
quitação do saldo devedor enquanto o valor é amortizado de maneira constante em todos os períodos.
De forma geral, os juros e o capital são calculados uma única vez e divididos para o pagamento
em várias parcelas durante o prazo de quitação.
"""
def __init__(self, present_value, period, interest_rate):
"""
Sistema de Amortização Constante (SAC) ou Método Hamburguês
:param present_value: Valor total do empréstimo ou financiamento.
:param period: Número de parcelas.
:param interest_rate: Taxa de juros
"""
super().__init__()
self.__present_value = present_value
self.__period = period
self.__interest_rate = self.taxa_equivalente(interest_rate, 12, 1)
self.amortization = []
def calcular(self):
"""Calcula as parcelas, amortizações, juros e evolução do saldo devedor."""
amortization = round(self.__present_value / self.__period, 2)
saldo_devedor = self.__present_value
# Rotina de cálculo de cada prestação mensal.
for pmt in range(1, (self.__period + 1)):
juros = round(saldo_devedor * self.__interest_rate, 2)
# pagamento = amortização + juros Sobre Saldo Devedor
pgto = amortization + juros
saldo_devedor -= amortization
self.amortization.append([pmt, pgto, amortization, juros, saldo_devedor])
class TabelaPrice(Amortization):
"""O modelo de amortização por Tabela Price é um dos mais conhecidos. Por ele, o montante total é amortizado ao
longo do contrato e de forma crescente. Assim, o pagamento é feito através de um conjunto de prestações
sucessivas e constantes.
Geralmente, as parcelas são pagas mensalmente em valores iguais, já com os juros embutidos. Também pode ser
chamado de Sistema de Parcelas Fixas ou Sistema Francês.
"""
def __init__(self, present_value, period, interest_rate):
"""Amortização por Tabela Price
:param present_value: Valor total do empréstimo ou financiamento.
:param period: Número de parcelas.
:param interest_rate: Taxa de juros
"""
super().__init__()
self.__present_value = present_value
self.__period = period
self.__interest_rate = self.taxa_equivalente(interest_rate, 12, 1)
self.__parcela = self.payment_value()
self.amortization = []
def payment_value(self):
"""A tabela Price usa o regime de juros compostos para calcular o valor das parcelas de um empréstimo e,
dessa parcela, há uma proporção relativa ao pagamento de juros e amortização do valor emprestado."""
return (self.__present_value * self.__interest_rate) / (1 - (1 + self.__interest_rate) ** -self.__period)
def calcular(self):
"""Calcula as parcelas, amortizações, juros e evolução do saldo devedor."""
saldo_devedor = self.__present_value
# Rotina de cálculo de cada prestação mensal.
for pmt in range(1, (self.__period + 1)):
juros = round(saldo_devedor * self.__interest_rate, 2)
amortization = self.__parcela - juros
saldo_devedor -= amortization
self.amortization.append([pmt, self.__parcela, amortization, juros, saldo_devedor])
|
def reverse(my_list):
if type(my_list) != list:
return f"{my_list} is not a list"
elif len(my_list) ==0:
return 'list should not be empty'
reversed_list = my_list[::-1]
return reversed_list
if __name__ == "__main__":
riddle_index = 0
|
"""
@author: David Lei
@since: 28/08/2016
@modified:
ReTRIEval tree = Trie
Tree data structure (reTRIEval tree)
- used to store collections of strings
- if 2 strings have a common prefix, will have a same ancestor in this tree
- idea for dictionaries, less space compared to hashtable
a.k.a digital tree, radix tree, prefix tree (as they can be searched by prefixes)
is a search tree (ordered tree data structure) that is used to store a dynamic set or
associative array where the keys are usually strings.
note: associative array, map, symbol table, or dictionary is an abstract data type composed
of a collection of (key, value) pairs, such that each possible key appears at most once in the collection.
based on: https://www.youtube.com/watch?v=AXjmTQ8LEoI
Time Complexity:
There can not be more than n * l nodes in the tree, where n is the number of strings and l is the length of search string
so at worst the below operations are O(n * l)
- look up (search):
- delete (remove):
- insert (add):
Space Complexity: O(n * l) where l is the avg length of the strings
A standard trie storing a collection S of s strings of total length n from an alphabet Σ has the following properties:
• The height of T is equal to the length of the longest string in S. • Every internal node of T has at most |Σ| children.
• T has s leaves
• The number of nodes of T is at most n+1
"""
class Trie_Node:
def __init__(self):
self.children = {} # dictionary, can also be done with array of 26 for alphabet
self.end_of_word = False # dictionary provides a mapping of 'char': next_tree_node_object
class Trie:
def __init__(self):
self.root = Trie_Node()
def insert_iterative(self, string):
node = self.root
for character in string:
if character in node.children: # O(1) best=avg case look up for a dictionary
node = node.children[character]
else:
# finished searching prior to string ending
# add this character to the trie
new_node = Trie_Node()
node.children[character] = new_node # add the char:obj mapping to node.children
node = new_node # update the node to be the new node we just created
node.end_of_word = True
def insert_recursive(self, string):
self._insert_recursive_aux(self.root, string, 0)
def _insert_recursive_aux(self, node, string, char_index):
if char_index == len(string): # done looping through string
node.end_of_word = True
elif string[char_index] in node.children:
self._insert_recursive_aux(node.children[string[char_index]], string, char_index + 1)
else:
new_node = Trie_Node()
node.children[string[char_index]] = new_node
self._insert_recursive_aux(node.children[string[char_index]], string, char_index + 1)
def search_iterative(self, string):
node = self.root
for i in range(len(string)):
if string[i] in node.children:
node = node.children[string[i]]
else:
return False
if node.end_of_word:
return True
return False
def search_recursive(self, string):
start = self.root
return self._search_recursive_aux(start, string, 0)
def _search_recursive_aux(self, node, string, char_index):
if char_index == len(string): # search loop through string
return node.end_of_word
elif string[char_index] in node.children:
return self._search_recursive_aux(node.children[string[char_index]], string, char_index + 1)
else:
return False
def remove(self, string):
"""
needs a recessive implementation as you might delete all the way up one side of the tree
doing this iteratively is a lot of work and might take a lot of space
"""
start = self.root
self._remove_aux(start, string, 0)
def _remove_aux(self, node, string, char_index):
"""
note: we can remove a node from the trie if that node no children
"""
if char_index == len(string):
if node.end_of_word: # the string is in the tree, can delete
node.end_of_word = False # no string ends here anymore
print("string " + str(string) +" in trie, trying to delete up")
return len(node.children) == 0 # return whether this node has any children
# if not, we can delete, else we can't
else:
# raise KeyError("Not in trie")
print("Can't delete, it's not in the trie")
return False # can't delete, return false
elif string[char_index] in node.children:
# just keep searching
node_next = node.children[string[char_index]]
can_remove_child = self._remove_aux(node_next, string, char_index + 1)
if can_remove_child: # nothing in my child's .children
# can delete
print("Can delete, prev: " + str(node.children.items()))
node.children.pop(string[char_index]) # can remove the child referencing returning node
print("Can delete, after: " + str(node.children.items()))
return len(node.children) == 0 # no more children
else:
# can't delete
print("Can't delete, it's has other children")
return False
else: # character is not in the children dict of current node
# raise KeyError("Not in trie")
print("Can't delete, it's not in the trie")
return False
if __name__ == "__main__":
T = Trie()
T.insert_iterative('abcd')
T.insert_recursive('egg')
T.insert_recursive('abg')
print(T.search_iterative('gp'))
print(T.search_iterative('egg'))
print(T.search_iterative('eg'))
print(T.search_recursive('abc'))
print(T.search_recursive('abcd'))
print("\nTrie structure works fine!\n")
print(T.remove('xg'))
print(T.remove('eg'))
print(T.remove('abcd'))
print("Removed things, for the case where we could delete, the path from b --> c --> d got truncated, b --> g stil here ")
print()
# note: check tree strcuture via debugging because didn't have time to implement a print fn |
class _dafny:
def print(value):
if type(value) == bool:
print("true" if value else "false", end="")
elif type(value) == property:
print(value.fget(), end="")
else:
print(value, end="")
|
limit=int(input("enter the limit"))
no=int(input("enter the no"))
for i in range(1,limit+1,1):
multi=no*i
print(no,"*",i,"=",multi) |
"""Exceptions raised by `e2e.pom` at runtime."""
class PomError(Exception):
"""Base exception from which all `e2e.pom` errors inherit."""
class ElementNotUniqueErrror(PomError):
"""Raised when multiple DOM matches are found for a "unique" model."""
class ElementNotFoundErrror(PomError):
"""Raised when no DOM matches are found for a "unique" model."""
|
months = {
'01':'janvier',
'02':'février',
'03':'mars',
'04':'avril',
'05':'mai',
'06':'juin',
'07':'juillet',
'08':'août',
'09':'septembre',
'10':'octobre',
'11':'novembre',
'12':'décembre'
}
def str_date_fr(date: str) -> str:
date = date.split('-')
if len(date) == 3 and date[2][0] == '0':
date[2] = date[2][1]
if date[2] == '1':
date[2] += '<sup>er</sup>'
if len(date) == 1:
return date[0]
else:
date[1] = months[date[1]]
return ' '.join(reversed(date)) |
class Arithmetic:
def __init__(self, command):
self.text = command
def operation(self):
return self.text.strip()
class MemoryAccess:
def __init__(self, command):
self.op, self.seg, self.idx = tuple(command.split())
def operation(self):
return self.op
def segment(self):
return self.seg
def index(self):
return self.idx
class ProgramFlow:
def __init__(self, command, function):
self.op, self.lb = tuple(command.split())
self.func = function
def operation(self):
return self.op
def label(self):
return f'{self.func}${self.lb}'
class FunctionCall:
def __init__(self, command):
self.cmd = tuple(command.split())
def operation(self):
return self.cmd[0]
def func_name(self):
return self.cmd[1]
def arg_count(self):
return int(self.cmd[2])
|
N = int(input())
pokemons = []
while (N != 0):
Name = input()
pokemons.append(Name)
N-= 1
print('Falta(m) {} pomekon(s).'.format(151 - len(set(pokemons))))
|
def count_salutes(hallway):
count=hallway.count("<")
total=0
for i in hallway:
count-=i=="<"
if i==">":
total+=count*2
return total
|
# Python - 3.6.0
Test.assert_equals(catch_sign_change([1, 3, 4, 5]), 0)
Test.assert_equals(catch_sign_change([1, -3, -4, 0, 5]), 2)
Test.assert_equals(catch_sign_change([]), 0)
Test.assert_equals(catch_sign_change([-47, 84, -30, -11, -5, 74, 77]), 3)
|
num = int(input('Digite um número para teste:'))
tot = 0
for c in range(1, num + 1):
if num % c == 0:
print('\033[1;33m', end='')
tot +=1
else:
print('\033[1;34m', end='')
print(f'{c}', end=' ')
print(f'\nO número {c} foi divisível {tot} vezes.')
if tot == 2:
print('E por isso ele é primo!')
else:
print('E por isso ele não é primo!')
#OUTRA RESOLUCAO:
#frase = input("Qual a frase? ").upper().replace(" ", "")
#if frase == frase[::-1]:
#print("A frase é um palíndromo")
#else:
#print("A frase não é um palíndromo")
|
{
'targets': [
{
'target_name': 'murmurhash3',
'sources': ['src/MurmurHash3.cpp', 'src/node_murmurhash3.cc'],
'cflags': ['-fexceptions'],
'cflags_cc': ['-fexceptions'],
'cflags!': ['-fno-exceptions'],
'cflags_cc!': ['-fno-exception'],
"include_dirs" : [
"<!(node -e \"require('nan')\")"
],
'conditions': [
['OS=="win"', {
'msvs_settings': {
'VCCLCompilerTool': {
'AdditionalOptions': [ '/EHsc' ]
}
}
}
],
['OS=="mac"', {
'xcode_settings': {
'GCC_ENABLE_CPP_EXCEPTIONS': 'YES'
}
}
]
]
}
]
} |
def create_desktop_file_KDE():
path="/usr/share/applications/klusta_process_manager.desktop"
text=["[Desktop Entry]",
"Version=0.1",
"Name=klusta_process_manager",
"Comment=GUI",
"Exec=klusta_process_manager",
"Icon=eyes",
"Terminal=False",
"Type=Application",
"Categories=Applications;"]
with open(path,"w") as f:
f.write("\n".join(text))
if __name__=="__main__":
print("Create a .desktop file in /usr/share/application")
print("Only tested with Linux OpenSuse KDE")
print("--------------")
try:
create_desktop_file_KDE()
print("Shortcut created !")
except PermissionError:
print("Needs admin rights: try 'sudo python create_shortcut.py'")
|
class BinarySearchTreeNode:
def __init__(self,data):
self.data=data
self.left=None
self.right=None
def add_child(self,data):
if data == self.data:
return
if data <self.data:
#add on the left side of the subtree
if self.left:
self.left.add_child(data)
else:
self.left = BinarySearchTreeNode(data)
else:
#add on the right side of the subtree
if self.right:
self.right.add_child(data)
else:
self.right = BinarySearchTreeNode(data)
def in_order_traversal(self):
elements=[]
#visits left tree
if self.left:
elements+=self.left.in_order_traversal()
#visits root node
elements.append(self.data)
#visits right tree
if self.right:
elements+=self.right.in_order_traversal()
return elements
def post_traversal(self):
elements=[]
#visits left tree
if self.left:
elements+=self.left.post_traversal()
#vists right tree
if self.right:
elements+=self.right.post_traversal()
#vists root
elements.append(self.data)
def pre_traversal(self):
elements=[self.data]
#visits left tree
if self.left:
elements+=self.left.append.pre_traversal()
#visits right tree
if self.right:
elements+=self.right.append.pre_traversal()
def find_max(self):
if self.right is None:
return self.data
return self.right.find_max()
def find_min(self):
if self.left is None:
return self.data
return self.left.find_min()
def calculate_sum(self):
left_sum = self.left.calculate_sum() if self.left else 0
right_sum = self.right.calculate_sum() if self.right else 0
return self.data + left_sum + right_sum
def build_tree(elements):
root=BinarySearchTreeNode(elements[0])
for i in range(1,len(elements)):
root.add_child(elements[i])
return root
if __name__ == '__main__':
numbers = [17, 4, 1, 20, 9, 23, 18, 34]
numbers = [15,12,7,14,27,20,23,88 ]
numbers_tree = build_tree(numbers)
print("Input numbers:",numbers)
print("Min:",numbers_tree.find_min())
print("Max:",numbers_tree.find_max())
print("Sum:", numbers_tree.calculate_sum())
print("In order traversal:", numbers_tree.in_order_traversal())
print("Pre order traversal:", numbers_tree.pre_traversal())
print("Post order traversal:", numbers_tree.post_traversal()) |
# -*- coding: utf-8 -*-
# Scrapy settings for cosme project
#
# For simplicity, this file contains only the most important settings by
# default. All the other settings are documented here:
#
# http://doc.scrapy.org/en/latest/topics/settings.html
#
BOT_NAME = 'cosme'
SPIDER_MODULES = ['cosme.spiders']
NEWSPIDER_MODULE = 'cosme.spiders'
DOWNLOAD_DELAY = 1.5
COOKIES_ENABLES = False
ITEM_PIPELINES = {
# 'cosme.pipelines.CosmePipeline': 1,
# 'cosme.pipelines.ProductPipeline': 1,
'cosme.pipelines.ProductDetailPipeline': 1,
}
#---mysql config---
HOST, DB, USER, PWD = '127.0.0.1', 'cosme', 'root', '123456'
# Crawl responsibly by identifying yourself (and your website) on the user-agent
#USER_AGENT = 'cosme (+http://www.yourdomain.com)'
|
# The Tribonacci sequence Tn is defined as follows:
# T0 = 0, T1 = 1, T2 = 1, and Tn+3 = Tn + Tn+1 + Tn+2 for n >= 0.
# Given n, return the value of Tn.
# Example 1:
# Input: n = 4
# Output: 4
# Explanation:
# T_3 = 0 + 1 + 1 = 2
# T_4 = 1 + 1 + 2 = 4
# Example 2:
# Input: n = 25
# Output: 1389537
# Constraints:
# 0 <= n <= 37
# The answer is guaranteed to fit within a 32-bit integer, ie. answer <= 2^31 - 1.
# Hints:
# Make an array F of length 38, and set F[0] = 0, F[1] = F[2] = 1.
# Now write a loop where you set F[n+3] = F[n] + F[n+1] + F[n+2], and return F[n].
# M1. 动态规划
class Solution(object):
def tribonacci(self, n):
"""
:type n: int
:rtype: int
"""
if n < 3:
return 1 if n else 0
x, y, z = 0, 1, 1
for _ in range(n-2):
x, y, z = y, z, x + y + z
return z
# M2. 记忆递归
# class Tri:
# def __init__(self):
# def helper(k):
# if k == 0:
# return 0
# if nums[k]:
# return nums[k]
# nums[k] = helper(k - 1) + helper(k - 2) + helper(k - 3)
# return nums[k]
# n = 38
# self.nums = nums = [0] * n
# nums[1] = nums[2] = 1
# helper(n - 1)
# class Solution:
# t = Tri()
# def tribonacci(self, n):
# """
# :type n: int
# :rtype: int
# """
# return self.t.nums[n]
# M3. 记忆动态规划
# class Tri:
# def __init__(self):
# n = 38
# self.nums = nums = [0] * n
# nums[1] = nums[2] = 1
# for i in range(3, n):
# nums[i] = nums[i - 1] + nums[i - 2] + nums[i - 3]
# class Solution:
# t = Tri()
# def tribonacci(self, n):
# """
# :type n: int
# :rtype: int
# """
# return self.t.nums[n] |
# Time: O(n)
# Space: O(h), h is height of binary tree
# 129
# Given a binary tree containing digits from 0-9 only, each root-to-leaf path could represent a number.
#
# An example is the root-to-leaf path 1->2->3 which represents the number 123.
#
# Find the total sum of all root-to-leaf numbers.
#
# For example,
#
# 1
# / \
# 2 3
# The root-to-leaf path 1->2 represents the number 12.
# The root-to-leaf path 1->3 represents the number 13.
#
# Return the sum = 12 + 13 = 25.
#
# Definition for a binary tree node
class TreeNode:
def __init__(self, x):
self.val = x
self.left = None
self.right = None
class Solution:
# @param root, a tree node
# @return an integer
def sumNumbers(self, root: TreeNode) -> int: # USE THIS
ans = 0
stack = [(root, 0)]
while stack:
node, v = stack.pop()
if node:
if not node.left and not node.right:
ans += v*10 + node.val
else:
stack.append((node.right, v*10+node.val))
stack.append((node.left, v*10+node.val))
return ans
def sumNumbers_rec1(self, root):
return self.recu(root, 0)
def recu(self, root, num):
if root is None:
return 0
if root.left is None and root.right is None:
return num * 10 + root.val
return self.recu(root.left, num * 10 + root.val) + self.recu(root.right, num * 10 + root.val)
# the following recursion is not very good (use global var, don't leverage return value)
def sumNumbers_rec2(self, root: TreeNode) -> int:
def dfs(node, v):
if node:
if not (node.left or node.right):
self.ans += v*10 + node.val
return
dfs(node.left, v*10+node.val)
dfs(node.right, v*10+node.val)
self.ans = 0
dfs(root, 0)
return self.ans
if __name__ == "__main__":
root = TreeNode(1)
root.left = TreeNode(2)
root.right = TreeNode(3)
root.left.left = TreeNode(4)
print(Solution().sumNumbers(root)) # 137
|
"""
Georgia Institute of Technology - CS1301
HW04 - Strings, Indexing and Lists
"""
#########################################
"""
Function Name: findMax()
Parameters: a caption list of numbers (list), start index (int), stop index (int)
Returns: highest number (int)
"""
def findMax(theNumbersMason, theStart, theEnd):
highscore = theNumbersMason[theStart]
for x in theNumbersMason[theStart:theEnd+1]:
if x > highscore:
highscore = x
return highscore
#########################################
"""
Function Name: fruitPie()
Parameters: list of fruits (list), minimum quantity (int)
Returns: list of fruits (list)
"""
def fruitPie(theFruit, theMin):
acceptableFruit = []
for x in range(0, len(theFruit)):
if x % 2 != 0 and theFruit[x] >= theMin:
acceptableFruit.append(theFruit[x-1])
return acceptableFruit
#########################################
"""
Function Name: replaceWord()
Parameters: initial sentence (str), replacement word (str)
Returns: corrected sentence (str)
"""
def replaceWord(sentence, word):
segments = sentence.split()
sentence = ""
for x in segments:
if len(x) >= 5:
sentence = sentence + word + " "
else:
sentence = sentence + x + " "
return sentence[0:len(sentence) - 1]
#########################################
"""
Function Name: highestSum()
Parameters: list of strings (strings)
Returns: index of string with the highest sum (int)
"""
def highestSum(theStrings):
high = [0, 0] # index, score
for x in range(0, len(theStrings)):
sum = 0
for y in theStrings[x]:
if y.isdigit():
sum = sum + int(y)
if sum > high[1]:
high = [x, sum]
return high[0]
#########################################
"""
Function: sublist()
Parameters: alist (list), blist (list)
Returns: True or False (`boolean`)
"""
def sublist(aList, bList):
bLength = len(bList)
if bLength == 0:
return True
for x in aList:
if x == bList[0]:
if len(bList) == 1:
return True
bList = bList[1:len(bList)]
else:
if bLength != len(bList):
return False
return False
|
"""
Midi pitch values:
A0 has value 21
C8 has value 108
"""
NAME_TO_VAL = {
"C": 0,
"D": 2,
"E": 4,
"F": 5,
"G": 7,
"A": 9,
"B": 11,
}
def name_to_val(name):
name = name.upper()
note = name[0]
mod = None
octave = None
offset = 12
if name[1] in ("#", "B"):
mod = name[1]
octave = int(name[2:])
else:
octave = int(name[1:])
val = NAME_TO_VAL[note]
if mod == "#":
val += 1
elif mod == "B":
val -= 1
val += octave * 12
val += offset
return val
|
task = int(input())
points = int(input())
course = input()
if task == 1:
if course == 'Basics':
points = points * 0.08 - (0.2 * (points * 0.08))
elif course == 'Fundamentals':
points = points * 0.11
elif course == 'Advanced':
points = points * 0.14 + (0.2 * (points * 0.14))
elif task == 2:
if course == 'Basics':
points = points * 0.09
elif course == 'Fundamentals':
points = points * 0.11
elif course == 'Advanced':
points = points * 0.14 + (0.2 * (points * 0.14))
elif task == 3:
if course == 'Basics':
points = points * 0.09
elif course == 'Fundamentals':
points = points * 0.12
elif course == 'Advanced':
points = points * 0.15 + (0.2 * (points * 0.15))
elif task == 4:
if course == 'Basics':
points = points * 0.10
elif course == 'Fundamentals':
points = points * 0.13
elif course == 'Advanced':
points = points * 0.16 + (0.2 * (points * 0.16))
print(f'Total points: {points:.2f}') |
# Given a number N, print the odd digits in the number(space seperated) or print -1 if there is no odd digit in the given number.
number = int(input(''))
array = list(str(number))
flag = 0
for digit in range(0, len(array)-1):
if(int(array[digit]) % 2 == 0):
print(' ', end='')
else:
print(array[digit], end='')
flag = flag+1
if(int(array[len(array)-1]) % 2 == 0):
print('', end='')
else:
print(int(array[len(array)-1]), end='')
if(flag == 0):
print(-1)
|
"""A function to reverse a string.
By Ted Silbernagel
"""
def reverse_string(input_word: str) -> str:
return_word = ''
for _ in input_word:
return_word += input_word[-1:]
input_word = input_word[:-1]
return return_word
if __name__ == '__main__':
user_string = input('Please enter a word/string to reverse: ')
result = reverse_string(user_string)
print(result)
|
"""
File: forestfire.py
----------------
This program highlights fires in an image by identifying
pixels who red intensity is more than INTENSITY_THRESHOLD times
the average of the red, green, and blue values at a pixel.
Those "sufficiently red" pixels are then highlighted in the
image and the rest of the image is turned grey, by setting the
pixels red, green, and blue values all to be the same average
value.
"""
def main():
# write a program to ask user their height in METERS
# it will be a float!
# evaluate if their height is too short or too tall or ok to ride
# print response depending on evaluation
# precondition: we don't know if they can ride
# postcondition: we know if they can ride and tell them.
# what is their height in meters?
rider_height = float(input("Enter height in meters: "))
if (rider_height < 1 or rider_height > 2):
print("You can't ride the roller coaster.")
else:
print("You can ride the roller coaster.")
if __name__ == '__main__':
main()
|
class Rectangle:
def __init__(self, width):
self.__width = width
@property
def width(self):
return self.__width
@width.setter
def width(self, w):
if w > 0:
self.__width = w
else:
raise ValueError
# Теперь работать с width и height можно так, как будто они являются атрибутами:
rect = Rectangle(10)
print(rect.width)
# Можно не только читать, но и задавать новые значения свойствам: rect.width = 50
rect.height = 70
print(rect.width)
print(rect.height)
# Если вы обратили внимание: в setter’ах этих свойств осуществляется
# проверка входных значений, если значение меньше нуля, то будет выброшено исключение ValueE rect.width = -50
|
t5_generation_config = {
"do_sample": True,
"num_beams": 2,
"repetition_penalty": 5.0,
"length_penalty": 1.0,
"num_return_sequences": 1,
}
GPT2_generation_config = {
"do_sample": True,
"num_beams": 2,
"repetition_penalty": 5.0,
"length_penalty": 1.0,
} |
# -*- coding: utf-8 -*-
"""
Created on Tue May 7 12:11:09 2019
@author: DiPu
"""
A1=int(input())
A2=int(input())
A3=int(input())
E1=int(input())
E2=int(input())
weighted_score=((A1+A2+A3)*0.1)+((E1+E2)*0.35 )
print("weightrd score is",weighted_score)
|
# Pyomniar
# Copyright 2011 Chris Kelly
# See LICENSE for details.
class OmniarError(Exception):
"""Omniar exception"""
def __init__(self, reason, response=None):
self.reason = unicode(reason)
self.response = response
def __str__(self):
return self.reason |
while True:
number = int(input('Enter a number: '))
while number != 1:
if number % 2 == 0:
number //= 2
else:
number = number * 3 + 1
print(number)
print()
|
# ------------------------------
# 276. Paint Fence
#
# Description:
# There is a fence with n posts, each post can be painted with one of the k colors.
# You have to paint all the posts such that no more than two adjacent fence posts have the same color.
#
# Return the total number of ways you can paint the fence.
#
# Note:
# n and k are non-negative integers.
#
# Version: 1.0
# 12/11/17 by Jianfa
# ------------------------------
class Solution(object):
def numWays(self, n, k):
"""
:type n: int
:type k: int
:rtype: int
"""
if n == 0:
return 0
if n == 1:
return k
same, diff = k, k * (k-1)
for i in range(3, n + 1): # Note it's n + 1 here, not n
same, diff = diff, (same + diff) * (k-1)
return same + diff
# Used for testing
if __name__ == "__main__":
test = Solution()
# ------------------------------
# Summary:
# Get the idea from "Python solution with explanation" in discuss section
# If n == 1, there would be k-ways to paint.
#
# if n == 2, there would be two situations:
#
# 2.1 You paint same color with the previous post: k*1 ways to paint, named it as same
# 2.2 You paint differently with the previous post: k*(k-1) ways to paint this way, named it as dif
# So, you can think, if n >= 3, you can always maintain these two situations,
# You either paint the same color with the previous one, or differently.
#
# Since there is a rule: "no more than two adjacent fence posts have the same color."
#
# We can further analyze:
#
# from 2.1, since previous two are in the same color, next one you could only paint differently, and it would
# form one part of "paint differently" case in the n == 3 level, and the number of ways to paint this way
# would equal to same*(k-1).
# from 2.2, since previous two are not the same, you can either paint the same color this time (dif*1) ways
# to do so, or stick to paint differently (dif*(k-1)) times.
# Here you can conclude, when seeing back from the next level, ways to paint the same, or variable same would
# equal to dif*1 = dif, and ways to paint differently, variable dif, would equal to same*(k-1)+dif*(k-1) = (same + dif)*(k-1) |
def get_index_different_char(chars):
alphanumeric_count, not_alphanumeric_count = 0, 0
last_alphanumeric_idx, last_not_alphanumeric_idx = 0, 0
alphanumeric = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'
for idx, char in enumerate(chars):
if str(char) in alphanumeric:
alphanumeric_count += 1
last_alphanumeric_idx = idx
else:
not_alphanumeric_count += 1
last_not_alphanumeric_idx = idx
if alphanumeric_count > not_alphanumeric_count:
return last_not_alphanumeric_idx
return last_alphanumeric_idx
if __name__ == '__main__':
print(get_index_different_char(['A', 'f', '.', 'Q', 2]))
print(get_index_different_char(['.', '{', ' ^', '%', 'a']))
print(get_index_different_char([1, '=', 3, 4, 5, 'A', 'b', 'a', 'b', 'c']))
print(get_index_different_char(['=', '=', '', '/', '/', 9, ':', ';', '?', '¡']))
print(get_index_different_char(list(range(1,9)) + ['}'] + list('abcde')))
#pytest --cov-report term-missing --cov='.'
|
#Conditional if
x = 22
y = 100
if y < x:
print("This is True, y is not greater than x!")
elif y == x:
print("This is True, y is greater than x!")
else:
print("Anything else!")
print("Completed")
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
models
----------------------------------
Models store record state during parsing and serialisation to other formats.
"""
class InventoryItem(object):
""" Inventory Item Model """
def __init__(self, id=None, price=None, description=None, cost=None, price_type=None,
quantity_on_hand=None, modifiers=[]):
self._id = id
self._price = price
self._description = description
self._cost = cost
self._price_type = price_type
self._quantity_on_hand = quantity_on_hand
self._modifiers = modifiers
@property
def id(self):
""" get id property """
return self._id
@id.setter
def id(self, id):
""" set id property """
self._id = id
@property
def price(self):
""" get price property """
return self._price
@price.setter
def price(self, price):
""" set price property """
self._price = price
@property
def description(self):
""" get description property """
return self._description
@description.setter
def description(self, _description):
""" set description property """
self._description = _description
@property
def cost(self):
""" set cost property """
return self._cost
@cost.setter
def cost(self, cost):
""" get cost property """
self._cost = cost
@property
def price_type(self):
""" get price_type property """
return self._price_type
@price_type.setter
def price_type(self, price_type):
""" set price_type property """
self._price_type = price_type
@property
def quantity_on_hand(self):
""" set quantity_on_hand property """
return self._quantity_on_hand
@quantity_on_hand.setter
def quantity_on_hand(self, quantity_on_hand):
""" get quantity_on_hand property """
self._quantity_on_hand = quantity_on_hand
@property
def modifiers(self):
""" get modifiers property """
return self._modifiers
@modifiers.setter
def modifiers(self, modifiers):
""" set modifiers property """
self._modifiers = modifiers
|
""""""
_TEST_TEMPLATE = """#!/bin/bash
# Unset TEST_SRCDIR since we're trying to test the non-test behavior
unset TEST_SRCDIR
# --- begin runfiles.bash initialization v2 ---
# Copy-pasted from the Bazel Bash runfiles library v2.
set -uo pipefail; f=bazel_tools/tools/bash/runfiles/runfiles.bash
source "${RUNFILES_DIR:-/dev/null}/$f" 2>/dev/null || \
source "$(grep -sm1 "^$f " "${RUNFILES_MANIFEST_FILE:-/dev/null}" | cut -f2- -d' ')" 2>/dev/null || \
source "$0.runfiles/$f" 2>/dev/null || \
source "$(grep -sm1 "^$f " "$0.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \
source "$(grep -sm1 "^$f " "$0.exe.runfiles_manifest" | cut -f2- -d' ')" 2>/dev/null || \
{ echo>&2 "ERROR: cannot find $f"; exit 1; }; f=; set -e
# --- end runfiles.bash initialization v2 ---
runfiles_export_envvars
$(rlocation {nested_tool})
"""
def _runfiles_path(ctx, file):
if file.short_path.startswith("../"):
return file.short_path[3:]
else:
return ctx.workspace_name + "/" + file.short_path
def _impl(ctx):
runfiles = ctx.runfiles()
runfiles = runfiles.merge(ctx.attr._bash_runfiles.default_runfiles)
runfiles = runfiles.merge(ctx.attr.nested_tool.default_runfiles)
script = ctx.actions.declare_file(ctx.label.name)
ctx.actions.write(
script,
_TEST_TEMPLATE.replace("{nested_tool}", _runfiles_path(ctx, ctx.executable.nested_tool)),
is_executable = True
)
return [
DefaultInfo(
executable = script,
runfiles = runfiles,
),
]
nested_tool_test = rule(
implementation = _impl,
test = True,
# executable = True,
attrs = {
"nested_tool": attr.label(
executable = True,
mandatory = True,
cfg = "target",
),
"_bash_runfiles": attr.label(
allow_files = True,
default = Label("@bazel_tools//tools/bash/runfiles"),
),
},
)
|
#!/usr/bin/env python
# encoding: utf-8
"""
constants.py
Useful constants; the ones embedded in classes can be thought of as Enums.
Created by Niall Richard Murphy on 2011-05-25.
"""
_DNS_SEPARATOR = "." # What do we use to join hostname to domain name
_FIRST_ONE_ONLY = 0 # If we only want the first match back from an array
class Types(object):
"""Types of router configuration."""
UNKNOWN=0
DEFAULT_CISCO=1
DEFAULT_JUNIPER=2
class Regex(object):
"""These regular expressions use named capturing groups; most of them
are gross simplifications."""
V4_ADDR = '((25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)\.){3}(25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)'
V6_ADDR = '::'
ANY_ADDR = '\S+'
ANY_MASK = '\S+'
INTERFACE = '[a-zA-Z-]+\d+(/\d+)?'
ANY_METRIC = '\d+'
SNMP_VERSION = '\d|\dc'
SSH_VERSION = '1|2'
SINGLE_STRING = '\S+'
GREEDY_STRING = '.*'
DIGITS = '\d+'
STANDARD_ACL_DIGITS = '\d{1,2}'
EXTENDED_ACL_DIGITS = '\d{3}'
ACL_DIRECTION = 'in|out'
ACCESS_GROUP = DIGITS
CISCO_WILDCARD = '(\d+)\.(\d+)\.(\d+)\.(\d+)'
ETHER_SPEED = 'nonegotiate|auto|\d+'
ETHER_DUPLEX = 'full|half|auto'
SHUTDOWN_STATE = 'shutdown'
NO_IP_STATE = 'no ip address'
VTY_COMPRESS = '(\d+)\s+(\d+)'
ACL_PROTO = 'ip|tcp|udp'
ACL_ACTION = 'permit|deny'
ACL_SOURCE = '\S+'
INTERFACE_PROPERTIES = "ip address (?P<addr1>%s) (?P<mask1>%s)|" \
"ipv6 address (?P<addr2>%s)|" \
"speed (?P<speed>%s)|" \
"duplex (?P<duplex>%s)|" \
"ip access-group (?P<aclin>%s) in|" \
"ip access-group (?P<aclout>%s) out|" \
"(?P<shutdown>%s)|" \
"(?P<noip>%s)|" \
"description (?P<descr>%s)" % (
SINGLE_STRING, # ip address
ANY_MASK, # mask
SINGLE_STRING, # ip address
ETHER_SPEED, # ethernet speed
ETHER_DUPLEX, # ethernet duplicity
ACCESS_GROUP, # access group
ACCESS_GROUP, # access group
SHUTDOWN_STATE, # shutdown state
NO_IP_STATE, # no ip address
GREEDY_STRING) # description
CON_CONFIG = "transport preferred (?P<tpref>%s)|transport output (?P<tout>%s)|" \
"exec-timeout (?P<timeo>%s\ +\d+)|stopbits (?P<stopb>%s)|" \
"password (?P<encrlevel>%s) (?P<passw>%s)" % (
SINGLE_STRING, # tpref
SINGLE_STRING, # tout
SINGLE_STRING, # timeo
DIGITS, # stopb
DIGITS, # encrlevel
SINGLE_STRING) # passwd
VTY_CONFIG = CON_CONFIG + "|transport input (?P<inputm>%s)" \
"|access-class (?P<acl>%s) (?P<acldir>%s)" \
"|ipv6 access-class (?P<aclv6>%s) (?P<dirv6>%s)" % (
GREEDY_STRING, # inputm - could be multiple inputs supported
SINGLE_STRING, # v4 acl
SINGLE_STRING, # v4 direction
SINGLE_STRING, # v6 acl
SINGLE_STRING) # v6 direction
STANDARD_ACL = "^access-list (?P<id>%s) (?P<action>%s) (?P<netw>%s) (?P<netm>%s)$" % (
STANDARD_ACL_DIGITS, # id
ACL_ACTION, # permit
SINGLE_STRING, # 127.0.0.1
SINGLE_STRING) # 0.0.0.255
EXTENDED_ACL = "(?P<action1>%s) (?P<netw1>%s) (?P<netm1>%s)|" \
"(?P<action2>%s) (?P<proto>%s) (?P<netw2>%s) (?P<netm2>%s) (.*$)" % (
ACL_ACTION, # permit
ANY_ADDR, # 127.0.0.1
SINGLE_STRING, # 0.0.0.255
ACL_ACTION, # permit
ACL_PROTO, # tcp
ANY_ADDR, # 8.8.8.0
SINGLE_STRING) # 0.0.0.255
AAA_NEWMODEL = "^aaa new-model"
TACACS_SERVERS = "tacacs-server host (?P<host>%s)" % (ANY_ADDR)
TACACS_KEY = "tacacs-server key 7 (?P<key>%s)" % (SINGLE_STRING)
class UserClasses(object):
CORE_ROUTER = 0
ACCESS_ROUTER = 1
DISTRIBUTION_ROUTER = 2
class NetworkConstants(object):
SLASH_32 = '255.255.255.255'
|
"""
Given a binary tree and a sum, determine if the tree has a root-to-leaf path such that adding up all the values along the path equals the given sum.
For example:
Given the below binary tree and sum = 22,
5
/ \
4 8
/ / \
11 13 4
/ \ \
7 2 1
return true, as there exist a root-to-leaf path 5->4->11->2 which sum is 22.
"""
# Definition for a binary tree node
# class TreeNode:
# def __init__(self, x):
# self.val = x
# self.left = None
# self.right = None
class Solution:
# @param root, a tree node
# @param sum, an integer
# @return a boolean
def hasPathSum(self, root, sum):
if root is None:
return False
if root.left is None and root.right is None: # Found a leaf
if sum == root.val:
return True
return self.hasPathSum(root.left, sum-root.val) or self.hasPathSum(root.right, sum-root.val)
# Need to note, a leaf is a node has no left chind and no right child
|
#import sys
#sys.stdin = open('rectangles.in', 'r')
#sys.stdout = open('rectangles.out', 'w')
n, m, k = map(int, input().split())
a = [[100000, 0, 100000, 0] for i in range(k)]
field = []
for i in range(n):
field.append(list(map(int, input().split())))
field.reverse()
for i in range(n):
for j in range(m):
if field[i][j] > 0:
v = field[i][j] - 1
a[v][0] = min(a[v][0], j)
a[v][1] = max(a[v][1], j)
a[v][2] = min(a[v][2], i)
a[v][3] = max(a[v][3], i)
for i in range(k):
print(a[i][0], a[i][2], a[i][1] + 1, a[i][3] + 1)
|
def _cc_injected_toolchain_header_library_impl(ctx):
hdrs = ctx.files.hdrs
transitive_cc_infos = [dep[CcInfo] for dep in ctx.attr.deps]
compilation_ctx = cc_common.create_compilation_context(headers = depset(hdrs))
info = cc_common.merge_cc_infos(
cc_infos = transitive_cc_infos + [CcInfo(compilation_context = compilation_ctx)],
)
return [info, DefaultInfo(files = depset(hdrs))]
cc_injected_toolchain_header_library = rule(
_cc_injected_toolchain_header_library_impl,
attrs = {
"hdrs": attr.label_list(
doc = "A list of headers to be included into a toolchain implicitly using -include",
allow_files = True,
),
"deps": attr.label_list(
doc = "list of injected header libraries that this target depends on",
providers = [CcInfo],
),
},
provides = [CcInfo],
)
def _cc_toolchain_header_polyfill_library_impl(ctx):
hdrs = ctx.files.hdrs
system_includes = [ctx.label.package + "/" + inc for inc in ctx.attr.system_includes] + [ctx.label.workspace_root]
transitive_cc_infos = [dep[CcInfo] for dep in ctx.attr.deps]
compilation_ctx = cc_common.create_compilation_context(headers = depset(hdrs), system_includes = depset(system_includes))
info = cc_common.merge_cc_infos(cc_infos = transitive_cc_infos + [CcInfo(compilation_context = compilation_ctx)])
return [info, DefaultInfo(files = depset(hdrs, transitive = [info.compilation_context.headers]))]
cc_polyfill_toolchain_library = rule(
_cc_toolchain_header_polyfill_library_impl,
attrs = {
"hdrs": attr.label_list(
doc = "A list of headers to be included into the toolchains system libraries",
allow_files = True,
),
"system_includes": attr.string_list(
doc = "A list of directories to be included when the toolchain searches for headers",
),
"deps": attr.label_list(
doc = "list of injected header libraries that this target depends on",
providers = [CcInfo],
),
},
)
|
"""
Given two integers n and k, return all possible combinations of k numbers out
of 1 ... n.
For example,
If n = 4 and k = 2, a solution is:
[
[2,4],
[3,4],
[2,3],
[1,2],
[1,3],
[1,4],
]
"""
class Solution(object):
def combine(self, n, k):
"""
:type n: int
:type k: int
:rtype: List[List[int]]
"""
a = range(1, n + 1)
return self.combine_aux(a, k)
def combine_aux(self, a, k):
if k == 0:
return [[]]
else:
res = []
for i, e in enumerate(a):
rest_comb = self.combine_aux(a[i + 1:], k - 1)
for comb in rest_comb:
comb.insert(0, e)
res += rest_comb
return res
|
#
# PySNMP MIB module TRAPEZE-NETWORKS-REGISTRATION-DEVICES-MIB (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TRAPEZE-NETWORKS-REGISTRATION-DEVICES-MIB
# Produced by pysmi-0.3.4 at Wed May 1 15:27:22 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
OctetString, ObjectIdentifier, Integer = mibBuilder.importSymbols("ASN1", "OctetString", "ObjectIdentifier", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsIntersection, ValueSizeConstraint, ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
Unsigned32, iso, MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Counter32, Counter64, Gauge32, MibIdentifier, IpAddress, TimeTicks, ObjectIdentity, NotificationType, Bits, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "iso", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Counter32", "Counter64", "Gauge32", "MibIdentifier", "IpAddress", "TimeTicks", "ObjectIdentity", "NotificationType", "Bits", "Integer32")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
trpzRegistration, = mibBuilder.importSymbols("TRAPEZE-NETWORKS-ROOT-MIB", "trpzRegistration")
trpzRegistrationDevicesMib = ModuleIdentity((1, 3, 6, 1, 4, 1, 14525, 3, 6))
trpzRegistrationDevicesMib.setRevisions(('2011-08-09 00:32', '2011-03-08 00:22', '2010-12-02 00:11', '2009-12-18 00:10', '2007-11-30 00:01', '2007-08-22 00:00',))
if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0):
if mibBuilder.loadTexts: trpzRegistrationDevicesMib.setRevisionsDescriptions(('v1.4.2: added switch models WLC8, WLC2, WLC800R, WLC2800. (This was first published in 7.3 MR4 release.)', 'v1.3.2: added switch model WLC880R (This will be published in 7.5 release.)', 'v1.2.1: Revision history correction for v1.2: switch model MX-800 was introduced in 7.3 release.', 'v1.2: added switch model MX-800.', 'v1.1: added switch model MX-2800 (This will be published in 7.0 release.)', 'v1.0: initial version, published in 6.2 release',))
if mibBuilder.loadTexts: trpzRegistrationDevicesMib.setLastUpdated('201108090032Z')
if mibBuilder.loadTexts: trpzRegistrationDevicesMib.setOrganization('Trapeze Networks')
if mibBuilder.loadTexts: trpzRegistrationDevicesMib.setContactInfo('Trapeze Networks Technical Support www.trapezenetworks.com US: 866.TRPZ.TAC International: 925.474.2400 [email protected]')
if mibBuilder.loadTexts: trpzRegistrationDevicesMib.setDescription("The MIB module for Trapeze Networks wireless device OID registrations. Copyright 2007-2011 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.")
mobilityExchange = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 1))
mobilityExchange20 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 1))
mobilityExchange8 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 2))
mobilityExchange400 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 3))
mobilityExchangeR2 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 4))
mobilityExchange216 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 6))
mobilityExchange200 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 7))
mobilityExchange2800 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 12))
mobilityExchange800 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 1, 13))
mobilityPoint = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 2))
mobilityPoint101 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 2, 1))
mobilityPoint122 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 2, 2))
mobilityPoint241 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 2, 3))
mobilityPoint252 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 2, 4))
wirelessLANController = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 3))
wirelessLANController880R = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 3, 1))
wirelessLANController8 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 3, 2))
wirelessLANController2 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 3, 3))
wirelessLANController800r = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 3, 4))
wirelessLANController2800 = MibIdentifier((1, 3, 6, 1, 4, 1, 14525, 3, 3, 5))
mibBuilder.exportSymbols("TRAPEZE-NETWORKS-REGISTRATION-DEVICES-MIB", mobilityExchange2800=mobilityExchange2800, mobilityExchange8=mobilityExchange8, wirelessLANController880R=wirelessLANController880R, wirelessLANController800r=wirelessLANController800r, mobilityPoint101=mobilityPoint101, wirelessLANController2800=wirelessLANController2800, mobilityPoint241=mobilityPoint241, mobilityExchange20=mobilityExchange20, wirelessLANController2=wirelessLANController2, mobilityPoint122=mobilityPoint122, mobilityExchange800=mobilityExchange800, mobilityExchange400=mobilityExchange400, mobilityPoint252=mobilityPoint252, mobilityExchange=mobilityExchange, mobilityPoint=mobilityPoint, mobilityExchange216=mobilityExchange216, mobilityExchangeR2=mobilityExchangeR2, PYSNMP_MODULE_ID=trpzRegistrationDevicesMib, mobilityExchange200=mobilityExchange200, wirelessLANController8=wirelessLANController8, wirelessLANController=wirelessLANController, trpzRegistrationDevicesMib=trpzRegistrationDevicesMib)
|
# coding: utf-8
def base_reducer(suffler_results):
# Неплохо бы рекурсивную реализацию
n = len(suffler_results)
if n == 1:
return suffler_results
else:
A_raw = suffler_results[:n/2]
B_raw = suffler_results[n/2:]
A = base_reducer(A_raw)
B = base_reducer(B_raw)
D = base_merge(A, B)
return D
def split_and_merge(C):
n = len(C)
if n == 1:
return C
else:
A_raw = C[:n/2]
B_raw = C[n/2:]
A = split_and_merge(A_raw)
B = split_and_merge(B_raw)
D = merge(A, B)
return D
def merge(A, B):
for at in A[0][0]:
B[0][0][at] += A[0][0][at]
# Суммирование списков
B[0][1][0] += A[0][1][0]
B[0][1][1] += A[0][1][1]
return B
def base_merge(A, B):
""" [{index}, [count_sents, summ_sents_len], url] """
#print A[1], B[1]
#asfdasd
for at in A[0][0]:
try:
B[0][0][at]['N'] += A[0][0][at]['N']
for iat in A[0][0][at]['S']:
B[0][0][at]['S'].append(iat)
# Сжатие
tmp = set(B[0][0][at]['S'])
B[0][0][at]['S'] = list(tmp)
except KeyError as e:
B[0][0][at] = {'S': [], 'N': 0}
B[0][0][at]['N'] = A[0][0][at]['N']
for iat in A[0][0][at]['S']:
B[0][0][at]['S'].append(iat)
# Сжатие
tmp = set(B[0][0][at]['S'])
B[0][0][at]['S'] = list(tmp)
# Сжать списки слов возникшие после работы стеммера
#print B
return B |
class Solution:
def searchMatrix(self, matrix, target):
i = 0
m = len(matrix)
while i < m and matrix[i][0] <= target:
i = i + 1
i = i - 1
return target in matrix[i]
if __name__ == '__main__':
matrix = [[1]]
target = 1
ans = Solution().searchMatrix(matrix, target)
print(ans) |
load("@bazel_tools//tools/build_defs/repo:http.bzl", "http_file")
def _download_binary(ctx):
ctx.download(
url = [
ctx.attr.uri,
],
output = ctx.attr.binary_name,
executable = True,
)
ctx.file(
"BUILD.bazel",
content = 'exports_files(glob(["*"]))',
)
download_binary = repository_rule(
_download_binary,
doc = """Downloads a single binary that is not tarballed.
Example:
download_binary(
name = "jq_macos_amd64",
binary_name = "jq",
uri = "https://github.com/stedolan/jq/releases/download/jq-1.6/jq-osx-amd64",
)
""",
attrs = {
"binary_name": attr.string(
mandatory = True,
),
"uri": attr.string(
mandatory = True,
),
},
)
def _declare_binary(ctx):
out = ctx.actions.declare_file(ctx.attr.binary_name)
ctx.actions.symlink(
output = out,
target_file = ctx.files.binary[0],
)
return DefaultInfo(executable = out)
declare_binary = rule(
_declare_binary,
doc = """Declares a single binary, used as a wrapper around a select() statement
Example:
declare_binary(
name = "jq",
binary = select({
"@platforms//os:linux": "@jq_linux_amd64//:jq",
"@platforms//os:osx": "@jq_macos_amd64//:jq",
}),
binary_name = "jq",
visibility = ["//visibility:public"],
)
""",
attrs = {
"binary_name": attr.string(
mandatory = True,
),
"binary": attr.label(
mandatory = True,
executable = True,
cfg = "exec",
allow_files = True,
),
},
)
|
# Basic type checking: no types necessary
x = 3
x + 'a'
def return_type() -> float:
return 'a'
return_type(9)
def argument_type(x: float):
return
argument_type()
|
def sudoku(board, rows, columns):
return helper(board, 0, 0, columns, rows)
def helper(board, r, c, rows, columns):
def inbound(r, c):
return (0 <= r < rows) and (0 <= c < columns)
# Out of bounds:
# We filled all blank cells and, thus, a valid solution
if not inbound(r, c):
return True
nr, nc = next_pos(r, c, rows, columns)
if board[r][c] != 0:
# This is a pre-filled cell, so skip
# for the next one
return helper(board, nr, nc, rows, columns)
for i in range(1, 10):
if valid_placement(board, r, c, rows, columns, i):
# "i" can be place in the cell without breaking
# the sudoku rules. So, it's a canditate for solution.
# Mark the cell with the value and try to solve
# recursively for the remaining blank cells
board[r][c] = i
if helper(board, nr, nc, rows, columns):
return True
else:
# No solution found for the search branch:
# reset the cell for the future attemps
board[r][c] = 0
return False
def next_pos(r, c, rows, columns):
if c + 1 == columns:
return (r + 1, 0)
else:
return (r, c + 1)
def valid_placement(board, r, c, rows, columns, v):
# Check conflict with row
if v in board[r]:
return False
# Check conflict with column
for i in range(0, rows):
if v == board[i][c]:
return False
# Check conflict with the subgrid
row_offset = r - r % 3
col_offset = c - c % 3
for i in range(3):
for j in range(3):
if board[i + row_offset][j + col_offset] == v:
return False
return True
|
"""
Configuration file
"""
URL = 'localhost'
PORT = 1883
KEEPALIVE = 60
UDP_URL = 'localhost'
UDP_PORT = 1885
|
'''Print multiplication table of given number'''
n=int(input("Enter the no:"))
print("Multiplication table is:")
for i in range(1,11):
print(i*n) |
# CONVERT DB_DATA TO STRING FOR SELF-MESSAGE
def format_to_writeable_db_data(db_data: list) -> str:
writeable_data = ""
for user in db_data:
listed_mangoes = ""
for manga in user['mangoes']:
listed_mangoes += f"{manga}>(u*u)>"
writeable_data = f"{writeable_data}{user['name']}:{listed_mangoes}\n"
return writeable_data
# ADD OR REMOVE SUBSCRIPTION BASED ON MESSAGE
def update(db_data: list, messages: list, conf: dict) -> list:
for message in messages:
if message.subject.lower() == conf['UNSUB_MESSAGE_SUBJECT']:
db_data = _update_unsubscribe(db_data, message)
elif message.subject.lower() == conf['SUB_MESSAGE_SUBJECT']:
db_data = _update_subscribe(db_data, message)
db_data = _remove_users_with_no_subscriptions(db_data)
return db_data
# DONT KEEP TRACK OF USERS WHEN THEY HAVE 0 SUBSCRIPTIONS
def _remove_users_with_no_subscriptions(db_data: list) -> list:
remove_users = []
for user in db_data:
if user['mangoes'] is None or len(user['mangoes']) == 0:
remove_users.append(user)
db_data = [x for x in db_data if x not in remove_users]
return db_data
# ADD NEWLY SUBSCRIBED MANGA TO USER OR NEW USER
def _update_subscribe(db_data: list, message: dict) -> list:
lines = message.body.splitlines()
for user in db_data:
if user['name'] == message.author.name:
for line in lines:
if line not in user['mangoes']:
user['mangoes'].append(line)
return db_data
db_data.append({'name': message.author.name, 'mangoes': lines})
return db_data
# REMOVE NEWLY UNSUBSCRIBED MANGA FROM USER
def _update_unsubscribe(db_data: list, message: dict) -> list:
print("unsubscribing")
for user in db_data:
if user['name'] == message.author.name:
lines = message.body.splitlines()
user['mangoes'] = [x for x in user['mangoes'] if x not in lines ]
break
return db_data
# INIT DB_DATA BASED ON SELF-MESSAGE
def init_db(message: str) -> list:
db_data = []
lines = message.splitlines()
for line in lines:
var_break = line.find(':')
db_data.append({'name': line[:var_break], 'mangoes': line[var_break+1:].split('>(u*u)>')[:-1]})
return db_data
|
class SuperList(list):
def __len__(self):
return 1000
super_list1 = SuperList()
print((len(super_list1)))
super_list1.append(5)
print(super_list1[0])
print(issubclass(SuperList, list)) # true
print(issubclass(list, object)) |
vline = '│'
hline = '─'
tlcorner = '┌'
trcorner = '┐'
blcorner = '└'
brcorner = '┘'
cross = '┼'
tcross = '┬'
lcross = '├'
rcross = '┤'
bcross = '┴'
block = '█'
lblock = '▌'
rblock = '▐'
edge = hline * 4
tile_blank = ' ' * 4
tile_full = ' ' + block*2 + ' '
class Grid:
def __init__(self, x, y):
self.x = x
self.y = y
self.board = [0 for _ in range(x*y)]
self.top_row = tlcorner + (edge + tcross) * (self.x-1) + edge + trcorner
self.mid_row = lcross + (edge + cross) * (self.x-1) + edge + rcross
self.bot_row = blcorner + (edge + bcross) * (self.x-1) + edge + brcorner
self.hold_array = list()
def _get_pos(self, x, y):
return y * self.y + x
def get_tile(self, x, y):
if self.board[self._get_pos(x, y)]:
return tile_full
return tile_blank
def flip_tile(self, x, y):
self.board[self._get_pos(x, y)] = 1 - self.board[self._get_pos(x, y)]
def array(self, x, y, piece):
for i in self.hold_array:
self.board[i] = 0
self.hold_array = list()
for i in range(1, 26):
if piece[i-1]:
self.hold_array.append(self._get_pos(x, y))
if i % 5 == 0:
y += 1
x -= 4
else:
x += 1
for i in self.hold_array:
self.board[i] = 1
#def set_array(self, array):
# for i in array:
# self.board[i] = 1
def display(self):
# top
print(self.top_row)
# mid
for y in range(self.y):
tiles = [self.get_tile(x, y) for x in range(self.x)]
print(vline + vline.join(tiles) + vline)
if y != self.y-1:
print(self.mid_row)
# bot
print(self.bot_row)
|
def reverse(SA):
reverse = [0] * len(SA)
for i in range(len(SA)):
reverse[SA[i] - 1] = i + 1
return reverse
def prefix_doubling(text, n):
'''Computes suffix array using Karp-Miller-Rosenberg algorithm'''
text += '$'
mapping = {v: i + 1 for i, v in enumerate(sorted(set(text[1:])))}
R, k = [mapping[v] for v in text[1:]], 1
while k < 2 * n:
pairs = [(R[i], R[i + k] if i + k < len(R) else 0) for i in range(len(R))]
mapping = {v: i + 1 for i, v in enumerate(sorted(set(pairs)))}
R, k = [mapping[pair] for pair in pairs], 2 * k
return reverse(R)
|
N, M = map(int, input().split())
case = [i for i in range(1, N+1)]
disk = []
for _ in range(M):
disk.append(int(input()))
now = 0
for d in disk:
if d == now:
continue
i = case.index(d)
tmp = case[i]
case[i] = now
now = tmp
for c in case:
print(c)
|
def maximum():
A = input('Enter the 1st number:')
B = input('Enter the 2nd number:')
if A > B:
print("%d The highest num than %d"%(A,B))
else:
print('The highest num is:' ,B)
print("Optised max",max(A,B))
def minimum():
A1 = input('Enter the 1st number:')
B1 = input('Enter the 2nd number:')
C1 = input('Enter the 3rd number:')
print("Optimised min " ,min(A1,B1,C1))
if(A1<B1) and (A1<C1):
print("Smallest number is",A1)
else :
if(B1 <C1):
print("Smallest number is ",B1)
else :
print("Smallest number is ", C1)
def main():
print("Enter your choice")
print("1.Max of 2 numbers")
print("2.Min of 3 numbers")
choice=input("Enter your choice")
if(choice == 1):
maximum()
else :
minimum()
main()
|
position = list(input())
xPos = int(position[1])
yPos = int(ord(position[0])) - int(ord('a')) + 1
result = 0
# x 2칸 이동
if xPos + 2 > 0 and yPos - 1 > 0:
result += 1
if xPos + 2 > 0 and yPos + 1 > 0:
result += 1
if xPos - 2 > 0 and yPos - 1 > 0:
result += 1
if xPos - 2 > 0 and yPos + 1 > 0:
result += 1
# y 2칸 이동
if xPos + 1 > 0 and yPos - 2 > 0:
result += 1
if xPos + 1 > 0 and yPos + 2 > 0:
result += 1
if xPos - 1 > 0 and yPos - 2 > 0:
result += 1
if xPos - 1 > 0 and yPos + 2 > 0:
result += 1
print(result) |
"""
# Sample code to perform I/O:
name = input() # Reading input from STDIN
print('Hi, %s.' % name) # Writing output to STDOUT
# Warning: Printing unwanted or ill-formatted data to output will cause the test cases to fail
"""
# Write your code here
n = int(input())
shelters = [0] * (n + 1)
for _ in range(n - 1):
x, y = map(int, input().strip().split())
shelters[x] += 1
shelters[y] += 1
max_seen = max(shelters)
good_shelters = [i for i, v in enumerate(shelters) if i != 0 and v == max_seen]
print(len(good_shelters))
print(' '.join(map(str, good_shelters)))
|
__author__ = 'varx'
class BaseRenderer(object):
"""
Base renderer that all renders should inherit from
"""
def can_render(self, path):
raise NotImplementedError()
def render(self, path):
raise NotImplementedError() |
# -*- coding: utf-8 -*-
# According to https://tools.ietf.org/html/rfc2616#section-7.1
_ENTITY_HEADERS = frozenset(
[
"allow",
"content-encoding",
"content-language",
"content-length",
"content-location",
"content-md5",
"content-range",
"content-type",
"expires",
"last-modified",
"extension-header",
]
)
# According to https://tools.ietf.org/html/rfc2616#section-13.5.1
_HOP_BY_HOP_HEADERS = frozenset(
[
"connection",
"keep-alive",
"proxy-authenticate",
"proxy-authorization",
"te",
"trailers",
"transfer-encoding",
"upgrade",
]
)
def is_entity_header(header):
"""Checks if the given header is an Entity Header"""
return header.lower() in _ENTITY_HEADERS
def is_hop_by_hop_header(header):
"""Checks if the given header is a Hop By Hop header"""
return header.lower() in _HOP_BY_HOP_HEADERS
def remove_entity_headers(headers, allowed=("content-location", "expires")):
"""去掉实体头部
Removes all the entity headers present in the headers given.
According to RFC 2616 Section 10.3.5,
Content-Location and Expires are allowed as for the
"strong cache validator".
https://tools.ietf.org/html/rfc2616#section-10.3.5
returns the headers without the entity headers
"""
allowed = set([h.lower() for h in allowed])
headers = {
header: value
for header, value in headers.items()
if not is_entity_header(header) or header.lower() in allowed
}
return headers
|
# 2020 @Cmlohr
MENU = {
"espresso": {
"ingredients": {
"water": 50,
"coffee": 18,
},
"cost": 1.5,
},
"latte": {
"ingredients": {
"water": 200,
"milk": 150,
"coffee": 24,
},
"cost": 2.5,
},
"cappuccino": {
"ingredients": {
"water": 250,
"milk": 100,
"coffee": 24,
},
"cost": 3.0,
}
}
resources = {
"water": 300,
"milk": 200,
"coffee": 100,
}
def menu():
print("Welcome to the Coffee Kiosk")
print(" MENU")
print("---------------------------")
print("Espresso\nLatte\nCappuccino")
print("---------------------------")
print(" type your selection")
def kiosk_help():
print("Instructions")
print("Type your order, eg: espresso")
print("Other kiosk commands:")
print("---------------------------")
print("'report' displays a report of\nthe stock level and bank")
print("'off' turns off machine")
print("---------------------------")
def kiosk():
print("---------------------------")
nickle = 0.05
dime = 0.10
penny = 0.01
quarter = 0.25
wallet = 0.00
bank = 0.00
water_supply = resources.get('water')
milk_supply = resources.get('milk')
coffee_supply = resources.get('coffee')
cont = True
while cont:
# Separating out the values
espr_drink = MENU.get('espresso')
latte_drink = MENU.get('latte')
capp_drink = MENU.get('cappuccino')
# PRICES
price_espr = float(espr_drink.get('cost'))
price_latte = float(latte_drink.get('cost'))
price_capp = float(capp_drink.get('cost'))
# Drink resources requirements
espr_rec = espr_drink.get('ingredients')
latte_rec = latte_drink.get('ingredients')
capp_rec = capp_drink.get('ingredients')
menu()
order = input("What would you like to order?:\n> ").lower()
if order == "help":
kiosk_help()
elif order == "report":
print("----------report-----------")
print(f"Water Level: {water_supply}ml")
print(f"Milk Level: {milk_supply}ml")
print(f"Coffee Level: {coffee_supply}g")
form_bank = "{:.2f}".format(bank)
print(f"Bank: ${form_bank}")
print("---------------------------")
elif order == "espresso":
if espr_rec.get('water') > water_supply:
print("Sorry there isn't enough water.\nPlease contact management.")
print("---------------------------")
kiosk()
if espr_rec.get('coffee') > coffee_supply:
print("Sorry there isn't enough coffee grounds.\nPlease contact management.")
print("---------------------------")
kiosk()
total = 0.00
total += price_espr
water_supply -= espr_rec.get('water')
coffee_supply -= espr_rec.get('coffee')
form_total = "{:.2f}".format(total)
print(f"your total is: {form_total}")
print("Please insert coins:")
q_coin = float(input("How many Quarters?\n> "))
wallet += q_coin * quarter
d_coin = float(input("How many Dimes?\n> "))
wallet += d_coin * dime
n_coin = float(input("How many Nickles?\n> "))
wallet += n_coin * nickle
p_coin = float(input("How many Pennies?\n> "))
wallet += p_coin * penny
if wallet < total:
print("---------------------------")
print("Sorry, that is not enough.\nYour transaction has been\ncanceled and money refunded.")
print("---------------------------")
kiosk()
change = wallet - total
form_change = "{:.2f}".format(change)
bank += total
print(f"Your change is ${form_change}")
print(f"Here is your Espresso.️Enjoy!")
print("Thank you for shopping with us!")
print("---------------------------")
elif order == "latte":
if latte_rec.get('water') > water_supply:
print("Sorry there isn't enough water.\nPlease contact management.")
kiosk()
if latte_rec.get('coffee') > coffee_supply:
print("Sorry there isn't enough coffee grounds.\nPlease contact management.")
kiosk()
if latte_rec.get('milk') > milk_supply:
print("Sorry there isn't enough milk.\nPlease contact management.")
kiosk()
total = 0.00
total += price_latte
water_supply = water_supply - latte_rec.get('water')
coffee_supply = coffee_supply - latte_rec.get('coffee')
milk_supply = milk_supply - latte_rec.get('milk')
form_total = "{:.2f}".format(total)
print(f"your total is: {form_total}")
print("Please insert coins:")
q_coin = float(input("How many Quarters?\n> "))
wallet += q_coin * quarter
d_coin = float(input("How many Dimes?\n> "))
wallet += d_coin * dime
n_coin = float(input("How many Nickles?\n> "))
wallet += n_coin * nickle
p_coin = float(input("How many Pennies?\n> "))
wallet += p_coin * penny
if wallet < total:
print("---------------------------")
print("Sorry, that is not enough.\nYour transaction has been\ncanceled and money refunded.")
kiosk()
change = wallet - total
form_change = "{:.2f}".format(change)
bank += total
print(f"Your change is ${form_change}")
print(f"Here is your Latte.️Enjoy!")
print("Thank you for shopping with us!")
elif order == "cappuccino":
if capp_rec.get('water') > water_supply:
print("Sorry there isn't enough water.\nPlease contact management.")
kiosk()
if capp_rec.get('coffee') > coffee_supply:
print("Sorry there isn't enough coffee grounds.\nPlease contact management.")
kiosk()
if capp_rec.get('milk') > milk_supply:
print("Sorry there isn't enough milk.\nPlease contact management.")
kiosk()
total = 0
total += price_capp
water_supply -= capp_rec.get('water')
coffee_supply -= capp_rec.get('coffee')
milk_supply -= capp_rec.get('milk')
form_total = "{:.2f}".format(total)
print(f"your total is: ${form_total}")
print("Please insert coins:")
q_coin = float(input("How many Quarters?\n> "))
wallet += q_coin * quarter
d_coin = float(input("How many Dimes?\n> "))
wallet += d_coin * dime
n_coin = float(input("How many Nickles?\n> "))
wallet += n_coin * nickle
p_coin = float(input("How many Pennies?\n> "))
wallet += p_coin * penny
if wallet < total:
print("---------------------------")
print("Sorry, that is not enough.\nYour transaction has been\ncanceled and money refunded.")
kiosk()
change = wallet - total
form_change = "{:.2f}".format(change)
bank += total
print(f"Your change is ${form_change}")
print(f"Here is your Cappuccino. Enjoy!")
print("Thank you for shopping with us!")
elif order == "off":
cont = False
else:
print("Invalid Input")
kiosk()
kiosk()
|
stores = []
command = input()
while command != 'END':
tokens = command.split('->')
store_name = tokens[1]
if tokens[0] == 'Add':
items = tokens[2].split(',')
if len([x for x in stores if x[0] == store_name]) > 0:
idx = stores.index([x for x in stores if x[0] == store_name][0])
stores[idx][1].extend(items)
else:
stores.append([store_name, items])
elif tokens[0] == 'Remove':
if len([x for x in stores if x[0] == store_name]) > 0:
idx = stores.index([x for x in stores if x[0] == store_name][0])
del stores[idx]
command = input()
sorted_stores = sorted(stores, key=lambda x: (len(x[1]), x[0]), reverse=True)
print('Stores list:')
for store in sorted_stores:
store_name = store[0]
items = store[1]
print(store_name)
for item in items:
print(f'<<{item}>>')
|
# This is a great place to put your bot's version number.
__version__ = "0.1.0"
# You'll want to change this.
GUILD_ID = 845688627265536010
|
#dictionary and for statements with values method
linguagens = {
'lea': 'python',
'sara': 'c',
'eddie': 'java',
'phil': 'python',
}
for linguagem in linguagens.values(): #values method shows us the values of a dictionary
print(linguagem.title()) |
class EmitterTypeError(Exception):
pass
class EmitterValidationError(Exception):
pass
|
class BSTNode():
def __init__(self, Key, Value=None):
self.key = Key
self.Value = Value
self.left = None
self.right = None
self.parent = None
@staticmethod
def remove_none(lst):
return [x for x in lst if x is not None]
def check_BSTNode(self):
if self is None:
return True, None, None
is_BSTNode_l, max_l, min_l = BSTNode.check_BSTNode(self.left)
is_BSTNode_r, max_r, min_r = BSTNode.check_BSTNode(self.right)
is_BSTNode = (is_BSTNode_l and is_BSTNode_r and (max_l is None or max_l < self.key) and (
min_l is None or min_r > self.key))
min_key = min(BSTNode.remove_none([min_l, self.key, min_r]))
max_key = max(BSTNode.remove_none([max_l, self.key, max_r]))
return is_BSTNode, max_key, min_key
def display(self, lvl=0):
if self is None:
return
if self.right is None and self.left is None:
print("\t" * lvl + str(self.key))
return
BSTNode.display(self.right, lvl + 1)
print("\t" * lvl + str(self.key))
BSTNode.display(self.left, lvl + 1)
@staticmethod
def parse(data):
if isinstance(data, tuple) and len(data) == 3:
node = BSTNode(data[1])
node.left = BSTNode.parse(data[0])
node.right = BSTNode.parse(data[2])
node.left.parent = node
node.right.parent = node
elif data is None:
node = None
else:
node = BSTNode(data)
return node
def insert(self, key, value=None):
if self is None:
self = BSTNode(key, value)
elif self.key > key:
self.left = BSTNode.insert(self.left, key, value)
self.left.parent = self
elif self.key < key:
self.right = BSTNode.insert(self.right, key, value)
self.right.parent = self
return self
def find(self, key):
if self is None:
return False
elif self.key == key:
return True
elif self.key<key:
return BSTNode.find(self.right, key)
else:
return BSTNode.find(self.left, key)
if __name__ == "__main__":
print(f"Input Range :")
k = BSTNode.insert(None, 7)
k.insert(1)
k.insert(9)
k.insert(4)
k.insert(10)
k.insert(8)
k.display()
print(f"\n\n Find- { k.find(0) }")
|
LSM9DS1_MAG_ADDRESS = 0x1C #Would be 0x1E if SDO_M is HIGH
LSM9DS1_ACC_ADDRESS = 0x6A
LSM9DS1_GYR_ADDRESS = 0x6A #Would be 0x6B if SDO_AG is HIGH
#/////////////////////////////////////////
#// LSM9DS1 Accel/Gyro (XL/G) Registers //
#/////////////////////////////////////////
LSM9DS1_ACT_THS = 0x04
LSM9DS1_ACT_DUR = 0x05
LSM9DS1_INT_GEN_CFG_XL = 0x06
LSM9DS1_INT_GEN_THS_X_XL = 0x07
LSM9DS1_INT_GEN_THS_Y_XL = 0x08
LSM9DS1_INT_GEN_THS_Z_XL = 0x09
LSM9DS1_INT_GEN_DUR_XL = 0x0A
LSM9DS1_REFERENCE_G = 0x0B
LSM9DS1_INT1_CTRL = 0x0C
LSM9DS1_INT2_CTRL = 0x0D
LSM9DS1_WHO_AM_I_XG = 0x0F
LSM9DS1_CTRL_REG1_G = 0x10
LSM9DS1_CTRL_REG2_G = 0x11
LSM9DS1_CTRL_REG3_G = 0x12
LSM9DS1_ORIENT_CFG_G = 0x13
LSM9DS1_INT_GEN_SRC_G = 0x14
LSM9DS1_OUT_TEMP_L = 0x15
LSM9DS1_OUT_TEMP_H = 0x16
LSM9DS1_STATUS_REG_0 = 0x17
LSM9DS1_OUT_X_L_G = 0x18
LSM9DS1_OUT_X_H_G = 0x19
LSM9DS1_OUT_Y_L_G = 0x1A
LSM9DS1_OUT_Y_H_G = 0x1B
LSM9DS1_OUT_Z_L_G = 0x1C
LSM9DS1_OUT_Z_H_G = 0x1D
LSM9DS1_CTRL_REG4 = 0x1E
LSM9DS1_CTRL_REG5_XL = 0x1F
LSM9DS1_CTRL_REG6_XL = 0x20
LSM9DS1_CTRL_REG7_XL = 0x21
LSM9DS1_CTRL_REG8 = 0x22
LSM9DS1_CTRL_REG9 = 0x23
LSM9DS1_CTRL_REG10 = 0x24
LSM9DS1_INT_GEN_SRC_XL = 0x26
LSM9DS1_STATUS_REG_1 = 0x27
LSM9DS1_OUT_X_L_XL = 0x28
LSM9DS1_OUT_X_H_XL = 0x29
LSM9DS1_OUT_Y_L_XL = 0x2A
LSM9DS1_OUT_Y_H_XL = 0x2B
LSM9DS1_OUT_Z_L_XL = 0x2C
LSM9DS1_OUT_Z_H_XL = 0x2D
LSM9DS1_FIFO_CTRL = 0x2E
LSM9DS1_FIFO_SRC = 0x2F
LSM9DS1_INT_GEN_CFG_G = 0x30
LSM9DS1_INT_GEN_THS_XH_G = 0x31
LSM9DS1_INT_GEN_THS_XL_G = 0x32
LSM9DS1_INT_GEN_THS_YH_G = 0x33
LSM9DS1_INT_GEN_THS_YL_G = 0x34
LSM9DS1_INT_GEN_THS_ZH_G = 0x35
LSM9DS1_INT_GEN_THS_ZL_G = 0x36
LSM9DS1_INT_GEN_DUR_G = 0x37
#///////////////////////////////
#// LSM9DS1 Magneto Registers //
#///////////////////////////////
LSM9DS1_OFFSET_X_REG_L_M = 0x05
LSM9DS1_OFFSET_X_REG_H_M = 0x06
LSM9DS1_OFFSET_Y_REG_L_M = 0x07
LSM9DS1_OFFSET_Y_REG_H_M = 0x08
LSM9DS1_OFFSET_Z_REG_L_M = 0x09
LSM9DS1_OFFSET_Z_REG_H_M = 0x0A
LSM9DS1_WHO_AM_I_M = 0x0F
LSM9DS1_CTRL_REG1_M = 0x20
LSM9DS1_CTRL_REG2_M = 0x21
LSM9DS1_CTRL_REG3_M = 0x22
LSM9DS1_CTRL_REG4_M = 0x23
LSM9DS1_CTRL_REG5_M = 0x24
LSM9DS1_STATUS_REG_M = 0x27
LSM9DS1_OUT_X_L_M = 0x28
LSM9DS1_OUT_X_H_M = 0x29
LSM9DS1_OUT_Y_L_M = 0x2A
LSM9DS1_OUT_Y_H_M = 0x2B
LSM9DS1_OUT_Z_L_M = 0x2C
LSM9DS1_OUT_Z_H_M = 0x2D
LSM9DS1_INT_CFG_M = 0x30
LSM9DS1_INT_SRC_M = 0x30
LSM9DS1_INT_THS_L_M = 0x32
LSM9DS1_INT_THS_H_M = 0x33
#////////////////////////////////
#// LSM9DS1 WHO_AM_I Responses //
#////////////////////////////////
LSM9DS1_WHO_AM_I_AG_RSP = 0x68
LSM9DS1_WHO_AM_I_M_RSP = 0x3D
|
def handle(event, context):
"""handle a request to the function
Args:
event (dict): request params
context (dict): function call metadata
"""
return {
"message": "Hello From Python3 runtime on Serverless Framework and Scaleway Functions"
}
|
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Mon Aug 10 15:19:36 2020
@author: krishan
"""
class Book:
def __init__(self, pages):
self.pages = pages
def __add__(self, other):
total = self.pages + other.pages
b = Book(total)
return b
def __mul__(self, other):
total = self.pages * other.pages
b = Book(total)
return b
def __str__(self):
return str(self.pages)
b1 = Book(100)
b2 = Book(200)
b3 = Book(300)
b4 = Book(400)
b5 = Book(500)
print(b1 + b2 + b3 + b4 + b5)
print(b1 * b2 + b3 + b4 * b5)
|
"""
字符串抽取程序
抽取类型:
- 抽取单个,抽取全部
"""
"""
string_util 主要处理 比较短的文本,长文本的处理交给text_util
对字符串的一些常见的判断.
1. is_blank 为None或者strip以后为0
2. is_empty 为None或者长度为0
3. has?
4. 返回字符串特点
提取请求url中的中文内容.
"""
def is_blank(_str):
"""
判断是否为空(除去空格换行)
:param _str:
:return:
"""
return _str is None or len(_str.strip()) == 0
def is_empty(_str):
"""
判断是否为空(包含空格字符)
:param _str:
:return:
"""
return _str is None or len(_str) == 0
def is_valid_string(_str):
return isinstance(_str, str) and _str.strip() != ''
def is_equal(actual, expected):
'''
:param _str:
:return:
'''
return actual == expected
def approximate_equal(actual, expected, min_length=5, accepted_rate=0.8):
"""
利用字符串近似算法进行近似比较
:param actual:
:param expected:
:param min_length:
:param accepted_rate:
:return:
"""
raise NotImplementedError()
HALF2FULL = dict((i, i + 0xFEE0) for i in range(0x21, 0x7F))
HALF2FULL[0x20] = 0x3000
FULL2HALF = dict((i + 0xFEE0, i) for i in range(0x21, 0x7F))
FULL2HALF[0x3000] = 0x20
def turn_full_to_half_width(_str):
'''
Convert all ASCII characters to the full-width counterpart.
'''
return str(_str).translate(FULL2HALF)
def turn_half_to_full_width(_str):
'''
Convert full-width characters to ASCII counterpart
'''
return str(_str).translate(HALF2FULL)
def LevenshteinDistance(s, t):
'''字符串相似度算法(Levenshtein Distance算法)
一个字符串可以通过增加一个字符,删除一个字符,替换一个字符得到另外一个
字符串,假设,我们把从字符串A转换成字符串B,前面3种操作所执行的最少
次数称为AB相似度
这算法是由俄国科学家Levenshtein提出的。
Step Description
1 Set n to be the length of s.
Set m to be the length of t.
If n = 0, return m and exit.
If m = 0, return n and exit.
Construct a matrix containing 0..m rows and 0..n columns.
2 Initialize the first row to 0..n.
Initialize the first column to 0..m.
3 Examine each character of s (i from 1 to n).
4 Examine each character of t (j from 1 to m).
5 If s[i] equals t[j], the cost is 0.
If s[i] doesn't equal t[j], the cost is 1.
6 Set cell d[i,j] of the matrix equal to the minimum of:
a. The cell immediately above plus 1: d[i-1,j] + 1.
b. The cell immediately to the left plus 1: d[i,j-1] + 1.
c. The cell diagonally above and to the left plus the cost:
d[i-1,j-1] + cost.
7 After the iteration steps (3, 4, 5, 6) are complete, the distance is
found in cell d[n,m]. '''
m, n = len(s), len(t)
if not (m and n):
return m or n
# 构造矩阵
matrix = [[0 for i in range(n + 1)] for j in range(m + 1)]
matrix[0] = list(range(n + 1))
for i in range(m + 1):
matrix[i][0] = i
for i in range(m):
for j in range(n):
cost = int(s[i] != t[j])
# 因为 Python 的字符索引从 0 开始
matrix[i + 1][j + 1] = min(
matrix[i][j + 1] + 1, # a.
matrix[i + 1][j] + 1, # b.
matrix[i][j] + cost # c.
)
return matrix[m][n]
valid_similarity = LevenshteinDistance
|
n = int(input('digite um numero: '))
n2 = int(input('digite um numero: '))
def soma ():
s = n + n2
print(soma)
|
# noinspection PyUnusedLocal
# skus = unicode string
def checkout(skus):
sd = dict()
for sku in skus:
if sku in 'ABCDEFGHIJKLMNOPQRSTUVWXYZ':
if sku in sd:
sd[sku] += 1
else:
sd[sku] = 1
else:
return -1
na = sd.get('A', 0)
p = int(na/5) * 200
na %= 5
p += int(na/3) * 130 + (na%3) * 50
p += 20 * sd.get('C', 0)
p += 15 * sd.get('D', 0)
ne = sd.get('E', 0)
p += 40 * ne
nb = max(0, sd.get('B', 0)-int(ne/2))
p += int(nb / 2) * 45 + (nb % 2) * 30
ff = int(sd.get('F', 0) / 3)
nf = max(0, sd.get('F', 0)-ff)
p += 10 * nf
p += 20 * sd.get('G', 0)
nh = sd.get('H', 0)
p += int(nh/10) * 80
nh %= 10
p += int(nh/5) * 45
nh %= 5
p += nh * 10
p += sd.get('I', 0) * 35
p += sd.get('J', 0) * 60
nk = sd.get('K', 0)
p += int(nk/2) * 120
nk %= 2
p += nk * 70
p += sd.get('L', 0) * 90
nn = sd.get('N', 0)
p += 40 * nn
nm = max(0, sd.get('M', 0)-int(nn/3))
p += nm * 15
p += sd.get('O', 0) * 10
np = sd.get('P', 0)
p += int(np/5) * 200
np %= 5
p += np * 50
nr = sd.get('R', 0)
p += nr * 50
fq = int(nr/3)
nq = max(0, sd.get('Q', 0)-fq)
p += int(nq/3) * 80
p += (nq%3) * 30
fu = int(sd.get('U', 0) / 4)
nu = max(0, sd.get('U', 0)-fu)
p += 40 * nu
nv = sd.get('V', 0)
p += int(nv/3) * 130
nv %= 3
p += int(nv/2) * 90
nv %= 2
p += nv * 50
p += 20 * sd.get('W', 0)
ns = sd.get('S', 0)
nt = sd.get('T', 0)
nx = sd.get('X', 0)
ny = sd.get('Y', 0)
nz = sd.get('Z', 0)
# it was cut highest priced first then others (ZSTYX)
# actually I could not get the exact criteria from the specs :(
ngrp = ns + nt + nx + ny + nz
p += int(ngrp/3) * 45
fgrp = ngrp % 3
while fgrp > 0:
if nx > 0:
p += 17
nx -= 1
elif ny > 0:
p += 20
ny -= 1
elif nt > 0:
p += 20
nt -= 1
elif ns > 0:
p += 20
ns -= 1
elif nz > 0:
p += 21
nz -= 1
fgrp -= 1
return int(p)
|
def test_upgrade_atac_alignment_enrichment_quality_metric_1_2(
upgrader, atac_alignment_enrichment_quality_metric_1
):
value = upgrader.upgrade(
'atac_alignment_enrichment_quality_metric',
atac_alignment_enrichment_quality_metric_1,
current_version='1',
target_version='2',
)
assert value['schema_version'] == '2'
assert 'fri_blacklist' not in value
assert value['fri_exclusion_list'] == 0.0013046877081284722
|
PREVIEW_CHOICES = [
('slider', 'Slider'),
('pre-order', 'Pre-order'),
('new', 'New'),
('offer', 'Offer'),
('hidden', 'Hidden'),
]
CATEGORY_CHOICES = [
('accesory', 'Accesory'),
('bottom', 'Bottoms'),
('hoodie', 'Hoodies'),
('outerwear', 'Outerwears'),
('sneaker', 'Sneakers'),
('t-shirt', 'T-Shirts'),
] |
# SPDX-License-Identifier: BSD-2-Clause
"""osdk-manager about details.
Manage osdk and opm binary installation, and help to scaffold, release, and
version Operator SDK-based Kubernetes operators.
This file contains some basic variables used for setup.
"""
__title__ = "osdk-manager"
__name__ = __title__
__summary__ = "A script for managing Operator SDK-based operators."
__uri__ = "https://github.com/jharmison-redhat/osdk-manager"
__version__ = "0.3.0"
__release__ = "1"
__status__ = "Development"
__author__ = "James Harmison"
__email__ = "[email protected]"
__license__ = "BSD-2-Clause"
__copyright__ = "2020 %s" % __author__
__requires__ = [
'requests',
'click',
'lastversion',
'python-gnupg',
'PyYAML'
]
|
print("Let's practice everything")
print('You\'d need to know \'bout escapes with \\ that do:')
print('\n newlines and \t tabs.')
poem="""
\tThe lovely world
with logic so firmly planted
cannnot discern \n the needs of love
nor comprehend passion from intuition
and requires an explanation
\n\t\twhere there is none.
"""
print("---------------")
print(poem)
print("---------------")
five=10-2+3-6
print(f"This should be five:{five}")
def secret_formula(started):
jelly_beans=started*500
jars=jelly_beans / 1000
crates=jars /100
return jelly_beans,jars,crates
start_point=10000
beans,jars,crates=secret_formula(start_point)
print("With a starting point of :{}".format(start_point))
print(f"We'd have {beans} beans,{jars} jars, and {crates}crates.")
start_point=start_point /10
print("We can also do that this way:")
formula=secret_formula(start_point)
print("We'd have {} beans,{} jars,{} crates.".format(*formula))
|
class Estereo:
def __init__(self, marca) -> None:
self.marca = marca
self.estado = 'apagado'
|
list = [2, 4, 6, 8]
sum = 0
for num in list:
sum = sum + num
print("The sum is:", sum)
|
class RDBMSHost:
def __init__(self, host: str, port: int, db_name: str, db_schema: str, db_user: str, db_password: str):
self.host: str = host
self.port: int = port
self.db_name: str = db_name
self.db_schema: str = db_schema
self.db_user: str = db_user
self.db_password: str = db_password
|
grid = [input() for _ in range(323)]
width = len(grid[0])
height = len(grid)
trees = 0
i, j = 0, 0
while (i := i + 1) < height:
j = (j + 3) % width
if grid[i][j] == '#':
trees += 1
print(trees)
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.