content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
class Twitter(): Consumer_Key = '' Consumer_Secret = '' Access_Token = '' Access_Token_Secret = '' CONNECTION_STRING = "sqlite:///Twitter.db" LANG = ["en"]
class Twitter: consumer__key = '' consumer__secret = '' access__token = '' access__token__secret = '' connection_string = 'sqlite:///Twitter.db' lang = ['en']
feature_types = { # features with continuous numeric values "continuous": [ "number_diagnoses", "time_in_hospital", "number_inpatient", "number_emergency", "num_procedures", "num_medications", "num_lab_procedures"], # features which describe buckets of a continuous-valued feature "range": ["age", "weight"], # features which take one of two or more non-continuous values "categorical": [ "diabetesMed", "chlorpropamide", "repaglinide", "medical_specialty", "rosiglitazone", "miglitol", "glipizide", "acetohexamide", "admission_source_id", "glipizide-metformin", "glyburide", "metformin", "tolbutamide", "pioglitazone", "glimepiride-pioglitazone", "glimepiride", "glyburide-metformin", "A1Cresult", "troglitazone", "metformin-rosiglitazone", "max_glu_serum", "acarbose", "metformin-pioglitazone", "payer_code", "discharge_disposition_id", "change", "gender", "nateglinide", "tolazamide", "race", "number_outpatient", "insulin", "admission_type_id", "diag_1", "diag_2", "diag_3"], # features which are either unique or constant for all samples "constant": ["patient_nbr", "encounter_id", "examide", "citoglipton"]}
feature_types = {'continuous': ['number_diagnoses', 'time_in_hospital', 'number_inpatient', 'number_emergency', 'num_procedures', 'num_medications', 'num_lab_procedures'], 'range': ['age', 'weight'], 'categorical': ['diabetesMed', 'chlorpropamide', 'repaglinide', 'medical_specialty', 'rosiglitazone', 'miglitol', 'glipizide', 'acetohexamide', 'admission_source_id', 'glipizide-metformin', 'glyburide', 'metformin', 'tolbutamide', 'pioglitazone', 'glimepiride-pioglitazone', 'glimepiride', 'glyburide-metformin', 'A1Cresult', 'troglitazone', 'metformin-rosiglitazone', 'max_glu_serum', 'acarbose', 'metformin-pioglitazone', 'payer_code', 'discharge_disposition_id', 'change', 'gender', 'nateglinide', 'tolazamide', 'race', 'number_outpatient', 'insulin', 'admission_type_id', 'diag_1', 'diag_2', 'diag_3'], 'constant': ['patient_nbr', 'encounter_id', 'examide', 'citoglipton']}
while True: try: input() alice = set(input().split()) beatriz = set(input().split()) repeticoes = [1 for carta in alice if carta in beatriz] print(min([len(alice), len(beatriz)]) - len(repeticoes)) except EOFError: break
while True: try: input() alice = set(input().split()) beatriz = set(input().split()) repeticoes = [1 for carta in alice if carta in beatriz] print(min([len(alice), len(beatriz)]) - len(repeticoes)) except EOFError: break
def square(a): return(a*a) # a=int(input("enter the number")) # square(a) s=[2,3,4,5,6,7,8,9,10] print(list(map(square,s)))
def square(a): return a * a s = [2, 3, 4, 5, 6, 7, 8, 9, 10] print(list(map(square, s)))
features = [ "mtarg1", "mtarg2", "mtarg3", "roll", "pitch", "LACCX", "LACCY", "LACCZ", "GYROX", "GYROY", "SC1I", "SC2I", "SC3I", "BT1I", "BT2I", "vout", "iout", "cpuUsage", ] fault_features = ["fault", "fault_type", "fault_value", "fault_duration"]
features = ['mtarg1', 'mtarg2', 'mtarg3', 'roll', 'pitch', 'LACCX', 'LACCY', 'LACCZ', 'GYROX', 'GYROY', 'SC1I', 'SC2I', 'SC3I', 'BT1I', 'BT2I', 'vout', 'iout', 'cpuUsage'] fault_features = ['fault', 'fault_type', 'fault_value', 'fault_duration']
maxsimal = 0 while True: a = int(input("Masukan bilangan = ")) if maxsimal < a: maxsimal = a if a == 0: break print("Bilangan Terbesarnya Adalah = ", maxsimal)
maxsimal = 0 while True: a = int(input('Masukan bilangan = ')) if maxsimal < a: maxsimal = a if a == 0: break print('Bilangan Terbesarnya Adalah = ', maxsimal)
class Holding(object): def __init__(self, name, symbol, sector, market_val_percent, market_value, number_of_shares): self.name = name self.symbol = symbol self.sector = sector self.market_val_percent = market_val_percent self.market_value = market_value self.number_of_shares = number_of_shares def __eq__(self, other): return ( self.__class__ == other.__class__ and self.name == other.name and self.symbol == other.symbol and self.sector == other.sector and self.market_val_percent == other.market_val_percent and self.market_value == other.market_value and self.number_of_shares == other.number_of_shares )
class Holding(object): def __init__(self, name, symbol, sector, market_val_percent, market_value, number_of_shares): self.name = name self.symbol = symbol self.sector = sector self.market_val_percent = market_val_percent self.market_value = market_value self.number_of_shares = number_of_shares def __eq__(self, other): return self.__class__ == other.__class__ and self.name == other.name and (self.symbol == other.symbol) and (self.sector == other.sector) and (self.market_val_percent == other.market_val_percent) and (self.market_value == other.market_value) and (self.number_of_shares == other.number_of_shares)
# rps data for the rock-paper-scissors portion of the red-green game # to be imported by rg.cgi # this file represents the "host throw" for each numbered round rps_data = { 0: "rock", 1: "rock", 2: "scissors", 3: "paper", 4: "paper", 5: "scissors", 6: "rock", 7: "scissors", 8: "paper", 9: "paper", 10: "scissors", 11: "rock", 12: "paper", 13: "paper", 14: "rock", 15: "scissors", 16: "scissors", 17: "scissors", 18: "rock", 19: "scissors", 20: "paper", 21: "rock", 22: "paper", 23: "scissors", 24: "rock", 25: "scissors", 26: "rock", 27: "rock", 28: "paper", 29: "paper", 30: "rock", 31: "paper", 32: "paper", 33: "scissors", 34: "rock", 35: "rock", 36: "scissors", 37: "rock", 38: "rock", 39: "paper", 40: "rock", 41: "rock", 42: "paper", 43: "paper", 44: "paper", 45: "paper", 46: "scissors", 47: "rock", 48: "scissors", 49: "scissors", }
rps_data = {0: 'rock', 1: 'rock', 2: 'scissors', 3: 'paper', 4: 'paper', 5: 'scissors', 6: 'rock', 7: 'scissors', 8: 'paper', 9: 'paper', 10: 'scissors', 11: 'rock', 12: 'paper', 13: 'paper', 14: 'rock', 15: 'scissors', 16: 'scissors', 17: 'scissors', 18: 'rock', 19: 'scissors', 20: 'paper', 21: 'rock', 22: 'paper', 23: 'scissors', 24: 'rock', 25: 'scissors', 26: 'rock', 27: 'rock', 28: 'paper', 29: 'paper', 30: 'rock', 31: 'paper', 32: 'paper', 33: 'scissors', 34: 'rock', 35: 'rock', 36: 'scissors', 37: 'rock', 38: 'rock', 39: 'paper', 40: 'rock', 41: 'rock', 42: 'paper', 43: 'paper', 44: 'paper', 45: 'paper', 46: 'scissors', 47: 'rock', 48: 'scissors', 49: 'scissors'}
user_info = {} while True: print("\n\t\t\tUnits:metric") name = str(input("Enter your name: ")) height = float(input("Input your height in meters(For instance:1.89): ")) weight = float(input("Input your weight in kilogram(For instance:69): ")) age = int(input("Input your age: ")) sex = str(input("Input your sex: ")) bmi = (weight/(height*height)) print("Your body mass index (or BMI) is: ", round(bmi, 2)) if sex == 'male': if bmi < 15: print("\n\t\t\tYour BMI is", round(bmi, 2), "Very severely underweight:\ \nIt is important to know whether a serious disease \ or other conditions have caused the emaciation. Whatever \ the case, medical help is advisable.\n\t\t\tPossible causes: \ \nUndernourishment \ \nMaldigestion \ \nEating disorders: anorexia, bulimia \ \nSlimming caused by a disease") elif 15 < bmi < 16: print("\n\t\t\tYour BMI is", round(bmi, 2), "Severely underweight:\ \nIt is important to know whether a serious disease \ or other conditions have caused the emaciation. Whatever \ the case, medical help is advisable.\n\t\t\tPossible causes: \ \nUndernourishment \ \nMaldigestion \ \nEating disorders: anorexia, bulimia \ \nSlimming caused by a disease") elif 16 < bmi < 18.5: print("\n\t\t\tYour BMI is", round(bmi, 2), "Underweight:\ \nIt is important to know whether a serious disease \ or other conditions have caused the emaciation. Whatever \ the case, medical help is advisable.\n\t\t\tPossible causes: \ \nUndernourishment \ \nMaldigestion \ \nEating disorders: anorexia, bulimia \ \nSlimming caused by a disease") elif 18.5 < bmi < 25: print("\n\t\t\tYour BMI is", round(bmi, 2), "Normal(healthy weight):\ \nPlay physical games and do physical \ exercise at least for an hour daily at \ moderate to vigorous intensity.Try out a \ variety of foods, including fresh \ fruit and vegetables.Eat and drink what \ you like, but not too much sweets \ and sweetened drinks.") elif 25 < bmi < 30: print("\n\t\t\tYour BMI is", round(bmi, 2), "Overweight:\ \nPlay physical games and do physical \ exercise at least for an hour daily at \ moderate to vigorous intensity.Try out a \ variety of foods, including fresh \ fruit and vegetables.Eat and drink what \ you like, but not too much sweets \ and sweetened drinks.") elif 30 < bmi < 35: print("\n\t\t\tYour BMI is", round(bmi, 2), "Moderately obese:\ \nPlay physical games and do physical \ exercise at least for an hour daily at \ moderate to vigorous intensity.Try out a \ variety of foods, including fresh \ fruit and vegetables.Eat and drink what \ you like, but not too much sweets \ and sweetened drinks.") elif 35 < bmi < 40: print("\n\t\t\tYour BMI is", round(bmi, 2), "Severely obese:\ \nPlay physical games and do physical \ exercise at least for an hour daily at \ moderate to vigorous intensity.Try out a \ variety of foods, including fresh \ fruit and vegetables.Eat and drink what \ you like, but not too much sweets \ and sweetened drinks.") elif bmi > 40: print("\n\t\t\tYour BMI is", round(bmi, 2), "Very severely obese:\ \nPlay physical games and do physical \ exercise at least for an hour daily at \ moderate to vigorous intensity.Try out a \ variety of foods, including fresh \ fruit and vegetables.Eat and drink what \ you like, but not too much sweets \ and sweetened drinks.") else: print("There is an error with your input") else: if bmi < 18.5: print("\n\t\t\tYour BMI is", round(bmi, 2), "Underweight:\ \nIt is important to know whether a serious disease \ or other conditions have caused the emaciation. Whatever \ the case, medical help is advisable.\n\t\t\tPossible causes: \ \nUndernourishment \ \nMaldigestion \ \nEating disorders: anorexia, bulimia \ \nSlimming caused by a disease") elif 18.5 < bmi < 24.9: print("\n\t\t\tYour BMI is", round(bmi, 2), "Healthy weight:\ \nPlay physical games and do physical \ exercise at least for an hour daily at \ moderate to vigorous intensity.Try out a \ variety of foods, including fresh \ fruit and vegetables.Eat and drink what \ you like, but not too much sweets \ and sweetened drinks.") elif 25 < bmi < 29.9: print("\n\t\t\tYour BMI is", round(bmi, 2), "Overweight:\ \nPlay physical games and do physical \ exercise at least for an hour daily at \ moderate to vigorous intensity.Try out a \ variety of foods, including fresh \ fruit and vegetables.Eat and drink what \ you like, but not too much sweets \ and sweetened drinks.") elif bmi > 30: print("\n\t\t\tYour BMI is", round(bmi, 2), "Moderately obese:\ \nPlay physical games and do physical \ exercise at least for an hour daily at \ moderate to vigorous intensity.Try out a \ variety of foods, including fresh \ fruit and vegetables.Eat and drink what \ you like, but not too much sweets \ and sweetened drinks.") else: print("There is an error with your input") print('\n\n10' + '=' * (int(round(bmi, 0))-10-1)+'|'+'=\ '*(60-int(round(bmi, 0))-1)+'60') if not name: break user_info[name] = height, weight, age, sex print(user_info) print(user_info.get(str(input("Enter your name: "))))
user_info = {} while True: print('\n\t\t\tUnits:metric') name = str(input('Enter your name: ')) height = float(input('Input your height in meters(For instance:1.89): ')) weight = float(input('Input your weight in kilogram(For instance:69): ')) age = int(input('Input your age: ')) sex = str(input('Input your sex: ')) bmi = weight / (height * height) print('Your body mass index (or BMI) is: ', round(bmi, 2)) if sex == 'male': if bmi < 15: print('\n\t\t\tYour BMI is', round(bmi, 2), 'Very severely underweight:\nIt is important to know whether a serious disease or other conditions have caused the emaciation. Whatever the case, medical help is advisable.\n\t\t\tPossible causes: \nUndernourishment \nMaldigestion \nEating disorders: anorexia, bulimia \nSlimming caused by a disease') elif 15 < bmi < 16: print('\n\t\t\tYour BMI is', round(bmi, 2), 'Severely underweight:\nIt is important to know whether a serious disease or other conditions have caused the emaciation. Whatever the case, medical help is advisable.\n\t\t\tPossible causes: \nUndernourishment \nMaldigestion \nEating disorders: anorexia, bulimia \nSlimming caused by a disease') elif 16 < bmi < 18.5: print('\n\t\t\tYour BMI is', round(bmi, 2), 'Underweight:\nIt is important to know whether a serious disease or other conditions have caused the emaciation. Whatever the case, medical help is advisable.\n\t\t\tPossible causes: \nUndernourishment \nMaldigestion \nEating disorders: anorexia, bulimia \nSlimming caused by a disease') elif 18.5 < bmi < 25: print('\n\t\t\tYour BMI is', round(bmi, 2), 'Normal(healthy weight):\nPlay physical games and do physical exercise at least for an hour daily at moderate to vigorous intensity.Try out a variety of foods, including fresh fruit and vegetables.Eat and drink what you like, but not too much sweets and sweetened drinks.') elif 25 < bmi < 30: print('\n\t\t\tYour BMI is', round(bmi, 2), 'Overweight:\nPlay physical games and do physical exercise at least for an hour daily at moderate to vigorous intensity.Try out a variety of foods, including fresh fruit and vegetables.Eat and drink what you like, but not too much sweets and sweetened drinks.') elif 30 < bmi < 35: print('\n\t\t\tYour BMI is', round(bmi, 2), 'Moderately obese:\nPlay physical games and do physical exercise at least for an hour daily at moderate to vigorous intensity.Try out a variety of foods, including fresh fruit and vegetables.Eat and drink what you like, but not too much sweets and sweetened drinks.') elif 35 < bmi < 40: print('\n\t\t\tYour BMI is', round(bmi, 2), 'Severely obese:\nPlay physical games and do physical exercise at least for an hour daily at moderate to vigorous intensity.Try out a variety of foods, including fresh fruit and vegetables.Eat and drink what you like, but not too much sweets and sweetened drinks.') elif bmi > 40: print('\n\t\t\tYour BMI is', round(bmi, 2), 'Very severely obese:\nPlay physical games and do physical exercise at least for an hour daily at moderate to vigorous intensity.Try out a variety of foods, including fresh fruit and vegetables.Eat and drink what you like, but not too much sweets and sweetened drinks.') else: print('There is an error with your input') elif bmi < 18.5: print('\n\t\t\tYour BMI is', round(bmi, 2), 'Underweight:\nIt is important to know whether a serious disease or other conditions have caused the emaciation. Whatever the case, medical help is advisable.\n\t\t\tPossible causes: \nUndernourishment \nMaldigestion \nEating disorders: anorexia, bulimia \nSlimming caused by a disease') elif 18.5 < bmi < 24.9: print('\n\t\t\tYour BMI is', round(bmi, 2), 'Healthy weight:\nPlay physical games and do physical exercise at least for an hour daily at moderate to vigorous intensity.Try out a variety of foods, including fresh fruit and vegetables.Eat and drink what you like, but not too much sweets and sweetened drinks.') elif 25 < bmi < 29.9: print('\n\t\t\tYour BMI is', round(bmi, 2), 'Overweight:\nPlay physical games and do physical exercise at least for an hour daily at moderate to vigorous intensity.Try out a variety of foods, including fresh fruit and vegetables.Eat and drink what you like, but not too much sweets and sweetened drinks.') elif bmi > 30: print('\n\t\t\tYour BMI is', round(bmi, 2), 'Moderately obese:\nPlay physical games and do physical exercise at least for an hour daily at moderate to vigorous intensity.Try out a variety of foods, including fresh fruit and vegetables.Eat and drink what you like, but not too much sweets and sweetened drinks.') else: print('There is an error with your input') print('\n\n10' + '=' * (int(round(bmi, 0)) - 10 - 1) + '|' + '=' * (60 - int(round(bmi, 0)) - 1) + '60') if not name: break user_info[name] = (height, weight, age, sex) print(user_info) print(user_info.get(str(input('Enter your name: '))))
#!/usr/bin/env python #-*- coding: utf-8 -*- def getHeaders(fileName): headers = [] headerList = ['User-Agent','Cookie'] with open(fileName, 'r') as fp: for line in fp.readlines(): name, value = line.split(':', 1) if name in headerList: headers.append((name.strip(), value.strip())) return headers if __name__=="__main__": headers = getHeaders('headersRaw.txt') print(headers)
def get_headers(fileName): headers = [] header_list = ['User-Agent', 'Cookie'] with open(fileName, 'r') as fp: for line in fp.readlines(): (name, value) = line.split(':', 1) if name in headerList: headers.append((name.strip(), value.strip())) return headers if __name__ == '__main__': headers = get_headers('headersRaw.txt') print(headers)
class ComponentsAssembly: def __init__(self, broker, strategy, datafeed, sizer, metrics_collection, *args): self._components = [broker, strategy, datafeed, sizer, metrics_collection, *args] def __iter__(self): self.index = 0 return self def __next__(self): if self.index < len(self._components): component = self._components[self.index] self.index += 1 return component raise StopIteration def __getitem__(self, item): return self._components[item] def __setitem__(self, key, value): self._components[key] = value def append(self, item): self._components.append(item)
class Componentsassembly: def __init__(self, broker, strategy, datafeed, sizer, metrics_collection, *args): self._components = [broker, strategy, datafeed, sizer, metrics_collection, *args] def __iter__(self): self.index = 0 return self def __next__(self): if self.index < len(self._components): component = self._components[self.index] self.index += 1 return component raise StopIteration def __getitem__(self, item): return self._components[item] def __setitem__(self, key, value): self._components[key] = value def append(self, item): self._components.append(item)
# Lecture 3.6, slide 2 # Defines the value to take the square root of, epsilon, and the number of guesses. x = 9 epsilon = 0.01 numGuesses = 0 # Here, 0 < x < 1, then the low is x and the high is 1 - the sqrt(x) > x if 0 < x < 1. # If x > 1, then the low is 0 and the high is x - the sqrt(x) < x if x > 1. if (x >= 0 and x < 1): low = x high = 1.0 elif (x >= 1): low = 0.0 high = x # Sets the initial answer to the average of low and high. ans = (low + high) / 2.0 # While the answer is still not close enough to epsilon, continue searching. while (abs(ans ** 2 - x) >= epsilon): # For each case, it prints the low and high values. print ('low = ' + str(low) + ' ; high = ' + str(high) + ' ; ans = ' + str(ans)) numGuesses += 1 # If the guess is lower than x, then set the new ans = low. # If the guess is higher than x, then set the new ans = high. if (ans ** 2) < x: low = ans elif (ans ** 2) >= x: high = ans # At the end, the answer is updated. ans = (low + high) / 2.0 # Prints the number of guesses and the final guess. print ('Number of guesses taken: ' + str(numGuesses)) print (str(ans) + ' is close to the squre root of ' + str(x))
x = 9 epsilon = 0.01 num_guesses = 0 if x >= 0 and x < 1: low = x high = 1.0 elif x >= 1: low = 0.0 high = x ans = (low + high) / 2.0 while abs(ans ** 2 - x) >= epsilon: print('low = ' + str(low) + ' ; high = ' + str(high) + ' ; ans = ' + str(ans)) num_guesses += 1 if ans ** 2 < x: low = ans elif ans ** 2 >= x: high = ans ans = (low + high) / 2.0 print('Number of guesses taken: ' + str(numGuesses)) print(str(ans) + ' is close to the squre root of ' + str(x))
# ctx.addClock("csi_rx_i.dphy_clk", 96) # ctx.addClock("video_clk", 24) # ctx.addClock("uart_i.sys_clk_i", 12) ctx.addClock("EXTERNAL_CLK", 12) # ctx.addClock("clk", 25)
ctx.addClock('EXTERNAL_CLK', 12)
class Solution: def soupServings(self, N: int) -> float: def dfs(a: int, b: int) -> float: if a <= 0 and b <= 0: return 0.5 if a <= 0: return 1.0 if b <= 0: return 0.0 if memo[a][b] > 0: return memo[a][b] memo[a][b] = 0.25 * (dfs(a - 4, b) + dfs(a - 3, b - 1) + dfs(a - 2, b - 2) + dfs(a - 1, b - 3)) return memo[a][b] memo = [[0.0] * 192 for _ in range(192)] return 1 if N >= 4800 else dfs((N + 24) // 25, (N + 24) // 25)
class Solution: def soup_servings(self, N: int) -> float: def dfs(a: int, b: int) -> float: if a <= 0 and b <= 0: return 0.5 if a <= 0: return 1.0 if b <= 0: return 0.0 if memo[a][b] > 0: return memo[a][b] memo[a][b] = 0.25 * (dfs(a - 4, b) + dfs(a - 3, b - 1) + dfs(a - 2, b - 2) + dfs(a - 1, b - 3)) return memo[a][b] memo = [[0.0] * 192 for _ in range(192)] return 1 if N >= 4800 else dfs((N + 24) // 25, (N + 24) // 25)
# First we define a variable "to_find" which contains the alphabet to be checked for in the file # fo is the file which is to be read. to_find="e" fo = open('E:/file1.txt' ,'r+') count=0 for line in fo: for word in line.split(): if word.find(to_find)!=-1: count=count+1 print(count)
to_find = 'e' fo = open('E:/file1.txt', 'r+') count = 0 for line in fo: for word in line.split(): if word.find(to_find) != -1: count = count + 1 print(count)
DELIVERY_TYPES = ( (1, "Vaginal Birth"), # Execise care when changing... (2, "Caesarian") )
delivery_types = ((1, 'Vaginal Birth'), (2, 'Caesarian'))
class Solution: def makeGood(self, s: str) -> str: i = 0 string = list(s) while i < len(string) - 1: a = string[i] b = string[i + 1] if a.lower() == b.lower() and a != b: string.pop(i) string.pop(i) i = 0 else: i += 1 return "".join(string) if __name__ == "__main__": # fmt: off test_cases = [ "leEeetcode", "abBAcC", ] results = [ "leetcode", "", ] # fmt: on app = Solution() for test_case, correct_result in zip(test_cases, results): my_result = app.makeGood(test_case) assert ( my_result == correct_result ), f"My result: {my_result}, correct result: {correct_result}\nTest Case: {test_case}"
class Solution: def make_good(self, s: str) -> str: i = 0 string = list(s) while i < len(string) - 1: a = string[i] b = string[i + 1] if a.lower() == b.lower() and a != b: string.pop(i) string.pop(i) i = 0 else: i += 1 return ''.join(string) if __name__ == '__main__': test_cases = ['leEeetcode', 'abBAcC'] results = ['leetcode', ''] app = solution() for (test_case, correct_result) in zip(test_cases, results): my_result = app.makeGood(test_case) assert my_result == correct_result, f'My result: {my_result}, correct result: {correct_result}\nTest Case: {test_case}'
l,j,k=[list(input()) for i in range(3)] l.extend(j) for i in l: if i not in k : k.append(i) break k.remove(i) print('YES' if k==[] else 'NO')
(l, j, k) = [list(input()) for i in range(3)] l.extend(j) for i in l: if i not in k: k.append(i) break k.remove(i) print('YES' if k == [] else 'NO')
# # PySNMP MIB module CXQLLC-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CXQLLC-MIB # Produced by pysmi-0.3.4 at Wed May 1 12:33: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) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsUnion, SingleValueConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsIntersection") cxQLLC, ThruputClass, Alias, SapIndex = mibBuilder.importSymbols("CXProduct-SMI", "cxQLLC", "ThruputClass", "Alias", "SapIndex") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") iso, NotificationType, Gauge32, Unsigned32, MibIdentifier, IpAddress, Counter64, Counter32, Bits, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, TimeTicks, ModuleIdentity, Integer32 = mibBuilder.importSymbols("SNMPv2-SMI", "iso", "NotificationType", "Gauge32", "Unsigned32", "MibIdentifier", "IpAddress", "Counter64", "Counter32", "Bits", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "TimeTicks", "ModuleIdentity", "Integer32") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") class X25Address(DisplayString): subtypeSpec = DisplayString.subtypeSpec + ValueSizeConstraint(0, 15) class PacketSize(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(4, 5, 6, 7, 8, 9, 10, 11, 12)) namedValues = NamedValues(("bytes16", 4), ("bytes32", 5), ("bytes64", 6), ("bytes128", 7), ("bytes256", 8), ("bytes512", 9), ("bytes1024", 10), ("bytes2048", 11), ("bytes4096", 12)) qllcSapTable = MibTable((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1), ) if mibBuilder.loadTexts: qllcSapTable.setReference('Memotec Communications Inc.') if mibBuilder.loadTexts: qllcSapTable.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapTable.setDescription('A table containing configuration information for each QLLC service access point.') qllcSapEntry = MibTableRow((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1), ).setIndexNames((0, "CXQLLC-MIB", "qllcSapNumber")) if mibBuilder.loadTexts: qllcSapEntry.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapEntry.setDescription('Defines a row in the qllcSapTable. Each row contains the objects which are used to define a service access point.') qllcSapNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 1), SapIndex()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcSapNumber.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapNumber.setDescription('Identifies a SAP (service access point) in the qllcSapTable.') qllcSapRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("invalid", 1), ("valid", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcSapRowStatus.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapRowStatus.setDescription('Determines the status of the objects in a table row. Options: invalid (1): Row is flagged, after next reset the values will be disabled and the row will be deleted from the table. valid (2): Values are enabled. Configuration Changed: administrative') qllcSapType = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("lower", 1), ("upper", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcSapType.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapType.setDescription("Specifies this SAP (service access point) as either 'upper' or 'lower'. Options: lower (1): This is a lower SAP which communicates with the X.25 layer. upper (2): This is an upper SAP, which acts as an inter-layer port communicating with the SNA Link Conversion layer. Configuration Changed: administrative") qllcSapAlias = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 4), Alias()).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcSapAlias.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapAlias.setDescription('Identifies this service access point by a textual name. Names must be unique across all service access points at all layers. Range of Values: 1 - 16 alphanumeric characters (first character must be a letter) Default Value: none Configuration Changed: administrative') qllcSapCompanionAlias = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 5), Alias()).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcSapCompanionAlias.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapCompanionAlias.setDescription('Identifies the X.25 SAP that this SAP communicates with. Range of Values: 1 - 16 alphanumeric characters (first character must be a letter) Default Value: none Configuration Changed: administrative') qllcSapSnalcRef = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 6), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 8))).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcSapSnalcRef.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapSnalcRef.setDescription('This object applies only to lower SAPs (service access points). Determines the upper SAP (service access point) that is associated with this SAP. Range of Values: 0 - 8 Default Value: none Configuration Changed: administrative') qllcSapOperationalMode = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("offline", 1), ("online", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcSapOperationalMode.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapOperationalMode.setDescription('Identifies the operational state of this SAP (service access point). Options: offLine (1): Indicates that this SAP is not operational. onLine (2): Indicates that this SAP is operational.') qllcDteTable = MibTable((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2), ) if mibBuilder.loadTexts: qllcDteTable.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteTable.setDescription('The DTE table contains the parameter settings that are used to create an X.25 Call Request packet for calls established by a particular lower service access point for a particular control unit.') qllcDteEntry = MibTableRow((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1), ).setIndexNames((0, "CXQLLC-MIB", "qllcDteSap"), (0, "CXQLLC-MIB", "qllcDteIndex")) if mibBuilder.loadTexts: qllcDteEntry.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteEntry.setDescription('Defines a row in the qllcDteTable. Each row contains the objects which are used to define a the parameters for an X.25 Call Request packet.') qllcDteSap = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 1), SapIndex()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteSap.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteSap.setDescription('Identifies the SAP (service access point) associated with this entry. Configuration Changed: administrative ') qllcDteIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 64))).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteIndex.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteIndex.setDescription('Identifies the control unit address associated with this DTE entry. Configuration Changed: administrative ') qllcDteRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("invalid", 1), ("valid", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteRowStatus.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteRowStatus.setDescription('Determines the status of the objects in a table row. Options: invalid (1): Row is flagged, after next reset the values will be disabled and the row will be deleted from the table. valid (2): Values are enabled. Configuration Changed: administrative') qllcDteType = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 4), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("terminalInterfaceUnit", 1), ("hostInterfaceUnit", 2))).clone('terminalInterfaceUnit')).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteType.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteType.setDescription('Determines the type of interface (HIU or TIU) associated with this DTE. Options: terminalInterfaceUnit (1): The SAP type is a TIU, which means it is connected to one or more control units (secondary link stations). The TIU emulates a primary link station, and polls the attached control units. The SDLC interface can support a total of 64 control units across all TIU SAPs. hostInterfaceUnit (2): The SAP type is an HIU, which means it is connected to an SNA host (primary link station). The HIU emulates the control units connected to a TIU. It responds to polls issued by the host. Default Value: terminalInterfaceUnit (1) Configuration Changed: administrative') qllcDteCalledAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 5), X25Address()).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteCalledAddress.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteCalledAddress.setDescription('Determines the DTE to call to establish a QLLC connection. Range of Values: DTE address enclosed in quotes (up to 15 characters in length) Default Value: none Configuration Changed: administrative and operative') qllcDteCallingAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 6), X25Address()).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteCallingAddress.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteCallingAddress.setDescription('Determines the DTE address of the caller. Range of Values: DTE address enclosed in quotes (up to 15 characters in length) Default Value: none Configuration Changed: administrative and operative') qllcDteDBitCall = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2))).clone('yes')).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteDBitCall.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteDBitCall.setDescription('Determines if segmentation is supported and is to be performed by the QLLC layer for the specific DTE entry. Options: no (1): QLLC does not support segmentation. yes (2): QLLC supports segmentation. (For future use.) Default Value: yes (2) Configuration Changed: administrative and operative') qllcDteWindow = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 8), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 7)).clone(7)).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteWindow.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteWindow.setDescription('Determines the transmit and receive window sizes for this DTE. This window size is used when establishing calls from this DTE, or when receiving calls at this DTE. QLLC only supports modulo 8 window size. Range of Values: 1 - 7 Default Value: 7 Configuration Changed: administrative and operative') qllcDtePacketSize = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 9), PacketSize().clone('bytes128')).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDtePacketSize.setStatus('mandatory') if mibBuilder.loadTexts: qllcDtePacketSize.setDescription('Determines the transmit and receive packet size for this DTE when flow control negotiation (x25SapSbscrFlowCntrlParamNegotiation) is not subscribed to, or when a D-bit call is routed through this SAP. Options: bytes16 (4): 16 bytes bytes32 (5): 32 bytes bytes64 (6): 64 bytes bytes128 (7): 128 bytes bytes256 (8): 256 bytes bytes512 (9): 512 bytes bytes1024 (10): 1024 bytes bytes2048 (11): 2048 bytes bytes4096 (12): 4096 bytes Default Value: bytes128 (7) Related Objects: x25SapSbscrFlowCntrlParamNegotiation Configuration Changed: administrative and operative') qllcDteThroughput = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 10), ThruputClass().clone('bps9600')).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteThroughput.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteThroughput.setDescription('Determines the transmit and receive throughput class for this DTE when flow control negotiation (x25SapSbscrThruputClassNegotiation) is not subscribed to, or when a D-bit call is routed through this SAP. Options: bps75 (3) bps150 (4) bps300 (5) bps600 (6) bps1200 (7) bps2400 (8) bps4800 (9) bps9600 (10) bps19200 (11) bps38400 (12) bps64000 (13) Default Value: bps9600 (10) Related Objects: x25SapSbscrThruputClassNegotiation Configuration Changed: administrative and operative') qllcDteUserData = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 11), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 12))).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteUserData.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteUserData.setDescription('Determines the data included in the call user data field of each outgoing call initiated by this DTE. Call user data can only be included when calling non-Memotec devices. In this case, up to 12 characters can be specified. The format of the call user data field is determined by the value of the qllcDteMemotec object. Related Object: qllcDteMemotec Range of Values: 0 - 12 characters Default Value: none Configuration Changed: administrative and operative') qllcDteFacility = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 12), OctetString()).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteFacility.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteFacility.setDescription('Determines the facility codes and associated parameters for this DTE. Default Value: 0 Range of Values: 0 - 20 hexadecimal characters Configuration Changed: administrative and operative') qllcDteMemotec = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("nonmemotec", 1), ("cx900", 2), ("legacy", 3), ("pvc", 4))).clone('cx900')).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteMemotec.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteMemotec.setDescription('Determines the type of product that the called DTE address is associated with, which in turn determines how the call user data (CUD) field is constructed for all outgoing calls from this DTE. This object also determines whether the call is associated to a Switched Virtual Circuit (SVC) or a Permanent Virtual Circuit (PVC). Options: (1): Called DTE address is a non- Memotec product. CUD field = QLLC protocol ID + value of object qllcDteUserData (2): Called DTE is a Memotec CX900 product. CUD field = QLLC protocol ID + value of object qllcDteIndex (3): Called DTE is an older Memotec product (including CX1000). CUD field = QLLC protocol ID + / + Port Group GE + CU Alias + FF + Port + FF + FF (4): The DTE is connected through a Permanent Virtual Circuit (PVC), and can be either TIU or HIU. Note that if the DTE is configured for an SVC but a PVC call is received, the QLLC layer will attempt to connect to the PVC. Default Value: cx900 (2) Related Objects: qllcDteUserData qllcDteCalledAddress qllcDteConnectMethod Configuration Changed: administrative and operative') qllcDtePvc = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("no", 1), ("yes", 2))).clone('no')).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDtePvc.setStatus('mandatory') if mibBuilder.loadTexts: qllcDtePvc.setDescription('Determines if this DTE makes its calls on a PVC (permanent virtual circuit). Options: no (1): This DTE does not make its calls on a PVC (all calls are switched). yes (2): This DTE makes its calls on a PVC. (For future use.) Default Value: no (1) Configuration Changed: administrative ') qllcDteConnectMethod = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("userdata", 1), ("callingaddress", 2))).clone('userdata')).setMaxAccess("readwrite") if mibBuilder.loadTexts: qllcDteConnectMethod.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteConnectMethod.setDescription("Determines if this DTE accepts calls by validating the user-data field, or by matching the calling address with its corresponding called address. Note: This object only applies to the HIU. Options: userdata (1): The HIU DTE validates the call using the user-data field. callingaddress (2): The HIU DTE validates the call by matching the call's calling address with the configured called address. Default Value: userdata (1) Configuration Changed: administrative ") qllcDteControl = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 20), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1))).clone(namedValues=NamedValues(("clearStats", 1)))).setMaxAccess("writeonly") if mibBuilder.loadTexts: qllcDteControl.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteControl.setDescription('Clears all statistics for this service access point. Options: clearStats (1): Clear statistics. Default Value: none Configuration Changed: administrative and operative') qllcDteStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 30), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("connected", 1), ("pendingConnect", 2), ("disconnected", 3), ("pendingDisconnect", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteStatus.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteStatus.setDescription('Indicates the connection status of this DTE. Options: connected (1): This DTE is connected. pendingConnect (2): This DTE has issued a call and is waiting for it to complete. disconnected (3): This DTE is not connected. pendingDisconnect (4): This DTE has issued a call clear and is waiting for it to complete. Configuration Changed: administrative and operative') qllcDteOperationalMode = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 31), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("offline", 1), ("online", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteOperationalMode.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteOperationalMode.setDescription('Indicates the operational state of this DTE. Options: offLine (1): Indicates that this DTE is not operational. onLine (2): Indicates that this DTE is operational.') qllcDteState = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 32), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))).clone(namedValues=NamedValues(("opened", 1), ("closed", 2), ("xidcmd", 3), ("tstcmd", 4), ("xidrsp", 5), ("tstrsp", 6), ("reset", 7), ("setmode", 8), ("disc", 9), ("reqdisc", 10), ("unknown", 11)))).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteState.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteState.setDescription('Indicates the state of this DTE with regards to SNA traffic. Options: opened (1): Indicates that this DTE is in data transfer mode (a QSM was sent and a QUA was received). closed (2): Indicates that this DTE is not in data transfer mode (QSM not sent or QUA not received). xidcmd (3): Indicates that an XID was sent by the TIU and received by the HIU. tstcmd (4): Indicates that a TEST was sent by the TIU and received by the HIU. xiddrsp (5): Indicates that the HIU received an XID response from the TIU, or that the TIU received an XID response from the control unit. tsttrsp (6): Indicates that the HIU received a TEST response from the TIU, or that the TIU received a TEST response from the control unit. reset (7): Indicates that an X.25 reset was received. setmode (8): Indicates that a QSM was received. disc (9): Indicates that the HIU received a DISC from the host, or that the TIU sent a DISC to the control unit. reqdisc (10): Indicates that the HIU sent a DISC to the host, or that the TIU received a DISC from the control unit. unknown (11): Indicates that an unknown condition has occurred. ') qllcDteConnectionType = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 33), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("none", 1), ("svc", 2), ("pvc", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteConnectionType.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteConnectionType.setDescription('Identifies the type of X.25 connection that the DTE is supporting. Options: none (1): No X.25 connection exists yet. svc (2): The QLLC DTE is transmitting SNA data over a Switched Virtual Circuit (SVC). pvc (3): The QLLC DTE is transmitting SNA data over a Permanent Virtual Circuit (PVC).') qllcDteCalls = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 40), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteCalls.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteCalls.setDescription('Indicates the number of incoming calls received by this DTE.') qllcDteClears = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 41), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteClears.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteClears.setDescription('Indicates the number of calls cleared by this DTE.') qllcDteTxPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 42), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteTxPackets.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteTxPackets.setDescription('Indicates the number of data packets sent by this DTE.') qllcDteRxPackets = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 43), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteRxPackets.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteRxPackets.setDescription('Indicates the number of data packets received by this DTE.') qllcDteQdc = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 44), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteQdc.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteQdc.setDescription('Indicates the number of SNA disconnects sent and received by this DTE.') qllcDteQxid = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 45), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteQxid.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteQxid.setDescription('Indicates the number of SNA XIDs sent and received by this DTE.') qllcDteQua = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 46), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteQua.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteQua.setDescription('Indicates the number of unnumbered acknowledgments sent and received by this DTE.') qllcDteQsm = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 47), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteQsm.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteQsm.setDescription('Indicates the number of SNRMs sent and received by this DTE.') qllcDteX25Reset = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 48), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteX25Reset.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteX25Reset.setDescription('Indicates the number of X.25 resets sent and received by this DTE.') qllcDteSnalcRnr = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 49), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteSnalcRnr.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteSnalcRnr.setDescription('Indicates the number of SNA link conversion layer flow control RNRs sent and received by this DTE.') qllcDteSnalcRr = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 50), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteSnalcRr.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteSnalcRr.setDescription('Indicates the number of SNA link conversion layer flow control RRs sent and received by this DTE.') qllcDteX25Rnr = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 51), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteX25Rnr.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteX25Rnr.setDescription('Indicates the number of X.25 flow control RNRs sent and received by this DTE.') qllcDteX25Rr = MibTableColumn((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 52), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcDteX25Rr.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteX25Rr.setDescription('Indicates the number of X.25 flow control RRs sent and received by this DTE.') qllcMibLevel = MibScalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 3), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: qllcMibLevel.setStatus('mandatory') if mibBuilder.loadTexts: qllcMibLevel.setDescription('Used to determine current MIB module release supported by the agent. Object is in decimal.') mibBuilder.exportSymbols("CXQLLC-MIB", qllcSapAlias=qllcSapAlias, qllcDteCalls=qllcDteCalls, qllcDteClears=qllcDteClears, qllcSapTable=qllcSapTable, qllcDtePacketSize=qllcDtePacketSize, qllcDteStatus=qllcDteStatus, qllcSapCompanionAlias=qllcSapCompanionAlias, qllcDteRowStatus=qllcDteRowStatus, qllcDteQdc=qllcDteQdc, qllcDtePvc=qllcDtePvc, qllcDteQua=qllcDteQua, qllcSapOperationalMode=qllcSapOperationalMode, qllcDteOperationalMode=qllcDteOperationalMode, qllcDteDBitCall=qllcDteDBitCall, qllcSapRowStatus=qllcSapRowStatus, qllcDteEntry=qllcDteEntry, qllcDteCalledAddress=qllcDteCalledAddress, qllcDteConnectionType=qllcDteConnectionType, qllcDteType=qllcDteType, qllcDteSnalcRr=qllcDteSnalcRr, qllcDteX25Rnr=qllcDteX25Rnr, qllcMibLevel=qllcMibLevel, qllcDteQsm=qllcDteQsm, qllcDteTxPackets=qllcDteTxPackets, qllcDteMemotec=qllcDteMemotec, qllcDteQxid=qllcDteQxid, qllcDteTable=qllcDteTable, qllcDteSap=qllcDteSap, qllcDteThroughput=qllcDteThroughput, qllcDteConnectMethod=qllcDteConnectMethod, qllcDteX25Reset=qllcDteX25Reset, qllcSapNumber=qllcSapNumber, qllcDteSnalcRnr=qllcDteSnalcRnr, qllcSapEntry=qllcSapEntry, qllcDteControl=qllcDteControl, qllcDteFacility=qllcDteFacility, qllcDteState=qllcDteState, PacketSize=PacketSize, qllcSapType=qllcSapType, qllcSapSnalcRef=qllcSapSnalcRef, qllcDteCallingAddress=qllcDteCallingAddress, qllcDteIndex=qllcDteIndex, qllcDteUserData=qllcDteUserData, X25Address=X25Address, qllcDteX25Rr=qllcDteX25Rr, qllcDteRxPackets=qllcDteRxPackets, qllcDteWindow=qllcDteWindow)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_union, single_value_constraint, value_size_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsUnion', 'SingleValueConstraint', 'ValueSizeConstraint', 'ConstraintsIntersection') (cx_qllc, thruput_class, alias, sap_index) = mibBuilder.importSymbols('CXProduct-SMI', 'cxQLLC', 'ThruputClass', 'Alias', 'SapIndex') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (iso, notification_type, gauge32, unsigned32, mib_identifier, ip_address, counter64, counter32, bits, object_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, time_ticks, module_identity, integer32) = mibBuilder.importSymbols('SNMPv2-SMI', 'iso', 'NotificationType', 'Gauge32', 'Unsigned32', 'MibIdentifier', 'IpAddress', 'Counter64', 'Counter32', 'Bits', 'ObjectIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'TimeTicks', 'ModuleIdentity', 'Integer32') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') class X25Address(DisplayString): subtype_spec = DisplayString.subtypeSpec + value_size_constraint(0, 15) class Packetsize(Integer32): subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(4, 5, 6, 7, 8, 9, 10, 11, 12)) named_values = named_values(('bytes16', 4), ('bytes32', 5), ('bytes64', 6), ('bytes128', 7), ('bytes256', 8), ('bytes512', 9), ('bytes1024', 10), ('bytes2048', 11), ('bytes4096', 12)) qllc_sap_table = mib_table((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1)) if mibBuilder.loadTexts: qllcSapTable.setReference('Memotec Communications Inc.') if mibBuilder.loadTexts: qllcSapTable.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapTable.setDescription('A table containing configuration information for each QLLC service access point.') qllc_sap_entry = mib_table_row((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1)).setIndexNames((0, 'CXQLLC-MIB', 'qllcSapNumber')) if mibBuilder.loadTexts: qllcSapEntry.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapEntry.setDescription('Defines a row in the qllcSapTable. Each row contains the objects which are used to define a service access point.') qllc_sap_number = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 1), sap_index()).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcSapNumber.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapNumber.setDescription('Identifies a SAP (service access point) in the qllcSapTable.') qllc_sap_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('invalid', 1), ('valid', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: qllcSapRowStatus.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapRowStatus.setDescription('Determines the status of the objects in a table row. Options: invalid (1): Row is flagged, after next reset the values will be disabled and the row will be deleted from the table. valid (2): Values are enabled. Configuration Changed: administrative') qllc_sap_type = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('lower', 1), ('upper', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: qllcSapType.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapType.setDescription("Specifies this SAP (service access point) as either 'upper' or 'lower'. Options: lower (1): This is a lower SAP which communicates with the X.25 layer. upper (2): This is an upper SAP, which acts as an inter-layer port communicating with the SNA Link Conversion layer. Configuration Changed: administrative") qllc_sap_alias = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 4), alias()).setMaxAccess('readwrite') if mibBuilder.loadTexts: qllcSapAlias.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapAlias.setDescription('Identifies this service access point by a textual name. Names must be unique across all service access points at all layers. Range of Values: 1 - 16 alphanumeric characters (first character must be a letter) Default Value: none Configuration Changed: administrative') qllc_sap_companion_alias = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 5), alias()).setMaxAccess('readwrite') if mibBuilder.loadTexts: qllcSapCompanionAlias.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapCompanionAlias.setDescription('Identifies the X.25 SAP that this SAP communicates with. Range of Values: 1 - 16 alphanumeric characters (first character must be a letter) Default Value: none Configuration Changed: administrative') qllc_sap_snalc_ref = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 6), integer32().subtype(subtypeSpec=value_range_constraint(0, 8))).setMaxAccess('readwrite') if mibBuilder.loadTexts: qllcSapSnalcRef.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapSnalcRef.setDescription('This object applies only to lower SAPs (service access points). Determines the upper SAP (service access point) that is associated with this SAP. Range of Values: 0 - 8 Default Value: none Configuration Changed: administrative') qllc_sap_operational_mode = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 1, 1, 20), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('offline', 1), ('online', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcSapOperationalMode.setStatus('mandatory') if mibBuilder.loadTexts: qllcSapOperationalMode.setDescription('Identifies the operational state of this SAP (service access point). Options: offLine (1): Indicates that this SAP is not operational. onLine (2): Indicates that this SAP is operational.') qllc_dte_table = mib_table((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2)) if mibBuilder.loadTexts: qllcDteTable.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteTable.setDescription('The DTE table contains the parameter settings that are used to create an X.25 Call Request packet for calls established by a particular lower service access point for a particular control unit.') qllc_dte_entry = mib_table_row((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1)).setIndexNames((0, 'CXQLLC-MIB', 'qllcDteSap'), (0, 'CXQLLC-MIB', 'qllcDteIndex')) if mibBuilder.loadTexts: qllcDteEntry.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteEntry.setDescription('Defines a row in the qllcDteTable. Each row contains the objects which are used to define a the parameters for an X.25 Call Request packet.') qllc_dte_sap = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 1), sap_index()).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteSap.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteSap.setDescription('Identifies the SAP (service access point) associated with this entry. Configuration Changed: administrative ') qllc_dte_index = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 64))).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteIndex.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteIndex.setDescription('Identifies the control unit address associated with this DTE entry. Configuration Changed: administrative ') qllc_dte_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('invalid', 1), ('valid', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: qllcDteRowStatus.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteRowStatus.setDescription('Determines the status of the objects in a table row. Options: invalid (1): Row is flagged, after next reset the values will be disabled and the row will be deleted from the table. valid (2): Values are enabled. Configuration Changed: administrative') qllc_dte_type = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 4), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('terminalInterfaceUnit', 1), ('hostInterfaceUnit', 2))).clone('terminalInterfaceUnit')).setMaxAccess('readwrite') if mibBuilder.loadTexts: qllcDteType.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteType.setDescription('Determines the type of interface (HIU or TIU) associated with this DTE. Options: terminalInterfaceUnit (1): The SAP type is a TIU, which means it is connected to one or more control units (secondary link stations). The TIU emulates a primary link station, and polls the attached control units. The SDLC interface can support a total of 64 control units across all TIU SAPs. hostInterfaceUnit (2): The SAP type is an HIU, which means it is connected to an SNA host (primary link station). The HIU emulates the control units connected to a TIU. It responds to polls issued by the host. Default Value: terminalInterfaceUnit (1) Configuration Changed: administrative') qllc_dte_called_address = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 5), x25_address()).setMaxAccess('readwrite') if mibBuilder.loadTexts: qllcDteCalledAddress.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteCalledAddress.setDescription('Determines the DTE to call to establish a QLLC connection. Range of Values: DTE address enclosed in quotes (up to 15 characters in length) Default Value: none Configuration Changed: administrative and operative') qllc_dte_calling_address = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 6), x25_address()).setMaxAccess('readwrite') if mibBuilder.loadTexts: qllcDteCallingAddress.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteCallingAddress.setDescription('Determines the DTE address of the caller. Range of Values: DTE address enclosed in quotes (up to 15 characters in length) Default Value: none Configuration Changed: administrative and operative') qllc_dte_d_bit_call = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('no', 1), ('yes', 2))).clone('yes')).setMaxAccess('readwrite') if mibBuilder.loadTexts: qllcDteDBitCall.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteDBitCall.setDescription('Determines if segmentation is supported and is to be performed by the QLLC layer for the specific DTE entry. Options: no (1): QLLC does not support segmentation. yes (2): QLLC supports segmentation. (For future use.) Default Value: yes (2) Configuration Changed: administrative and operative') qllc_dte_window = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 8), integer32().subtype(subtypeSpec=value_range_constraint(1, 7)).clone(7)).setMaxAccess('readwrite') if mibBuilder.loadTexts: qllcDteWindow.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteWindow.setDescription('Determines the transmit and receive window sizes for this DTE. This window size is used when establishing calls from this DTE, or when receiving calls at this DTE. QLLC only supports modulo 8 window size. Range of Values: 1 - 7 Default Value: 7 Configuration Changed: administrative and operative') qllc_dte_packet_size = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 9), packet_size().clone('bytes128')).setMaxAccess('readwrite') if mibBuilder.loadTexts: qllcDtePacketSize.setStatus('mandatory') if mibBuilder.loadTexts: qllcDtePacketSize.setDescription('Determines the transmit and receive packet size for this DTE when flow control negotiation (x25SapSbscrFlowCntrlParamNegotiation) is not subscribed to, or when a D-bit call is routed through this SAP. Options: bytes16 (4): 16 bytes bytes32 (5): 32 bytes bytes64 (6): 64 bytes bytes128 (7): 128 bytes bytes256 (8): 256 bytes bytes512 (9): 512 bytes bytes1024 (10): 1024 bytes bytes2048 (11): 2048 bytes bytes4096 (12): 4096 bytes Default Value: bytes128 (7) Related Objects: x25SapSbscrFlowCntrlParamNegotiation Configuration Changed: administrative and operative') qllc_dte_throughput = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 10), thruput_class().clone('bps9600')).setMaxAccess('readwrite') if mibBuilder.loadTexts: qllcDteThroughput.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteThroughput.setDescription('Determines the transmit and receive throughput class for this DTE when flow control negotiation (x25SapSbscrThruputClassNegotiation) is not subscribed to, or when a D-bit call is routed through this SAP. Options: bps75 (3) bps150 (4) bps300 (5) bps600 (6) bps1200 (7) bps2400 (8) bps4800 (9) bps9600 (10) bps19200 (11) bps38400 (12) bps64000 (13) Default Value: bps9600 (10) Related Objects: x25SapSbscrThruputClassNegotiation Configuration Changed: administrative and operative') qllc_dte_user_data = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 11), display_string().subtype(subtypeSpec=value_size_constraint(0, 12))).setMaxAccess('readwrite') if mibBuilder.loadTexts: qllcDteUserData.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteUserData.setDescription('Determines the data included in the call user data field of each outgoing call initiated by this DTE. Call user data can only be included when calling non-Memotec devices. In this case, up to 12 characters can be specified. The format of the call user data field is determined by the value of the qllcDteMemotec object. Related Object: qllcDteMemotec Range of Values: 0 - 12 characters Default Value: none Configuration Changed: administrative and operative') qllc_dte_facility = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 12), octet_string()).setMaxAccess('readwrite') if mibBuilder.loadTexts: qllcDteFacility.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteFacility.setDescription('Determines the facility codes and associated parameters for this DTE. Default Value: 0 Range of Values: 0 - 20 hexadecimal characters Configuration Changed: administrative and operative') qllc_dte_memotec = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 13), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('nonmemotec', 1), ('cx900', 2), ('legacy', 3), ('pvc', 4))).clone('cx900')).setMaxAccess('readwrite') if mibBuilder.loadTexts: qllcDteMemotec.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteMemotec.setDescription('Determines the type of product that the called DTE address is associated with, which in turn determines how the call user data (CUD) field is constructed for all outgoing calls from this DTE. This object also determines whether the call is associated to a Switched Virtual Circuit (SVC) or a Permanent Virtual Circuit (PVC). Options: (1): Called DTE address is a non- Memotec product. CUD field = QLLC protocol ID + value of object qllcDteUserData (2): Called DTE is a Memotec CX900 product. CUD field = QLLC protocol ID + value of object qllcDteIndex (3): Called DTE is an older Memotec product (including CX1000). CUD field = QLLC protocol ID + / + Port Group GE + CU Alias + FF + Port + FF + FF (4): The DTE is connected through a Permanent Virtual Circuit (PVC), and can be either TIU or HIU. Note that if the DTE is configured for an SVC but a PVC call is received, the QLLC layer will attempt to connect to the PVC. Default Value: cx900 (2) Related Objects: qllcDteUserData qllcDteCalledAddress qllcDteConnectMethod Configuration Changed: administrative and operative') qllc_dte_pvc = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 14), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('no', 1), ('yes', 2))).clone('no')).setMaxAccess('readwrite') if mibBuilder.loadTexts: qllcDtePvc.setStatus('mandatory') if mibBuilder.loadTexts: qllcDtePvc.setDescription('Determines if this DTE makes its calls on a PVC (permanent virtual circuit). Options: no (1): This DTE does not make its calls on a PVC (all calls are switched). yes (2): This DTE makes its calls on a PVC. (For future use.) Default Value: no (1) Configuration Changed: administrative ') qllc_dte_connect_method = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 15), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('userdata', 1), ('callingaddress', 2))).clone('userdata')).setMaxAccess('readwrite') if mibBuilder.loadTexts: qllcDteConnectMethod.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteConnectMethod.setDescription("Determines if this DTE accepts calls by validating the user-data field, or by matching the calling address with its corresponding called address. Note: This object only applies to the HIU. Options: userdata (1): The HIU DTE validates the call using the user-data field. callingaddress (2): The HIU DTE validates the call by matching the call's calling address with the configured called address. Default Value: userdata (1) Configuration Changed: administrative ") qllc_dte_control = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 20), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1))).clone(namedValues=named_values(('clearStats', 1)))).setMaxAccess('writeonly') if mibBuilder.loadTexts: qllcDteControl.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteControl.setDescription('Clears all statistics for this service access point. Options: clearStats (1): Clear statistics. Default Value: none Configuration Changed: administrative and operative') qllc_dte_status = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 30), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('connected', 1), ('pendingConnect', 2), ('disconnected', 3), ('pendingDisconnect', 4)))).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteStatus.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteStatus.setDescription('Indicates the connection status of this DTE. Options: connected (1): This DTE is connected. pendingConnect (2): This DTE has issued a call and is waiting for it to complete. disconnected (3): This DTE is not connected. pendingDisconnect (4): This DTE has issued a call clear and is waiting for it to complete. Configuration Changed: administrative and operative') qllc_dte_operational_mode = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 31), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('offline', 1), ('online', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteOperationalMode.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteOperationalMode.setDescription('Indicates the operational state of this DTE. Options: offLine (1): Indicates that this DTE is not operational. onLine (2): Indicates that this DTE is operational.') qllc_dte_state = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 32), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11))).clone(namedValues=named_values(('opened', 1), ('closed', 2), ('xidcmd', 3), ('tstcmd', 4), ('xidrsp', 5), ('tstrsp', 6), ('reset', 7), ('setmode', 8), ('disc', 9), ('reqdisc', 10), ('unknown', 11)))).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteState.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteState.setDescription('Indicates the state of this DTE with regards to SNA traffic. Options: opened (1): Indicates that this DTE is in data transfer mode (a QSM was sent and a QUA was received). closed (2): Indicates that this DTE is not in data transfer mode (QSM not sent or QUA not received). xidcmd (3): Indicates that an XID was sent by the TIU and received by the HIU. tstcmd (4): Indicates that a TEST was sent by the TIU and received by the HIU. xiddrsp (5): Indicates that the HIU received an XID response from the TIU, or that the TIU received an XID response from the control unit. tsttrsp (6): Indicates that the HIU received a TEST response from the TIU, or that the TIU received a TEST response from the control unit. reset (7): Indicates that an X.25 reset was received. setmode (8): Indicates that a QSM was received. disc (9): Indicates that the HIU received a DISC from the host, or that the TIU sent a DISC to the control unit. reqdisc (10): Indicates that the HIU sent a DISC to the host, or that the TIU received a DISC from the control unit. unknown (11): Indicates that an unknown condition has occurred. ') qllc_dte_connection_type = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 33), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('none', 1), ('svc', 2), ('pvc', 3)))).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteConnectionType.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteConnectionType.setDescription('Identifies the type of X.25 connection that the DTE is supporting. Options: none (1): No X.25 connection exists yet. svc (2): The QLLC DTE is transmitting SNA data over a Switched Virtual Circuit (SVC). pvc (3): The QLLC DTE is transmitting SNA data over a Permanent Virtual Circuit (PVC).') qllc_dte_calls = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 40), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteCalls.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteCalls.setDescription('Indicates the number of incoming calls received by this DTE.') qllc_dte_clears = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 41), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteClears.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteClears.setDescription('Indicates the number of calls cleared by this DTE.') qllc_dte_tx_packets = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 42), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteTxPackets.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteTxPackets.setDescription('Indicates the number of data packets sent by this DTE.') qllc_dte_rx_packets = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 43), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteRxPackets.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteRxPackets.setDescription('Indicates the number of data packets received by this DTE.') qllc_dte_qdc = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 44), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteQdc.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteQdc.setDescription('Indicates the number of SNA disconnects sent and received by this DTE.') qllc_dte_qxid = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 45), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteQxid.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteQxid.setDescription('Indicates the number of SNA XIDs sent and received by this DTE.') qllc_dte_qua = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 46), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteQua.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteQua.setDescription('Indicates the number of unnumbered acknowledgments sent and received by this DTE.') qllc_dte_qsm = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 47), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteQsm.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteQsm.setDescription('Indicates the number of SNRMs sent and received by this DTE.') qllc_dte_x25_reset = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 48), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteX25Reset.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteX25Reset.setDescription('Indicates the number of X.25 resets sent and received by this DTE.') qllc_dte_snalc_rnr = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 49), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteSnalcRnr.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteSnalcRnr.setDescription('Indicates the number of SNA link conversion layer flow control RNRs sent and received by this DTE.') qllc_dte_snalc_rr = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 50), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteSnalcRr.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteSnalcRr.setDescription('Indicates the number of SNA link conversion layer flow control RRs sent and received by this DTE.') qllc_dte_x25_rnr = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 51), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteX25Rnr.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteX25Rnr.setDescription('Indicates the number of X.25 flow control RNRs sent and received by this DTE.') qllc_dte_x25_rr = mib_table_column((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 2, 1, 52), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcDteX25Rr.setStatus('mandatory') if mibBuilder.loadTexts: qllcDteX25Rr.setDescription('Indicates the number of X.25 flow control RRs sent and received by this DTE.') qllc_mib_level = mib_scalar((1, 3, 6, 1, 4, 1, 495, 2, 1, 6, 38, 3), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: qllcMibLevel.setStatus('mandatory') if mibBuilder.loadTexts: qllcMibLevel.setDescription('Used to determine current MIB module release supported by the agent. Object is in decimal.') mibBuilder.exportSymbols('CXQLLC-MIB', qllcSapAlias=qllcSapAlias, qllcDteCalls=qllcDteCalls, qllcDteClears=qllcDteClears, qllcSapTable=qllcSapTable, qllcDtePacketSize=qllcDtePacketSize, qllcDteStatus=qllcDteStatus, qllcSapCompanionAlias=qllcSapCompanionAlias, qllcDteRowStatus=qllcDteRowStatus, qllcDteQdc=qllcDteQdc, qllcDtePvc=qllcDtePvc, qllcDteQua=qllcDteQua, qllcSapOperationalMode=qllcSapOperationalMode, qllcDteOperationalMode=qllcDteOperationalMode, qllcDteDBitCall=qllcDteDBitCall, qllcSapRowStatus=qllcSapRowStatus, qllcDteEntry=qllcDteEntry, qllcDteCalledAddress=qllcDteCalledAddress, qllcDteConnectionType=qllcDteConnectionType, qllcDteType=qllcDteType, qllcDteSnalcRr=qllcDteSnalcRr, qllcDteX25Rnr=qllcDteX25Rnr, qllcMibLevel=qllcMibLevel, qllcDteQsm=qllcDteQsm, qllcDteTxPackets=qllcDteTxPackets, qllcDteMemotec=qllcDteMemotec, qllcDteQxid=qllcDteQxid, qllcDteTable=qllcDteTable, qllcDteSap=qllcDteSap, qllcDteThroughput=qllcDteThroughput, qllcDteConnectMethod=qllcDteConnectMethod, qllcDteX25Reset=qllcDteX25Reset, qllcSapNumber=qllcSapNumber, qllcDteSnalcRnr=qllcDteSnalcRnr, qllcSapEntry=qllcSapEntry, qllcDteControl=qllcDteControl, qllcDteFacility=qllcDteFacility, qllcDteState=qllcDteState, PacketSize=PacketSize, qllcSapType=qllcSapType, qllcSapSnalcRef=qllcSapSnalcRef, qllcDteCallingAddress=qllcDteCallingAddress, qllcDteIndex=qllcDteIndex, qllcDteUserData=qllcDteUserData, X25Address=X25Address, qllcDteX25Rr=qllcDteX25Rr, qllcDteRxPackets=qllcDteRxPackets, qllcDteWindow=qllcDteWindow)
RGB2HEX = 1 RGB2HSV = 2 RGB2HSL = 3 HEX2RGB = 4 HSV2RGB = 5 OPCV_RGB2HSV = 100 OPCV_HSV2RGB = 101
rgb2_hex = 1 rgb2_hsv = 2 rgb2_hsl = 3 hex2_rgb = 4 hsv2_rgb = 5 opcv_rgb2_hsv = 100 opcv_hsv2_rgb = 101
class ImageGroupsComponent: def __init__(self, key=None, imageGroup=None): self.key = 'imagegroups' self.current = None self.animationList = {} self.alpha = 255 self.hue = None self.playing = True if key is not None and imageGroup is not None: self.add(key, imageGroup) def getCurrentImageGroup(self): if self.animationList == {} or self.current is None: return None return self.animationList[self.current] def add(self, state, animation): self.animationList[state] = animation if self.current == None: self.current = state def pause(self): self.playing = False def play(self): self.playing = True def stop(self): self.playing = False self.animationList[self.current].reset()
class Imagegroupscomponent: def __init__(self, key=None, imageGroup=None): self.key = 'imagegroups' self.current = None self.animationList = {} self.alpha = 255 self.hue = None self.playing = True if key is not None and imageGroup is not None: self.add(key, imageGroup) def get_current_image_group(self): if self.animationList == {} or self.current is None: return None return self.animationList[self.current] def add(self, state, animation): self.animationList[state] = animation if self.current == None: self.current = state def pause(self): self.playing = False def play(self): self.playing = True def stop(self): self.playing = False self.animationList[self.current].reset()
class Tag(object): def __init__(self, tag_name : str, type_ = None): self.__tag_name = tag_name self.__type : str = type_ if type_ is not None else "" @property def type(self) -> str: return self.__type @property def name(self) -> str: return self.__tag_name def __str__(self) -> str: return self.type + ":" + self.__tag_name def __eq__(self, o: object): return str(o).lower() == str(self).lower() def __hash__(self) -> int: return hash(str(self)) def __repr__(self) -> str: return "<%s>" % str(self)
class Tag(object): def __init__(self, tag_name: str, type_=None): self.__tag_name = tag_name self.__type: str = type_ if type_ is not None else '' @property def type(self) -> str: return self.__type @property def name(self) -> str: return self.__tag_name def __str__(self) -> str: return self.type + ':' + self.__tag_name def __eq__(self, o: object): return str(o).lower() == str(self).lower() def __hash__(self) -> int: return hash(str(self)) def __repr__(self) -> str: return '<%s>' % str(self)
#First go print("Hello, World!") message = "Hello, World!" print(message) #-------> print "Hello World!" is Python 2 syntax, use print("Hello World!") for Python 3
print('Hello, World!') message = 'Hello, World!' print(message)
# https://leetcode.com/problems/minimum-depth-of-binary-tree # Definition for a binary tree node. # class TreeNode: # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution: def minDepth(self, root): if not root: return 0 ans = set() def helper(node, depth): if (not node.left) and (not node.right): ans.add(depth) return if node.right: helper(node.right, depth + 1) if node.left: helper(node.left, depth + 1) helper(root, 1) return min(ans)
class Solution: def min_depth(self, root): if not root: return 0 ans = set() def helper(node, depth): if not node.left and (not node.right): ans.add(depth) return if node.right: helper(node.right, depth + 1) if node.left: helper(node.left, depth + 1) helper(root, 1) return min(ans)
EXCHANGE_CFFEX = 0 EXCHANGE_SHFE = 1 EXCHANGE_DCE = 2 EXCHANGE_SSEOPT = 3 EXCHANGE_CZCE = 4 EXCHANGE_SZSE = 5 EXCHANGE_SSE = 6 EXCHANGE_UNKNOWN = 7
exchange_cffex = 0 exchange_shfe = 1 exchange_dce = 2 exchange_sseopt = 3 exchange_czce = 4 exchange_szse = 5 exchange_sse = 6 exchange_unknown = 7
numerator = int(input("Enter a numerator: ")) denominator = int(input("Enter denominator: ")) while denominator == 0: print("Denominator cannot be 0") denominator = int(input("Enter denominator: ")) if int(numerator / denominator) * denominator == numerator: print("Divides evenly!") else: print("Doesn't divide evenly.")
numerator = int(input('Enter a numerator: ')) denominator = int(input('Enter denominator: ')) while denominator == 0: print('Denominator cannot be 0') denominator = int(input('Enter denominator: ')) if int(numerator / denominator) * denominator == numerator: print('Divides evenly!') else: print("Doesn't divide evenly.")
class Solution: #Function to find sum of weights of edges of the Minimum Spanning Tree. def spanningTree(self, V, adj): #code here ##findpar with rank compression def findpar(x): if parent[x]==x: return x else: parent[x]=findpar(parent[x]) return parent[x] ##Union by rank def union(x,y): lp_x=findpar(x) lp_y=findpar(y) if rank[lp_x]>rank[lp_y]: parent[lp_y]=lp_x elif rank[lp_x]<rank[lp_y]: parent[lp_x]=lp_y else: parent[lp_y]=lp_x rank[lp_x] += 1 # print(adj) s=0 parent=[] E={} rank=[0 for i in range(V)] for i in range(V): parent.append(i) for i in range(len(adj)): edges=adj[i] # print(edges) for edge in edges: u=i v=edge[0] w=edge[1] if (u,v) not in E and (v,u) not in E: E[(u,v)]=w # print(E) Ef={} Ef=sorted(E.items(),key=lambda x:x[1]) # print(Ef) for i in Ef: # print(i) w=i[1] u=i[0][0] v=i[0][1] # print(u,v,w) lp_u=findpar(u) lp_v=findpar(v) if lp_u!=lp_v: union(u,v) s += w return s
class Solution: def spanning_tree(self, V, adj): def findpar(x): if parent[x] == x: return x else: parent[x] = findpar(parent[x]) return parent[x] def union(x, y): lp_x = findpar(x) lp_y = findpar(y) if rank[lp_x] > rank[lp_y]: parent[lp_y] = lp_x elif rank[lp_x] < rank[lp_y]: parent[lp_x] = lp_y else: parent[lp_y] = lp_x rank[lp_x] += 1 s = 0 parent = [] e = {} rank = [0 for i in range(V)] for i in range(V): parent.append(i) for i in range(len(adj)): edges = adj[i] for edge in edges: u = i v = edge[0] w = edge[1] if (u, v) not in E and (v, u) not in E: E[u, v] = w ef = {} ef = sorted(E.items(), key=lambda x: x[1]) for i in Ef: w = i[1] u = i[0][0] v = i[0][1] lp_u = findpar(u) lp_v = findpar(v) if lp_u != lp_v: union(u, v) s += w return s
class Pegawai: def __init__(self, nama, email, gaji): self.__namaPegawai = nama self.__emailPegawai = email self.__gajiPegawai = gaji # decoration ini digunakan untuk mengakses property # nama pegawai agar dapat diakses tanpa menggunakan # intance.namaPegawai() melainkan instance.namaPegawai @property def namaPegawai(self): return self.__namaPegawai # nama dari decoration harus sama dengan nama property # kemudian diakhiri dengan kata setter untuk menandakan bahwa ini adalah setter dari property @namaPegawai.setter def namaPegawai(self, nama): self.__namaPegawai = nama @property def emailPegawai(self): return self.__emailPegawai @emailPegawai.setter def emailPegawai(self, email): self.__emailPegawai = email @property def gajiPegawai(self): return self.__gajiPegawai @gajiPegawai.setter def gajiPegawai(self, gaji): self.__gajiPegawai = gaji def __str__(self): return "Nama Pegawai : {} \nEmail : {}\nGajiPegawai : {}".format(self.namaPegawai,self.emailPegawai,self.gajiPegawai)
class Pegawai: def __init__(self, nama, email, gaji): self.__namaPegawai = nama self.__emailPegawai = email self.__gajiPegawai = gaji @property def nama_pegawai(self): return self.__namaPegawai @namaPegawai.setter def nama_pegawai(self, nama): self.__namaPegawai = nama @property def email_pegawai(self): return self.__emailPegawai @emailPegawai.setter def email_pegawai(self, email): self.__emailPegawai = email @property def gaji_pegawai(self): return self.__gajiPegawai @gajiPegawai.setter def gaji_pegawai(self, gaji): self.__gajiPegawai = gaji def __str__(self): return 'Nama Pegawai : {} \nEmail : {}\nGajiPegawai : {}'.format(self.namaPegawai, self.emailPegawai, self.gajiPegawai)
snippet_normalize (cr, width, height) cr.set_line_width (0.12) cr.set_line_cap (cairo.LINE_CAP_BUTT) #/* default */ cr.move_to (0.25, 0.2); cr.line_to (0.25, 0.8) cr.stroke () cr.set_line_cap (cairo.LINE_CAP_ROUND) cr.move_to (0.5, 0.2); cr.line_to (0.5, 0.8) cr.stroke () cr.set_line_cap (cairo.LINE_CAP_SQUARE) cr.move_to (0.75, 0.2); cr.line_to (0.75, 0.8) cr.stroke () #/* draw helping lines */ cr.set_source_rgb (1,0.2,0.2) cr.set_line_width (0.01) cr.move_to (0.25, 0.2); cr.line_to (0.25, 0.8) cr.move_to (0.5, 0.2); cr.line_to (0.5, 0.8) cr.move_to (0.75, 0.2); cr.line_to (0.75, 0.8) cr.stroke ()
snippet_normalize(cr, width, height) cr.set_line_width(0.12) cr.set_line_cap(cairo.LINE_CAP_BUTT) cr.move_to(0.25, 0.2) cr.line_to(0.25, 0.8) cr.stroke() cr.set_line_cap(cairo.LINE_CAP_ROUND) cr.move_to(0.5, 0.2) cr.line_to(0.5, 0.8) cr.stroke() cr.set_line_cap(cairo.LINE_CAP_SQUARE) cr.move_to(0.75, 0.2) cr.line_to(0.75, 0.8) cr.stroke() cr.set_source_rgb(1, 0.2, 0.2) cr.set_line_width(0.01) cr.move_to(0.25, 0.2) cr.line_to(0.25, 0.8) cr.move_to(0.5, 0.2) cr.line_to(0.5, 0.8) cr.move_to(0.75, 0.2) cr.line_to(0.75, 0.8) cr.stroke()
class DiscreteEnvWrapper: def __init__(self, env): self.__env = env def reset(self): return self.__env.reset() def step(self, action): next_state, reward, done, info = self.__env.step(action) return next_state, reward, done, info def render(self): self.__env.render() def close(self): self.__env.close() def get_random_action(self): return self.__env.action_space.sample() def get_total_actions(self): return self.__env.action_space.n def get_total_states(self): return self.__env.observation_space.n def seed(self, seed=None, set_action_seed=True): if set_action_seed: self.__env.action_space.seed(seed) return self.__env.seed(seed)
class Discreteenvwrapper: def __init__(self, env): self.__env = env def reset(self): return self.__env.reset() def step(self, action): (next_state, reward, done, info) = self.__env.step(action) return (next_state, reward, done, info) def render(self): self.__env.render() def close(self): self.__env.close() def get_random_action(self): return self.__env.action_space.sample() def get_total_actions(self): return self.__env.action_space.n def get_total_states(self): return self.__env.observation_space.n def seed(self, seed=None, set_action_seed=True): if set_action_seed: self.__env.action_space.seed(seed) return self.__env.seed(seed)
def mse(x, target): n = max(x.numel(), target.numel()) return (x - target).pow(2).sum() / n def snr(x, target): noise = (x - target).pow(2).sum() signal = target.pow(2).sum() SNR = 10 * (signal / noise).log10_() return SNR
def mse(x, target): n = max(x.numel(), target.numel()) return (x - target).pow(2).sum() / n def snr(x, target): noise = (x - target).pow(2).sum() signal = target.pow(2).sum() snr = 10 * (signal / noise).log10_() return SNR
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def bstFromPreorder(self, preorder: List[int]) -> TreeNode: size = len(preorder) root = TreeNode(preorder[0]) s = [] s.append(root) i = 1 while (i < size): temp = None while(len(s)>0 and preorder[i] > s[-1].val): temp = s.pop() if (temp != None): temp.right = TreeNode(preorder[i]) s.append(temp.right) else: temp = s[-1] temp.left = TreeNode(preorder[i]) s.append(temp.left) i = i+1 return root
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def bst_from_preorder(self, preorder: List[int]) -> TreeNode: size = len(preorder) root = tree_node(preorder[0]) s = [] s.append(root) i = 1 while i < size: temp = None while len(s) > 0 and preorder[i] > s[-1].val: temp = s.pop() if temp != None: temp.right = tree_node(preorder[i]) s.append(temp.right) else: temp = s[-1] temp.left = tree_node(preorder[i]) s.append(temp.left) i = i + 1 return root
def get_account(account_id: int): return { 'account_id': 1, 'email': 'noreply@gerenciagram.com', 'first_name': 'Gerenciagram' }
def get_account(account_id: int): return {'account_id': 1, 'email': 'noreply@gerenciagram.com', 'first_name': 'Gerenciagram'}
__author__ = 'Michael Andrew michael@hazardmedia.co.nz' class SoundModel(object): sound = None path = "" delay = 0 delay_min = 0 delay_max = 0 def __init__(self, sound, path, delay=0, delay_min=0, delay_max=0): self.sound = sound self.path = path self.delay = delay self.delay_min = delay_min self.delay_max = delay_max
__author__ = 'Michael Andrew michael@hazardmedia.co.nz' class Soundmodel(object): sound = None path = '' delay = 0 delay_min = 0 delay_max = 0 def __init__(self, sound, path, delay=0, delay_min=0, delay_max=0): self.sound = sound self.path = path self.delay = delay self.delay_min = delay_min self.delay_max = delay_max
max_strlen=[] max_strindex=[] for i in range(1,11): file_name="sample."+str(i) with open(file_name,"rb") as f: offsets=[] len_of_file=[] for strand in f.readlines(): offsets.append(sum(len_of_file)) len_of_file.append(len(strand)) max_strlen.append(max(len_of_file)) max_strindex.append(len_of_file.index(max(len_of_file))) print("The lengths of strand in file {} are:\n{}".format(file_name,str(len_of_file)[1:-1])) print("The offsets for each strand to appear in file {} are:\n{}".format(file_name,str(offsets)[1:-1])) print("The file name of the largest strand that appears is: sample.{}".format(max_strlen.index(max(max_strlen))+1)) # file=open("sample.1","rb") # # print(type(file.readlines()[1][:-1].decode("gbk"))) # # print(len(file.readline()[:-1])) # # e=[] # # for i in file.readlines(): # # e.append(len(i)) # # print(sum(e)) # # print(file.read()) # print(len(file.read()))
max_strlen = [] max_strindex = [] for i in range(1, 11): file_name = 'sample.' + str(i) with open(file_name, 'rb') as f: offsets = [] len_of_file = [] for strand in f.readlines(): offsets.append(sum(len_of_file)) len_of_file.append(len(strand)) max_strlen.append(max(len_of_file)) max_strindex.append(len_of_file.index(max(len_of_file))) print('The lengths of strand in file {} are:\n{}'.format(file_name, str(len_of_file)[1:-1])) print('The offsets for each strand to appear in file {} are:\n{}'.format(file_name, str(offsets)[1:-1])) print('The file name of the largest strand that appears is: sample.{}'.format(max_strlen.index(max(max_strlen)) + 1))
tokens = ('IMPLY', 'LPAREN', 'RPAREN', 'PREDICATENAME', 'PREDICATEVAR') precedence = ( ('left', 'IMPLY'), ('left', '|', '&'), ('right', '~'), ) t_ignore = ' \t' t_IMPLY = r'=>' t_RPAREN = r'\)' t_LPAREN = r'\(' literals = ['|', ',', '&', '~'] def t_PREDICATENAME(t): r'[A-Z][a-zA-Z0-9_]*' t.value = str(t.value) return t def t_PREDICATEVAR(t): r'[a-z]' t.value = str(t.value) return t def t_newline(t): r'\n+' t.lexer.lineno += t.value.count("\n") def t_error(t): print("Illegal character '%s'" % t.value[0]) t.lexer.skip(1)
tokens = ('IMPLY', 'LPAREN', 'RPAREN', 'PREDICATENAME', 'PREDICATEVAR') precedence = (('left', 'IMPLY'), ('left', '|', '&'), ('right', '~')) t_ignore = ' \t' t_imply = '=>' t_rparen = '\\)' t_lparen = '\\(' literals = ['|', ',', '&', '~'] def t_predicatename(t): """[A-Z][a-zA-Z0-9_]*""" t.value = str(t.value) return t def t_predicatevar(t): """[a-z]""" t.value = str(t.value) return t def t_newline(t): """\\n+""" t.lexer.lineno += t.value.count('\n') def t_error(t): print("Illegal character '%s'" % t.value[0]) t.lexer.skip(1)
for i in range(int(input())): n = int(input()) a = [0 for j in range(32)] for j in range(n): s = input() p = 0 if('a' in s): p|=1 if('e' in s): p|=2 if('i' in s): p|=4 if('o' in s): p|=8 if('u' in s): p|=16 a[p]+=1 c = 0 for j in range(32): for k in range(j+1,32): if(j|k==31): c+=a[j]*a[k] c+=int(a[31]*(a[31]-1)/2) print(c)
for i in range(int(input())): n = int(input()) a = [0 for j in range(32)] for j in range(n): s = input() p = 0 if 'a' in s: p |= 1 if 'e' in s: p |= 2 if 'i' in s: p |= 4 if 'o' in s: p |= 8 if 'u' in s: p |= 16 a[p] += 1 c = 0 for j in range(32): for k in range(j + 1, 32): if j | k == 31: c += a[j] * a[k] c += int(a[31] * (a[31] - 1) / 2) print(c)
begin_unit comment|'# Copyright 2013 OpenStack Foundation' nl|'\n' comment|'#' nl|'\n' comment|'# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl|'\n' comment|'# not use this file except in compliance with the License. You may obtain' nl|'\n' comment|'# a copy of the License at' nl|'\n' comment|'#' nl|'\n' comment|'# http://www.apache.org/licenses/LICENSE-2.0' nl|'\n' comment|'#' nl|'\n' comment|'# Unless required by applicable law or agreed to in writing, software' nl|'\n' comment|'# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT' nl|'\n' comment|'# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the' nl|'\n' comment|'# License for the specific language governing permissions and limitations' nl|'\n' comment|'# under the License.' nl|'\n' nl|'\n' name|'import' name|'datetime' newline|'\n' nl|'\n' name|'from' name|'nova' name|'import' name|'db' newline|'\n' nl|'\n' nl|'\n' DECL|variable|FAKE_UUID name|'FAKE_UUID' op|'=' string|"'b48316c5-71e8-45e4-9884-6c78055b9b13'" newline|'\n' DECL|variable|FAKE_REQUEST_ID1 name|'FAKE_REQUEST_ID1' op|'=' string|"'req-3293a3f1-b44c-4609-b8d2-d81b105636b8'" newline|'\n' DECL|variable|FAKE_REQUEST_ID2 name|'FAKE_REQUEST_ID2' op|'=' string|"'req-25517360-b757-47d3-be45-0e8d2a01b36a'" newline|'\n' DECL|variable|FAKE_ACTION_ID1 name|'FAKE_ACTION_ID1' op|'=' number|'123' newline|'\n' DECL|variable|FAKE_ACTION_ID2 name|'FAKE_ACTION_ID2' op|'=' number|'456' newline|'\n' nl|'\n' DECL|variable|FAKE_ACTIONS name|'FAKE_ACTIONS' op|'=' op|'{' nl|'\n' name|'FAKE_UUID' op|':' op|'{' nl|'\n' name|'FAKE_REQUEST_ID1' op|':' op|'{' string|"'id'" op|':' name|'FAKE_ACTION_ID1' op|',' nl|'\n' string|"'action'" op|':' string|"'reboot'" op|',' nl|'\n' string|"'instance_uuid'" op|':' name|'FAKE_UUID' op|',' nl|'\n' string|"'request_id'" op|':' name|'FAKE_REQUEST_ID1' op|',' nl|'\n' string|"'project_id'" op|':' string|"'147'" op|',' nl|'\n' string|"'user_id'" op|':' string|"'789'" op|',' nl|'\n' string|"'start_time'" op|':' name|'datetime' op|'.' name|'datetime' op|'(' nl|'\n' number|'2012' op|',' number|'12' op|',' number|'5' op|',' number|'0' op|',' number|'0' op|',' number|'0' op|',' number|'0' op|')' op|',' nl|'\n' string|"'finish_time'" op|':' name|'None' op|',' nl|'\n' string|"'message'" op|':' string|"''" op|',' nl|'\n' string|"'created_at'" op|':' name|'None' op|',' nl|'\n' string|"'updated_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted'" op|':' name|'False' op|',' nl|'\n' op|'}' op|',' nl|'\n' name|'FAKE_REQUEST_ID2' op|':' op|'{' string|"'id'" op|':' name|'FAKE_ACTION_ID2' op|',' nl|'\n' string|"'action'" op|':' string|"'resize'" op|',' nl|'\n' string|"'instance_uuid'" op|':' name|'FAKE_UUID' op|',' nl|'\n' string|"'request_id'" op|':' name|'FAKE_REQUEST_ID2' op|',' nl|'\n' string|"'user_id'" op|':' string|"'789'" op|',' nl|'\n' string|"'project_id'" op|':' string|"'842'" op|',' nl|'\n' string|"'start_time'" op|':' name|'datetime' op|'.' name|'datetime' op|'(' nl|'\n' number|'2012' op|',' number|'12' op|',' number|'5' op|',' number|'1' op|',' number|'0' op|',' number|'0' op|',' number|'0' op|')' op|',' nl|'\n' string|"'finish_time'" op|':' name|'None' op|',' nl|'\n' string|"'message'" op|':' string|"''" op|',' nl|'\n' string|"'created_at'" op|':' name|'None' op|',' nl|'\n' string|"'updated_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted'" op|':' name|'False' op|',' nl|'\n' op|'}' nl|'\n' op|'}' nl|'\n' op|'}' newline|'\n' nl|'\n' DECL|variable|FAKE_EVENTS name|'FAKE_EVENTS' op|'=' op|'{' nl|'\n' name|'FAKE_ACTION_ID1' op|':' op|'[' op|'{' string|"'id'" op|':' number|'1' op|',' nl|'\n' string|"'action_id'" op|':' name|'FAKE_ACTION_ID1' op|',' nl|'\n' string|"'event'" op|':' string|"'schedule'" op|',' nl|'\n' string|"'start_time'" op|':' name|'datetime' op|'.' name|'datetime' op|'(' nl|'\n' number|'2012' op|',' number|'12' op|',' number|'5' op|',' number|'1' op|',' number|'0' op|',' number|'2' op|',' number|'0' op|')' op|',' nl|'\n' string|"'finish_time'" op|':' name|'datetime' op|'.' name|'datetime' op|'(' nl|'\n' number|'2012' op|',' number|'12' op|',' number|'5' op|',' number|'1' op|',' number|'2' op|',' number|'0' op|',' number|'0' op|')' op|',' nl|'\n' string|"'result'" op|':' string|"'Success'" op|',' nl|'\n' string|"'traceback'" op|':' string|"''" op|',' nl|'\n' string|"'created_at'" op|':' name|'None' op|',' nl|'\n' string|"'updated_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted'" op|':' name|'False' op|',' nl|'\n' op|'}' op|',' nl|'\n' op|'{' string|"'id'" op|':' number|'2' op|',' nl|'\n' string|"'action_id'" op|':' name|'FAKE_ACTION_ID1' op|',' nl|'\n' string|"'event'" op|':' string|"'compute_create'" op|',' nl|'\n' string|"'start_time'" op|':' name|'datetime' op|'.' name|'datetime' op|'(' nl|'\n' number|'2012' op|',' number|'12' op|',' number|'5' op|',' number|'1' op|',' number|'3' op|',' number|'0' op|',' number|'0' op|')' op|',' nl|'\n' string|"'finish_time'" op|':' name|'datetime' op|'.' name|'datetime' op|'(' nl|'\n' number|'2012' op|',' number|'12' op|',' number|'5' op|',' number|'1' op|',' number|'4' op|',' number|'0' op|',' number|'0' op|')' op|',' nl|'\n' string|"'result'" op|':' string|"'Success'" op|',' nl|'\n' string|"'traceback'" op|':' string|"''" op|',' nl|'\n' string|"'created_at'" op|':' name|'None' op|',' nl|'\n' string|"'updated_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted'" op|':' name|'False' op|',' nl|'\n' op|'}' nl|'\n' op|']' op|',' nl|'\n' name|'FAKE_ACTION_ID2' op|':' op|'[' op|'{' string|"'id'" op|':' number|'3' op|',' nl|'\n' string|"'action_id'" op|':' name|'FAKE_ACTION_ID2' op|',' nl|'\n' string|"'event'" op|':' string|"'schedule'" op|',' nl|'\n' string|"'start_time'" op|':' name|'datetime' op|'.' name|'datetime' op|'(' nl|'\n' number|'2012' op|',' number|'12' op|',' number|'5' op|',' number|'3' op|',' number|'0' op|',' number|'0' op|',' number|'0' op|')' op|',' nl|'\n' string|"'finish_time'" op|':' name|'datetime' op|'.' name|'datetime' op|'(' nl|'\n' number|'2012' op|',' number|'12' op|',' number|'5' op|',' number|'3' op|',' number|'2' op|',' number|'0' op|',' number|'0' op|')' op|',' nl|'\n' string|"'result'" op|':' string|"'Error'" op|',' nl|'\n' string|"'traceback'" op|':' string|"''" op|',' nl|'\n' string|"'created_at'" op|':' name|'None' op|',' nl|'\n' string|"'updated_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted_at'" op|':' name|'None' op|',' nl|'\n' string|"'deleted'" op|':' name|'False' op|',' nl|'\n' op|'}' nl|'\n' op|']' nl|'\n' op|'}' newline|'\n' nl|'\n' nl|'\n' DECL|function|fake_action_event_start name|'def' name|'fake_action_event_start' op|'(' op|'*' name|'args' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'FAKE_EVENTS' op|'[' name|'FAKE_ACTION_ID1' op|']' op|'[' number|'0' op|']' newline|'\n' nl|'\n' nl|'\n' DECL|function|fake_action_event_finish dedent|'' name|'def' name|'fake_action_event_finish' op|'(' op|'*' name|'args' op|')' op|':' newline|'\n' indent|' ' name|'return' name|'FAKE_EVENTS' op|'[' name|'FAKE_ACTION_ID1' op|']' op|'[' number|'0' op|']' newline|'\n' nl|'\n' nl|'\n' DECL|function|stub_out_action_events dedent|'' name|'def' name|'stub_out_action_events' op|'(' name|'stubs' op|')' op|':' newline|'\n' indent|' ' name|'stubs' op|'.' name|'Set' op|'(' name|'db' op|',' string|"'action_event_start'" op|',' name|'fake_action_event_start' op|')' newline|'\n' name|'stubs' op|'.' name|'Set' op|'(' name|'db' op|',' string|"'action_event_finish'" op|',' name|'fake_action_event_finish' op|')' newline|'\n' dedent|'' endmarker|'' end_unit
begin_unit comment | '# Copyright 2013 OpenStack Foundation' nl | '\n' comment | '#' nl | '\n' comment | '# Licensed under the Apache License, Version 2.0 (the "License"); you may' nl | '\n' comment | '# not use this file except in compliance with the License. You may obtain' nl | '\n' comment | '# a copy of the License at' nl | '\n' comment | '#' nl | '\n' comment | '# http://www.apache.org/licenses/LICENSE-2.0' nl | '\n' comment | '#' nl | '\n' comment | '# Unless required by applicable law or agreed to in writing, software' nl | '\n' comment | '# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT' nl | '\n' comment | '# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the' nl | '\n' comment | '# License for the specific language governing permissions and limitations' nl | '\n' comment | '# under the License.' nl | '\n' nl | '\n' name | 'import' name | 'datetime' newline | '\n' nl | '\n' name | 'from' name | 'nova' name | 'import' name | 'db' newline | '\n' nl | '\n' nl | '\n' DECL | variable | FAKE_UUID name | 'FAKE_UUID' op | '=' string | "'b48316c5-71e8-45e4-9884-6c78055b9b13'" newline | '\n' DECL | variable | FAKE_REQUEST_ID1 name | 'FAKE_REQUEST_ID1' op | '=' string | "'req-3293a3f1-b44c-4609-b8d2-d81b105636b8'" newline | '\n' DECL | variable | FAKE_REQUEST_ID2 name | 'FAKE_REQUEST_ID2' op | '=' string | "'req-25517360-b757-47d3-be45-0e8d2a01b36a'" newline | '\n' DECL | variable | FAKE_ACTION_ID1 name | 'FAKE_ACTION_ID1' op | '=' number | '123' newline | '\n' DECL | variable | FAKE_ACTION_ID2 name | 'FAKE_ACTION_ID2' op | '=' number | '456' newline | '\n' nl | '\n' DECL | variable | FAKE_ACTIONS name | 'FAKE_ACTIONS' op | '=' op | '{' nl | '\n' name | 'FAKE_UUID' op | ':' op | '{' nl | '\n' name | 'FAKE_REQUEST_ID1' op | ':' op | '{' string | "'id'" op | ':' name | 'FAKE_ACTION_ID1' op | ',' nl | '\n' string | "'action'" op | ':' string | "'reboot'" op | ',' nl | '\n' string | "'instance_uuid'" op | ':' name | 'FAKE_UUID' op | ',' nl | '\n' string | "'request_id'" op | ':' name | 'FAKE_REQUEST_ID1' op | ',' nl | '\n' string | "'project_id'" op | ':' string | "'147'" op | ',' nl | '\n' string | "'user_id'" op | ':' string | "'789'" op | ',' nl | '\n' string | "'start_time'" op | ':' name | 'datetime' op | '.' name | 'datetime' op | '(' nl | '\n' number | '2012' op | ',' number | '12' op | ',' number | '5' op | ',' number | '0' op | ',' number | '0' op | ',' number | '0' op | ',' number | '0' op | ')' op | ',' nl | '\n' string | "'finish_time'" op | ':' name | 'None' op | ',' nl | '\n' string | "'message'" op | ':' string | "''" op | ',' nl | '\n' string | "'created_at'" op | ':' name | 'None' op | ',' nl | '\n' string | "'updated_at'" op | ':' name | 'None' op | ',' nl | '\n' string | "'deleted_at'" op | ':' name | 'None' op | ',' nl | '\n' string | "'deleted'" op | ':' name | 'False' op | ',' nl | '\n' op | '}' op | ',' nl | '\n' name | 'FAKE_REQUEST_ID2' op | ':' op | '{' string | "'id'" op | ':' name | 'FAKE_ACTION_ID2' op | ',' nl | '\n' string | "'action'" op | ':' string | "'resize'" op | ',' nl | '\n' string | "'instance_uuid'" op | ':' name | 'FAKE_UUID' op | ',' nl | '\n' string | "'request_id'" op | ':' name | 'FAKE_REQUEST_ID2' op | ',' nl | '\n' string | "'user_id'" op | ':' string | "'789'" op | ',' nl | '\n' string | "'project_id'" op | ':' string | "'842'" op | ',' nl | '\n' string | "'start_time'" op | ':' name | 'datetime' op | '.' name | 'datetime' op | '(' nl | '\n' number | '2012' op | ',' number | '12' op | ',' number | '5' op | ',' number | '1' op | ',' number | '0' op | ',' number | '0' op | ',' number | '0' op | ')' op | ',' nl | '\n' string | "'finish_time'" op | ':' name | 'None' op | ',' nl | '\n' string | "'message'" op | ':' string | "''" op | ',' nl | '\n' string | "'created_at'" op | ':' name | 'None' op | ',' nl | '\n' string | "'updated_at'" op | ':' name | 'None' op | ',' nl | '\n' string | "'deleted_at'" op | ':' name | 'None' op | ',' nl | '\n' string | "'deleted'" op | ':' name | 'False' op | ',' nl | '\n' op | '}' nl | '\n' op | '}' nl | '\n' op | '}' newline | '\n' nl | '\n' DECL | variable | FAKE_EVENTS name | 'FAKE_EVENTS' op | '=' op | '{' nl | '\n' name | 'FAKE_ACTION_ID1' op | ':' op | '[' op | '{' string | "'id'" op | ':' number | '1' op | ',' nl | '\n' string | "'action_id'" op | ':' name | 'FAKE_ACTION_ID1' op | ',' nl | '\n' string | "'event'" op | ':' string | "'schedule'" op | ',' nl | '\n' string | "'start_time'" op | ':' name | 'datetime' op | '.' name | 'datetime' op | '(' nl | '\n' number | '2012' op | ',' number | '12' op | ',' number | '5' op | ',' number | '1' op | ',' number | '0' op | ',' number | '2' op | ',' number | '0' op | ')' op | ',' nl | '\n' string | "'finish_time'" op | ':' name | 'datetime' op | '.' name | 'datetime' op | '(' nl | '\n' number | '2012' op | ',' number | '12' op | ',' number | '5' op | ',' number | '1' op | ',' number | '2' op | ',' number | '0' op | ',' number | '0' op | ')' op | ',' nl | '\n' string | "'result'" op | ':' string | "'Success'" op | ',' nl | '\n' string | "'traceback'" op | ':' string | "''" op | ',' nl | '\n' string | "'created_at'" op | ':' name | 'None' op | ',' nl | '\n' string | "'updated_at'" op | ':' name | 'None' op | ',' nl | '\n' string | "'deleted_at'" op | ':' name | 'None' op | ',' nl | '\n' string | "'deleted'" op | ':' name | 'False' op | ',' nl | '\n' op | '}' op | ',' nl | '\n' op | '{' string | "'id'" op | ':' number | '2' op | ',' nl | '\n' string | "'action_id'" op | ':' name | 'FAKE_ACTION_ID1' op | ',' nl | '\n' string | "'event'" op | ':' string | "'compute_create'" op | ',' nl | '\n' string | "'start_time'" op | ':' name | 'datetime' op | '.' name | 'datetime' op | '(' nl | '\n' number | '2012' op | ',' number | '12' op | ',' number | '5' op | ',' number | '1' op | ',' number | '3' op | ',' number | '0' op | ',' number | '0' op | ')' op | ',' nl | '\n' string | "'finish_time'" op | ':' name | 'datetime' op | '.' name | 'datetime' op | '(' nl | '\n' number | '2012' op | ',' number | '12' op | ',' number | '5' op | ',' number | '1' op | ',' number | '4' op | ',' number | '0' op | ',' number | '0' op | ')' op | ',' nl | '\n' string | "'result'" op | ':' string | "'Success'" op | ',' nl | '\n' string | "'traceback'" op | ':' string | "''" op | ',' nl | '\n' string | "'created_at'" op | ':' name | 'None' op | ',' nl | '\n' string | "'updated_at'" op | ':' name | 'None' op | ',' nl | '\n' string | "'deleted_at'" op | ':' name | 'None' op | ',' nl | '\n' string | "'deleted'" op | ':' name | 'False' op | ',' nl | '\n' op | '}' nl | '\n' op | ']' op | ',' nl | '\n' name | 'FAKE_ACTION_ID2' op | ':' op | '[' op | '{' string | "'id'" op | ':' number | '3' op | ',' nl | '\n' string | "'action_id'" op | ':' name | 'FAKE_ACTION_ID2' op | ',' nl | '\n' string | "'event'" op | ':' string | "'schedule'" op | ',' nl | '\n' string | "'start_time'" op | ':' name | 'datetime' op | '.' name | 'datetime' op | '(' nl | '\n' number | '2012' op | ',' number | '12' op | ',' number | '5' op | ',' number | '3' op | ',' number | '0' op | ',' number | '0' op | ',' number | '0' op | ')' op | ',' nl | '\n' string | "'finish_time'" op | ':' name | 'datetime' op | '.' name | 'datetime' op | '(' nl | '\n' number | '2012' op | ',' number | '12' op | ',' number | '5' op | ',' number | '3' op | ',' number | '2' op | ',' number | '0' op | ',' number | '0' op | ')' op | ',' nl | '\n' string | "'result'" op | ':' string | "'Error'" op | ',' nl | '\n' string | "'traceback'" op | ':' string | "''" op | ',' nl | '\n' string | "'created_at'" op | ':' name | 'None' op | ',' nl | '\n' string | "'updated_at'" op | ':' name | 'None' op | ',' nl | '\n' string | "'deleted_at'" op | ':' name | 'None' op | ',' nl | '\n' string | "'deleted'" op | ':' name | 'False' op | ',' nl | '\n' op | '}' nl | '\n' op | ']' nl | '\n' op | '}' newline | '\n' nl | '\n' nl | '\n' DECL | function | fake_action_event_start name | 'def' name | 'fake_action_event_start' op | '(' op | '*' name | 'args' op | ')' op | ':' newline | '\n' indent | ' ' name | 'return' name | 'FAKE_EVENTS' op | '[' name | 'FAKE_ACTION_ID1' op | ']' op | '[' number | '0' op | ']' newline | '\n' nl | '\n' nl | '\n' DECL | function | fake_action_event_finish dedent | '' name | 'def' name | 'fake_action_event_finish' op | '(' op | '*' name | 'args' op | ')' op | ':' newline | '\n' indent | ' ' name | 'return' name | 'FAKE_EVENTS' op | '[' name | 'FAKE_ACTION_ID1' op | ']' op | '[' number | '0' op | ']' newline | '\n' nl | '\n' nl | '\n' DECL | function | stub_out_action_events dedent | '' name | 'def' name | 'stub_out_action_events' op | '(' name | 'stubs' op | ')' op | ':' newline | '\n' indent | ' ' name | 'stubs' op | '.' name | 'Set' op | '(' name | 'db' op | ',' string | "'action_event_start'" op | ',' name | 'fake_action_event_start' op | ')' newline | '\n' name | 'stubs' op | '.' name | 'Set' op | '(' name | 'db' op | ',' string | "'action_event_finish'" op | ',' name | 'fake_action_event_finish' op | ')' newline | '\n' dedent | '' endmarker | '' end_unit
## https://blog.ionelmc.ro/2015/02/09/understanding-python-metaclasses/ ## Restrictions with multiple metaclasses # class Meta1(type): # pass # class Meta2(type): # pass # class Base1(metaclass=Meta1): # pass # class Base2(metaclass=Meta2): # pass # class Foobar(Base1, Base2): # pass # class Meta(type): # pass # class SubMeta(Meta): # pass class Base1(metaclass=Meta): pass class Base2(metaclass=SubMeta): pass class Foobar(Base1, Base2): pass type(Foobar)
class Base1(metaclass=Meta): pass class Base2(metaclass=SubMeta): pass class Foobar(Base1, Base2): pass type(Foobar)
STRING_FILTER = 'string' CHOICE_FILTER = 'choice' BOOLEAN_FILTER = 'boolean' RADIO_FILTER = 'radio' HALF_WIDTH_FILTER = 'half_width' FULL_WIDTH_FILTER = 'full_width' VALID_FILTERS = ( STRING_FILTER, CHOICE_FILTER, BOOLEAN_FILTER, RADIO_FILTER, ) VALID_FILTER_WIDTHS = ( HALF_WIDTH_FILTER, FULL_WIDTH_FILTER, ) SORT_PARAM = 'sort' LAYOUT_PARAM = 'layout' # These constructors are using pascal case to masquerade as classes, but they're simply # generating dictionaries that declare the desired structure for the UI. This helps to # reduce verbosity when declaring options, while also providing an API that'll allow us # to add more features/validation/etc. def ListViewOptions(filters=None, sorts=None, layouts=None): assert isinstance(filters, (dict, type(None))) assert isinstance(sorts, (dict, type(None))) assert isinstance(layouts, (dict, type(None))) return { 'filters': filters, 'sorts': sorts, 'layouts': layouts, } def FilterOptions(children): assert isinstance(children, list) return { 'object_type': 'filter_options', 'children': children, } def FilterGroup(title, children): assert isinstance(title, str) assert isinstance(children, list) for obj in children: assert isinstance(obj, dict) return { 'object_type': 'filter_group', 'title': title, 'children': children, } def Filter( name, label, type, value, results_description, choices=None, multiple=None, clearable=None, width=None, is_default=None, ): if width is None: width = HALF_WIDTH_FILTER assert type in VALID_FILTERS assert width in VALID_FILTER_WIDTHS return { 'object_type': 'filter', 'name': name, 'label': label, 'type': type, 'value': value, 'results_description': results_description, 'choices': choices, 'multiple': multiple, 'clearable': clearable, 'width': width, 'is_default': is_default, } def SortOptions(children): assert isinstance(children, list) return { 'object_type': 'sort_options', 'children': children, } def Sort(label, value, is_selected, results_description, name=None, is_default=None): if name is None: name = SORT_PARAM return { 'object_type': 'sort', 'name': name, 'label': label, 'value': value, 'is_selected': is_selected, 'results_description': results_description, 'is_default': is_default, } def LayoutOptions(children): assert isinstance(children, list) return { 'object_type': 'layout_options', 'children': children, } def Layout(label, value, is_selected, icon_class, template=None, name=None): if name is None: name = LAYOUT_PARAM return { 'object_type': 'layout', 'name': name, 'label': label, 'value': value, 'is_selected': is_selected, 'icon_class': icon_class, 'template': template, }
string_filter = 'string' choice_filter = 'choice' boolean_filter = 'boolean' radio_filter = 'radio' half_width_filter = 'half_width' full_width_filter = 'full_width' valid_filters = (STRING_FILTER, CHOICE_FILTER, BOOLEAN_FILTER, RADIO_FILTER) valid_filter_widths = (HALF_WIDTH_FILTER, FULL_WIDTH_FILTER) sort_param = 'sort' layout_param = 'layout' def list_view_options(filters=None, sorts=None, layouts=None): assert isinstance(filters, (dict, type(None))) assert isinstance(sorts, (dict, type(None))) assert isinstance(layouts, (dict, type(None))) return {'filters': filters, 'sorts': sorts, 'layouts': layouts} def filter_options(children): assert isinstance(children, list) return {'object_type': 'filter_options', 'children': children} def filter_group(title, children): assert isinstance(title, str) assert isinstance(children, list) for obj in children: assert isinstance(obj, dict) return {'object_type': 'filter_group', 'title': title, 'children': children} def filter(name, label, type, value, results_description, choices=None, multiple=None, clearable=None, width=None, is_default=None): if width is None: width = HALF_WIDTH_FILTER assert type in VALID_FILTERS assert width in VALID_FILTER_WIDTHS return {'object_type': 'filter', 'name': name, 'label': label, 'type': type, 'value': value, 'results_description': results_description, 'choices': choices, 'multiple': multiple, 'clearable': clearable, 'width': width, 'is_default': is_default} def sort_options(children): assert isinstance(children, list) return {'object_type': 'sort_options', 'children': children} def sort(label, value, is_selected, results_description, name=None, is_default=None): if name is None: name = SORT_PARAM return {'object_type': 'sort', 'name': name, 'label': label, 'value': value, 'is_selected': is_selected, 'results_description': results_description, 'is_default': is_default} def layout_options(children): assert isinstance(children, list) return {'object_type': 'layout_options', 'children': children} def layout(label, value, is_selected, icon_class, template=None, name=None): if name is None: name = LAYOUT_PARAM return {'object_type': 'layout', 'name': name, 'label': label, 'value': value, 'is_selected': is_selected, 'icon_class': icon_class, 'template': template}
class Passenger(): def __init__(self, weight, floor, destination, time): self.weight = weight self.floor = floor self.destination = destination self.elevator = None self.created_at = time def enter(self, elevator): ''' Input: the elevator that the passenger attempts to enter ''' if elevator.enter(self): self.elevator = elevator self.elevator.request(self.destination) return True return False def leave_if_arrived(self): if self.destination == self.floor: self.elevator.leave(self) return True return False def update_floor(self, floor): '''Allows the elevator to update the floor attribute of the passenger''' self.floor = floor
class Passenger: def __init__(self, weight, floor, destination, time): self.weight = weight self.floor = floor self.destination = destination self.elevator = None self.created_at = time def enter(self, elevator): """ Input: the elevator that the passenger attempts to enter """ if elevator.enter(self): self.elevator = elevator self.elevator.request(self.destination) return True return False def leave_if_arrived(self): if self.destination == self.floor: self.elevator.leave(self) return True return False def update_floor(self, floor): """Allows the elevator to update the floor attribute of the passenger""" self.floor = floor
# ============================================================ # Title: Keep Talking and Nobody Explodes Solver: Who's on First? # Author: Ryan J. Slater # Date: 4/4/2019 # ============================================================ def solveSimonSays(textList, # List of strings [displayText, topLeft, topRight, middleLeft, middleRight, bottomLeft, bottomRight] bombSpecs): # Dictionary of bomb specs such as serial number last digit, parallel port, battery count, etc # Top Left if textList[0] in ['ur']: return getResponsesFromWord(textList[1]) # Top Right elif textList[0] in ['first', 'okay', 'c']: return getResponsesFromWord(textList[2]) # Middle Left elif textList[0] in ['yes', 'nothing', 'led', 'they are']: return getResponsesFromWord(textList[3]) # Middle Right elif textList[0] in ['blank', 'read', 'red', 'you', 'you\'re', 'their']: return getResponsesFromWord(textList[4]) # Bottom Left elif textList[0] in ['', 'reed', 'leed', 'they\'re']: return getResponsesFromWord(textList[5]) # Bottom Right elif textList[0] in ['display', 'says', 'no', 'lead', 'hold on', 'you are', 'there', 'see', 'cee']: return getResponsesFromWord(textList[6]) def getResponsesFromWord(word): # Word to be used as the key for step 2 # Returns a csv string in the order of words to try if word == 'ready': return 'YES, OKAY, WHAT, MIDDLE, LEFT, PRESS, RIGHT, BLANK, READY, NO, FIRST, UHHH, NOTHING, WAIT'.lower() elif word == 'first': return 'LEFT, OKAY, YES, MIDDLE, NO, RIGHT, NOTHING, UHHH, WAIT, READY, BLANK, WHAT, PRESS, FIRST'.lower() elif word == 'no': return 'BLANK, UHHH, WAIT, FIRST, WHAT, READY, RIGHT, YES, NOTHING, LEFT, PRESS, OKAY, NO, MIDDLE'.lower() elif word == 'blank': return 'WAIT, RIGHT, OKAY, MIDDLE, BLANK, PRESS, READY, NOTHING, NO, WHAT, LEFT, UHHH, YES, FIRST'.lower() elif word == 'nothing': return 'UHHH, RIGHT, OKAY, MIDDLE, YES, BLANK, NO, PRESS, LEFT, WHAT, WAIT, FIRST, NOTHING, READY'.lower() elif word == 'yes': return 'OKAY, RIGHT, UHHH, MIDDLE, FIRST, WHAT, PRESS, READY, NOTHING, YES, LEFT, BLANK, NO, WAIT'.lower() elif word == 'what': return 'UHHH, WHAT, LEFT, NOTHING, READY, BLANK, MIDDLE, NO, OKAY, FIRST, WAIT, YES, PRESS, RIGHT'.lower() elif word == 'uhhh': return 'READY, NOTHING, LEFT, WHAT, OKAY, YES, RIGHT, NO, PRESS, BLANK, UHHH, MIDDLE, WAIT, FIRST'.lower() elif word == 'left': return 'RIGHT, LEFT, FIRST, NO, MIDDLE, YES, BLANK, WHAT, UHHH, WAIT, PRESS, READY, OKAY, NOTHING'.lower() elif word == 'right': return 'YES, NOTHING, READY, PRESS, NO, WAIT, WHAT, RIGHT, MIDDLE, LEFT, UHHH, BLANK, OKAY, FIRST'.lower() elif word == 'middle': return 'BLANK, READY, OKAY, WHAT, NOTHING, PRESS, NO, WAIT, LEFT, MIDDLE, RIGHT, FIRST, UHHH, YES'.lower() elif word == 'okay': return 'MIDDLE, NO, FIRST, YES, UHHH, NOTHING, WAIT, OKAY, LEFT, READY, BLANK, PRESS, WHAT, RIGHT'.lower() elif word == 'wait': return 'UHHH, NO, BLANK, OKAY, YES, LEFT, FIRST, PRESS, WHAT, WAIT, NOTHING, READY, RIGHT, MIDDLE'.lower() elif word == 'press': return 'RIGHT, MIDDLE, YES, READY, PRESS, OKAY, NOTHING, UHHH, BLANK, LEFT, FIRST, WHAT, NO, WAIT'.lower() elif word == 'you': return 'SURE, YOU ARE, YOUR, YOU\'RE, NEXT, UH HUH, UR, HOLD, WHAT?, YOU, UH UH, LIKE, DONE, U'.lower() elif word == 'you are': return 'YOUR, NEXT, LIKE, UH HUH, WHAT?, DONE, UH UH, HOLD, YOU, U, YOU\'RE, SURE, UR, YOU ARE'.lower() elif word == 'your': return 'UH UH, YOU ARE, UH HUH, YOUR, NEXT, UR, SURE, U, YOU\'RE, YOU, WHAT?, HOLD, LIKE, DONE'.lower() elif word == 'you\'re': return 'YOU, YOU\'RE, UR, NEXT, UH UH, YOU ARE, U, YOUR, WHAT?, UH HUH, SURE, DONE, LIKE, HOLD'.lower() elif word == 'ur': return 'DONE, U, UR, UH HUH, WHAT?, SURE, YOUR, HOLD, YOU\'RE, LIKE, NEXT, UH UH, YOU ARE, YOU'.lower() elif word == 'u': return 'UH HUH, SURE, NEXT, WHAT?, YOU\'RE, UR, UH UH, DONE, U, YOU, LIKE, HOLD, YOU ARE, YOUR'.lower() elif word == 'uh huh': return 'UH HUH, YOUR, YOU ARE, YOU, DONE, HOLD, UH UH, NEXT, SURE, LIKE, YOU\'RE, UR, U, WHAT?'.lower() elif word == 'uh uh': return 'UR, U, YOU ARE, YOU\'RE, NEXT, UH UH, DONE, YOU, UH HUH, LIKE, YOUR, SURE, HOLD, WHAT?'.lower() elif word == 'what?': return 'YOU, HOLD, YOU\'RE, YOUR, U, DONE, UH UH, LIKE, YOU ARE, UH HUH, UR, NEXT, WHAT?, SURE'.lower() elif word == 'done': return 'SURE, UH HUH, NEXT, WHAT?, YOUR, UR, YOU\'RE, HOLD, LIKE, YOU, U, YOU ARE, UH UH, DONE'.lower() elif word == 'next': return 'WHAT?, UH HUH, UH UH, YOUR, HOLD, SURE, NEXT, LIKE, DONE, YOU ARE, UR, YOU\'RE, U, YOU'.lower() elif word == 'hold': return 'YOU ARE, U, DONE, UH UH, YOU, UR, SURE, WHAT?, YOU\'RE, NEXT, HOLD, UH HUH, YOUR, LIKE'.lower() elif word == 'sure': return 'YOU ARE, DONE, LIKE, YOU\'RE, YOU, HOLD, UH HUH, UR, SURE, U, WHAT?, NEXT, YOUR, UH UH'.lower() elif word == 'like': return 'YOU\'RE, NEXT, U, UR, HOLD, DONE, UH UH, WHAT?, UH HUH, YOU, LIKE, SURE, YOU ARE, YOUR'.lower()
def solve_simon_says(textList, bombSpecs): if textList[0] in ['ur']: return get_responses_from_word(textList[1]) elif textList[0] in ['first', 'okay', 'c']: return get_responses_from_word(textList[2]) elif textList[0] in ['yes', 'nothing', 'led', 'they are']: return get_responses_from_word(textList[3]) elif textList[0] in ['blank', 'read', 'red', 'you', "you're", 'their']: return get_responses_from_word(textList[4]) elif textList[0] in ['', 'reed', 'leed', "they're"]: return get_responses_from_word(textList[5]) elif textList[0] in ['display', 'says', 'no', 'lead', 'hold on', 'you are', 'there', 'see', 'cee']: return get_responses_from_word(textList[6]) def get_responses_from_word(word): if word == 'ready': return 'YES, OKAY, WHAT, MIDDLE, LEFT, PRESS, RIGHT, BLANK, READY, NO, FIRST, UHHH, NOTHING, WAIT'.lower() elif word == 'first': return 'LEFT, OKAY, YES, MIDDLE, NO, RIGHT, NOTHING, UHHH, WAIT, READY, BLANK, WHAT, PRESS, FIRST'.lower() elif word == 'no': return 'BLANK, UHHH, WAIT, FIRST, WHAT, READY, RIGHT, YES, NOTHING, LEFT, PRESS, OKAY, NO, MIDDLE'.lower() elif word == 'blank': return 'WAIT, RIGHT, OKAY, MIDDLE, BLANK, PRESS, READY, NOTHING, NO, WHAT, LEFT, UHHH, YES, FIRST'.lower() elif word == 'nothing': return 'UHHH, RIGHT, OKAY, MIDDLE, YES, BLANK, NO, PRESS, LEFT, WHAT, WAIT, FIRST, NOTHING, READY'.lower() elif word == 'yes': return 'OKAY, RIGHT, UHHH, MIDDLE, FIRST, WHAT, PRESS, READY, NOTHING, YES, LEFT, BLANK, NO, WAIT'.lower() elif word == 'what': return 'UHHH, WHAT, LEFT, NOTHING, READY, BLANK, MIDDLE, NO, OKAY, FIRST, WAIT, YES, PRESS, RIGHT'.lower() elif word == 'uhhh': return 'READY, NOTHING, LEFT, WHAT, OKAY, YES, RIGHT, NO, PRESS, BLANK, UHHH, MIDDLE, WAIT, FIRST'.lower() elif word == 'left': return 'RIGHT, LEFT, FIRST, NO, MIDDLE, YES, BLANK, WHAT, UHHH, WAIT, PRESS, READY, OKAY, NOTHING'.lower() elif word == 'right': return 'YES, NOTHING, READY, PRESS, NO, WAIT, WHAT, RIGHT, MIDDLE, LEFT, UHHH, BLANK, OKAY, FIRST'.lower() elif word == 'middle': return 'BLANK, READY, OKAY, WHAT, NOTHING, PRESS, NO, WAIT, LEFT, MIDDLE, RIGHT, FIRST, UHHH, YES'.lower() elif word == 'okay': return 'MIDDLE, NO, FIRST, YES, UHHH, NOTHING, WAIT, OKAY, LEFT, READY, BLANK, PRESS, WHAT, RIGHT'.lower() elif word == 'wait': return 'UHHH, NO, BLANK, OKAY, YES, LEFT, FIRST, PRESS, WHAT, WAIT, NOTHING, READY, RIGHT, MIDDLE'.lower() elif word == 'press': return 'RIGHT, MIDDLE, YES, READY, PRESS, OKAY, NOTHING, UHHH, BLANK, LEFT, FIRST, WHAT, NO, WAIT'.lower() elif word == 'you': return "SURE, YOU ARE, YOUR, YOU'RE, NEXT, UH HUH, UR, HOLD, WHAT?, YOU, UH UH, LIKE, DONE, U".lower() elif word == 'you are': return "YOUR, NEXT, LIKE, UH HUH, WHAT?, DONE, UH UH, HOLD, YOU, U, YOU'RE, SURE, UR, YOU ARE".lower() elif word == 'your': return "UH UH, YOU ARE, UH HUH, YOUR, NEXT, UR, SURE, U, YOU'RE, YOU, WHAT?, HOLD, LIKE, DONE".lower() elif word == "you're": return "YOU, YOU'RE, UR, NEXT, UH UH, YOU ARE, U, YOUR, WHAT?, UH HUH, SURE, DONE, LIKE, HOLD".lower() elif word == 'ur': return "DONE, U, UR, UH HUH, WHAT?, SURE, YOUR, HOLD, YOU'RE, LIKE, NEXT, UH UH, YOU ARE, YOU".lower() elif word == 'u': return "UH HUH, SURE, NEXT, WHAT?, YOU'RE, UR, UH UH, DONE, U, YOU, LIKE, HOLD, YOU ARE, YOUR".lower() elif word == 'uh huh': return "UH HUH, YOUR, YOU ARE, YOU, DONE, HOLD, UH UH, NEXT, SURE, LIKE, YOU'RE, UR, U, WHAT?".lower() elif word == 'uh uh': return "UR, U, YOU ARE, YOU'RE, NEXT, UH UH, DONE, YOU, UH HUH, LIKE, YOUR, SURE, HOLD, WHAT?".lower() elif word == 'what?': return "YOU, HOLD, YOU'RE, YOUR, U, DONE, UH UH, LIKE, YOU ARE, UH HUH, UR, NEXT, WHAT?, SURE".lower() elif word == 'done': return "SURE, UH HUH, NEXT, WHAT?, YOUR, UR, YOU'RE, HOLD, LIKE, YOU, U, YOU ARE, UH UH, DONE".lower() elif word == 'next': return "WHAT?, UH HUH, UH UH, YOUR, HOLD, SURE, NEXT, LIKE, DONE, YOU ARE, UR, YOU'RE, U, YOU".lower() elif word == 'hold': return "YOU ARE, U, DONE, UH UH, YOU, UR, SURE, WHAT?, YOU'RE, NEXT, HOLD, UH HUH, YOUR, LIKE".lower() elif word == 'sure': return "YOU ARE, DONE, LIKE, YOU'RE, YOU, HOLD, UH HUH, UR, SURE, U, WHAT?, NEXT, YOUR, UH UH".lower() elif word == 'like': return "YOU'RE, NEXT, U, UR, HOLD, DONE, UH UH, WHAT?, UH HUH, YOU, LIKE, SURE, YOU ARE, YOUR".lower()
#coding:utf-8 #pulic BASE_DIR = "/home/dengerqiang/Documents/WORK/" VQA_BASE = BASE_DIR + 'VQA/' DATA10 = VQA_BASE + "data1.0/" DATA20 = VQA_BASE + "data2.0/" IMAGE_DIR = VQA_BASE + "images/" GLOVE_DIR = BASE_DIR + 'glove/' NLTK_DIR = BASE_DIR + "nltk_data" #private WORK_DIR = BASE_DIR+ "VQA/DenseCoAttention/" GLOVE_FILE = "glove.6B.100d.pt" #global arguments RNN_DIM = 100 CNN_TYPE = "resnet152"
base_dir = '/home/dengerqiang/Documents/WORK/' vqa_base = BASE_DIR + 'VQA/' data10 = VQA_BASE + 'data1.0/' data20 = VQA_BASE + 'data2.0/' image_dir = VQA_BASE + 'images/' glove_dir = BASE_DIR + 'glove/' nltk_dir = BASE_DIR + 'nltk_data' work_dir = BASE_DIR + 'VQA/DenseCoAttention/' glove_file = 'glove.6B.100d.pt' rnn_dim = 100 cnn_type = 'resnet152'
def toMinutesArray(times: str): res = [0, 0] startEnd = times.split() hourMin = startEnd[0].split(':') res[0] = int(hourMin[0]) * 60 + int(hourMin[1]) hourMin = startEnd[1].split(':') res[1] = int(hourMin[0]) * 60 + int(hourMin[1]) return res MAX_MINS = 1500 N = int(input()) table = [0] * MAX_MINS res = 0 for i in range(N): startEnd = toMinutesArray(input()) table[startEnd[0]] += 1 table[startEnd[1]] -= 1 for i in range(1, MAX_MINS): table[i] += table[i-1] res = max(res, table[i]) print(res)
def to_minutes_array(times: str): res = [0, 0] start_end = times.split() hour_min = startEnd[0].split(':') res[0] = int(hourMin[0]) * 60 + int(hourMin[1]) hour_min = startEnd[1].split(':') res[1] = int(hourMin[0]) * 60 + int(hourMin[1]) return res max_mins = 1500 n = int(input()) table = [0] * MAX_MINS res = 0 for i in range(N): start_end = to_minutes_array(input()) table[startEnd[0]] += 1 table[startEnd[1]] -= 1 for i in range(1, MAX_MINS): table[i] += table[i - 1] res = max(res, table[i]) print(res)
# For the central discovery server LOG_FILE = 'discovered.pkl' DISCOVERY_PORT = 4444 MESSAGING_PORT = 8192 PROMPT_FILE = 'prompt' SHARED_FOLDER = 'shared' DOWNLOAD_FOLDER = 'download' CHUNK_SIZE = 1000000
log_file = 'discovered.pkl' discovery_port = 4444 messaging_port = 8192 prompt_file = 'prompt' shared_folder = 'shared' download_folder = 'download' chunk_size = 1000000
class FindImage: def __init__(self, image_repo): self.image_repo = image_repo def by_ayah_id(self, ayah_id): return self.image_repo.find_by_ayah_id(ayah_id)
class Findimage: def __init__(self, image_repo): self.image_repo = image_repo def by_ayah_id(self, ayah_id): return self.image_repo.find_by_ayah_id(ayah_id)
# To review... adding up the lengths of strings in a list # e.g. totalLength(["UCSB","Apple","Pie"]) should be: 12 # because len("UCSB")=4, len("Apple")=5, and len("Pie")=3, and 4+5+3 = 12 def totalLength(listOfStrings): " add up length of all the strings " # for now, ignore errors.. assume they are all of type str count = 0 for string in listOfStrings: count = count + len(string) return count def test_totalLength_1(): assert totalLength(["UCSB","Apple","Pie"])==12 def test_totalLength_2(): assert totalLength([])==0 def test_totalLength_3(): assert totalLength(["Cal Poly"])==8
def total_length(listOfStrings): """ add up length of all the strings """ count = 0 for string in listOfStrings: count = count + len(string) return count def test_total_length_1(): assert total_length(['UCSB', 'Apple', 'Pie']) == 12 def test_total_length_2(): assert total_length([]) == 0 def test_total_length_3(): assert total_length(['Cal Poly']) == 8
T = int(input('')) X = 0 Y = 0 for i in range(T): B = int(input('')) A1, D1, L1 = map(int, input().split()) A2, D2, L2 = map(int, input().split()) X = (A1 + D1) / 2 if L1 % 2 == 0: X = X + L1 Y = (A2 + D2) / 2 if L2 % 2 == 0: Y = Y + L1 if X == Y: print('Empate') elif X > Y: print('Dabriel') else: print('Guarte')
t = int(input('')) x = 0 y = 0 for i in range(T): b = int(input('')) (a1, d1, l1) = map(int, input().split()) (a2, d2, l2) = map(int, input().split()) x = (A1 + D1) / 2 if L1 % 2 == 0: x = X + L1 y = (A2 + D2) / 2 if L2 % 2 == 0: y = Y + L1 if X == Y: print('Empate') elif X > Y: print('Dabriel') else: print('Guarte')
class Solution: def XXX(self, n: int) -> str: ans = '1#' for i in range(1, n): t, cnt = '', 1 for j in range(1, len(ans)): if ans[j] == ans[j - 1]: cnt += 1 else: t += (str(cnt) + ans[j - 1]) cnt = 1 t += '#' ans = t return ans[:-1]
class Solution: def xxx(self, n: int) -> str: ans = '1#' for i in range(1, n): (t, cnt) = ('', 1) for j in range(1, len(ans)): if ans[j] == ans[j - 1]: cnt += 1 else: t += str(cnt) + ans[j - 1] cnt = 1 t += '#' ans = t return ans[:-1]
# This kata was seen in programming competitions with a wide range of variations. A strict bouncy array of numbers, of # length three or longer, is an array that each term (neither the first nor the last element) is strictly higher or lower # than its neighbours. # For example, the array: # arr = [7,9,6,10,5,11,10,12,13,4,2,5,1,6,4,8] (length = 16) # The two longest bouncy subarrays of arr are # [7,9,6,10,5,11,10,12] (length = 8) and [4,2,5,1,6,4,8] (length = 7) # According to the given definition, the arrays [8,1,4,6,7], [1,2,2,1,4,5], are not bouncy. # For the special case of length 2 arrays, we will consider them strict bouncy if the two elements are different. # The arrays [-1,4] and [0,-10] are both bouncy, while [0,0] is not. # An array of length 1 will be considered strict bouncy itself. # You will be given an array of integers and you should output the longest strict bouncy subarray. # In the case of having more than one bouncy subarray of same length, it should be output the subarray with its first term of lowest index in the original array. # Let's see the result for the first given example. # arr = [7,9,6,10,5,11,10,12,13,4,2,5,1,6,4,8] # longest_bouncy_list(arr) === [7,9,6,10,5,11,10,12] # See more examples in the example tests box. # Features of the random tests # length of the array inputs up to 1000 # -500 <= arr[i] <= 500 # Toy Problem in Progress # Giant Failure - Still in progress def longest_bouncy_list(arr): bounce = '' count = 0 value = [] depths = [[] for i in range(4)] if arr[1:] == arr[:-1]: return [arr[0]] if arr[0] < arr[1]: bounce = 'low' elif arr[0] > arr[1]: bounce = 'high' for x, y in zip(arr[::], arr[1::]): current_depth = 0 if bounce == 'high' and x > y: print("true high:", 'x:', x, 'y:', y) count += 1 bounce = 'low' depths[current_depth].append(x) elif bounce == 'low' and x < y: print("true low:", 'x:', x, 'y:', y) count += 1 bounce = 'high' depths[current_depth].append(x) elif bounce == 'low' and x > y or bounce == 'high' and x < y: current_depth += 1 depths[current_depth].append(x) depths[current_depth].append(y) print('break:', 'x:', x, 'y:', y) print('depths:', depths) arr4 = [10, 8, 1, -11, -14, 7, 0, 8, -2, 2, -9, 9, -2, 14, -16, -12, -12, -8, -1, -13, -11, 11] print(longest_bouncy_list(arr4)) # [-11, -14, 7, 0, 8, -2, 2, -9, 9, -2, 14, -16, -12] # [13, 2] arr1 = [7, 9, 6, 10, 5, 11, 10, 12, 13, 4, 2, 5, 1, 6, 4, 8] print(longest_bouncy_list(arr1)) # [7, 9, 6, 10, 5, 11, 10, 12] # arr2 = [7, 7, 7, 7, 7] # print(longest_bouncy_list(arr2)) # # [7] # arr3 = [1, 2, 3, 4, 5, 6] # print(longest_bouncy_list(arr3)) # [1,2]
def longest_bouncy_list(arr): bounce = '' count = 0 value = [] depths = [[] for i in range(4)] if arr[1:] == arr[:-1]: return [arr[0]] if arr[0] < arr[1]: bounce = 'low' elif arr[0] > arr[1]: bounce = 'high' for (x, y) in zip(arr[:], arr[1:]): current_depth = 0 if bounce == 'high' and x > y: print('true high:', 'x:', x, 'y:', y) count += 1 bounce = 'low' depths[current_depth].append(x) elif bounce == 'low' and x < y: print('true low:', 'x:', x, 'y:', y) count += 1 bounce = 'high' depths[current_depth].append(x) elif bounce == 'low' and x > y or (bounce == 'high' and x < y): current_depth += 1 depths[current_depth].append(x) depths[current_depth].append(y) print('break:', 'x:', x, 'y:', y) print('depths:', depths) arr4 = [10, 8, 1, -11, -14, 7, 0, 8, -2, 2, -9, 9, -2, 14, -16, -12, -12, -8, -1, -13, -11, 11] print(longest_bouncy_list(arr4)) arr1 = [7, 9, 6, 10, 5, 11, 10, 12, 13, 4, 2, 5, 1, 6, 4, 8] print(longest_bouncy_list(arr1))
DEFAULTS = { 'label': "{win[title]}", 'label_alt': "[class_name='{win[class_name]}' exe='{win[process][name]}' hwnd={win[hwnd]}]", 'label_no_window': None, 'max_length': None, 'max_length_ellipsis': '...', 'monitor_exclusive': True, 'ignore_windows': { 'classes': [], 'processes': [], 'titles': [] }, 'callbacks': { 'on_left': 'toggle_label', 'on_middle': 'do_nothing', 'on_right': 'do_nothing' } } VALIDATION_SCHEMA = { 'label': { 'type': 'string', 'default': DEFAULTS['label'] }, 'label_alt': { 'type': 'string', 'default': DEFAULTS['label_alt'] }, 'label_no_window': { 'type': 'string', 'nullable': True, 'default': DEFAULTS['label_no_window'] }, 'max_length': { 'type': 'integer', 'min': 1, 'nullable': True, 'default': DEFAULTS['max_length'] }, 'max_length_ellipsis': { 'type': 'string', 'default': DEFAULTS['max_length_ellipsis'] }, 'monitor_exclusive': { 'type': 'boolean', 'required': False, 'default': DEFAULTS['monitor_exclusive'] }, 'ignore_window': { 'type': 'dict', 'schema': { 'classes': { 'type': 'list', 'schema': { 'type': 'string' }, 'default': DEFAULTS['ignore_windows']['classes'] }, 'processes': { 'type': 'list', 'schema': { 'type': 'string' }, 'default': DEFAULTS['ignore_windows']['processes'] }, 'titles': { 'type': 'list', 'schema': { 'type': 'string' }, 'default': DEFAULTS['ignore_windows']['titles'] } }, 'default': DEFAULTS['ignore_windows'] }, 'callbacks': { 'type': 'dict', 'schema': { 'on_left': { 'type': 'string', 'default': DEFAULTS['callbacks']['on_left'], }, 'on_middle': { 'type': 'string', 'default': DEFAULTS['callbacks']['on_middle'], }, 'on_right': { 'type': 'string', 'default': DEFAULTS['callbacks']['on_right'] } }, 'default': DEFAULTS['callbacks'] } }
defaults = {'label': '{win[title]}', 'label_alt': "[class_name='{win[class_name]}' exe='{win[process][name]}' hwnd={win[hwnd]}]", 'label_no_window': None, 'max_length': None, 'max_length_ellipsis': '...', 'monitor_exclusive': True, 'ignore_windows': {'classes': [], 'processes': [], 'titles': []}, 'callbacks': {'on_left': 'toggle_label', 'on_middle': 'do_nothing', 'on_right': 'do_nothing'}} validation_schema = {'label': {'type': 'string', 'default': DEFAULTS['label']}, 'label_alt': {'type': 'string', 'default': DEFAULTS['label_alt']}, 'label_no_window': {'type': 'string', 'nullable': True, 'default': DEFAULTS['label_no_window']}, 'max_length': {'type': 'integer', 'min': 1, 'nullable': True, 'default': DEFAULTS['max_length']}, 'max_length_ellipsis': {'type': 'string', 'default': DEFAULTS['max_length_ellipsis']}, 'monitor_exclusive': {'type': 'boolean', 'required': False, 'default': DEFAULTS['monitor_exclusive']}, 'ignore_window': {'type': 'dict', 'schema': {'classes': {'type': 'list', 'schema': {'type': 'string'}, 'default': DEFAULTS['ignore_windows']['classes']}, 'processes': {'type': 'list', 'schema': {'type': 'string'}, 'default': DEFAULTS['ignore_windows']['processes']}, 'titles': {'type': 'list', 'schema': {'type': 'string'}, 'default': DEFAULTS['ignore_windows']['titles']}}, 'default': DEFAULTS['ignore_windows']}, 'callbacks': {'type': 'dict', 'schema': {'on_left': {'type': 'string', 'default': DEFAULTS['callbacks']['on_left']}, 'on_middle': {'type': 'string', 'default': DEFAULTS['callbacks']['on_middle']}, 'on_right': {'type': 'string', 'default': DEFAULTS['callbacks']['on_right']}}, 'default': DEFAULTS['callbacks']}}
#!python3 class Error(Exception): pass class IncompatibleArgumentError(Error): pass class DataShapeError(Error): pass
class Error(Exception): pass class Incompatibleargumenterror(Error): pass class Datashapeerror(Error): pass
x = 9 def f(x): return x
x = 9 def f(x): return x
# Definition for a binary tree node. # class TreeNode: # def __init__(self, val=0, left=None, right=None): # self.val = val # self.left = left # self.right = right class Solution: def findTilt(self, root: TreeNode) -> int: tilt = [0] def dfs(node): if node is None: return 0 left = dfs(node.left) right = dfs(node.right) tilt[0] += abs(left - right) return left + right + node.val dfs(root) return tilt[0]
class Solution: def find_tilt(self, root: TreeNode) -> int: tilt = [0] def dfs(node): if node is None: return 0 left = dfs(node.left) right = dfs(node.right) tilt[0] += abs(left - right) return left + right + node.val dfs(root) return tilt[0]
def test_filtering_sequential_blocks_with_bounded_range( w3, emitter, Emitter, wait_for_transaction): builder = emitter.events.LogNoArguments.build_filter() builder.fromBlock = "latest" initial_block_number = w3.eth.block_number builder.toBlock = initial_block_number + 100 filter_ = builder.deploy(w3) for i in range(100): emitter.functions.logNoArgs(which=1).transact() assert w3.eth.block_number == initial_block_number + 100 assert len(filter_.get_new_entries()) == 100 def test_filtering_starting_block_range( w3, emitter, Emitter, wait_for_transaction): for i in range(10): emitter.functions.logNoArgs(which=1).transact() builder = emitter.events.LogNoArguments.build_filter() filter_ = builder.deploy(w3) initial_block_number = w3.eth.block_number for i in range(10): emitter.functions.logNoArgs(which=1).transact() assert w3.eth.block_number == initial_block_number + 10 assert len(filter_.get_new_entries()) == 10 def test_requesting_results_with_no_new_blocks(w3, emitter): builder = emitter.events.LogNoArguments.build_filter() filter_ = builder.deploy(w3) assert len(filter_.get_new_entries()) == 0
def test_filtering_sequential_blocks_with_bounded_range(w3, emitter, Emitter, wait_for_transaction): builder = emitter.events.LogNoArguments.build_filter() builder.fromBlock = 'latest' initial_block_number = w3.eth.block_number builder.toBlock = initial_block_number + 100 filter_ = builder.deploy(w3) for i in range(100): emitter.functions.logNoArgs(which=1).transact() assert w3.eth.block_number == initial_block_number + 100 assert len(filter_.get_new_entries()) == 100 def test_filtering_starting_block_range(w3, emitter, Emitter, wait_for_transaction): for i in range(10): emitter.functions.logNoArgs(which=1).transact() builder = emitter.events.LogNoArguments.build_filter() filter_ = builder.deploy(w3) initial_block_number = w3.eth.block_number for i in range(10): emitter.functions.logNoArgs(which=1).transact() assert w3.eth.block_number == initial_block_number + 10 assert len(filter_.get_new_entries()) == 10 def test_requesting_results_with_no_new_blocks(w3, emitter): builder = emitter.events.LogNoArguments.build_filter() filter_ = builder.deploy(w3) assert len(filter_.get_new_entries()) == 0
num_acc=int(input()) accounts={} for i in range(num_acc): p,b = input().split() accounts[p] = int(b) #print (accounts) num_t=int(input()) trans=[] for i in range(num_t): pf,pt,c,t = input().split() trans.append((int(t),pf,pt,int(c))) trans = sorted(trans) for i in trans: accounts[i[1]]-=i[3] accounts[i[2]]+=i[3] print (num_acc) for i in accounts.keys(): print(i,accounts[i])
num_acc = int(input()) accounts = {} for i in range(num_acc): (p, b) = input().split() accounts[p] = int(b) num_t = int(input()) trans = [] for i in range(num_t): (pf, pt, c, t) = input().split() trans.append((int(t), pf, pt, int(c))) trans = sorted(trans) for i in trans: accounts[i[1]] -= i[3] accounts[i[2]] += i[3] print(num_acc) for i in accounts.keys(): print(i, accounts[i])
count = 1 def show_title(msg): global count print('\n') print('#' * 30) print(count, '.', msg) print('#' * 30) count += 1
count = 1 def show_title(msg): global count print('\n') print('#' * 30) print(count, '.', msg) print('#' * 30) count += 1
# result = 5/3 # if result: data = ['asdf', '123', 'Aa'] names = ['asdf', '123', 'Aa'] # builtin functions that operate on sequences # zip # max # min # sum sum([1, 2, 3]) # generator expressions print(sum(len(x) for x in data)) # all # any print(all(len(x) > 2 for x in data)) print(any(len(x) > 2 for x in data)) # enumerate # reversed for x in reversed(data): pass get_len = lambda x: len(x) def get_length(x): # equiv to "len" or "lambda x: len(x)" return len(x) def get_second_item(x): # equiv to lambda x: x[1] return x[1] # sorted print(sorted(data)) print(sorted(data, key=len)) print(sorted(data, key=get_len)) print(sorted(data, key=get_length)) print(sorted(data, key=(lambda x: len(x)))) print(sorted(names, key=lambda name: name[1])) # result = [] # for x in data: # if len(x) > 3: # result.append(x) # functional programming type functions # filter print(list(filter((lambda x: len(x) > 3), data))) # comprehension syntax is sometimes preferred to using filter print([x for x in data if len(x) > 3]) # map print(list(map((lambda x: len(x) > 3), data))) print(list(map((lambda x: len(x)), data))) print([len(x) for x in data if len(x) > 2]) # reduce def get_length_and_first_two_chars(string): return len(string), string[0], string[1] l, *_ = get_length_and_first_two_chars('abcdef') print(get_length_and_first_two_chars('abcdef')) one_million = 1_000_000 # sometimes you want to define a function # that can take in any of many optional parameters def print_all_args(*args, do_thing = False, **kwargs): # if len(args) == 1 and type(args[0]) == 'int': print(args) print(kwargs) def helper_function(commonly_used_arg, *args, **kwargs): print_all_args(1, commonly_used_arg, 3, '45', *args, myarg=5, do_thing=True, custom_option=False, **kwargs)
data = ['asdf', '123', 'Aa'] names = ['asdf', '123', 'Aa'] sum([1, 2, 3]) print(sum((len(x) for x in data))) print(all((len(x) > 2 for x in data))) print(any((len(x) > 2 for x in data))) for x in reversed(data): pass get_len = lambda x: len(x) def get_length(x): return len(x) def get_second_item(x): return x[1] print(sorted(data)) print(sorted(data, key=len)) print(sorted(data, key=get_len)) print(sorted(data, key=get_length)) print(sorted(data, key=lambda x: len(x))) print(sorted(names, key=lambda name: name[1])) print(list(filter(lambda x: len(x) > 3, data))) print([x for x in data if len(x) > 3]) print(list(map(lambda x: len(x) > 3, data))) print(list(map(lambda x: len(x), data))) print([len(x) for x in data if len(x) > 2]) def get_length_and_first_two_chars(string): return (len(string), string[0], string[1]) (l, *_) = get_length_and_first_two_chars('abcdef') print(get_length_and_first_two_chars('abcdef')) one_million = 1000000 def print_all_args(*args, do_thing=False, **kwargs): print(args) print(kwargs) def helper_function(commonly_used_arg, *args, **kwargs): print_all_args(1, commonly_used_arg, 3, '45', *args, myarg=5, do_thing=True, custom_option=False, **kwargs)
__copyright__ = "2015 Cisco Systems, Inc." # Define your areas here. you can add or remove area in areas_container areas_container = [ { "areaId": "area1", "areaName": "Area Name 1", "dimension": { "length": 100, "offsetX": 0, "offsetY": 0, "unit": "FEET", "width": 100 }, "floorRefId": "723402329507758200" }, { "areaId": "area2", "areaName": "Area Name 2", "dimension": { "length": 500, "offsetX": 0, "offsetY": 100, "unit": "FEET", "width": 500 }, "floorRefId": "723402329507758200" }, { "areaId": "area3", "areaName": "Area Name 3", "dimension": { "length": 100, "offsetX": 100, "offsetY": 0, "unit": "FEET", "width": 100 }, "floorRefId": "723402329507758200" } ] # none area area_none = { "areaId": "none" }
__copyright__ = '2015 Cisco Systems, Inc.' areas_container = [{'areaId': 'area1', 'areaName': 'Area Name 1', 'dimension': {'length': 100, 'offsetX': 0, 'offsetY': 0, 'unit': 'FEET', 'width': 100}, 'floorRefId': '723402329507758200'}, {'areaId': 'area2', 'areaName': 'Area Name 2', 'dimension': {'length': 500, 'offsetX': 0, 'offsetY': 100, 'unit': 'FEET', 'width': 500}, 'floorRefId': '723402329507758200'}, {'areaId': 'area3', 'areaName': 'Area Name 3', 'dimension': {'length': 100, 'offsetX': 100, 'offsetY': 0, 'unit': 'FEET', 'width': 100}, 'floorRefId': '723402329507758200'}] area_none = {'areaId': 'none'}
Errors = { 400: "BAD_REQUEST_BODY", 401: "UNAUTHORIZED", 403: "ACCESS_DENIED", 404: "NotFoundError", 406: "NotAcceptableError", 409: "ConflictError", 415: "UnsupportedMediaTypeError", 422: "UnprocessableEntityError", 429: "TooManyRequestsError", 500: "API_CONFIGURATION_ERROR", 502: "BadGatewayError", 503: "ServiceUnavailableError", 504: "GatewayTimeoutError" }
errors = {400: 'BAD_REQUEST_BODY', 401: 'UNAUTHORIZED', 403: 'ACCESS_DENIED', 404: 'NotFoundError', 406: 'NotAcceptableError', 409: 'ConflictError', 415: 'UnsupportedMediaTypeError', 422: 'UnprocessableEntityError', 429: 'TooManyRequestsError', 500: 'API_CONFIGURATION_ERROR', 502: 'BadGatewayError', 503: 'ServiceUnavailableError', 504: 'GatewayTimeoutError'}
response = {"username": "username", "password": "pass"} db = list() def add_user(user_obj): password = response.get("password") if len(password) < 5: return "Password is shorter than 5 characters." else: db.append(user_obj) return "User has been added." print(add_user(response)) print(db)
response = {'username': 'username', 'password': 'pass'} db = list() def add_user(user_obj): password = response.get('password') if len(password) < 5: return 'Password is shorter than 5 characters.' else: db.append(user_obj) return 'User has been added.' print(add_user(response)) print(db)
#errorcodes.py #version 2.0.6 errorList = ["no error", "error code 1", "mrBayes.py: Could not open quartets file", "mrBayes.py: Could not interpret quartets file", "mrBayes.py: Could not open translate file", "mrBayes.py: Could not interpret translate file", "mrBayes.py: Could not interpret condor job name", "mrBayes.py: Could not find tarfile", "mrBayes.py: Could not create data subdirectory", "mrBayes.py: Could not open tarfile", "mrBayes.py: Could not open list of gene files", "mrBayes.py: Could not get gene files from tarfile", "mrBayes.py: Could not get gene files from data directory", "mrBayes.py: Could not interpret read tar.gz", "mrBayes.py: Could not extract file from tar.gz", "mrBayes.py: Could not open gene file", "mrBayes.py: Could not interpret gene file", "mrBayes.py: Could not initialize quartet subset of gene file", "mrBayes.py: Could not write quartet subset of gene file", "mrBayes.py: Could not run mrBayes", "mrBayes.py: Filename mismatch", "mrBayes.py: Could not find expected mcmc output", "mrBayes.py: Could not run mbsum", "mrBayes.py: Could not delete temporary files", "mrBayes.py: Could not create or write results file", "mrBayes.py: Could not create gene group zip file", "mrBayes.py: Could not delete file after zipping", "mrBayes.py: Statistics do not add", "mrBayes.py: Could not write gene group zip file" "zip_mb_output.py: Could not interpret condor job name", "zip_mb_output.py: Could not open target tar file", "zip_mb_output.py: Could not open input tar.gz", "zip_mb_output.py: Could not extract .in file", "zip_mb_output.py: Could not add .in file", "zip_mb_output.py: Could not delete .in file", "zip_mb_output.py: Could not delete input tar.gz", "zip_mb_output.py: Could not get directory.", "zip_mb_output.py: No input tar.gz found", "post_organize: missing node return status", "post_organize: organize.submit returned an error value", "post_organize: Could not update QuartetAnalysis metafile", "post_organize: Could not interpret QuartetAnalysis metafile", "post_organize: missing output suffix", "report_results: missing node return status" "report_results: missing job name", "report_results: run_mrbayes.submit returned a non-zero value", "report_results: Could not read new stats from file", "report_results: Could not open QuartetAnalysis metafile", "report_results: Could not create new statistics line", "report_results: Could not interpret QuartetAnalysis metafile", "report_results: Could not delete stats file", "report_results: missing output suffix", "delete_mb_output: missing node return status", "delete_mb_output: missing job name", "delete_mb_output: error finding quartet index", "delete_mb_output: Could not open QuartetAnalysis metafile", "delete_mb_output: Could not interpret QuartetAnalysis metafile", "delete_mb_output: Could not delete bucky results file", "delete_mb_output: missing output suffix", "fileWriter_condor: Could not initialize", "fileWriter_condor: Less than four taxa found", "fileWriter_condor: Could not open new nexus file", "fileWriter_condor: Could not create or write header", "fileWriter_condor: Could not write data", "fileWriter_condor: Could not write END to data block", "fileWriter_condor: Could not write MrBayes Block", "fileWriter_condor: Could not close new nexus file", "run_bucky.py: Could not open/interpret translate file", "run_bucky.py: Could not interpret job name", "run_bucky.py: Could not interpret gene file", "run_bucky.py: could not open/interpret quartet file in mrBayes.py", "run_bucky.py: number of gene files is zero", "run_bucky.py: could not open/interpret QuartetAnalysis metafile", "run_bucky.py: could not open tar file with mrBayes/mbsum results", "run_bucky.py: mrBayes/mbsum results empty", "run_bucky.py: mrBayes/mbsum results too few", "run_bucky.py: could not extract files from .tar.gz", "run_bucky.py: error in BUCKy", "run_bucky.py: could not write gene stats", "run_bucky.py: could not make gene dictionary", "run_bucky.py: error writing results", "run_bucky.py: error deleting files.", "mrBayes.py: Execution failed", "mrBayes.py: Unknown mrBayes execution error" ] def findErrorCode(errorString): try: errorCode = errorList.index(errorString) except: errorCode = -1 return errorCode def errorString(errorCode): if( errorCode == -1 ): return "unknown error code" try: errorString = errorList[errorCode] except: errorString = "unknown error code" return errorString
error_list = ['no error', 'error code 1', 'mrBayes.py: Could not open quartets file', 'mrBayes.py: Could not interpret quartets file', 'mrBayes.py: Could not open translate file', 'mrBayes.py: Could not interpret translate file', 'mrBayes.py: Could not interpret condor job name', 'mrBayes.py: Could not find tarfile', 'mrBayes.py: Could not create data subdirectory', 'mrBayes.py: Could not open tarfile', 'mrBayes.py: Could not open list of gene files', 'mrBayes.py: Could not get gene files from tarfile', 'mrBayes.py: Could not get gene files from data directory', 'mrBayes.py: Could not interpret read tar.gz', 'mrBayes.py: Could not extract file from tar.gz', 'mrBayes.py: Could not open gene file', 'mrBayes.py: Could not interpret gene file', 'mrBayes.py: Could not initialize quartet subset of gene file', 'mrBayes.py: Could not write quartet subset of gene file', 'mrBayes.py: Could not run mrBayes', 'mrBayes.py: Filename mismatch', 'mrBayes.py: Could not find expected mcmc output', 'mrBayes.py: Could not run mbsum', 'mrBayes.py: Could not delete temporary files', 'mrBayes.py: Could not create or write results file', 'mrBayes.py: Could not create gene group zip file', 'mrBayes.py: Could not delete file after zipping', 'mrBayes.py: Statistics do not add', 'mrBayes.py: Could not write gene group zip filezip_mb_output.py: Could not interpret condor job name', 'zip_mb_output.py: Could not open target tar file', 'zip_mb_output.py: Could not open input tar.gz', 'zip_mb_output.py: Could not extract .in file', 'zip_mb_output.py: Could not add .in file', 'zip_mb_output.py: Could not delete .in file', 'zip_mb_output.py: Could not delete input tar.gz', 'zip_mb_output.py: Could not get directory.', 'zip_mb_output.py: No input tar.gz found', 'post_organize: missing node return status', 'post_organize: organize.submit returned an error value', 'post_organize: Could not update QuartetAnalysis metafile', 'post_organize: Could not interpret QuartetAnalysis metafile', 'post_organize: missing output suffix', 'report_results: missing node return statusreport_results: missing job name', 'report_results: run_mrbayes.submit returned a non-zero value', 'report_results: Could not read new stats from file', 'report_results: Could not open QuartetAnalysis metafile', 'report_results: Could not create new statistics line', 'report_results: Could not interpret QuartetAnalysis metafile', 'report_results: Could not delete stats file', 'report_results: missing output suffix', 'delete_mb_output: missing node return status', 'delete_mb_output: missing job name', 'delete_mb_output: error finding quartet index', 'delete_mb_output: Could not open QuartetAnalysis metafile', 'delete_mb_output: Could not interpret QuartetAnalysis metafile', 'delete_mb_output: Could not delete bucky results file', 'delete_mb_output: missing output suffix', 'fileWriter_condor: Could not initialize', 'fileWriter_condor: Less than four taxa found', 'fileWriter_condor: Could not open new nexus file', 'fileWriter_condor: Could not create or write header', 'fileWriter_condor: Could not write data', 'fileWriter_condor: Could not write END to data block', 'fileWriter_condor: Could not write MrBayes Block', 'fileWriter_condor: Could not close new nexus file', 'run_bucky.py: Could not open/interpret translate file', 'run_bucky.py: Could not interpret job name', 'run_bucky.py: Could not interpret gene file', 'run_bucky.py: could not open/interpret quartet file in mrBayes.py', 'run_bucky.py: number of gene files is zero', 'run_bucky.py: could not open/interpret QuartetAnalysis metafile', 'run_bucky.py: could not open tar file with mrBayes/mbsum results', 'run_bucky.py: mrBayes/mbsum results empty', 'run_bucky.py: mrBayes/mbsum results too few', 'run_bucky.py: could not extract files from .tar.gz', 'run_bucky.py: error in BUCKy', 'run_bucky.py: could not write gene stats', 'run_bucky.py: could not make gene dictionary', 'run_bucky.py: error writing results', 'run_bucky.py: error deleting files.', 'mrBayes.py: Execution failed', 'mrBayes.py: Unknown mrBayes execution error'] def find_error_code(errorString): try: error_code = errorList.index(errorString) except: error_code = -1 return errorCode def error_string(errorCode): if errorCode == -1: return 'unknown error code' try: error_string = errorList[errorCode] except: error_string = 'unknown error code' return errorString
size_matrix = int(input()) matrix = [] pls = [] for i in range(size_matrix): matrix.append([x for x in input()]) for row in range(size_matrix): for col in range(size_matrix): if matrix[row][col] == 'B': pls.append((row, col)) count_food = 0 for row in range(size_matrix): for col in range(size_matrix): if matrix[row][col] == '*': count_food += 1 row_s = 0 col_s = 0 for search_s in matrix: if "S" in search_s: col_s = search_s.index("S") break else: row_s += 1 first_position_s = matrix[row_s][col_s] countar_stop_food = 0 if pls: exit_B_row = int(pls[1][0]) exit_B_col = int(pls[1][1]) while True: command = input() if not command: break if command == "up": if row_s - 1 >= 0: if matrix[row_s - 1][col_s] == "B": matrix[row_s][col_s] = "." matrix[row_s - 1][col_s] = "." matrix[exit_B_row][exit_B_col] = "S" row_s = exit_B_row col_s = exit_B_col elif matrix[row_s - 1][col_s] == "*": matrix[row_s][col_s] = "." matrix[row_s - 1][col_s] = "S" countar_stop_food += 1 row_s -= 1 if countar_stop_food == 10: print("You won! You fed the snake.") print("Food eaten: 10") for d in matrix: print(''.join(d)) exit() elif matrix[row_s - 1][col_s] == "-": matrix[row_s - 1][col_s] = "S" matrix[row_s][col_s] = "." row_s -= 1 else: matrix[row_s][col_s] = "." print("Game over!") print(f"Food eaten: {countar_stop_food}") for d in matrix: print(''.join(d)) exit() elif command == "down": if row_s + 1 < len(matrix): if matrix[row_s + 1][col_s] == "B": matrix[row_s][col_s] = "." matrix[row_s + 1][col_s] = "." matrix[exit_B_row][exit_B_col] = "S" row_s = exit_B_row col_s = exit_B_col elif matrix[row_s + 1][col_s] == "*": matrix[row_s][col_s] = "." matrix[row_s + 1][col_s] = "S" countar_stop_food += 1 row_s += 1 if countar_stop_food == 10: print("You won! You fed the snake.") print("Food eaten: 10") for d in matrix: print(''.join(d)) exit() elif matrix[row_s + 1][col_s] == "-": matrix[row_s + 1][col_s] = "S" matrix[row_s][col_s] = "." row_s += 1 else: matrix[row_s][col_s] = "." print("Game over!") print(f"Food eaten: {countar_stop_food}") for d in matrix: print(''.join(d)) exit() elif command == "left": if col_s - 1 >= 0: if matrix[row_s][col_s - 1] == "B": matrix[row_s][col_s] = "." matrix[row_s][col_s - 1] = "." matrix[exit_B_row][exit_B_col] = "S" row_s = exit_B_row col_s = exit_B_col elif matrix[row_s][col_s - 1] == "*": matrix[row_s][col_s] = "." matrix[row_s][col_s - 1] = "S" countar_stop_food += 1 col_s -= 1 if countar_stop_food == 10: print("You won! You fed the snake.") print("Food eaten: 10") for d in matrix: print(''.join(d)) exit() elif matrix[row_s][col_s - 1] == "-": matrix[row_s][col_s - 1] = "S" matrix[row_s][col_s] = "." col_s -= 1 else: matrix[row_s][col_s] = "." print("Game over!") print(f"Food eaten: {countar_stop_food}") for l in matrix: print(''.join(l)) exit() elif command == "right": if col_s + 1 < len(matrix): if matrix[row_s][col_s + 1] == "B": matrix[row_s][col_s] = "." matrix[row_s][col_s + 1] = "." matrix[exit_B_row][exit_B_col] = "S" row_s = exit_B_row col_s = exit_B_col elif matrix[row_s][col_s + 1] == "*": matrix[row_s][col_s] = "." matrix[row_s][col_s + 1] = "S" countar_stop_food += 1 col_s += 1 if countar_stop_food == 10: print("You won! You fed the snake.") print("Food eaten: 10") for r in matrix: print(''.join(r)) exit() elif matrix[row_s][col_s + 1] == "-": matrix[row_s][col_s + 1] = "S" matrix[row_s][col_s] = "." col_s += 1 else: matrix[row_s][col_s] = "." print("Game over!") print(f"Food eaten: {countar_stop_food}") for r in matrix: print(''.join(r)) exit()
size_matrix = int(input()) matrix = [] pls = [] for i in range(size_matrix): matrix.append([x for x in input()]) for row in range(size_matrix): for col in range(size_matrix): if matrix[row][col] == 'B': pls.append((row, col)) count_food = 0 for row in range(size_matrix): for col in range(size_matrix): if matrix[row][col] == '*': count_food += 1 row_s = 0 col_s = 0 for search_s in matrix: if 'S' in search_s: col_s = search_s.index('S') break else: row_s += 1 first_position_s = matrix[row_s][col_s] countar_stop_food = 0 if pls: exit_b_row = int(pls[1][0]) exit_b_col = int(pls[1][1]) while True: command = input() if not command: break if command == 'up': if row_s - 1 >= 0: if matrix[row_s - 1][col_s] == 'B': matrix[row_s][col_s] = '.' matrix[row_s - 1][col_s] = '.' matrix[exit_B_row][exit_B_col] = 'S' row_s = exit_B_row col_s = exit_B_col elif matrix[row_s - 1][col_s] == '*': matrix[row_s][col_s] = '.' matrix[row_s - 1][col_s] = 'S' countar_stop_food += 1 row_s -= 1 if countar_stop_food == 10: print('You won! You fed the snake.') print('Food eaten: 10') for d in matrix: print(''.join(d)) exit() elif matrix[row_s - 1][col_s] == '-': matrix[row_s - 1][col_s] = 'S' matrix[row_s][col_s] = '.' row_s -= 1 else: matrix[row_s][col_s] = '.' print('Game over!') print(f'Food eaten: {countar_stop_food}') for d in matrix: print(''.join(d)) exit() elif command == 'down': if row_s + 1 < len(matrix): if matrix[row_s + 1][col_s] == 'B': matrix[row_s][col_s] = '.' matrix[row_s + 1][col_s] = '.' matrix[exit_B_row][exit_B_col] = 'S' row_s = exit_B_row col_s = exit_B_col elif matrix[row_s + 1][col_s] == '*': matrix[row_s][col_s] = '.' matrix[row_s + 1][col_s] = 'S' countar_stop_food += 1 row_s += 1 if countar_stop_food == 10: print('You won! You fed the snake.') print('Food eaten: 10') for d in matrix: print(''.join(d)) exit() elif matrix[row_s + 1][col_s] == '-': matrix[row_s + 1][col_s] = 'S' matrix[row_s][col_s] = '.' row_s += 1 else: matrix[row_s][col_s] = '.' print('Game over!') print(f'Food eaten: {countar_stop_food}') for d in matrix: print(''.join(d)) exit() elif command == 'left': if col_s - 1 >= 0: if matrix[row_s][col_s - 1] == 'B': matrix[row_s][col_s] = '.' matrix[row_s][col_s - 1] = '.' matrix[exit_B_row][exit_B_col] = 'S' row_s = exit_B_row col_s = exit_B_col elif matrix[row_s][col_s - 1] == '*': matrix[row_s][col_s] = '.' matrix[row_s][col_s - 1] = 'S' countar_stop_food += 1 col_s -= 1 if countar_stop_food == 10: print('You won! You fed the snake.') print('Food eaten: 10') for d in matrix: print(''.join(d)) exit() elif matrix[row_s][col_s - 1] == '-': matrix[row_s][col_s - 1] = 'S' matrix[row_s][col_s] = '.' col_s -= 1 else: matrix[row_s][col_s] = '.' print('Game over!') print(f'Food eaten: {countar_stop_food}') for l in matrix: print(''.join(l)) exit() elif command == 'right': if col_s + 1 < len(matrix): if matrix[row_s][col_s + 1] == 'B': matrix[row_s][col_s] = '.' matrix[row_s][col_s + 1] = '.' matrix[exit_B_row][exit_B_col] = 'S' row_s = exit_B_row col_s = exit_B_col elif matrix[row_s][col_s + 1] == '*': matrix[row_s][col_s] = '.' matrix[row_s][col_s + 1] = 'S' countar_stop_food += 1 col_s += 1 if countar_stop_food == 10: print('You won! You fed the snake.') print('Food eaten: 10') for r in matrix: print(''.join(r)) exit() elif matrix[row_s][col_s + 1] == '-': matrix[row_s][col_s + 1] = 'S' matrix[row_s][col_s] = '.' col_s += 1 else: matrix[row_s][col_s] = '.' print('Game over!') print(f'Food eaten: {countar_stop_food}') for r in matrix: print(''.join(r)) exit()
+ utility('transmissionMgmt',50) + requiresFunction('transmissionMgmt','transmissionF') + utility('transmissionF',100) + requiresFunction('transmissionF','opcF') + implements('opcF','opc',0) + consumesData('transmissionMgmt','engineerWorkstation','statusRestData',False,0,True,1,True,0.5) #Allocation/Deployments +isType('opc','service') +isType('switchA','switch') + networkConnectsToWithAttributes('opc','switchA',True,True,True) #Style validConnection(SourceService,TargetService) <= isType(SourceService,'switch') & isType(TargetService,'service')
+utility('transmissionMgmt', 50) +requires_function('transmissionMgmt', 'transmissionF') +utility('transmissionF', 100) +requires_function('transmissionF', 'opcF') +implements('opcF', 'opc', 0) +consumes_data('transmissionMgmt', 'engineerWorkstation', 'statusRestData', False, 0, True, 1, True, 0.5) +is_type('opc', 'service') +is_type('switchA', 'switch') +network_connects_to_with_attributes('opc', 'switchA', True, True, True) valid_connection(SourceService, TargetService) <= is_type(SourceService, 'switch') & is_type(TargetService, 'service')
class AsyncSerialPy3Mixin: async def read_exactly(self, n): data = bytearray() while len(data) < n: remaining = n - len(data) data += await self.read(remaining) return data async def write_exactly(self, data): while data: res = await self.write(data) data = data[res:]
class Asyncserialpy3Mixin: async def read_exactly(self, n): data = bytearray() while len(data) < n: remaining = n - len(data) data += await self.read(remaining) return data async def write_exactly(self, data): while data: res = await self.write(data) data = data[res:]
def test_clear_group(app): while 0 != app.group.count_groups(): app.group.delete_first_group() else: print("Group list is already empty")
def test_clear_group(app): while 0 != app.group.count_groups(): app.group.delete_first_group() else: print('Group list is already empty')
def attritems(class_): def _getitem(self, key): return getattr(self, key) setattr(class_, '__getitem__', _getitem) if getattr(class_, '__setitem__', None): delattr(class_, '__setitem__') if getattr(class_, '__delitem__', None): delattr(class_, '__delitem__') return class_ @attritems class Foo: def __init__(self): self.a = 'hello' self.b = 'world' f = Foo() assert f['a'] == 'hello' assert f['b'] == 'world'
def attritems(class_): def _getitem(self, key): return getattr(self, key) setattr(class_, '__getitem__', _getitem) if getattr(class_, '__setitem__', None): delattr(class_, '__setitem__') if getattr(class_, '__delitem__', None): delattr(class_, '__delitem__') return class_ @attritems class Foo: def __init__(self): self.a = 'hello' self.b = 'world' f = foo() assert f['a'] == 'hello' assert f['b'] == 'world'
BINGO_BOARD_LENGTH = 5 class BingoField: def __init__(self, number): self.number = number self.marked = False class BingoBoard: def __init__(self, numbers: list): self.board = [[], [], [], [], []] self.already_won = False for row_idx, _ in enumerate(numbers): for number in numbers[row_idx]: self.board[row_idx].append(BingoField(int(number))) def mark_number(self, number): for row in self.board: for bingo_field in row: if bingo_field.number == number: bingo_field.marked = True self.check_for_win() def check_for_win(self): for row in self.board: all_marked = True for bingo_field in row: if not bingo_field.marked: all_marked = False if all_marked: self.already_won = True for col_idx in range(len(self.board[0])): all_marked = True for row_idx in range(len(self.board)): if not self.board[row_idx][col_idx].marked: all_marked = False if all_marked: self.already_won = True def calculate_score(self, last_marked_number): score = 0 for row in self.board: for bingo_field in row: if not bingo_field.marked: score += bingo_field.number return score * last_marked_number def read_bingo_boards(lines: list): bingo_boards = [] current_board_numbers = [] for line in lines: if not line.strip() == '': current_board_numbers.append(line.strip().split()) if len(current_board_numbers) == BINGO_BOARD_LENGTH: bingo_boards.append(BingoBoard(current_board_numbers)) current_board_numbers = [] return bingo_boards def main(): lines = open('input.txt', 'r').readlines() drawn_numbers = lines[0].split(',') bingo_boards = read_bingo_boards(lines[2:]) board_to_check = None score_printed = False for drawn_number in drawn_numbers: if not score_printed: for bingo_board in bingo_boards: bingo_board.mark_number(int(drawn_number)) boards_not_yet_won = [] for bingo_board in bingo_boards: if board_to_check is None and not bingo_board.already_won: boards_not_yet_won.append(bingo_board) if board_to_check is None and len(boards_not_yet_won) == 1: board_to_check = boards_not_yet_won[0] if board_to_check is not None: if board_to_check.already_won: print(board_to_check.calculate_score(int(drawn_number))) score_printed = True if __name__ == '__main__': main()
bingo_board_length = 5 class Bingofield: def __init__(self, number): self.number = number self.marked = False class Bingoboard: def __init__(self, numbers: list): self.board = [[], [], [], [], []] self.already_won = False for (row_idx, _) in enumerate(numbers): for number in numbers[row_idx]: self.board[row_idx].append(bingo_field(int(number))) def mark_number(self, number): for row in self.board: for bingo_field in row: if bingo_field.number == number: bingo_field.marked = True self.check_for_win() def check_for_win(self): for row in self.board: all_marked = True for bingo_field in row: if not bingo_field.marked: all_marked = False if all_marked: self.already_won = True for col_idx in range(len(self.board[0])): all_marked = True for row_idx in range(len(self.board)): if not self.board[row_idx][col_idx].marked: all_marked = False if all_marked: self.already_won = True def calculate_score(self, last_marked_number): score = 0 for row in self.board: for bingo_field in row: if not bingo_field.marked: score += bingo_field.number return score * last_marked_number def read_bingo_boards(lines: list): bingo_boards = [] current_board_numbers = [] for line in lines: if not line.strip() == '': current_board_numbers.append(line.strip().split()) if len(current_board_numbers) == BINGO_BOARD_LENGTH: bingo_boards.append(bingo_board(current_board_numbers)) current_board_numbers = [] return bingo_boards def main(): lines = open('input.txt', 'r').readlines() drawn_numbers = lines[0].split(',') bingo_boards = read_bingo_boards(lines[2:]) board_to_check = None score_printed = False for drawn_number in drawn_numbers: if not score_printed: for bingo_board in bingo_boards: bingo_board.mark_number(int(drawn_number)) boards_not_yet_won = [] for bingo_board in bingo_boards: if board_to_check is None and (not bingo_board.already_won): boards_not_yet_won.append(bingo_board) if board_to_check is None and len(boards_not_yet_won) == 1: board_to_check = boards_not_yet_won[0] if board_to_check is not None: if board_to_check.already_won: print(board_to_check.calculate_score(int(drawn_number))) score_printed = True if __name__ == '__main__': main()
x=input('first number?') y=input('second number?') outcome=int(x)*int(y) print (outcome)
x = input('first number?') y = input('second number?') outcome = int(x) * int(y) print(outcome)
# -*- coding: utf-8 -*- # ##### BEGIN GPL LICENSE BLOCK ##### # # This program is free software; you can redistribute it and/or # modify it under the terms of the GNU General Public License # as published by the Free Software Foundation; either version 2 # 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 General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software Foundation, # Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. # # ##### END GPL LICENSE BLOCK ##### ''' ui_utils.py Some UI utility functions ''' class GUI: @classmethod def drawIconButton(cls, enabled, layout, iconName, operator, frame=True): col = layout.column() col.enabled = enabled bt = col.operator(operator, text='', icon=iconName, emboss=frame) @classmethod def drawTextButton(cls, enabled, layout, text, operator, frame=True): col = layout.column() col.enabled = enabled bt = col.operator(operator, text=text, emboss=frame)
""" ui_utils.py Some UI utility functions """ class Gui: @classmethod def draw_icon_button(cls, enabled, layout, iconName, operator, frame=True): col = layout.column() col.enabled = enabled bt = col.operator(operator, text='', icon=iconName, emboss=frame) @classmethod def draw_text_button(cls, enabled, layout, text, operator, frame=True): col = layout.column() col.enabled = enabled bt = col.operator(operator, text=text, emboss=frame)
''' Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element. Implement KthLargest class: KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums. int add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream. ''' class TreeNode: def __init__(self, val, cnt=1, left=None, right=None): self.val = val self.cnt = cnt self.left = left self.right = right class KthLargest: def __init__(self, k: int, nums: List[int]): self.k = k if nums == []: self.root = None else: self.root = TreeNode(nums[0], ) for num in nums[1:]: self.add(num) def add(self, val: int) -> int: k = self.k if not self.root: self.root = TreeNode(val) else: stack = [self.root] while stack: node = stack.pop() node.cnt += 1 if node.left and node.val > val: stack.append(node.left) elif not node.left and node.val > val: node.left = TreeNode(val) elif node.right and node.val <= val: stack.append(node.right) elif not node.right and node.val <= val: node.right = TreeNode(val) ## search for the k-largest element stack = [self.root] if self.k > self.root.cnt: return while stack: root = stack.pop() if root.right and k > root.right.cnt + 1: stack.append(root.left) k -= root.right.cnt + 1 elif root.right and k == root.right.cnt + 1: return root.val elif not root.right and k > 1: stack.append(root.left) k -= 1 elif not root.right and k == 1: return root.val else: stack.append(root.right) # Your KthLargest object will be instantiated and called as such: # obj = KthLargest(k, nums) # param_1 = obj.add(val)
""" Design a class to find the kth largest element in a stream. Note that it is the kth largest element in the sorted order, not the kth distinct element. Implement KthLargest class: KthLargest(int k, int[] nums) Initializes the object with the integer k and the stream of integers nums. int add(int val) Appends the integer val to the stream and returns the element representing the kth largest element in the stream. """ class Treenode: def __init__(self, val, cnt=1, left=None, right=None): self.val = val self.cnt = cnt self.left = left self.right = right class Kthlargest: def __init__(self, k: int, nums: List[int]): self.k = k if nums == []: self.root = None else: self.root = tree_node(nums[0]) for num in nums[1:]: self.add(num) def add(self, val: int) -> int: k = self.k if not self.root: self.root = tree_node(val) else: stack = [self.root] while stack: node = stack.pop() node.cnt += 1 if node.left and node.val > val: stack.append(node.left) elif not node.left and node.val > val: node.left = tree_node(val) elif node.right and node.val <= val: stack.append(node.right) elif not node.right and node.val <= val: node.right = tree_node(val) stack = [self.root] if self.k > self.root.cnt: return while stack: root = stack.pop() if root.right and k > root.right.cnt + 1: stack.append(root.left) k -= root.right.cnt + 1 elif root.right and k == root.right.cnt + 1: return root.val elif not root.right and k > 1: stack.append(root.left) k -= 1 elif not root.right and k == 1: return root.val else: stack.append(root.right)
# Challenge 9 : Write a function named same_values() that takes two lists of numbers of equal size as parameters. # The function should return a list of the indices where the values were equal in lst1 and lst2. # Date : Sun 07 Jun 2020 09:28:38 AM IST def same_values(lst1, lst2): newList = [] for i in range(len(lst1)): if lst1[i] == lst2[i]: newList.append(i) return newList print(same_values([5, 1, -10, 3, 3], [5, 10, -10, 3, 5]))
def same_values(lst1, lst2): new_list = [] for i in range(len(lst1)): if lst1[i] == lst2[i]: newList.append(i) return newList print(same_values([5, 1, -10, 3, 3], [5, 10, -10, 3, 5]))
def info(a): a = raw_input("type your height here: ") return a
def info(a): a = raw_input('type your height here: ') return a
def strategy(history, memory): if memory is None: memory = (0, 0) defections = memory[0] count = memory[1] choice = 1 if count > 0: if count < defections: choice = 0 count += 1 elif count == defections: count += 1 elif count > defections: count = 0 elif history.shape[1] >= 1 and history[1,-1] == 0: # Choose to defect if and only if the opponent just defected. defections += 1 choice = 0 count = 1 return choice, (defections, count)
def strategy(history, memory): if memory is None: memory = (0, 0) defections = memory[0] count = memory[1] choice = 1 if count > 0: if count < defections: choice = 0 count += 1 elif count == defections: count += 1 elif count > defections: count = 0 elif history.shape[1] >= 1 and history[1, -1] == 0: defections += 1 choice = 0 count = 1 return (choice, (defections, count))
def get_2(digits, one, seven, four): for digit in digits: if len(digit - one - seven - four) == 2: return digit assert False, f"2 cannot be calculated from {digits=} using {one=}, {seven=} and {four=}" def get_3(digits, two): for digit in digits: if len(digit - two) == 1: return digit assert False, f"3 cannot be calculated from {digits=} using {two=}" def get_9(digits, three): for digit in digits: if len(digit - three) == 1: return digit assert False, f"9 cannot be calculated from {digits=} using {three=}" def get_0(digits, five): for digit in digits: if len(digit - five) == 2: return digit assert False, f"0 cannot be calculated from {digits=} using {five=}" def process_entry(patterns: list, output: list): one = [set(p) for p in patterns if len(p) == 2][0] seven = [set(p) for p in patterns if len(p) == 3][0] four = [set(p) for p in patterns if len(p) == 4][0] eight = [set(p) for p in patterns if len(p) == 7][0] two_three_five = [set(p) for p in patterns if len(p) == 5] zero_six_nine = [set(p) for p in patterns if len(p) == 6] two = get_2(two_three_five, one, seven, four) three_five = [digit for digit in two_three_five if digit != two] three = get_3(three_five, two) five = [digit for digit in three_five if digit != three][0] nine = get_9(zero_six_nine, three) zero = get_0(zero_six_nine, five) zero_six_nine.remove(zero) zero_six_nine.remove(nine) six = zero_six_nine[0] digits = [zero, one, two, three, four, five, six, seven, eight, nine] value = ''.join(str(digits.index(set(d))) for d in output) return int(value) with open("inp8.txt") as file: data = file.read() p1, p2 = 0, 0 for line in data.splitlines(): patterns, output = line.split(' | ') patterns, output = patterns.split(), output.split() p1 += sum(1 for digit in output if len(digit) in (2, 3, 4, 7)) p2 += process_entry(patterns, output) print(f"Part 1: {p1}") assert p1 == 344 print(f"Part 2: {p2}") assert p2 == 1048410
def get_2(digits, one, seven, four): for digit in digits: if len(digit - one - seven - four) == 2: return digit assert False, f'2 cannot be calculated from digits={digits!r} using one={one!r}, seven={seven!r} and four={four!r}' def get_3(digits, two): for digit in digits: if len(digit - two) == 1: return digit assert False, f'3 cannot be calculated from digits={digits!r} using two={two!r}' def get_9(digits, three): for digit in digits: if len(digit - three) == 1: return digit assert False, f'9 cannot be calculated from digits={digits!r} using three={three!r}' def get_0(digits, five): for digit in digits: if len(digit - five) == 2: return digit assert False, f'0 cannot be calculated from digits={digits!r} using five={five!r}' def process_entry(patterns: list, output: list): one = [set(p) for p in patterns if len(p) == 2][0] seven = [set(p) for p in patterns if len(p) == 3][0] four = [set(p) for p in patterns if len(p) == 4][0] eight = [set(p) for p in patterns if len(p) == 7][0] two_three_five = [set(p) for p in patterns if len(p) == 5] zero_six_nine = [set(p) for p in patterns if len(p) == 6] two = get_2(two_three_five, one, seven, four) three_five = [digit for digit in two_three_five if digit != two] three = get_3(three_five, two) five = [digit for digit in three_five if digit != three][0] nine = get_9(zero_six_nine, three) zero = get_0(zero_six_nine, five) zero_six_nine.remove(zero) zero_six_nine.remove(nine) six = zero_six_nine[0] digits = [zero, one, two, three, four, five, six, seven, eight, nine] value = ''.join((str(digits.index(set(d))) for d in output)) return int(value) with open('inp8.txt') as file: data = file.read() (p1, p2) = (0, 0) for line in data.splitlines(): (patterns, output) = line.split(' | ') (patterns, output) = (patterns.split(), output.split()) p1 += sum((1 for digit in output if len(digit) in (2, 3, 4, 7))) p2 += process_entry(patterns, output) print(f'Part 1: {p1}') assert p1 == 344 print(f'Part 2: {p2}') assert p2 == 1048410
# Firstly, get the flatfile from the user. def getFile(): file_path = input("Input the path to the flat file: ") try: keypath = open(file_path, "r") return keypath except: print("No file found there.") # Secondly, iterate through the file and update a state dictionary containing string and grid states. # Also, the nested if statement checks for out of bounds and resets it accordingly. def analyzeFile(file): state_dict = { "string_state": "", "grid_state": [0, 0], } nav_grid = [ ['A', 'B', 'C', 'D', 'E', 'F'], ['G', 'H', 'I', 'J', 'K', 'L'], ['M', 'N', 'O', 'P', 'Q', 'R'], ['S', 'T', 'U', 'V', 'W', 'X'], ['Y', 'Z', '1', '2', '3', '4'], ['5', '6', '7', '8', '9', '0'] ] for character in file.read(): if character == "U": if state_dict["grid_state"][0] == -6: # Out of bounds check state_dict["grid_state"][0] = 0 state_dict["grid_state"][0] -= 1 elif character == "D": if state_dict["grid_state"][0] == 5: # Out of bounds check state_dict["grid_state"][0] = -1 state_dict["grid_state"][0] += 1 elif character == "L": if state_dict["grid_state"][1] == -6: # Out of bounds check state_dict["grid_state"][1] = 0 state_dict["grid_state"][1] -= 1 elif character == "R": if state_dict["grid_state"][1] == 5: # Out of bounds check state_dict["grid_state"][1] = -1 state_dict["grid_state"][1] += 1 elif character == "*": indexOne = state_dict["grid_state"][0] indexTwo = state_dict["grid_state"][1] state_dict["string_state"] += nav_grid[indexOne][indexTwo] elif character == "S": state_dict["string_state"] += " " elif character == "\n": state_dict.update({"grid_state": [0, 0]}) state_dict["string_state"] += "\n" return state_dict["string_state"] # Lastly, open a new file to return and give it your search term string. def outputSearchTerm(textToNewFile): searchTermFile = open("SearchTerm", "w") searchTermFile.write(textToNewFile) searchTermFile.close() def main(): try: outputSearchTerm(analyzeFile(getFile())) print("--Text from Keypath Complete.--") print("--File Created--") except: print("An error occurred. Refer to the above message for more information.") main()
def get_file(): file_path = input('Input the path to the flat file: ') try: keypath = open(file_path, 'r') return keypath except: print('No file found there.') def analyze_file(file): state_dict = {'string_state': '', 'grid_state': [0, 0]} nav_grid = [['A', 'B', 'C', 'D', 'E', 'F'], ['G', 'H', 'I', 'J', 'K', 'L'], ['M', 'N', 'O', 'P', 'Q', 'R'], ['S', 'T', 'U', 'V', 'W', 'X'], ['Y', 'Z', '1', '2', '3', '4'], ['5', '6', '7', '8', '9', '0']] for character in file.read(): if character == 'U': if state_dict['grid_state'][0] == -6: state_dict['grid_state'][0] = 0 state_dict['grid_state'][0] -= 1 elif character == 'D': if state_dict['grid_state'][0] == 5: state_dict['grid_state'][0] = -1 state_dict['grid_state'][0] += 1 elif character == 'L': if state_dict['grid_state'][1] == -6: state_dict['grid_state'][1] = 0 state_dict['grid_state'][1] -= 1 elif character == 'R': if state_dict['grid_state'][1] == 5: state_dict['grid_state'][1] = -1 state_dict['grid_state'][1] += 1 elif character == '*': index_one = state_dict['grid_state'][0] index_two = state_dict['grid_state'][1] state_dict['string_state'] += nav_grid[indexOne][indexTwo] elif character == 'S': state_dict['string_state'] += ' ' elif character == '\n': state_dict.update({'grid_state': [0, 0]}) state_dict['string_state'] += '\n' return state_dict['string_state'] def output_search_term(textToNewFile): search_term_file = open('SearchTerm', 'w') searchTermFile.write(textToNewFile) searchTermFile.close() def main(): try: output_search_term(analyze_file(get_file())) print('--Text from Keypath Complete.--') print('--File Created--') except: print('An error occurred. Refer to the above message for more information.') main()
# # @lc app=leetcode id=83 lang=python3 # # [83] Remove Duplicates from Sorted List # # https://leetcode.com/problems/remove-duplicates-from-sorted-list/description/ # # algorithms # Easy (41.95%) # Likes: 774 # Dislikes: 82 # Total Accepted: 333.1K # Total Submissions: 779.9K # Testcase Example: '[1,1,2]' # # Given a sorted linked list, delete all duplicates such that each element # appear only once. # # Example 1: # # # Input: 1->1->2 # Output: 1->2 # # # Example 2: # # # Input: 1->1->2->3->3 # Output: 1->2->3 # # # # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def deleteDuplicates(self, head: ListNode) -> ListNode: if not head: return head p, q = head, head.next while q: if p.val == q.val: p.next = q.next q = q.next else: p = p.next return head
class Solution: def delete_duplicates(self, head: ListNode) -> ListNode: if not head: return head (p, q) = (head, head.next) while q: if p.val == q.val: p.next = q.next q = q.next else: p = p.next return head
def high_and_low(numbers): numbers = list((max(map(int,numbers.split())),min(map(int,numbers.split())))) return ' '.join(map(str,numbers)) def high_and_lowB(numbers): nn = [int(s) for s in numbers.split(" ")] return "%i %i" % (max(nn),min(nn))
def high_and_low(numbers): numbers = list((max(map(int, numbers.split())), min(map(int, numbers.split())))) return ' '.join(map(str, numbers)) def high_and_low_b(numbers): nn = [int(s) for s in numbers.split(' ')] return '%i %i' % (max(nn), min(nn))
grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] def gridOutput(grid): for s in range(len(grid[0])): print() for i in range(len(grid)): print(grid[i][s],end='') gridOutput(grid)
grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] def grid_output(grid): for s in range(len(grid[0])): print() for i in range(len(grid)): print(grid[i][s], end='') grid_output(grid)
t = int(input()) for i in range(t): b,c=map(int,input().split()) ans = (2*b-c-1)//2 print(2*ans)
t = int(input()) for i in range(t): (b, c) = map(int, input().split()) ans = (2 * b - c - 1) // 2 print(2 * ans)
def moveZeroes(nums): lastNonZero = 0 for i in range(len(nums)): if nums[i] != 0: nums[lastNonZero], nums[i] = nums[i], nums[lastNonZero] lastNonZero += 1 nums = [0, 1, 0, 3, 12] moveZeroes(nums) print(nums) # [1, 3, 12, 0, 0] nums = [4, 2, 4, 0, 0, 3, 0, 5, 1, 0] moveZeroes(nums) print(nums) # [4, 2, 4, 3, 5, 1, 0, 0, 0, 0]
def move_zeroes(nums): last_non_zero = 0 for i in range(len(nums)): if nums[i] != 0: (nums[lastNonZero], nums[i]) = (nums[i], nums[lastNonZero]) last_non_zero += 1 nums = [0, 1, 0, 3, 12] move_zeroes(nums) print(nums) nums = [4, 2, 4, 0, 0, 3, 0, 5, 1, 0] move_zeroes(nums) print(nums)
def move(n, a, b, c): if n == 1: print(str(a) + " " + str(c)) else: move(n - 1, a, c, b) print(str(a) + " " + str(c)) move(n - 1, b, a, c) def Num11729(): n = int(input()) print(2 ** n -1) move(n, 1, 2, 3) Num11729()
def move(n, a, b, c): if n == 1: print(str(a) + ' ' + str(c)) else: move(n - 1, a, c, b) print(str(a) + ' ' + str(c)) move(n - 1, b, a, c) def num11729(): n = int(input()) print(2 ** n - 1) move(n, 1, 2, 3) num11729()
def get_synset(path='../data/imagenet_synset_words.txt'): with open(path, 'r') as f: # Strip off the first word (until space, maxsplit=1), then synset is remainder return [ line.strip().split(' ', 1)[1] for line in f]
def get_synset(path='../data/imagenet_synset_words.txt'): with open(path, 'r') as f: return [line.strip().split(' ', 1)[1] for line in f]
class Deque: def __init__(self): self.deque =[] def addFront(self,element): self.deque.append(element) print("After adding from front the deque value is : ", self.deque) def addRear(self,element): self.deque.insert(0,element) print("After adding from end the deque value is : ", self.deque) def removeFront(self): self.deque.pop() print("After removing from the front the deque value is : ", self.deque) def removeRear(self): self.deque.pop(0) print("After removing from the end the deque value is : ", self.deque) D = Deque() print("Adding from front") D.addFront(1) print("Adding from front") D.addFront(2) print("Adding from Rear") D.addRear(3) print("Adding from Rear") D.addRear(4) print("Removing from Front") D.removeFront() print("Removing from Rear") D.removeRear()
class Deque: def __init__(self): self.deque = [] def add_front(self, element): self.deque.append(element) print('After adding from front the deque value is : ', self.deque) def add_rear(self, element): self.deque.insert(0, element) print('After adding from end the deque value is : ', self.deque) def remove_front(self): self.deque.pop() print('After removing from the front the deque value is : ', self.deque) def remove_rear(self): self.deque.pop(0) print('After removing from the end the deque value is : ', self.deque) d = deque() print('Adding from front') D.addFront(1) print('Adding from front') D.addFront(2) print('Adding from Rear') D.addRear(3) print('Adding from Rear') D.addRear(4) print('Removing from Front') D.removeFront() print('Removing from Rear') D.removeRear()
things = [ 'An old Box', 'Ancient Knife', 'Oppenheimer Blue Diamond', '1962 Ferrari 250 GTO Berlinetta', 'Hindoostan Antique Map 1826', 'Rare 19th C. Mughal Indian ZANGHAL Axe with Strong', '1850 $5 Baldwin Gold Half Eagle UNCIRCULATED', 'Chevrolet Corvette 1963' ]
things = ['An old Box', 'Ancient Knife', 'Oppenheimer Blue Diamond', '1962 Ferrari 250 GTO Berlinetta', 'Hindoostan Antique Map 1826', 'Rare 19th C. Mughal Indian ZANGHAL Axe with Strong', '1850 $5 Baldwin Gold Half Eagle UNCIRCULATED', 'Chevrolet Corvette 1963']
x,y=0,0 for i in range(5): b=input("").split() for j in range(5): if(b[j]=='1'): x=i+1 y=j+1 x=x-3; y=y-3; if(x<0): x=-x if(y<0): y=-y print(x+y) a=[[],[],[]] b=len(a[1])//2 a[b][b],a[i][j]=a[i][j],a[b][b] a=tan(3.33)
(x, y) = (0, 0) for i in range(5): b = input('').split() for j in range(5): if b[j] == '1': x = i + 1 y = j + 1 x = x - 3 y = y - 3 if x < 0: x = -x if y < 0: y = -y print(x + y) a = [[], [], []] b = len(a[1]) // 2 (a[b][b], a[i][j]) = (a[i][j], a[b][b]) a = tan(3.33)
class Salary: def __init__(self, pay): self._pay = pay def get_total(self): return (self._pay * 12) // 4.9545 class SalarySenior: def __init__(self, pay): self._pay = pay def get_total(self): return (self._pay * 24) // 4.9545 class Employee: def __init__(self, pay, bonus): self._bonus = bonus self._pay = pay def annual_salary(self): return f'Total salary is: {self._pay.get_total() + self._bonus}' emp_middle = Employee(Salary(10000), 500) emp_senior = Employee(SalarySenior(10000), 600) print(emp_middle.annual_salary())
class Salary: def __init__(self, pay): self._pay = pay def get_total(self): return self._pay * 12 // 4.9545 class Salarysenior: def __init__(self, pay): self._pay = pay def get_total(self): return self._pay * 24 // 4.9545 class Employee: def __init__(self, pay, bonus): self._bonus = bonus self._pay = pay def annual_salary(self): return f'Total salary is: {self._pay.get_total() + self._bonus}' emp_middle = employee(salary(10000), 500) emp_senior = employee(salary_senior(10000), 600) print(emp_middle.annual_salary())
changes = {'.': 0, ',': 1, '+': 2, '-': 3, '>':4, '<': 5, '[': 6, ']': 7} def convert(code): current = 0 x = "" for i in code: dest = changes.get(i) if dest is None: continue diff = (dest - current) % 8 x += "+" * diff + "!" current = dest print(current) return x
changes = {'.': 0, ',': 1, '+': 2, '-': 3, '>': 4, '<': 5, '[': 6, ']': 7} def convert(code): current = 0 x = '' for i in code: dest = changes.get(i) if dest is None: continue diff = (dest - current) % 8 x += '+' * diff + '!' current = dest print(current) return x
{'application':{'type':'Application', 'name':'webgrabber', 'backgrounds': [ {'type':'Background', 'name':'bgGrabber', 'title':'webgrabber PythonCard Application', 'size':(540, 172), 'statusBar':1, 'menubar': {'type':'MenuBar', 'menus': [ {'type':'Menu', 'name':'menuFile', 'label':'&File', 'items': [ {'type':'MenuItem', 'name':'menuFileExit', 'label':'E&xit\tAlt+X', 'command':'exit', }, ] }, ] }, 'components': [ {'type':'TextField', 'name':'fldURL', 'position':(65, 0), 'size':(466, -1), }, {'type':'TextField', 'name':'fldDirectory', 'position':(65, 30), 'size':(370, -1), }, {'type':'StaticText', 'name':'stcDirectory', 'position':(0, 30), 'text':'Directory:', }, {'type':'StaticText', 'name':'stcURL', 'position':(0, 5), 'text':'URL:', }, {'type':'Button', 'name':'btnDirectory', 'position':(455, 30), 'label':'Directory...', }, {'type':'Button', 'name':'btnGo', 'position':(360, 70), 'label':'Go', 'default':1, }, {'type':'Button', 'name':'btnCancel', 'position':(455, 70), 'label':'Cancel', }, ] # end components } # end background ] # end backgrounds } }
{'application': {'type': 'Application', 'name': 'webgrabber', 'backgrounds': [{'type': 'Background', 'name': 'bgGrabber', 'title': 'webgrabber PythonCard Application', 'size': (540, 172), 'statusBar': 1, 'menubar': {'type': 'MenuBar', 'menus': [{'type': 'Menu', 'name': 'menuFile', 'label': '&File', 'items': [{'type': 'MenuItem', 'name': 'menuFileExit', 'label': 'E&xit\tAlt+X', 'command': 'exit'}]}]}, 'components': [{'type': 'TextField', 'name': 'fldURL', 'position': (65, 0), 'size': (466, -1)}, {'type': 'TextField', 'name': 'fldDirectory', 'position': (65, 30), 'size': (370, -1)}, {'type': 'StaticText', 'name': 'stcDirectory', 'position': (0, 30), 'text': 'Directory:'}, {'type': 'StaticText', 'name': 'stcURL', 'position': (0, 5), 'text': 'URL:'}, {'type': 'Button', 'name': 'btnDirectory', 'position': (455, 30), 'label': 'Directory...'}, {'type': 'Button', 'name': 'btnGo', 'position': (360, 70), 'label': 'Go', 'default': 1}, {'type': 'Button', 'name': 'btnCancel', 'position': (455, 70), 'label': 'Cancel'}]}]}}
# ------------------------------------------------------------------------------------ # Tutorial: The replace method replaces a specified string with another specified string. # ------------------------------------------------------------------------------------ # Example 1. # Replace all occurences of "dog" with "cat" dog_txt = "I always wanted a dog! My dog is awsome :) My dog\'s name is Taco" cat_txt = dog_txt.replace("dog", "cat") print("\nExample 1. - Replace all occurences of \"dog\" with \"cat\"") print(f'Old String: {dog_txt}') print(f'New String: {cat_txt}') # Example 2. # Replace the two first occurences of "dog" with "cat" dog_txt = "I always wanted a dog! My dog is awsome :) My dog\'s name is Taco" cat_txt = dog_txt.replace("dog", "cat", 2) print("\nExample 2. - Replace first two occurences of \"dog\" with \"cat\"") print(f'Old String: {dog_txt}') print(f'New String: {cat_txt}\n') # ------------------------------------------------------------------------------------ # Challenge: # 1. From the string "Teach me Python like Im 5" produce the string "Teach me Java like Im 10". # 2. From the string "Im 10 years old" produce the string "How old are you?". # ------------------------------------------------------------------------------------
dog_txt = "I always wanted a dog! My dog is awsome :) My dog's name is Taco" cat_txt = dog_txt.replace('dog', 'cat') print('\nExample 1. - Replace all occurences of "dog" with "cat"') print(f'Old String: {dog_txt}') print(f'New String: {cat_txt}') dog_txt = "I always wanted a dog! My dog is awsome :) My dog's name is Taco" cat_txt = dog_txt.replace('dog', 'cat', 2) print('\nExample 2. - Replace first two occurences of "dog" with "cat"') print(f'Old String: {dog_txt}') print(f'New String: {cat_txt}\n')
is_day = False lights_on = not is_day print("Daytime?") print(is_day) print("Lights on?") print(lights_on)
is_day = False lights_on = not is_day print('Daytime?') print(is_day) print('Lights on?') print(lights_on)
def insertionSort(arr): output = arr[:] #go through each element for index in range(1, len(output)): #grab current element current = output[index] #get last index of sorted output j = index #shift up all sorted elements that are greater than current one while j > 0 and output[j - 1] > current: output[j] = output[j - 1] j = j - 1 #insert current element at newly created space output[j] = current return output
def insertion_sort(arr): output = arr[:] for index in range(1, len(output)): current = output[index] j = index while j > 0 and output[j - 1] > current: output[j] = output[j - 1] j = j - 1 output[j] = current return output
SCHEMA_URL = "https://raw.githubusercontent.com/vz-risk/veris/master/verisc-merged.json" VARIETY_AMT_ENUMS = ['asset.assets', 'attribute.confidentiality.data', 'impact.loss'] VARIETY_AMT = ['variety', 'amount'] ASSETMAP = {'S ' : 'Server', 'N ' : 'Network', 'U ' : 'User Dev', 'M ' : 'Media', 'P ' : 'Person', 'T ' : 'Kiosk/Term', 'Un' : 'Unknown', 'E ' : 'Embedded'} A4NAMES = {'actor': ['External', 'Internal', 'Partner', 'Unknown'], 'action': ['Malware', 'Hacking', 'Social', 'Physical', 'Misuse', 'Error', 'Environmental', 'Unknown'], 'attribute': ['Confidentiality', 'Integrity', 'Availability'], 'asset': {'variety': list(ASSETMAP.values()), 'assets.variety': list(ASSETMAP.keys())}} SMALL_ORG_SUFFIXES = ['1 to 10', '11 to 100', '101 to 1000', 'Small'] LARGE_ORG_SUFFIXES = ['1001 to 10000', '10001 to 25000', '25001 to 50000', '50001 to 100000', 'Over 100000', 'Large'] SMALL_ORG = ['.'.join(('victim.employee_count', suffix)) for suffix in SMALL_ORG_SUFFIXES] LARGE_ORG = ['.'.join(('victim.employee_count', suffix)) for suffix in LARGE_ORG_SUFFIXES] ORG_SMALL_LARGE = {'victim.orgsize.Small' : SMALL_ORG, 'victim.orgsize.Large' : LARGE_ORG} # MATRIX CONSTANTS MATRIX_ENUMS = ['actor', 'action', 'victim.employee_count', 'security_incident', 'asset.assets', "asset.assets.variety", "asset.cloud", "asset.hosting", "asset.management", "asset.ownership", "attribute.confidentiality.data.variety", "attribute.confidentiality.data_disclosure", "discovery_method", "targeted", "attribute.integrity.variety", "attribute.availability.variety"] MATRIX_IGNORE = ['cve', 'name', 'notes', 'country', 'industry']
schema_url = 'https://raw.githubusercontent.com/vz-risk/veris/master/verisc-merged.json' variety_amt_enums = ['asset.assets', 'attribute.confidentiality.data', 'impact.loss'] variety_amt = ['variety', 'amount'] assetmap = {'S ': 'Server', 'N ': 'Network', 'U ': 'User Dev', 'M ': 'Media', 'P ': 'Person', 'T ': 'Kiosk/Term', 'Un': 'Unknown', 'E ': 'Embedded'} a4_names = {'actor': ['External', 'Internal', 'Partner', 'Unknown'], 'action': ['Malware', 'Hacking', 'Social', 'Physical', 'Misuse', 'Error', 'Environmental', 'Unknown'], 'attribute': ['Confidentiality', 'Integrity', 'Availability'], 'asset': {'variety': list(ASSETMAP.values()), 'assets.variety': list(ASSETMAP.keys())}} small_org_suffixes = ['1 to 10', '11 to 100', '101 to 1000', 'Small'] large_org_suffixes = ['1001 to 10000', '10001 to 25000', '25001 to 50000', '50001 to 100000', 'Over 100000', 'Large'] small_org = ['.'.join(('victim.employee_count', suffix)) for suffix in SMALL_ORG_SUFFIXES] large_org = ['.'.join(('victim.employee_count', suffix)) for suffix in LARGE_ORG_SUFFIXES] org_small_large = {'victim.orgsize.Small': SMALL_ORG, 'victim.orgsize.Large': LARGE_ORG} matrix_enums = ['actor', 'action', 'victim.employee_count', 'security_incident', 'asset.assets', 'asset.assets.variety', 'asset.cloud', 'asset.hosting', 'asset.management', 'asset.ownership', 'attribute.confidentiality.data.variety', 'attribute.confidentiality.data_disclosure', 'discovery_method', 'targeted', 'attribute.integrity.variety', 'attribute.availability.variety'] matrix_ignore = ['cve', 'name', 'notes', 'country', 'industry']
N = int(input()) ans = min(9, N) + max(0, min(999, N) - 99) + max(0, min(99999, N) - 9999) print(ans)
n = int(input()) ans = min(9, N) + max(0, min(999, N) - 99) + max(0, min(99999, N) - 9999) print(ans)
''' done ''' def Jumlah(a, b): return a + b print(Jumlah(2, 8))
""" done """ def jumlah(a, b): return a + b print(jumlah(2, 8))
greetings = ["hello", "world", "Jenn"] for greeting in greetings: print(f"{greeting}, World") def add_number(x, y): return x + y add_number(1, 2) things_to_do = ["pickup meds", "shower", "change bandage", "python", "brush Baby and pack dogs", "Whole Foods", "Jocelyn"]
greetings = ['hello', 'world', 'Jenn'] for greeting in greetings: print(f'{greeting}, World') def add_number(x, y): return x + y add_number(1, 2) things_to_do = ['pickup meds', 'shower', 'change bandage', 'python', 'brush Baby and pack dogs', 'Whole Foods', 'Jocelyn']
class Solution: #Function to convert a binary tree into its mirror tree. def mirror(self,root): # Code here if(root == None): return else: self.mirror(root.left) self.mirror(root.right) root.left, root.right = root.right, root.left
class Solution: def mirror(self, root): if root == None: return else: self.mirror(root.left) self.mirror(root.right) (root.left, root.right) = (root.right, root.left)
## robot_servant.py ## This code implements a search space model for a robot ## that can move around a house and pick up and put down ## objects. ## The function calls provided for a general search algorithm are: ## robot_print_problem_info() ## robot_initial_state ## robot_possible_actions(state) ## robot_successor_state(action,state) ## robot_goal_state( state ) ## robot_display_state( state ) ## not yet implemented print( "Loading robot_servant.py" ) ROBOT_GOAL = "undefined" ## will be defined when problem is initialised def robot_initialise_1(): global permanent_facts, initial_state, ROBOT_GOAL permanent_facts = robot_permanent_facts_1 initial_state = robot_initial_state_1 ROBOT_GOAL = robot_goal_1 robot_permanent_facts_1 = [ ('connected', 'kitchen', 'garage', 'door_kg'), ('connected', 'kitchen', 'larder', 'door_kl'), ] robot_initial_state_1 = [ ('locked', 'door_kl'), ('unlocked', 'door_kg'), ('located', 'robot', 'kitchen'), ('located', 'key', 'garage' ), ('located', 'spade', 'garage' ), ('located', 'ring', 'larder' ), ('located', 'sausages', 'larder') ] robot_goal_1 = ('and', ('carrying','ring'), ('located', 'sausages', 'kitchen')) robot_goal_easy = ('carrying','ring') def robot_possible_actions(state): pickup_actions = possible_pickup_actions(state) move_actions = possible_move_actions(state) drop_actions = possible_drop_actions(state) unlock_actions = possible_unlock_actions(state) return pickup_actions + move_actions + drop_actions + unlock_actions def robot_successor_state( action, state ): newstate = list(state) ## set newstate to a copy of state robloc = get_robot_location(state) if action[0] == 'pickup': item = action[1] newstate.remove(('located', item, robloc)) newstate.append(('carrying', item)) newstate.sort() return newstate if action[0] == 'drop': item = action[1] newstate.remove(('carrying', item)) newstate.append(('located', item, robloc)) newstate.sort() return newstate if action[0] == 'move': dest = action[1] newstate.remove(('located', 'robot', robloc)) newstate.append(('located', 'robot', dest)) newstate.sort() return newstate if action[0] == 'unlock': door = action[1] newstate.remove(('locked', door)) newstate.append(('unlocked', door)) newstate.sort() return newstate print( "ERROR: unrecognised action: " + action ) return ['error'] def possible_pickup_actions(state): loc = get_robot_location(state) items = get_location_items(loc, state) items.remove('robot') return [('pickup', item) for item in items] def possible_move_actions(state): robloc = get_robot_location(state) destinations = [] for fact in permanent_facts: ##print fact if (fact[0] == 'connected'): r1 = fact[1] r2 = fact[2] door = fact[3] if holds(('unlocked', door), state): if r1 == robloc: destinations = destinations + [r2] if r2 == robloc: destinations = destinations + [r1] return [('move', dest) for dest in destinations] def possible_drop_actions(state): items = [] for fact in state: if fact[0]=='carrying': items = items + [fact[1]] return [('drop',i) for i in items] def possible_unlock_actions(state): if not(holds( ('carrying', 'key'), state)): return [] robloc = get_robot_location(state) doors = [] for fact in permanent_facts: if (fact[0] == 'connected'): r1 = fact[1] r2 = fact[2] door = fact[3] if holds(('locked', door), state): if (r1 == robloc) | (r2 == robloc): doors = doors + [door] return [('unlock', d) for d in doors] def get_robot_location(state): for fact in state: if ((fact[0] == 'located') & (fact[1] == 'robot')): return fact[2] def get_location_items( loc, state ): items = [] for fact in state: if (fact[0] == 'located'): if (fact[2] == loc): items = items + [ fact[1] ] return items def goal_string(): global ROBOT_GOAL ##return " ".join(ROBOT_GOAL) return str(ROBOT_GOAL) def robot_print_problem_info(): print( "Problem: Robot in the Kitchen" ) print( "Goal: " + goal_string() ) def set_robot_goal( goal ): global ROBOT_GOAL ROBOT_GOAL = goal return robot_goal_state def robot_goal_state( state ): global ROBOT_GOAL return holds( ROBOT_GOAL, state ) def holds(fact,state): if fact[0] == 'and': return conjunction_holds( fact, state ) if fact in permanent_facts: return True if fact in state: return True return False def conjunction_holds( conjunction, state ): for i in range(1, len(conjunction)): if not( holds(conjunction[i],state) ): return False return True robot_search_problem_1 = ( robot_initialise_1, robot_print_problem_info, robot_initial_state_1, robot_possible_actions, robot_successor_state, robot_goal_state, )
print('Loading robot_servant.py') robot_goal = 'undefined' def robot_initialise_1(): global permanent_facts, initial_state, ROBOT_GOAL permanent_facts = robot_permanent_facts_1 initial_state = robot_initial_state_1 robot_goal = robot_goal_1 robot_permanent_facts_1 = [('connected', 'kitchen', 'garage', 'door_kg'), ('connected', 'kitchen', 'larder', 'door_kl')] robot_initial_state_1 = [('locked', 'door_kl'), ('unlocked', 'door_kg'), ('located', 'robot', 'kitchen'), ('located', 'key', 'garage'), ('located', 'spade', 'garage'), ('located', 'ring', 'larder'), ('located', 'sausages', 'larder')] robot_goal_1 = ('and', ('carrying', 'ring'), ('located', 'sausages', 'kitchen')) robot_goal_easy = ('carrying', 'ring') def robot_possible_actions(state): pickup_actions = possible_pickup_actions(state) move_actions = possible_move_actions(state) drop_actions = possible_drop_actions(state) unlock_actions = possible_unlock_actions(state) return pickup_actions + move_actions + drop_actions + unlock_actions def robot_successor_state(action, state): newstate = list(state) robloc = get_robot_location(state) if action[0] == 'pickup': item = action[1] newstate.remove(('located', item, robloc)) newstate.append(('carrying', item)) newstate.sort() return newstate if action[0] == 'drop': item = action[1] newstate.remove(('carrying', item)) newstate.append(('located', item, robloc)) newstate.sort() return newstate if action[0] == 'move': dest = action[1] newstate.remove(('located', 'robot', robloc)) newstate.append(('located', 'robot', dest)) newstate.sort() return newstate if action[0] == 'unlock': door = action[1] newstate.remove(('locked', door)) newstate.append(('unlocked', door)) newstate.sort() return newstate print('ERROR: unrecognised action: ' + action) return ['error'] def possible_pickup_actions(state): loc = get_robot_location(state) items = get_location_items(loc, state) items.remove('robot') return [('pickup', item) for item in items] def possible_move_actions(state): robloc = get_robot_location(state) destinations = [] for fact in permanent_facts: if fact[0] == 'connected': r1 = fact[1] r2 = fact[2] door = fact[3] if holds(('unlocked', door), state): if r1 == robloc: destinations = destinations + [r2] if r2 == robloc: destinations = destinations + [r1] return [('move', dest) for dest in destinations] def possible_drop_actions(state): items = [] for fact in state: if fact[0] == 'carrying': items = items + [fact[1]] return [('drop', i) for i in items] def possible_unlock_actions(state): if not holds(('carrying', 'key'), state): return [] robloc = get_robot_location(state) doors = [] for fact in permanent_facts: if fact[0] == 'connected': r1 = fact[1] r2 = fact[2] door = fact[3] if holds(('locked', door), state): if (r1 == robloc) | (r2 == robloc): doors = doors + [door] return [('unlock', d) for d in doors] def get_robot_location(state): for fact in state: if (fact[0] == 'located') & (fact[1] == 'robot'): return fact[2] def get_location_items(loc, state): items = [] for fact in state: if fact[0] == 'located': if fact[2] == loc: items = items + [fact[1]] return items def goal_string(): global ROBOT_GOAL return str(ROBOT_GOAL) def robot_print_problem_info(): print('Problem: Robot in the Kitchen') print('Goal: ' + goal_string()) def set_robot_goal(goal): global ROBOT_GOAL robot_goal = goal return robot_goal_state def robot_goal_state(state): global ROBOT_GOAL return holds(ROBOT_GOAL, state) def holds(fact, state): if fact[0] == 'and': return conjunction_holds(fact, state) if fact in permanent_facts: return True if fact in state: return True return False def conjunction_holds(conjunction, state): for i in range(1, len(conjunction)): if not holds(conjunction[i], state): return False return True robot_search_problem_1 = (robot_initialise_1, robot_print_problem_info, robot_initial_state_1, robot_possible_actions, robot_successor_state, robot_goal_state)
# [Root Abyss] The World Girl MYSTERIOUS_GIRL = 1064001 # npc Id sm.removeEscapeButton() sm.lockInGameUI(True) sm.setPlayerAsSpeaker() sm.sendNext("If you're really the World Tree, can't you just like... magic yourself outta here?") sm.setSpeakerID(MYSTERIOUS_GIRL) sm.sendNext("No! Those bad people did this to me!") sm.setPlayerAsSpeaker() sm.sendNext("Oh, here we go...") sm.setSpeakerID(MYSTERIOUS_GIRL) sm.sendNext("Before I laid down to rest, I set up a barrier to keep me safe here, but some creeps broke in. " "One of them even tried to kidnap me!") sm.setPlayerAsSpeaker() sm.sendNext("Were they the Black Mage's minions?") sm.setSpeakerID(MYSTERIOUS_GIRL) sm.sendNext("I don't know, they were all wearing hoods. One of them was this nasty little demon-faced guy with an eye patch. " "I think he was their boss.") sm.showFieldBackgroundEffect("Effect/Direction11.img/effect/meet/frame0/0") sm.showFieldEffect("Map/Effect.img/rootabyss/demian") sm.invokeAfterDelay(1000, "showFadeTransition", 1500, 0, 1000) sm.setPlayerAsSpeaker() sm.invokeAfterDelay(4500, "sendNext", "A demon with an eyepatch tried to kidnap you? Do you realise how crazy that sounds?") sm.setSpeakerID(MYSTERIOUS_GIRL) sm.sendNext("It's true! He was dragging me out of here until he found out I wasn't fully recovered. Then he sealed me up in here.") sm.setPlayerAsSpeaker() sm.sendNext("Is that why you couldn't get through the gateway?") sm.setSpeakerID(MYSTERIOUS_GIRL) sm.sendNext("I think so. I'm pretty sure he was the one who corrupted Root Abyss too. " "I just can't use my powers with all of this dark energy around.") sm.sendNext("I'm worried that the darkness will swallow me whole at this rate. Will you help me?") sm.lockInGameUI(False) sm.completeQuest(parentID)
mysterious_girl = 1064001 sm.removeEscapeButton() sm.lockInGameUI(True) sm.setPlayerAsSpeaker() sm.sendNext("If you're really the World Tree, can't you just like... magic yourself outta here?") sm.setSpeakerID(MYSTERIOUS_GIRL) sm.sendNext('No! Those bad people did this to me!') sm.setPlayerAsSpeaker() sm.sendNext('Oh, here we go...') sm.setSpeakerID(MYSTERIOUS_GIRL) sm.sendNext('Before I laid down to rest, I set up a barrier to keep me safe here, but some creeps broke in. One of them even tried to kidnap me!') sm.setPlayerAsSpeaker() sm.sendNext("Were they the Black Mage's minions?") sm.setSpeakerID(MYSTERIOUS_GIRL) sm.sendNext("I don't know, they were all wearing hoods. One of them was this nasty little demon-faced guy with an eye patch. I think he was their boss.") sm.showFieldBackgroundEffect('Effect/Direction11.img/effect/meet/frame0/0') sm.showFieldEffect('Map/Effect.img/rootabyss/demian') sm.invokeAfterDelay(1000, 'showFadeTransition', 1500, 0, 1000) sm.setPlayerAsSpeaker() sm.invokeAfterDelay(4500, 'sendNext', 'A demon with an eyepatch tried to kidnap you? Do you realise how crazy that sounds?') sm.setSpeakerID(MYSTERIOUS_GIRL) sm.sendNext("It's true! He was dragging me out of here until he found out I wasn't fully recovered. Then he sealed me up in here.") sm.setPlayerAsSpeaker() sm.sendNext("Is that why you couldn't get through the gateway?") sm.setSpeakerID(MYSTERIOUS_GIRL) sm.sendNext("I think so. I'm pretty sure he was the one who corrupted Root Abyss too. I just can't use my powers with all of this dark energy around.") sm.sendNext("I'm worried that the darkness will swallow me whole at this rate. Will you help me?") sm.lockInGameUI(False) sm.completeQuest(parentID)
#!usr/bin/python # -*- coding:utf8 -*- class MyException(Exception): pass try: raise MyException('my exception') # exception MyException as e: except Exception as e: print(e)
class Myexception(Exception): pass try: raise my_exception('my exception') except Exception as e: print(e)