content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
def asarray(a, dtype=None, order=None): """Convert the input to an array. Parameters ---------- a : array_like Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. dtype : data-type, optional By default, the data-type is inferred from the input data. order : {'C', 'F'}, optional Whether to use row-major (C-style) or column-major (Fortran-style) memory representation. Defaults to 'C'. Returns ------- out : ndarray Array interpretation of `a`. No copy is performed if the input is already an ndarray with matching dtype and order. If `a` is a subclass of ndarray, a base class ndarray is returned. """ return array(a, dtype, copy=False, order=order) asarray(10)
def asarray(a, dtype=None, order=None): """Convert the input to an array. Parameters ---------- a : array_like Input data, in any form that can be converted to an array. This includes lists, lists of tuples, tuples, tuples of tuples, tuples of lists and ndarrays. dtype : data-type, optional By default, the data-type is inferred from the input data. order : {'C', 'F'}, optional Whether to use row-major (C-style) or column-major (Fortran-style) memory representation. Defaults to 'C'. Returns ------- out : ndarray Array interpretation of `a`. No copy is performed if the input is already an ndarray with matching dtype and order. If `a` is a subclass of ndarray, a base class ndarray is returned. """ return array(a, dtype, copy=False, order=order) asarray(10)
[b'z' if foldnuls and not word else b'y' if foldspaces and word == 0x20202020 else (chars2[word // 614125] + chars2[word // 85 % 7225] + chars[word % 85]) ]
[b'z' if foldnuls and (not word) else b'y' if foldspaces and word == 538976288 else chars2[word // 614125] + chars2[word // 85 % 7225] + chars[word % 85]]
inputs = {"sentence": "a very well-made, funny and entertaining picture."} archive = ( "https://storage.googleapis.com/allennlp-public-models/" "basic_stanford_sentiment_treebank-2020.06.09.tar.gz" ) predictor = Predictor.from_path(archive) interpreter = SimpleGradient(predictor) interpretation = interpreter.saliency_interpret_from_json(inputs) print(interpretation)
inputs = {'sentence': 'a very well-made, funny and entertaining picture.'} archive = 'https://storage.googleapis.com/allennlp-public-models/basic_stanford_sentiment_treebank-2020.06.09.tar.gz' predictor = Predictor.from_path(archive) interpreter = simple_gradient(predictor) interpretation = interpreter.saliency_interpret_from_json(inputs) print(interpretation)
# -*- coding: utf-8 -*- """ Created on Fri Dec 6 15:17:07 2019 @author: bdobson """ """Constants """ M3_S_TO_ML_D = 86.4 MM_KM2_TO_ML = 1e-3 * 1e6 * 1e3 * 1e-6 PCT_TO_PROP = 1e-2 PROP_TO_PCT = 100 L_TO_ML = 1e-6 FLOAT_ACCURACY = 1e-10
""" Created on Fri Dec 6 15:17:07 2019 @author: bdobson """ 'Constants\n' m3_s_to_ml_d = 86.4 mm_km2_to_ml = 0.001 * 1000000.0 * 1000.0 * 1e-06 pct_to_prop = 0.01 prop_to_pct = 100 l_to_ml = 1e-06 float_accuracy = 1e-10
# File: adldap_view.py # # Copyright (c) 2021-2022 Splunk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under # the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific language governing permissions # and limitations under the License. def get_ctx_result(result): ctx_result = {} param = result.get_param() summary = result.get_summary() data = result.get_data() ctx_result['param'] = param if (data): ctx_result['data'] = data[0] if (summary): ctx_result['summary'] = summary return ctx_result def display_attributes(provides, all_app_runs, context): context['results'] = results = [] context['attributes'] = [] print("DEBUG all_app_runs = {}".format(all_app_runs)) for summary, action_results in all_app_runs: for result in action_results: ctx_result = get_ctx_result(result) if (not ctx_result): continue results.append(ctx_result) print("DEBUG ctx_result = {}".format(ctx_result)) # populate keys into 'attributes' variable for django template try: for n in list(ctx_result['data']['entries'][0]['attributes'].keys()): if n not in context['attributes']: context['attributes'].append(n) except Exception as e: context['attributes'] = False context['error'] = str(e) return 'display_attributes.html'
def get_ctx_result(result): ctx_result = {} param = result.get_param() summary = result.get_summary() data = result.get_data() ctx_result['param'] = param if data: ctx_result['data'] = data[0] if summary: ctx_result['summary'] = summary return ctx_result def display_attributes(provides, all_app_runs, context): context['results'] = results = [] context['attributes'] = [] print('DEBUG all_app_runs = {}'.format(all_app_runs)) for (summary, action_results) in all_app_runs: for result in action_results: ctx_result = get_ctx_result(result) if not ctx_result: continue results.append(ctx_result) print('DEBUG ctx_result = {}'.format(ctx_result)) try: for n in list(ctx_result['data']['entries'][0]['attributes'].keys()): if n not in context['attributes']: context['attributes'].append(n) except Exception as e: context['attributes'] = False context['error'] = str(e) return 'display_attributes.html'
while True: try: p = input() d = 0 for i in range(len(p)): if(p[i]=='('): d += 1 elif(p[i]==')'): d -= 1 if(d < 0): break if(d != 0): print('incorrect') else: print('correct') except EOFError: break
while True: try: p = input() d = 0 for i in range(len(p)): if p[i] == '(': d += 1 elif p[i] == ')': d -= 1 if d < 0: break if d != 0: print('incorrect') else: print('correct') except EOFError: break
f = open('69_sample.txt') # read 1st line data = f.readline() print (data) # read second line data = f.readline() print (data) f.close()
f = open('69_sample.txt') data = f.readline() print(data) data = f.readline() print(data) f.close()
class Node(object): def __init__(self, val, children): self.val = val self.children = children class Solution(object): def trace(self, node, nodelist): if node is None: return for n in node.children: self.trace(n, nodelist) nodelist.append(node.val) def postorder(self, root): """ :type root: Node :rtype: List[int] """ nodelist = [] self.trace(root, nodelist) return nodelist if __name__ == '__main__': solution = Solution() root = Node(1, []) root.children.append(Node(3, [])) root.children.append(Node(2, [])) root.children.append(Node(4, [])) print(solution.postorder(root)) else: pass
class Node(object): def __init__(self, val, children): self.val = val self.children = children class Solution(object): def trace(self, node, nodelist): if node is None: return for n in node.children: self.trace(n, nodelist) nodelist.append(node.val) def postorder(self, root): """ :type root: Node :rtype: List[int] """ nodelist = [] self.trace(root, nodelist) return nodelist if __name__ == '__main__': solution = solution() root = node(1, []) root.children.append(node(3, [])) root.children.append(node(2, [])) root.children.append(node(4, [])) print(solution.postorder(root)) else: pass
bot = {'owner': '', 'client_id': '', 'version': '', 'prefix': '|', 'pstart': 'python3 ./main.py', 'game': '', 'token': '', 'invite_url': '', 'update_name': '', 'release_details': './data/misc/releaseplaceholder.txt', 'checkin_details': './data/misc/checkin.txt', 'checkin_channel': '', 'update_details': './data/misc/update.txt', 'startup_time': '', 'pstart_time': '', 'imgur_client_id': '', 'imgur_client_secret': ''}
bot = {'owner': '', 'client_id': '', 'version': '', 'prefix': '|', 'pstart': 'python3 ./main.py', 'game': '', 'token': '', 'invite_url': '', 'update_name': '', 'release_details': './data/misc/releaseplaceholder.txt', 'checkin_details': './data/misc/checkin.txt', 'checkin_channel': '', 'update_details': './data/misc/update.txt', 'startup_time': '', 'pstart_time': '', 'imgur_client_id': '', 'imgur_client_secret': ''}
""" Module to contain the configuration information loaded from the config file. DO NOT MODIFY THIS FILE! Use yaml files in configurations directory to change the settings. """ # Optional settings (set defaults) show_labels = False show_sensory = False show_individual = False display_legend = True combination_strategy = "avg" confidence_threshold = 0 light_multiplier = 1 wind_multiplier = 1 polarisation_multiplier = 1 # Defined flags, makes tracking cue definitions easier polarisation_defined = False # Cue configuration lists cues_roll_one = [] cues_roll_two = [] def print_configuration(): print("=== Optional configuration ===\n" "show-labels: " + str(show_labels) + "\n" "show-geometry: " + str(show_sensory) + "\n" "show-individual: " + str(show_individual) + "\n" "display-legend: " + str(display_legend) + "\n" "combination-strategy: " + combination_strategy + "\n" "confidence-threshold: " + str(confidence_threshold) + "\n" "light-multiplier: " + str(light_multiplier) + "\n" "wind-multiplier: " + str(wind_multiplier) + "\n" "polarisation-multiplier: " + str(polarisation_multiplier) + "\n" "===============================\n")
""" Module to contain the configuration information loaded from the config file. DO NOT MODIFY THIS FILE! Use yaml files in configurations directory to change the settings. """ show_labels = False show_sensory = False show_individual = False display_legend = True combination_strategy = 'avg' confidence_threshold = 0 light_multiplier = 1 wind_multiplier = 1 polarisation_multiplier = 1 polarisation_defined = False cues_roll_one = [] cues_roll_two = [] def print_configuration(): print('=== Optional configuration ===\nshow-labels: ' + str(show_labels) + '\nshow-geometry: ' + str(show_sensory) + '\nshow-individual: ' + str(show_individual) + '\ndisplay-legend: ' + str(display_legend) + '\ncombination-strategy: ' + combination_strategy + '\nconfidence-threshold: ' + str(confidence_threshold) + '\nlight-multiplier: ' + str(light_multiplier) + '\nwind-multiplier: ' + str(wind_multiplier) + '\npolarisation-multiplier: ' + str(polarisation_multiplier) + '\n===============================\n')
""" This module provide solution for first task. """ def change_sub_strings(text, pattern, new_string): """ Function for changing all entrance of pattern to new_string. :param text: str String for changing. :param pattern: str String which should be removed. Any suffix of this string shouldn't be equal to prefix of same length. :param new_string: str String which should be added. :return: String with changed pattern to new_string. """ if not isinstance(text, str) or not isinstance(pattern, str) or \ not isinstance(new_string, str): assert TypeError for i in range(1, len(pattern)): if pattern[:i] == pattern[-i:]: raise ValueError return new_string.join(text.split(pattern)) def change_sentences(lines): """ Function for set all letters to lower case, changing all 'snake' to 'python' and filtering all sentence where no 'python' or 'anaconda' :param lines: list with str List of sentences for processing. :return: List of sentences with 'python' and 'anaconda'. """ if not isinstance(lines, list): raise TypeError result = [] for line in lines: if not isinstance(line, str): raise TypeError line = change_sub_strings(line.lower(), 'snake', 'python') if 'python' in line and 'anaconda' in line: result.append(line) return result def solution1(input_file_name, output_file_name): """ Function for solving first task. :param input_file_name: str Name of file for processing. :param output_file_name: str Name of file for writing result. :return: Text with changed substrings. """ if not isinstance(input_file_name, str) or \ not isinstance(output_file_name, str): raise TypeError try: with open(input_file_name, 'r') as f_in: with open(output_file_name, 'w') as f_out: f_out.writelines(change_sentences(f_in.readlines())) except FileNotFoundError: print("can't open file in first solution")
""" This module provide solution for first task. """ def change_sub_strings(text, pattern, new_string): """ Function for changing all entrance of pattern to new_string. :param text: str String for changing. :param pattern: str String which should be removed. Any suffix of this string shouldn't be equal to prefix of same length. :param new_string: str String which should be added. :return: String with changed pattern to new_string. """ if not isinstance(text, str) or not isinstance(pattern, str) or (not isinstance(new_string, str)): assert TypeError for i in range(1, len(pattern)): if pattern[:i] == pattern[-i:]: raise ValueError return new_string.join(text.split(pattern)) def change_sentences(lines): """ Function for set all letters to lower case, changing all 'snake' to 'python' and filtering all sentence where no 'python' or 'anaconda' :param lines: list with str List of sentences for processing. :return: List of sentences with 'python' and 'anaconda'. """ if not isinstance(lines, list): raise TypeError result = [] for line in lines: if not isinstance(line, str): raise TypeError line = change_sub_strings(line.lower(), 'snake', 'python') if 'python' in line and 'anaconda' in line: result.append(line) return result def solution1(input_file_name, output_file_name): """ Function for solving first task. :param input_file_name: str Name of file for processing. :param output_file_name: str Name of file for writing result. :return: Text with changed substrings. """ if not isinstance(input_file_name, str) or not isinstance(output_file_name, str): raise TypeError try: with open(input_file_name, 'r') as f_in: with open(output_file_name, 'w') as f_out: f_out.writelines(change_sentences(f_in.readlines())) except FileNotFoundError: print("can't open file in first solution")
ENTRY_POINT = 'fizz_buzz' FIX = """ Update doc string to remove requirement for print. """ #[PROMPT] def fizz_buzz(n: int): """Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13. >>> fizz_buzz(50) 0 >>> fizz_buzz(78) 2 >>> fizz_buzz(79) 3 """ #[SOLUTION] ns = [] for i in range(n): if i % 11 == 0 or i % 13 == 0: ns.append(i) s = ''.join(list(map(str, ns))) ans = 0 for c in s: ans += (c == '7') return ans #[CHECK] METADATA = {} def check(candidate): assert candidate(50) == 0 assert candidate(78) == 2 assert candidate(79) == 3 assert candidate(100) == 3 assert candidate(200) == 6 assert candidate(4000) == 192 assert candidate(10000) == 639 assert candidate(100000) == 8026
entry_point = 'fizz_buzz' fix = '\nUpdate doc string to remove requirement for print.\n' def fizz_buzz(n: int): """Return the number of times the digit 7 appears in integers less than n which are divisible by 11 or 13. >>> fizz_buzz(50) 0 >>> fizz_buzz(78) 2 >>> fizz_buzz(79) 3 """ ns = [] for i in range(n): if i % 11 == 0 or i % 13 == 0: ns.append(i) s = ''.join(list(map(str, ns))) ans = 0 for c in s: ans += c == '7' return ans metadata = {} def check(candidate): assert candidate(50) == 0 assert candidate(78) == 2 assert candidate(79) == 3 assert candidate(100) == 3 assert candidate(200) == 6 assert candidate(4000) == 192 assert candidate(10000) == 639 assert candidate(100000) == 8026
def type2diabetes(filepath): """ 1. Takes a text file as the only parameter and returns means and std of the phenotype typeII diabetes 2. Search for data labels on the text file and read text file to csv file starting from the rows of labels present 3. Replace missing data '--' with NaN and drop missing data 4. Looking for all 17 snps (we have in our data bank) in the uploaded file 5. Recreate a list of 8 pairs of snp information: rsid and corresponding genotype 6. Obtain effect values for each snp and sum up to get a polygenic risk score 7. Based on the polygenic risk score, return a mean and std of the bmi phenotype """ fopen = open(filepath,mode='r+') fread = fopen.readlines() x = '# rsid chromosome position genotype' n = 0 for line in fread: n += 1 if x in line: break df = pd.read_csv (filepath,'\s+', skiprows=n, names=['rsid','chromosome','position','genotype']) #df = df.replace('--', pd.NaT) # need to correct this on the data extract file #df = df.dropna testfile = df[(df['rsid'] == 'rs560887') | (df['rsid'] =='rs10830963') | (df['rsid'] == 'rs14607517')| (df['rsid'] == 'rs2191349') | (df['rsid'] == 'rs780094') | (df['rsid'] == 'rs11708067') | (df['rsid'] == 'rs7944584') | (df['rsid'] == 'rs10885122') | (df['rsid'] == 'rs174550') | (df['rsid'] == 'rs11605924') | (df['rsid'] == 'rs11920090') | (df['rsid'] == 'rs7034200') | (df['rsid'] == 'rs340874') | (df['rsid'] == 'rs11071657') | (df['rsid'] == 'rs13266634') | (df['rsid'] == 'rs7903146') | (df['rsid'] == 'rs35767')] testlist = [] for i in range(0, len(testfile.index)-1): rsid = testfile.iloc[i,0] genotype = testfile.iloc[i,3] i = (rsid, genotype) # tuples of one rsid with genotype testlist.append(i) # a list of tuples gendata = pd.read_csv('Genetic Data.csv') gendata['effect'] = pd.to_numeric(gendata['effect']) total = 0 for i in testlist: snp = gendata[(gendata['rsid'] == i[0]) & (gendata['genotype'] == i[1])] effect = snp.iloc[i,4] total += effect if total < 13: return (92.5, 8.7) elif total == 13: return (93.6, 8.8) elif total == 14: return (94.2, 8.6) elif total == 15: return (94.3, 8.8) elif total == 16: return (95.2, 8.9) elif total == 17: return (95.4, 8.7) elif total == 18: return (95.9, 8.9) elif total == 19: return (96.5, 8.7) elif total == 20: return (97.3, 8.8) elif total == 21: return (98.1, 8.6) elif total == 22: return (98.6, 8.7) else: return (98.6, 8.6)
def type2diabetes(filepath): """ 1. Takes a text file as the only parameter and returns means and std of the phenotype typeII diabetes 2. Search for data labels on the text file and read text file to csv file starting from the rows of labels present 3. Replace missing data '--' with NaN and drop missing data 4. Looking for all 17 snps (we have in our data bank) in the uploaded file 5. Recreate a list of 8 pairs of snp information: rsid and corresponding genotype 6. Obtain effect values for each snp and sum up to get a polygenic risk score 7. Based on the polygenic risk score, return a mean and std of the bmi phenotype """ fopen = open(filepath, mode='r+') fread = fopen.readlines() x = '# rsid\tchromosome\tposition\tgenotype' n = 0 for line in fread: n += 1 if x in line: break df = pd.read_csv(filepath, '\\s+', skiprows=n, names=['rsid', 'chromosome', 'position', 'genotype']) testfile = df[(df['rsid'] == 'rs560887') | (df['rsid'] == 'rs10830963') | (df['rsid'] == 'rs14607517') | (df['rsid'] == 'rs2191349') | (df['rsid'] == 'rs780094') | (df['rsid'] == 'rs11708067') | (df['rsid'] == 'rs7944584') | (df['rsid'] == 'rs10885122') | (df['rsid'] == 'rs174550') | (df['rsid'] == 'rs11605924') | (df['rsid'] == 'rs11920090') | (df['rsid'] == 'rs7034200') | (df['rsid'] == 'rs340874') | (df['rsid'] == 'rs11071657') | (df['rsid'] == 'rs13266634') | (df['rsid'] == 'rs7903146') | (df['rsid'] == 'rs35767')] testlist = [] for i in range(0, len(testfile.index) - 1): rsid = testfile.iloc[i, 0] genotype = testfile.iloc[i, 3] i = (rsid, genotype) testlist.append(i) gendata = pd.read_csv('Genetic Data.csv') gendata['effect'] = pd.to_numeric(gendata['effect']) total = 0 for i in testlist: snp = gendata[(gendata['rsid'] == i[0]) & (gendata['genotype'] == i[1])] effect = snp.iloc[i, 4] total += effect if total < 13: return (92.5, 8.7) elif total == 13: return (93.6, 8.8) elif total == 14: return (94.2, 8.6) elif total == 15: return (94.3, 8.8) elif total == 16: return (95.2, 8.9) elif total == 17: return (95.4, 8.7) elif total == 18: return (95.9, 8.9) elif total == 19: return (96.5, 8.7) elif total == 20: return (97.3, 8.8) elif total == 21: return (98.1, 8.6) elif total == 22: return (98.6, 8.7) else: return (98.6, 8.6)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- """ Created on Sun Jul 12 10:49:34 2020 @author: ravi """ def recordBreaker(arr): peak = 0 cmax = float("-inf") if len(arr)==0: return 0 if len(arr)==1: return 1 for i in range(len(arr)): if i==0: if arr[i]>arr[i+1]: if arr[i]>cmax: cmax=arr[i] peak+=1 if i>0 and i<len(arr)-1: if arr[i]>arr[i-1] and arr[i]>arr[i+1]: if arr[i]>cmax: cmax = arr[i] peak+=1 if i==len(arr)-1: if arr[i]>arr[i-1]: if arr[i]>cmax: cmax = arr[i] peak+=1 return peak t = int(input()) for i in range(t): n = int(input()) arr = list(map(int,input().split())) ans = recordBreaker(arr) print("Case #"+str(i+1)+":",str(ans))
""" Created on Sun Jul 12 10:49:34 2020 @author: ravi """ def record_breaker(arr): peak = 0 cmax = float('-inf') if len(arr) == 0: return 0 if len(arr) == 1: return 1 for i in range(len(arr)): if i == 0: if arr[i] > arr[i + 1]: if arr[i] > cmax: cmax = arr[i] peak += 1 if i > 0 and i < len(arr) - 1: if arr[i] > arr[i - 1] and arr[i] > arr[i + 1]: if arr[i] > cmax: cmax = arr[i] peak += 1 if i == len(arr) - 1: if arr[i] > arr[i - 1]: if arr[i] > cmax: cmax = arr[i] peak += 1 return peak t = int(input()) for i in range(t): n = int(input()) arr = list(map(int, input().split())) ans = record_breaker(arr) print('Case #' + str(i + 1) + ':', str(ans))
N = int(input()) for i in range(N): line = input() print("I am Toorg!")
n = int(input()) for i in range(N): line = input() print('I am Toorg!')
def divide(n1, n2):#dessa forma levantamos o erro sem parar o cod if n2 == 0:#se n2 for igual a zero raise ValueError("n2 nao pode ser 0 ") return n1 / n2 try: print(divide(n1=2,n2=1)) except ValueError as error: print('Voce esta tentando dividir por zero') print('log:', error)
def divide(n1, n2): if n2 == 0: raise value_error('n2 nao pode ser 0 ') return n1 / n2 try: print(divide(n1=2, n2=1)) except ValueError as error: print('Voce esta tentando dividir por zero') print('log:', error)
# 566. Reshape the Matrix # Runtime: 109 ms, faster than 30.83% of Python3 online submissions for Reshape the Matrix. # Memory Usage: 14.7 MB, less than 87.88% of Python3 online submissions for Reshape the Matrix. class Solution: # Using Queue def matrixReshape(self, mat: list[list[int]], r: int, c: int) -> list[list[int]]: if len(mat) == 0 or r * c != len(mat) * len(mat[0]): return mat nums = [] for i in range(len(mat)): for j in range(len(mat[0])): nums.append(mat[i][j]) res = [[0 for _ in range(c)] for _ in range(r)] for i in range(r): for j in range(c): res[i][j] = nums.pop(0) return res
class Solution: def matrix_reshape(self, mat: list[list[int]], r: int, c: int) -> list[list[int]]: if len(mat) == 0 or r * c != len(mat) * len(mat[0]): return mat nums = [] for i in range(len(mat)): for j in range(len(mat[0])): nums.append(mat[i][j]) res = [[0 for _ in range(c)] for _ in range(r)] for i in range(r): for j in range(c): res[i][j] = nums.pop(0) return res
def n_primos (x): numero =2 quantidadeDePrimos=0 while numero<=x: divisor = 2 divisores=0 while divisor<numero: if numero%divisor==0: divisores+=1 divisor+=1 if divisores==0: quantidadeDePrimos+=1 numero+=1 return quantidadeDePrimos
def n_primos(x): numero = 2 quantidade_de_primos = 0 while numero <= x: divisor = 2 divisores = 0 while divisor < numero: if numero % divisor == 0: divisores += 1 divisor += 1 if divisores == 0: quantidade_de_primos += 1 numero += 1 return quantidadeDePrimos
#Now let's make things a little more challenging. # #Last exercise, you wrote a function called word_count that #counted the number of words in a string essentially by #counting the spaces. However, if there were multiple spaces #in a row, it would incorrectly add additional words. For #example, it would have counted the string "Hi David" as #4 words instead of 2 because there are two additional #spaces. # #Revise your word_count method so that if it encounters #multiple consecutive spaces, it does *not* count an #additional word. For example, these three strings should #all be counted as having two words: # # "Hi David" # "Hi David" # "Hi David" # #Other than ignoring consecutive spaces, the directions are #the same: write a function called word_count that returns an #integer representing the number of words in the string, or #return "Not a string" if the input isn't a string. You may #assume that if the input is a string, it starts with a #letter word instead of a space. #Write your function here! def word_count(my_string): word_count = 1 try: string_len = len(my_string) i = 0 while string_len > 0: try: if my_string[i] == " " and not my_string[i+1] == " ": word_count += 1 i += 1 string_len -= 1 except IndexError: pass return word_count except TypeError: return "Not a string" #Below are some lines of code that will test your function. #You can change the value of the variable(s) to test your #function with different inputs. # #If your function works correctly, this will originally #print: #Word Count: 4 #Word Count: 2 #Word Count: Not a string #Word Count: Not a string #Word Count: Not a string print("Word Count:", word_count("Four words are here!")) print("Word Count:", word_count("Hi David")) print("Word Count:", word_count(5)) print("Word Count:", word_count(5.1)) print("Word Count:", word_count(True))
def word_count(my_string): word_count = 1 try: string_len = len(my_string) i = 0 while string_len > 0: try: if my_string[i] == ' ' and (not my_string[i + 1] == ' '): word_count += 1 i += 1 string_len -= 1 except IndexError: pass return word_count except TypeError: return 'Not a string' print('Word Count:', word_count('Four words are here!')) print('Word Count:', word_count('Hi David')) print('Word Count:', word_count(5)) print('Word Count:', word_count(5.1)) print('Word Count:', word_count(True))
def sortByHeight(a): trees = [] peoples = [] for i in range(len(a)): if (a[i] != -1): peoples.append(a[i]) else: trees.append(i) peoples = sorted(peoples) for i in range(len(trees)): peoples.insert(trees[i], -1) return peoples
def sort_by_height(a): trees = [] peoples = [] for i in range(len(a)): if a[i] != -1: peoples.append(a[i]) else: trees.append(i) peoples = sorted(peoples) for i in range(len(trees)): peoples.insert(trees[i], -1) return peoples
class Helper(object): defaultText = """Eddie knowledge - what your opponents don't want you to know.\n\nCommands: .help .changes .fd <CHAR> [<MOVENAME>] .fds <CHAR> [<MOVENAME>] .atklevel <LEVEL> .alias <ALIAS> .addalias <ALIAS> | <VALUE> .removealias <ALIAS> .charnames\n If you want to know more about a command, you can invoke its specific help by calling .help [command]. Example: .help fd\n For feature requests or bug reports etc., hit me up on Discord (prk`#1874).""" helpText = """Displays information about public commands of Eddie.""" changesText = """Sends a link to changelog.""" fdText = """Displays framedata of a specific move. Character names are: Axl Bedman Chipp Elphelt Faust I-No Ky May Millia Potemkin Ramlethal Sin Slayer Sol Sol-DI Venom Zato Leo Jack-O Jam Johnny Raven Kum Dizzy Answer Baiken Normals or command normals are written in the standard way of numpad directions and P/K/S/H/D for the button used. Special moves are named with their actual names. Some of the names are rather weird. In order to deal with that, the command will first search for a perfect fit. If that has not been found, it will search for moves which can be written in the following form: % MOVENAME % meaning that movename can start with anything and end with anything, as long as MOVENAME is present in the string. In case more moves are found (e.g. Leo has two versions of Graviert Wuerde), all are displayed. In case no MOVENAME is specified, Eddie sends a private message containing all the possible moves that a character has stored in the database. In case 3 or more moves are found which correspond to MOVENAME, all of them are sent in direct message to prevent cluttering of chat.""" fdsText = """Displays framedata of a specific move in a simplified manner. Character names are the same as when using the .fd command. Only displays startup, active frames, recovery frames, adv/ib adv and attack level. Special moves are named with their actual names. Some of the names are rather weird. In order to deal with that, the command will first search for a perfect fit. If that has not been found, it will search for moves which can be written in the following form: % MOVENAME % meaning that movename can start with anything and end with anything, as long as MOVENAME is present in the string. In case more moves are found (e.g. Leo has two versions of Graviert Wuerde), all are displayed. In case no MOVENAME is specified, Eddie sends a private message containing all the possible moves that a character has stored in the database. In case 3 or more moves are found which correspond to MOVENAME, all of them are sent in direct message to prevent cluttering of chat.""" atklevelText = """Displays data of an attack level.""" aliasText = """Displays value of an alias.""" addaliasText = """Adds alias which can be used to search for moves. Example: .addalias nobiru | anti air attack If an alias already exists, it will not be overwritten.""" aliasesText = """Sends a list of existing aliases as a PM.""" removealiasText = """Removes a specified alias from the DB. Currently usable only by admin.""" charnamesText = """Sends a PM with a list of character names in the DB.""" helpTable = dict() helpTable['default'] = defaultText helpTable['help'] = helpText helpTable['changes'] = changesText helpTable['fd'] = fdText helpTable['fds'] = fdsText helpTable['atklevel'] = atklevelText helpTable['alias'] = aliasText helpTable['addalias'] = addaliasText helpTable['aliases'] = aliasesText helpTable['removealias'] = removealiasText helpTable['charnames'] = charnamesText def getHelptext(self, *kw): if len(kw) == 0: return self.helpTable.get('default') return self.helpTable.get(kw[0])
class Helper(object): default_text = "Eddie knowledge - what your opponents don't want you to know.\n\nCommands:\n .help\n .changes\n .fd <CHAR> [<MOVENAME>]\n .fds <CHAR> [<MOVENAME>]\n .atklevel <LEVEL>\n .alias <ALIAS>\n .addalias <ALIAS> | <VALUE>\n .removealias <ALIAS>\n .charnames\n\nIf you want to know more about a command, you can invoke its specific help by calling .help [command].\n Example: .help fd\n\nFor feature requests or bug reports etc., hit me up on Discord (prk`#1874)." help_text = 'Displays information about public commands of Eddie.' changes_text = 'Sends a link to changelog.' fd_text = 'Displays framedata of a specific move. Character names are:\n Axl\n Bedman\n Chipp\n Elphelt\n Faust\n I-No\n Ky\n May\n Millia\n Potemkin\n Ramlethal\n Sin\n Slayer\n Sol\n Sol-DI\n Venom\n Zato\n Leo\n Jack-O\n Jam\n Johnny\n Raven\n Kum\n Dizzy\n Answer\n Baiken\n\nNormals or command normals are written in the standard way of numpad directions and P/K/S/H/D for the button used.\n\nSpecial moves are named with their actual names. Some of the names are rather weird. In order to deal with that, the command will first search for a perfect fit. If that has not been found, it will search for moves which can be written in the following form:\n % MOVENAME %\nmeaning that movename can start with anything and end with anything, as long as MOVENAME is present in the string. In case more moves are found (e.g. Leo has two versions of Graviert Wuerde), all are displayed.\n\nIn case no MOVENAME is specified, Eddie sends a private message containing all the possible moves that a character has stored in the database.\nIn case 3 or more moves are found which correspond to MOVENAME, all of them are sent in direct message to prevent cluttering of chat.' fds_text = 'Displays framedata of a specific move in a simplified manner. Character names are the same as when using the .fd command. Only displays startup, active frames, recovery frames, adv/ib adv and attack level.\n\nSpecial moves are named with their actual names. Some of the names are rather weird. In order to deal with that, the command will first search for a perfect fit. If that has not been found, it will search for moves which can be written in the following form:\n % MOVENAME %\nmeaning that movename can start with anything and end with anything, as long as MOVENAME is present in the string. In case more moves are found (e.g. Leo has two versions of Graviert Wuerde), all are displayed.\n\nIn case no MOVENAME is specified, Eddie sends a private message containing all the possible moves that a character has stored in the database.\nIn case 3 or more moves are found which correspond to MOVENAME, all of them are sent in direct message to prevent cluttering of chat.' atklevel_text = 'Displays data of an attack level.' alias_text = 'Displays value of an alias.' addalias_text = 'Adds alias which can be used to search for moves. Example:\n.addalias nobiru | anti air attack\nIf an alias already exists, it will not be overwritten.' aliases_text = 'Sends a list of existing aliases as a PM.' removealias_text = 'Removes a specified alias from the DB. Currently usable only by admin.' charnames_text = 'Sends a PM with a list of character names in the DB.' help_table = dict() helpTable['default'] = defaultText helpTable['help'] = helpText helpTable['changes'] = changesText helpTable['fd'] = fdText helpTable['fds'] = fdsText helpTable['atklevel'] = atklevelText helpTable['alias'] = aliasText helpTable['addalias'] = addaliasText helpTable['aliases'] = aliasesText helpTable['removealias'] = removealiasText helpTable['charnames'] = charnamesText def get_helptext(self, *kw): if len(kw) == 0: return self.helpTable.get('default') return self.helpTable.get(kw[0])
nome = str(input('qual o seu nome ')) print('Prazer em te conhecer {:-^20}! \n'.format(nome)) n = int(input(' Bem vindo a Tabuada, digite um numero para ver o resultado: ')) multiplicando = 0 cont = 0 while cont <= 10: print(n * multiplicando) multiplicando = multiplicando + 1 cont = cont + 1
nome = str(input('qual o seu nome ')) print('Prazer em te conhecer {:-^20}! \n'.format(nome)) n = int(input(' Bem vindo a Tabuada, digite um numero para ver o resultado: ')) multiplicando = 0 cont = 0 while cont <= 10: print(n * multiplicando) multiplicando = multiplicando + 1 cont = cont + 1
""" @FileName: __init__.py.py @Description: Implement __init__.py @Author: Ryuk @CreateDate: 2021/06/27 @LastEditTime: 2021/06/27 @LastEditors: Please set LastEditors @Version: v0.1 """
""" @FileName: __init__.py.py @Description: Implement __init__.py @Author: Ryuk @CreateDate: 2021/06/27 @LastEditTime: 2021/06/27 @LastEditors: Please set LastEditors @Version: v0.1 """
__all__ = ["RefMixin"] class RefMixin: def __init__(self, loop, ref=True): self.loop = loop self.ref = ref self._ref_increased = False def _increase_ref(self): if self.ref: self._ref_increased = True self.loop.increase_ref() def _decrease_ref(self): if self._ref_increased: self._ref_increased = False self.loop.decrease_ref() def __del__(self): self._decrease_ref()
__all__ = ['RefMixin'] class Refmixin: def __init__(self, loop, ref=True): self.loop = loop self.ref = ref self._ref_increased = False def _increase_ref(self): if self.ref: self._ref_increased = True self.loop.increase_ref() def _decrease_ref(self): if self._ref_increased: self._ref_increased = False self.loop.decrease_ref() def __del__(self): self._decrease_ref()
#!/usr/bin/env python3 max_seat = 0 with open('input.txt') as infile: for line in infile: row = 0 col = 0 for c in line: if c == 'B': row = 2*row + 1 if c == 'F': row *= 2 if c == 'R': col = 2*col + 1 if c == 'L': col *= 2 seat_id = row * 8 + col max_seat = max(max_seat, seat_id) print(max_seat)
max_seat = 0 with open('input.txt') as infile: for line in infile: row = 0 col = 0 for c in line: if c == 'B': row = 2 * row + 1 if c == 'F': row *= 2 if c == 'R': col = 2 * col + 1 if c == 'L': col *= 2 seat_id = row * 8 + col max_seat = max(max_seat, seat_id) print(max_seat)
class Solution: def closedIsland(self, grid: List[List[int]]) -> int: m = len(grid) n = len(grid[0]) vis = [[0]*n for i in range(m)] res = 0 def bfs(i,j): vis[i][j] = 1 q = [(i,j)] valid = 1 while len(q)> 0 : r,c = q.pop(0) if r == 0 or r == m-1 or c == 0 or c == n-1 : valid = 0 dire = [(1,0),(0,-1),(0,1),(-1,0)] for dx,dy in dire: x = r + dx y = c+ dy if 0<=x<m and 0<=y<n and grid[x][y] == 0 and not vis[x][y] : vis[x][y] = 1 q.append((x,y)) return valid for i in range(m): for j in range(n): if not vis[i][j] and grid[i][j] == 0 : if bfs(i,j): res += 1 return res
class Solution: def closed_island(self, grid: List[List[int]]) -> int: m = len(grid) n = len(grid[0]) vis = [[0] * n for i in range(m)] res = 0 def bfs(i, j): vis[i][j] = 1 q = [(i, j)] valid = 1 while len(q) > 0: (r, c) = q.pop(0) if r == 0 or r == m - 1 or c == 0 or (c == n - 1): valid = 0 dire = [(1, 0), (0, -1), (0, 1), (-1, 0)] for (dx, dy) in dire: x = r + dx y = c + dy if 0 <= x < m and 0 <= y < n and (grid[x][y] == 0) and (not vis[x][y]): vis[x][y] = 1 q.append((x, y)) return valid for i in range(m): for j in range(n): if not vis[i][j] and grid[i][j] == 0: if bfs(i, j): res += 1 return res
UK = "curb accessorise accessorised accessorises accessorising acclimatisation acclimatise acclimatised acclimatises acclimatising accoutrements aeon aeons aerogramme aerogrammes aeroplane aeroplanes aesthete aesthetes aesthetic aesthetically aesthetics aetiology ageing aggrandisement agonise agonised agonises agonising agonisingly almanack almanacks aluminium amortisable amortisation amortisations amortise amortised amortises amortising amphitheatre amphitheatres anaemia anaemic anaesthesia anaesthetic anaesthetics anaesthetise anaesthetised anaesthetises anaesthetising anaesthetist anaesthetists anaesthetize anaesthetized anaesthetizes anaesthetizing analogue analogues analyse analysed analyses analysing anglicise anglicised anglicises anglicising annualised antagonise antagonised antagonises antagonising apologise apologised apologises apologising appal appals appetiser appetisers appetising appetisingly arbour arbours archaeological archaeologically archaeologist archaeologists archaeology ardour armour armoured armourer armourers armouries armoury artefact artefacts authorise authorised authorises authorising axe backpedalled backpedalling bannister bannisters baptise baptised baptises baptising bastardise bastardised bastardises bastardising battleaxe baulk baulked baulking baulks bedevilled bedevilling behaviour behavioural behaviourism behaviourist behaviourists behaviours behove behoved behoves bejewelled belabour belaboured belabouring belabours bevelled bevvies bevvy biassed biassing bingeing bougainvillaea bougainvillaeas bowdlerise bowdlerised bowdlerises bowdlerising breathalyse breathalysed breathalyser breathalysers breathalyses breathalysing brutalise brutalised brutalises brutalising buses busing caesarean caesareans calibre calibres calliper callipers callisthenics canalise canalised canalises canalising cancellation cancellations cancelled cancelling candour cannibalise cannibalised cannibalises cannibalising canonise canonised canonises canonising capitalise capitalised capitalises capitalising caramelise caramelised caramelises caramelising carbonise carbonised carbonises carbonising carolled carolling catalogue catalogued catalogues cataloguing catalyse catalysed catalyses catalysing categorise categorised categorises categorising cauterise cauterised cauterises cauterising cavilled cavilling centigramme centigrammes centilitre centilitres centimetre centimetres centralise centralised centralises centralising centre centred centrefold centrefolds centrepiece centrepieces centres channelled channelling characterise characterised characterises characterising cheque chequebook chequebooks chequered cheques chilli chimaera chimaeras chiselled chiselling circularise circularised circularises circularising civilise civilised civilises civilising clamour clamoured clamouring clamours clangour clarinettist clarinettists collectivise collectivised collectivises collectivising colonisation colonise colonised coloniser colonisers colonises colonising colour colourant colourants coloured coloureds colourful colourfully colouring colourize colourized colourizes colourizing colourless colours commercialise commercialised commercialises commercialising compartmentalise compartmentalised compartmentalises compartmentalising computerise computerised computerises computerising conceptualise conceptualised conceptualises conceptualising connexion connexions contextualise contextualised contextualises contextualising cosier cosies cosiest cosily cosiness cosy councillor councillors counselled counselling counsellor counsellors crenellated criminalise criminalised criminalises criminalising criticise criticised criticises criticising crueller cruellest crystallisation crystallise crystallised crystallises crystallising cudgelled cudgelling customise customised customises customising cypher cyphers decentralisation decentralise decentralised decentralises decentralising decriminalisation decriminalise decriminalised decriminalises decriminalising defence defenceless defences dehumanisation dehumanise dehumanised dehumanises dehumanising demeanour demilitarisation demilitarise demilitarised demilitarises demilitarising demobilisation demobilise demobilised demobilises demobilising democratisation democratise democratised democratises democratising demonise demonised demonises demonising demoralisation demoralise demoralised demoralises demoralising denationalisation denationalise denationalised denationalises denationalising deodorise deodorised deodorises deodorising depersonalise depersonalised depersonalises depersonalising deputise deputised deputises deputising desensitisation desensitise desensitised desensitises desensitising destabilisation destabilise destabilised destabilises destabilising dialled dialling dialogue dialogues diarrhoea digitise digitised digitises digitising disc discolour discoloured discolouring discolours discs disembowelled disembowelling disfavour dishevelled dishonour dishonourable dishonourably dishonoured dishonouring dishonours disorganisation disorganised distil distils dramatisation dramatisations dramatise dramatised dramatises dramatising draught draughtboard draughtboards draughtier draughtiest draughts draughtsman draughtsmanship draughtsmen draughtswoman draughtswomen draughty drivelled drivelling duelled duelling economise economised economises economising edoema editorialise editorialised editorialises editorialising empathise empathised empathises empathising emphasise emphasised emphasises emphasising enamelled enamelling enamoured encyclopaedia encyclopaedias encyclopaedic endeavour endeavoured endeavouring endeavours energise energised energises energising enrol enrols enthral enthrals epaulette epaulettes epicentre epicentres epilogue epilogues epitomise epitomised epitomises epitomising equalisation equalise equalised equaliser equalisers equalises equalising eulogise eulogised eulogises eulogising evangelise evangelised evangelises evangelising exorcise exorcised exorcises exorcising extemporisation extemporise extemporised extemporises extemporising externalisation externalisations externalise externalised externalises externalising factorise factorised factorises factorising faecal faeces familiarisation familiarise familiarised familiarises familiarising fantasise fantasised fantasises fantasising favour favourable favourably favoured favouring favourite favourites favouritism favours feminise feminised feminises feminising fertilisation fertilise fertilised fertiliser fertilisers fertilises fertilising fervour fibre fibreglass fibres fictionalisation fictionalisations fictionalise fictionalised fictionalises fictionalising fillet filleted filleting fillets finalisation finalise finalised finalises finalising flautist flautists flavour flavoured flavouring flavourings flavourless flavours flavoursome flyer flier foetal foetid foetus foetuses formalisation formalise formalised formalises formalising fossilisation fossilise fossilised fossilises fossilising fraternisation fraternise fraternised fraternises fraternising fulfil fulfilment fulfils funnelled funnelling galvanise galvanised galvanises galvanising gambolled gambolling gaol gaolbird gaolbirds gaolbreak gaolbreaks gaoled gaoler gaolers gaoling gaols gases gauge gauged gauges gauging generalisation generalisations generalise generalised generalises generalising ghettoise ghettoised ghettoises ghettoising gipsies glamorise glamorised glamorises glamorising glamour globalisation globalise globalised globalises globalising glueing goitre goitres gonorrhoea gramme grammes gravelled grey greyed greying greyish greyness greys grovelled grovelling groyne groynes gruelling gruellingly gryphon gryphons gynaecological gynaecologist gynaecologists gynaecology haematological haematologist haematologists haematology haemoglobin haemophilia haemophiliac haemophiliacs haemorrhage haemorrhaged haemorrhages haemorrhaging haemorrhoids harbour harboured harbouring harbours harmonisation harmonise harmonised harmonises harmonising homoeopath homoeopathic homoeopaths homoeopathy homogenise homogenised homogenises homogenising honour honourable honourably honoured honouring honours hospitalisation hospitalise hospitalised hospitalises hospitalising humanise humanised humanises humanising humour humoured humouring humourless humours hybridise hybridised hybridises hybridising hypnotise hypnotised hypnotises hypnotising hypothesise hypothesised hypothesises hypothesising idealisation idealise idealised idealises idealising idolise idolised idolises idolising immobilisation immobilise immobilised immobiliser immobilisers immobilises immobilising immortalise immortalised immortalises immortalising immunisation immunise immunised immunises immunising impanelled impanelling imperilled imperilling individualise individualised individualises individualising industrialise industrialised industrialises industrialising inflexion inflexions initialise initialised initialises initialising initialled initialling instal instalment instalments instals instil instils institutionalisation institutionalise institutionalised institutionalises institutionalising intellectualise intellectualised intellectualises intellectualising internalisation internalise internalised internalises internalising internationalisation internationalise internationalised internationalises internationalising ionisation ionise ionised ioniser ionisers ionises ionising italicise italicised italicises italicising itemise itemised itemises itemising jeopardise jeopardised jeopardises jeopardising jewelled jeweller jewellers jewellery judgement kilogramme kilogrammes kilometre kilometres labelled labelling labour laboured labourer labourers labouring labours lacklustre legalisation legalise legalised legalises legalising legitimise legitimised legitimises legitimising leukaemia levelled leveller levellers levelling libelled libelling libellous liberalisation liberalise liberalised liberalises liberalising licence licenced licences licencing likeable lionisation lionise lionised lionises lionising liquidise liquidised liquidiser liquidisers liquidises liquidising litre litres localise localised localises localising louvre louvred louvres lustre magnetise magnetised magnetises magnetising manoeuvrability manoeuvrable manoeuvre manoeuvred manoeuvres manoeuvring manoeuvrings marginalisation marginalise marginalised marginalises marginalising marshalled marshalling marvelled marvelling marvellous marvellously materialisation materialise materialised materialises materialising maximisation maximise maximised maximises maximising meagre mechanisation mechanise mechanised mechanises mechanising mediaeval memorialise memorialised memorialises memorialising memorise memorised memorises memorising mesmerise mesmerised mesmerises mesmerising metabolise metabolised metabolises metabolising metre metres micrometre micrometres militarise militarised militarises militarising milligramme milligrammes millilitre millilitres millimetre millimetres miniaturisation miniaturise miniaturised miniaturises miniaturising minibuses minimise minimised minimises minimising misbehaviour misdemeanour misdemeanours misspelt mitre mitres mobilisation mobilise mobilised mobilises mobilising modelled modeller modellers modelling modernise modernised modernises modernising moisturise moisturised moisturiser moisturisers moisturises moisturising monologue monologues monopolisation monopolise monopolised monopolises monopolising moralise moralised moralises moralising motorised mould moulded moulder mouldered mouldering moulders mouldier mouldiest moulding mouldings moulds mouldy moult moulted moulting moults moustache moustached moustaches moustachioed multicoloured nationalisation nationalisations nationalise nationalised nationalises nationalising naturalisation naturalise naturalised naturalises naturalising neighbour neighbourhood neighbourhoods neighbouring neighbourliness neighbourly neighbours neutralisation neutralise neutralised neutralises neutralising normalisation normalise normalised normalises normalising odour odourless odours oesophagus oesophaguses oestrogen offence offences omelette omelettes optimise optimised optimises optimising organisation organisational organisations organise organised organiser organisers organises organising orthopaedic orthopaedics ostracise ostracised ostracises ostracising outmanoeuvre outmanoeuvred outmanoeuvres outmanoeuvring overemphasise overemphasised overemphasises overemphasising oxidisation oxidise oxidised oxidises oxidising paederast paederasts paediatric paediatrician paediatricians paediatrics paedophile paedophiles paedophilia palaeolithic palaeontologist palaeontologists palaeontology panelled panelling panellist panellists paralyse paralysed paralyses paralysing parcelled parcelling parlour parlours particularise particularised particularises particularising passivisation passivise passivised passivises passivising pasteurisation pasteurise pasteurised pasteurises pasteurising patronise patronised patronises patronising patronisingly pedalled pedalling pedestrianisation pedestrianise pedestrianised pedestrianises pedestrianising penalise penalised penalises penalising pencilled pencilling personalise personalised personalises personalising pharmacopoeia pharmacopoeias philosophise philosophised philosophises philosophising philtre philtres phoney plagiarise plagiarised plagiarises plagiarising plough ploughed ploughing ploughman ploughmen ploughs ploughshare ploughshares polarisation polarise polarised polarises polarising politicisation politicise politicised politicises politicising popularisation popularise popularised popularises popularising pouffe pouffes practise practised practises practising praesidium praesidiums pressurisation pressurise pressurised pressurises pressurising pretence pretences primaeval prioritisation prioritise prioritised prioritises prioritising privatisation privatisations privatise privatised privatises privatising professionalisation professionalise professionalised professionalises professionalising programme programmes prologue prologues propagandise propagandised propagandises propagandising proselytise proselytised proselytiser proselytisers proselytises proselytising psychoanalyse psychoanalysed psychoanalyses psychoanalysing publicise publicised publicises publicising pulverisation pulverise pulverised pulverises pulverising pummelled pummelling pyjama pyjamas pzazz quarrelled quarrelling radicalise radicalised radicalises radicalising rancour randomise randomised randomises randomising rationalisation rationalisations rationalise rationalised rationalises rationalising ravelled ravelling realisable realisation realisations realise realised realises realising recognisable recognisably recognisance recognise recognised recognises recognising reconnoitre reconnoitred reconnoitres reconnoitring refuelled refuelling regularisation regularise regularised regularises regularising remodelled remodelling remould remoulded remoulding remoulds reorganisation reorganisations reorganise reorganised reorganises reorganising revelled reveller revellers revelling revitalise revitalised revitalises revitalising revolutionise revolutionised revolutionises revolutionising rhapsodise rhapsodised rhapsodises rhapsodising rigour rigours ritualised rivalled rivalling romanticise romanticised romanticises romanticising rumour rumoured rumours sabre sabres saltpetre sanitise sanitised sanitises sanitising satirise satirised satirises satirising saviour saviours savour savoured savouries savouring savours savoury scandalise scandalised scandalises scandalising sceptic sceptical sceptically scepticism sceptics sceptre sceptres scrutinise scrutinised scrutinises scrutinising secularisation secularise secularised secularises secularising sensationalise sensationalised sensationalises sensationalising sensitise sensitised sensitises sensitising sentimentalise sentimentalised sentimentalises sentimentalising sepulchre sepulchres serialisation serialisations serialise serialised serialises serialising sermonise sermonised sermonises sermonising sheikh shovelled shovelling shrivelled shrivelling signalise signalised signalises signalising signalled signalling smoulder smouldered smouldering smoulders snivelled snivelling snorkelled snorkelling snowplough snowploughs socialisation socialise socialised socialises socialising sodomise sodomised sodomises sodomising solemnise solemnised solemnises solemnising sombre specialisation specialisations specialise specialised specialises specialising spectre spectres spiralled spiralling splendour splendours squirrelled squirrelling stabilisation stabilise stabilised stabiliser stabilisers stabilises stabilising standardisation standardise standardised standardises standardising stencilled stencilling sterilisation sterilisations sterilise sterilised steriliser sterilisers sterilises sterilising stigmatisation stigmatise stigmatised stigmatises stigmatising storey storeys subsidisation subsidise subsidised subsidiser subsidisers subsidises subsidising succour succoured succouring succours sulphate sulphates sulphide sulphides sulphur sulphurous summarise summarised summarises summarising swivelled swivelling symbolise symbolised symbolises symbolising sympathise sympathised sympathiser sympathisers sympathises sympathising synchronisation synchronise synchronised synchronises synchronising synthesise synthesised synthesiser synthesisers synthesises synthesising syphon syphoned syphoning syphons systematisation systematise systematised systematises systematising tantalise tantalised tantalises tantalising tantalisingly tasselled technicolour temporise temporised temporises temporising tenderise tenderised tenderises tenderising terrorise terrorised terrorises terrorising theatre theatregoer theatregoers theatres theorise theorised theorises theorising tonne tonnes towelled towelling toxaemia tranquillise tranquillised tranquilliser tranquillisers tranquillises tranquillising tranquillity tranquillize tranquillized tranquillizer tranquillizers tranquillizes tranquillizing tranquilly transistorised traumatise traumatised traumatises traumatising travelled traveller travellers travelling travelogue travelogues trialled trialling tricolour tricolours trivialise trivialised trivialises trivialising tumour tumours tunnelled tunnelling tyrannise tyrannised tyrannises tyrannising tyre tyres unauthorised uncivilised underutilised unequalled unfavourable unfavourably unionisation unionise unionised unionises unionising unorganised unravelled unravelling unrecognisable unrecognised unrivalled unsavoury untrammelled urbanisation urbanise urbanised urbanises urbanising utilisable utilisation utilise utilised utilises utilising valour vandalise vandalised vandalises vandalising vaporisation vaporise vaporised vaporises vaporising vapour vapours verbalise verbalised verbalises verbalising victimisation victimise victimised victimises victimising videodisc videodiscs vigour visualisation visualisations visualise visualised visualises visualising vocalisation vocalisations vocalise vocalised vocalises vocalising vulcanised vulgarisation vulgarise vulgarised vulgarises vulgarising waggon waggons watercolour watercolours weaselled weaselling westernisation westernise westernised westernises westernising womanise womanised womaniser womanisers womanises womanising woollen woollens woollies woolly worshipped worshipping worshipper yodelled yodelling yoghourt yoghourts yoghurt yoghurts".lower().split() US = "kerb accessorize accessorized accessorizes accessorizing acclimatization acclimatize acclimatized acclimatizes acclimatizing accouterments eon eons aerogram aerograms airplane airplanes esthete esthetes esthetic esthetically esthetics etiology aging aggrandizement agonize agonized agonizes agonizing agonizingly almanac almanacs aluminum amortizable amortization amortizations amortize amortized amortizes amortizing amphitheater amphitheaters anemia anemic anesthesia anesthetic anesthetics anesthetize anesthetized anesthetizes anesthetizing anesthetist anesthetists anesthetize anesthetized anesthetizes anesthetizing analog analogs analyze analyzed analyzes analyzing anglicize anglicized anglicizes anglicizing annualized antagonize antagonized antagonizes antagonizing apologize apologized apologizes apologizing appall appalls appetizer appetizers appetizing appetizingly arbor arbors archeological archeologically archeologist archeologists archeology ardor armor armored armorer armorers armories armory artifact artifacts authorize authorized authorizes authorizing ax backpedaled backpedaling banister banisters baptize baptized baptizes baptizing bastardize bastardized bastardizes bastardizing battleax balk balked balking balks bedeviled bedeviling behavior behavioral behaviorism behaviorist behaviorists behaviors behoove behooved behooves bejeweled belabor belabored belaboring belabors beveled bevies bevy biased biasing binging bougainvillea bougainvilleas bowdlerize bowdlerized bowdlerizes bowdlerizing breathalyze breathalyzed breathalyzer breathalyzers breathalyzes breathalyzing brutalize brutalized brutalizes brutalizing busses bussing cesarean cesareans caliber calibers caliper calipers calisthenics canalize canalized canalizes canalizing cancelation cancelations canceled canceling candor cannibalize cannibalized cannibalizes cannibalizing canonize canonized canonizes canonizing capitalize capitalized capitalizes capitalizing caramelize caramelized caramelizes caramelizing carbonize carbonized carbonizes carbonizing caroled caroling catalog cataloged catalogs cataloging catalyze catalyzed catalyzes catalyzing categorize categorized categorizes categorizing cauterize cauterized cauterizes cauterizing caviled caviling centigram centigrams centiliter centiliters centimeter centimeters centralize centralized centralizes centralizing center centered centerfold centerfolds centerpiece centerpieces centers channeled channeling characterize characterized characterizes characterizing check checkbook checkbooks checkered checks chili chimera chimeras chiseled chiseling circularize circularized circularizes circularizing civilize civilized civilizes civilizing clamor clamored clamoring clamors clangor clarinetist clarinetists collectivize collectivized collectivizes collectivizing colonization colonize colonized colonizer colonizers colonizes colonizing color colorant colorants colored coloreds colorful colorfully coloring colorize colorized colorizes colorizing colorless colors commercialize commercialized commercializes commercializing compartmentalize compartmentalized compartmentalizes compartmentalizing computerize computerized computerizes computerizing conceptualize conceptualized conceptualizes conceptualizing connection connections contextualize contextualized contextualizes contextualizing cozier cozies coziest cozily coziness cozy councilor councilors counseled counseling counselor counselors crenelated criminalize criminalized criminalizes criminalizing criticize criticized criticizes criticizing crueler cruelest crystallization crystallize crystallized crystallizes crystallizing cudgeled cudgeling customize customized customizes customizing cipher ciphers decentralization decentralize decentralized decentralizes decentralizing decriminalization decriminalize decriminalized decriminalizes decriminalizing defense defenseless defenses dehumanization dehumanize dehumanized dehumanizes dehumanizing demeanor demilitarization demilitarize demilitarized demilitarizes demilitarizing demobilization demobilize demobilized demobilizes demobilizing democratization democratize democratized democratizes democratizing demonize demonized demonizes demonizing demoralization demoralize demoralized demoralizes demoralizing denationalization denationalize denationalized denationalizes denationalizing deodorize deodorized deodorizes deodorizing depersonalize depersonalized depersonalizes depersonalizing deputize deputized deputizes deputizing desensitization desensitize desensitized desensitizes desensitizing destabilization destabilize destabilized destabilizes destabilizing dialed dialing dialog dialogs diarrhea digitize digitized digitizes digitizing disk discolor discolored discoloring discolors disks disemboweled disemboweling disfavor disheveled dishonor dishonorable dishonorably dishonored dishonoring dishonors disorganization disorganized distill distills dramatization dramatizations dramatize dramatized dramatizes dramatizing draft draftboard draftboards draftier draftiest drafts draftsman draftsmanship draftsmen draftswoman draftswomen drafty driveled driveling dueled dueling economize economized economizes economizing edema editorialize editorialized editorializes editorializing empathize empathized empathizes empathizing emphasize emphasized emphasizes emphasizing enameled enameling enamored encyclopedia encyclopedias encyclopedic endeavor endeavored endeavoring endeavors energize energized energizes energizing enroll enrolls enthrall enthralls epaulet epaulets epicenter epicenters epilog epilogs epitomize epitomized epitomizes epitomizing equalization equalize equalized equalizer equalizers equalizes equalizing eulogize eulogized eulogizes eulogizing evangelize evangelized evangelizes evangelizing exorcize exorcized exorcizes exorcizing extemporization extemporize extemporized extemporizes extemporizing externalization externalizations externalize externalized externalizes externalizing factorize factorized factorizes factorizing fecal feces familiarization familiarize familiarized familiarizes familiarizing fantasize fantasized fantasizes fantasizing favor favorable favorably favored favoring favorite favorites favoritism favors feminize feminized feminizes feminizing fertilization fertilize fertilized fertilizer fertilizers fertilizes fertilizing fervor fiber fiberglass fibers fictionalization fictionalizations fictionalize fictionalized fictionalizes fictionalizing filet fileted fileting filets finalization finalize finalized finalizes finalizing flutist flutists flavor flavored flavoring flavorings flavorless flavors flavorsome flier flyer fetal fetid fetus fetuses formalization formalize formalized formalizes formalizing fossilization fossilize fossilized fossilizes fossilizing fraternization fraternize fraternized fraternizes fraternizing fulfill fulfillment fulfills funneled funneling galvanize galvanized galvanizes galvanizing gamboled gamboling jail jailbird jailbirds jailbreak jailbreaks jailed jailer jailers jailing jails gasses gage gaged gages gaging generalization generalizations generalize generalized generalizes generalizing ghettoize ghettoized ghettoizes ghettoizing gypsies glamorize glamorized glamorizes glamorizing glamor globalization globalize globalized globalizes globalizing gluing goiter goiters gonorrhea gram grams graveled gray grayed graying grayish grayness grays groveled groveling groin groins grueling gruelingly griffin griffins gynecological gynecologist gynecologists gynecology hematological hematologist hematologists hematology hemoglobin hemophilia hemophiliac hemophiliacs hemorrhage hemorrhaged hemorrhages hemorrhaging hemorrhoids harbor harbored harboring harbors harmonization harmonize harmonized harmonizes harmonizing homeopath homeopathic homeopaths homeopathy homogenize homogenized homogenizes homogenizing honor honorable honorably honored honoring honors hospitalization hospitalize hospitalized hospitalizes hospitalizing humanize humanized humanizes humanizing humor humored humoring humorless humors hybridize hybridized hybridizes hybridizing hypnotize hypnotized hypnotizes hypnotizing hypothesize hypothesized hypothesizes hypothesizing idealization idealize idealized idealizes idealizing idolize idolized idolizes idolizing immobilization immobilize immobilized immobilizer immobilizers immobilizes immobilizing immortalize immortalized immortalizes immortalizing immunization immunize immunized immunizes immunizing impaneled impaneling imperiled imperiling individualize individualized individualizes individualizing industrialize industrialized industrializes industrializing inflection inflections initialize initialized initializes initializing initialed initialing install installment installments installs instill instills institutionalization institutionalize institutionalized institutionalizes institutionalizing intellectualize intellectualized intellectualizes intellectualizing internalization internalize internalized internalizes internalizing internationalization internationalize internationalized internationalizes internationalizing ionization ionize ionized ionizer ionizers ionizes ionizing italicize italicized italicizes italicizing itemize itemized itemizes itemizing jeopardize jeopardized jeopardizes jeopardizing jeweled jeweler jewelers jewelry judgment kilogram kilograms kilometer kilometers labeled labeling labor labored laborer laborers laboring labors lackluster legalization legalize legalized legalizes legalizing legitimize legitimized legitimizes legitimizing leukemia leveled leveler levelers leveling libeled libeling libelous liberalization liberalize liberalized liberalizes liberalizing license licensed licenses licensing likable lionization lionize lionized lionizes lionizing liquidize liquidized liquidizer liquidizers liquidizes liquidizing liter liters localize localized localizes localizing louver louvered louvers luster magnetize magnetized magnetizes magnetizing maneuverability maneuverable maneuver maneuvered maneuvers maneuvering maneuverings marginalization marginalize marginalized marginalizes marginalizing marshaled marshaling marveled marveling marvelous marvelously materialization materialize materialized materializes materializing maximization maximize maximized maximizes maximizing meager mechanization mechanize mechanized mechanizes mechanizing medieval memorialize memorialized memorializes memorializing memorize memorized memorizes memorizing mesmerize mesmerized mesmerizes mesmerizing metabolize metabolized metabolizes metabolizing meter meters micrometer micrometers militarize militarized militarizes militarizing milligram milligrams milliliter milliliters millimeter millimeters miniaturization miniaturize miniaturized miniaturizes miniaturizing minibusses minimize minimized minimizes minimizing misbehavior misdemeanor misdemeanors misspelled miter miters mobilization mobilize mobilized mobilizes mobilizing modeled modeler modelers modeling modernize modernized modernizes modernizing moisturize moisturized moisturizer moisturizers moisturizes moisturizing monolog monologs monopolization monopolize monopolized monopolizes monopolizing moralize moralized moralizes moralizing motorized mold molded molder moldered moldering molders moldier moldiest molding moldings molds moldy molt molted molting molts mustache mustached mustaches mustachioed multicolored nationalization nationalizations nationalize nationalized nationalizes nationalizing naturalization naturalize naturalized naturalizes naturalizing neighbor neighborhood neighborhoods neighboring neighborliness neighborly neighbors neutralization neutralize neutralized neutralizes neutralizing normalization normalize normalized normalizes normalizing odor odorless odors esophagus esophaguses estrogen offense offenses omelet omelets optimize optimized optimizes optimizing organization organizational organizations organize organized organizer organizers organizes organizing orthopedic orthopedics ostracize ostracized ostracizes ostracizing outmaneuver outmaneuvered outmaneuvers outmaneuvering overemphasize overemphasized overemphasizes overemphasizing oxidization oxidize oxidized oxidizes oxidizing pederast pederasts pediatric pediatrician pediatricians pediatrics pedophile pedophiles pedophilia paleolithic paleontologist paleontologists paleontology paneled paneling panelist panelists paralyze paralyzed paralyzes paralyzing parceled parceling parlor parlors particularize particularized particularizes particularizing passivization passivize passivized passivizes passivizing pasteurization pasteurize pasteurized pasteurizes pasteurizing patronize patronized patronizes patronizing patronizingly pedaled pedaling pedestrianization pedestrianize pedestrianized pedestrianizes pedestrianizing penalize penalized penalizes penalizing penciled penciling personalize personalized personalizes personalizing pharmacopeia pharmacopeias philosophize philosophized philosophizes philosophizing filter filters phony plagiarize plagiarized plagiarizes plagiarizing plow plowed plowing plowman plowmen plows plowshare plowshares polarization polarize polarized polarizes polarizing politicization politicize politicized politicizes politicizing popularization popularize popularized popularizes popularizing pouf poufs practice practiced practices practicing presidium presidiums pressurization pressurize pressurized pressurizes pressurizing pretense pretenses primeval prioritization prioritize prioritized prioritizes prioritizing privatization privatizations privatize privatized privatizes privatizing professionalization professionalize professionalized professionalizes professionalizing program programs prolog prologs propagandize propagandized propagandizes propagandizing proselytize proselytized proselytizer proselytizers proselytizes proselytizing psychoanalyze psychoanalyzed psychoanalyzes psychoanalyzing publicize publicized publicizes publicizing pulverization pulverize pulverized pulverizes pulverizing pummel pummeled pajama pajamas pizzazz quarreled quarreling radicalize radicalized radicalizes radicalizing rancor randomize randomized randomizes randomizing rationalization rationalizations rationalize rationalized rationalizes rationalizing raveled raveling realizable realization realizations realize realized realizes realizing recognizable recognizably recognizance recognize recognized recognizes recognizing reconnoiter reconnoitered reconnoiters reconnoitering refueled refueling regularization regularize regularized regularizes regularizing remodeled remodeling remold remolded remolding remolds reorganization reorganizations reorganize reorganized reorganizes reorganizing reveled reveler revelers reveling revitalize revitalized revitalizes revitalizing revolutionize revolutionized revolutionizes revolutionizing rhapsodize rhapsodized rhapsodizes rhapsodizing rigor rigors ritualized rivaled rivaling romanticize romanticized romanticizes romanticizing rumor rumored rumors saber sabers saltpeter sanitize sanitized sanitizes sanitizing satirize satirized satirizes satirizing savior saviors savor savored savories savoring savors savory scandalize scandalized scandalizes scandalizing skeptic skeptical skeptically skepticism skeptics scepter scepters scrutinize scrutinized scrutinizes scrutinizing secularization secularize secularized secularizes secularizing sensationalize sensationalized sensationalizes sensationalizing sensitize sensitized sensitizes sensitizing sentimentalize sentimentalized sentimentalizes sentimentalizing sepulcher sepulchers serialization serializations serialize serialized serializes serializing sermonize sermonized sermonizes sermonizing sheik shoveled shoveling shriveled shriveling signalize signalized signalizes signalizing signaled signaling smolder smoldered smoldering smolders sniveled sniveling snorkeled snorkeling snowplow snowplow socialization socialize socialized socializes socializing sodomize sodomized sodomizes sodomizing solemnize solemnized solemnizes solemnizing somber specialization specializations specialize specialized specializes specializing specter specters spiraled spiraling splendor splendors squirreled squirreling stabilization stabilize stabilized stabilizer stabilizers stabilizes stabilizing standardization standardize standardized standardizes standardizing stenciled stenciling sterilization sterilizations sterilize sterilized sterilizer sterilizers sterilizes sterilizing stigmatization stigmatize stigmatized stigmatizes stigmatizing story stories subsidization subsidize subsidized subsidizer subsidizers subsidizes subsidizing succor succored succoring succors sulfate sulfates sulfide sulfides sulfur sulfurous summarize summarized summarizes summarizing swiveled swiveling symbolize symbolized symbolizes symbolizing sympathize sympathized sympathizer sympathizers sympathizes sympathizing synchronization synchronize synchronized synchronizes synchronizing synthesize synthesized synthesizer synthesizers synthesizes synthesizing siphon siphoned siphoning siphons systematization systematize systematized systematizes systematizing tantalize tantalized tantalizes tantalizing tantalizingly tasseled technicolor temporize temporized temporizes temporizing tenderize tenderized tenderizes tenderizing terrorize terrorized terrorizes terrorizing theater theatergoer theatergoers theaters theorize theorized theorizes theorizing ton tons toweled toweling toxemia tranquilize tranquilized tranquilizer tranquilizers tranquilizes tranquilizing tranquility tranquilize tranquilized tranquilizer tranquilizers tranquilizes tranquilizing tranquility transistorized traumatize traumatized traumatizes traumatizing traveled traveler travelers traveling travelog travelogs trialed trialing tricolor tricolors trivialize trivialized trivializes trivializing tumor tumors tunneled tunneling tyrannize tyrannized tyrannizes tyrannizing tire tires unauthorized uncivilized underutilized unequaled unfavorable unfavorably unionization unionize unionized unionizes unionizing unorganized unraveled unraveling unrecognizable unrecognized unrivaled unsavory untrammeled urbanization urbanize urbanized urbanizes urbanizing utilizable utilization utilize utilized utilizes utilizing valor vandalize vandalized vandalizes vandalizing vaporization vaporize vaporized vaporizes vaporizing vapor vapors verbalize verbalized verbalizes verbalizing victimization victimize victimized victimizes victimizing videodisk videodisks vigor visualization visualizations visualize visualized visualizes visualizing vocalization vocalizations vocalize vocalized vocalizes vocalizing vulcanized vulgarization vulgarize vulgarized vulgarizes vulgarizing wagon wagons watercolor watercolors weaseled weaseling westernization westernize westernized westernizes westernizing womanize womanized womanizer womanizers womanizes womanizing woolen woolens woolies wooly worshiped worshiping worshiper yodeled yodeling yogurt yogurts yogurt yogurts".lower().split() ukUS = {} usUK = {} loopN = 0 for x in UK: ukUS[x] = US[loopN] loopN += 1 loopN = 0 for y in US: usUK[y] = UK[loopN] loopN += 1
uk = 'curb accessorise accessorised accessorises accessorising acclimatisation acclimatise acclimatised acclimatises acclimatising accoutrements aeon aeons aerogramme aerogrammes aeroplane aeroplanes aesthete aesthetes aesthetic aesthetically aesthetics aetiology ageing aggrandisement agonise agonised agonises agonising agonisingly almanack almanacks aluminium amortisable amortisation amortisations amortise amortised amortises amortising amphitheatre amphitheatres anaemia anaemic anaesthesia anaesthetic anaesthetics anaesthetise anaesthetised anaesthetises anaesthetising anaesthetist anaesthetists anaesthetize anaesthetized anaesthetizes anaesthetizing analogue analogues analyse analysed analyses analysing anglicise anglicised anglicises anglicising annualised antagonise antagonised antagonises antagonising apologise apologised apologises apologising appal appals appetiser appetisers appetising appetisingly arbour arbours archaeological archaeologically archaeologist archaeologists archaeology ardour armour armoured armourer armourers armouries armoury artefact artefacts authorise authorised authorises authorising axe backpedalled backpedalling bannister bannisters baptise baptised baptises baptising bastardise bastardised bastardises bastardising battleaxe baulk baulked baulking baulks bedevilled bedevilling behaviour behavioural behaviourism behaviourist behaviourists behaviours behove behoved behoves bejewelled belabour belaboured belabouring belabours bevelled bevvies bevvy biassed biassing bingeing bougainvillaea bougainvillaeas bowdlerise bowdlerised bowdlerises bowdlerising breathalyse breathalysed breathalyser breathalysers breathalyses breathalysing brutalise brutalised brutalises brutalising buses busing caesarean caesareans calibre calibres calliper callipers callisthenics canalise canalised canalises canalising cancellation cancellations cancelled cancelling candour cannibalise cannibalised cannibalises cannibalising canonise canonised canonises canonising capitalise capitalised capitalises capitalising caramelise caramelised caramelises caramelising carbonise carbonised carbonises carbonising carolled carolling catalogue catalogued catalogues cataloguing catalyse catalysed catalyses catalysing categorise categorised categorises categorising cauterise cauterised cauterises cauterising cavilled cavilling centigramme centigrammes centilitre centilitres centimetre centimetres centralise centralised centralises centralising centre centred centrefold centrefolds centrepiece centrepieces centres channelled channelling characterise characterised characterises characterising cheque chequebook chequebooks chequered cheques chilli chimaera chimaeras chiselled chiselling circularise circularised circularises circularising civilise civilised civilises civilising clamour clamoured clamouring clamours clangour clarinettist clarinettists collectivise collectivised collectivises collectivising colonisation colonise colonised coloniser colonisers colonises colonising colour colourant colourants coloured coloureds colourful colourfully colouring colourize colourized colourizes colourizing colourless colours commercialise commercialised commercialises commercialising compartmentalise compartmentalised compartmentalises compartmentalising computerise computerised computerises computerising conceptualise conceptualised conceptualises conceptualising connexion connexions contextualise contextualised contextualises contextualising cosier cosies cosiest cosily cosiness cosy councillor councillors counselled counselling counsellor counsellors crenellated criminalise criminalised criminalises criminalising criticise criticised criticises criticising crueller cruellest crystallisation crystallise crystallised crystallises crystallising cudgelled cudgelling customise customised customises customising cypher cyphers decentralisation decentralise decentralised decentralises decentralising decriminalisation decriminalise decriminalised decriminalises decriminalising defence defenceless defences dehumanisation dehumanise dehumanised dehumanises dehumanising demeanour demilitarisation demilitarise demilitarised demilitarises demilitarising demobilisation demobilise demobilised demobilises demobilising democratisation democratise democratised democratises democratising demonise demonised demonises demonising demoralisation demoralise demoralised demoralises demoralising denationalisation denationalise denationalised denationalises denationalising deodorise deodorised deodorises deodorising depersonalise depersonalised depersonalises depersonalising deputise deputised deputises deputising desensitisation desensitise desensitised desensitises desensitising destabilisation destabilise destabilised destabilises destabilising dialled dialling dialogue dialogues diarrhoea digitise digitised digitises digitising disc discolour discoloured discolouring discolours discs disembowelled disembowelling disfavour dishevelled dishonour dishonourable dishonourably dishonoured dishonouring dishonours disorganisation disorganised distil distils dramatisation dramatisations dramatise dramatised dramatises dramatising draught draughtboard draughtboards draughtier draughtiest draughts draughtsman draughtsmanship draughtsmen draughtswoman draughtswomen draughty drivelled drivelling duelled duelling economise economised economises economising edoema editorialise editorialised editorialises editorialising empathise empathised empathises empathising emphasise emphasised emphasises emphasising enamelled enamelling enamoured encyclopaedia encyclopaedias encyclopaedic endeavour endeavoured endeavouring endeavours energise energised energises energising enrol enrols enthral enthrals epaulette epaulettes epicentre epicentres epilogue epilogues epitomise epitomised epitomises epitomising equalisation equalise equalised equaliser equalisers equalises equalising eulogise eulogised eulogises eulogising evangelise evangelised evangelises evangelising exorcise exorcised exorcises exorcising extemporisation extemporise extemporised extemporises extemporising externalisation externalisations externalise externalised externalises externalising factorise factorised factorises factorising faecal faeces familiarisation familiarise familiarised familiarises familiarising fantasise fantasised fantasises fantasising favour favourable favourably favoured favouring favourite favourites favouritism favours feminise feminised feminises feminising fertilisation fertilise fertilised fertiliser fertilisers fertilises fertilising fervour fibre fibreglass fibres fictionalisation fictionalisations fictionalise fictionalised fictionalises fictionalising fillet filleted filleting fillets finalisation finalise finalised finalises finalising flautist flautists flavour flavoured flavouring flavourings flavourless flavours flavoursome flyer flier foetal foetid foetus foetuses formalisation formalise formalised formalises formalising fossilisation fossilise fossilised fossilises fossilising fraternisation fraternise fraternised fraternises fraternising fulfil fulfilment fulfils funnelled funnelling galvanise galvanised galvanises galvanising gambolled gambolling gaol gaolbird gaolbirds gaolbreak gaolbreaks gaoled gaoler gaolers gaoling gaols gases gauge gauged gauges gauging generalisation generalisations generalise generalised generalises generalising ghettoise ghettoised ghettoises ghettoising gipsies glamorise glamorised glamorises glamorising glamour globalisation globalise globalised globalises globalising glueing goitre goitres gonorrhoea gramme grammes gravelled grey greyed greying greyish greyness greys grovelled grovelling groyne groynes gruelling gruellingly gryphon gryphons gynaecological gynaecologist gynaecologists gynaecology haematological haematologist haematologists haematology haemoglobin haemophilia haemophiliac haemophiliacs haemorrhage haemorrhaged haemorrhages haemorrhaging haemorrhoids harbour harboured harbouring harbours harmonisation harmonise harmonised harmonises harmonising homoeopath homoeopathic homoeopaths homoeopathy homogenise homogenised homogenises homogenising honour honourable honourably honoured honouring honours hospitalisation hospitalise hospitalised hospitalises hospitalising humanise humanised humanises humanising humour humoured humouring humourless humours hybridise hybridised hybridises hybridising hypnotise hypnotised hypnotises hypnotising hypothesise hypothesised hypothesises hypothesising idealisation idealise idealised idealises idealising idolise idolised idolises idolising immobilisation immobilise immobilised immobiliser immobilisers immobilises immobilising immortalise immortalised immortalises immortalising immunisation immunise immunised immunises immunising impanelled impanelling imperilled imperilling individualise individualised individualises individualising industrialise industrialised industrialises industrialising inflexion inflexions initialise initialised initialises initialising initialled initialling instal instalment instalments instals instil instils institutionalisation institutionalise institutionalised institutionalises institutionalising intellectualise intellectualised intellectualises intellectualising internalisation internalise internalised internalises internalising internationalisation internationalise internationalised internationalises internationalising ionisation ionise ionised ioniser ionisers ionises ionising italicise italicised italicises italicising itemise itemised itemises itemising jeopardise jeopardised jeopardises jeopardising jewelled jeweller jewellers jewellery judgement kilogramme kilogrammes kilometre kilometres labelled labelling labour laboured labourer labourers labouring labours lacklustre legalisation legalise legalised legalises legalising legitimise legitimised legitimises legitimising leukaemia levelled leveller levellers levelling libelled libelling libellous liberalisation liberalise liberalised liberalises liberalising licence licenced licences licencing likeable lionisation lionise lionised lionises lionising liquidise liquidised liquidiser liquidisers liquidises liquidising litre litres localise localised localises localising louvre louvred louvres lustre magnetise magnetised magnetises magnetising manoeuvrability manoeuvrable manoeuvre manoeuvred manoeuvres manoeuvring manoeuvrings marginalisation marginalise marginalised marginalises marginalising marshalled marshalling marvelled marvelling marvellous marvellously materialisation materialise materialised materialises materialising maximisation maximise maximised maximises maximising meagre mechanisation mechanise mechanised mechanises mechanising mediaeval memorialise memorialised memorialises memorialising memorise memorised memorises memorising mesmerise mesmerised mesmerises mesmerising metabolise metabolised metabolises metabolising metre metres micrometre micrometres militarise militarised militarises militarising milligramme milligrammes millilitre millilitres millimetre millimetres miniaturisation miniaturise miniaturised miniaturises miniaturising minibuses minimise minimised minimises minimising misbehaviour misdemeanour misdemeanours misspelt mitre mitres mobilisation mobilise mobilised mobilises mobilising modelled modeller modellers modelling modernise modernised modernises modernising moisturise moisturised moisturiser moisturisers moisturises moisturising monologue monologues monopolisation monopolise monopolised monopolises monopolising moralise moralised moralises moralising motorised mould moulded moulder mouldered mouldering moulders mouldier mouldiest moulding mouldings moulds mouldy moult moulted moulting moults moustache moustached moustaches moustachioed multicoloured nationalisation nationalisations nationalise nationalised nationalises nationalising naturalisation naturalise naturalised naturalises naturalising neighbour neighbourhood neighbourhoods neighbouring neighbourliness neighbourly neighbours neutralisation neutralise neutralised neutralises neutralising normalisation normalise normalised normalises normalising odour odourless odours oesophagus oesophaguses oestrogen offence offences omelette omelettes optimise optimised optimises optimising organisation organisational organisations organise organised organiser organisers organises organising orthopaedic orthopaedics ostracise ostracised ostracises ostracising outmanoeuvre outmanoeuvred outmanoeuvres outmanoeuvring overemphasise overemphasised overemphasises overemphasising oxidisation oxidise oxidised oxidises oxidising paederast paederasts paediatric paediatrician paediatricians paediatrics paedophile paedophiles paedophilia palaeolithic palaeontologist palaeontologists palaeontology panelled panelling panellist panellists paralyse paralysed paralyses paralysing parcelled parcelling parlour parlours particularise particularised particularises particularising passivisation passivise passivised passivises passivising pasteurisation pasteurise pasteurised pasteurises pasteurising patronise patronised patronises patronising patronisingly pedalled pedalling pedestrianisation pedestrianise pedestrianised pedestrianises pedestrianising penalise penalised penalises penalising pencilled pencilling personalise personalised personalises personalising pharmacopoeia pharmacopoeias philosophise philosophised philosophises philosophising philtre philtres phoney plagiarise plagiarised plagiarises plagiarising plough ploughed ploughing ploughman ploughmen ploughs ploughshare ploughshares polarisation polarise polarised polarises polarising politicisation politicise politicised politicises politicising popularisation popularise popularised popularises popularising pouffe pouffes practise practised practises practising praesidium praesidiums pressurisation pressurise pressurised pressurises pressurising pretence pretences primaeval prioritisation prioritise prioritised prioritises prioritising privatisation privatisations privatise privatised privatises privatising professionalisation professionalise professionalised professionalises professionalising programme programmes prologue prologues propagandise propagandised propagandises propagandising proselytise proselytised proselytiser proselytisers proselytises proselytising psychoanalyse psychoanalysed psychoanalyses psychoanalysing publicise publicised publicises publicising pulverisation pulverise pulverised pulverises pulverising pummelled pummelling pyjama pyjamas pzazz quarrelled quarrelling radicalise radicalised radicalises radicalising rancour randomise randomised randomises randomising rationalisation rationalisations rationalise rationalised rationalises rationalising ravelled ravelling realisable realisation realisations realise realised realises realising recognisable recognisably recognisance recognise recognised recognises recognising reconnoitre reconnoitred reconnoitres reconnoitring refuelled refuelling regularisation regularise regularised regularises regularising remodelled remodelling remould remoulded remoulding remoulds reorganisation reorganisations reorganise reorganised reorganises reorganising revelled reveller revellers revelling revitalise revitalised revitalises revitalising revolutionise revolutionised revolutionises revolutionising rhapsodise rhapsodised rhapsodises rhapsodising rigour rigours ritualised rivalled rivalling romanticise romanticised romanticises romanticising rumour rumoured rumours sabre sabres saltpetre sanitise sanitised sanitises sanitising satirise satirised satirises satirising saviour saviours savour savoured savouries savouring savours savoury scandalise scandalised scandalises scandalising sceptic sceptical sceptically scepticism sceptics sceptre sceptres scrutinise scrutinised scrutinises scrutinising secularisation secularise secularised secularises secularising sensationalise sensationalised sensationalises sensationalising sensitise sensitised sensitises sensitising sentimentalise sentimentalised sentimentalises sentimentalising sepulchre sepulchres serialisation serialisations serialise serialised serialises serialising sermonise sermonised sermonises sermonising sheikh shovelled shovelling shrivelled shrivelling signalise signalised signalises signalising signalled signalling smoulder smouldered smouldering smoulders snivelled snivelling snorkelled snorkelling snowplough snowploughs socialisation socialise socialised socialises socialising sodomise sodomised sodomises sodomising solemnise solemnised solemnises solemnising sombre specialisation specialisations specialise specialised specialises specialising spectre spectres spiralled spiralling splendour splendours squirrelled squirrelling stabilisation stabilise stabilised stabiliser stabilisers stabilises stabilising standardisation standardise standardised standardises standardising stencilled stencilling sterilisation sterilisations sterilise sterilised steriliser sterilisers sterilises sterilising stigmatisation stigmatise stigmatised stigmatises stigmatising storey storeys subsidisation subsidise subsidised subsidiser subsidisers subsidises subsidising succour succoured succouring succours sulphate sulphates sulphide sulphides sulphur sulphurous summarise summarised summarises summarising swivelled swivelling symbolise symbolised symbolises symbolising sympathise sympathised sympathiser sympathisers sympathises sympathising synchronisation synchronise synchronised synchronises synchronising synthesise synthesised synthesiser synthesisers synthesises synthesising syphon syphoned syphoning syphons systematisation systematise systematised systematises systematising tantalise tantalised tantalises tantalising tantalisingly tasselled technicolour temporise temporised temporises temporising tenderise tenderised tenderises tenderising terrorise terrorised terrorises terrorising theatre theatregoer theatregoers theatres theorise theorised theorises theorising tonne tonnes towelled towelling toxaemia tranquillise tranquillised tranquilliser tranquillisers tranquillises tranquillising tranquillity tranquillize tranquillized tranquillizer tranquillizers tranquillizes tranquillizing tranquilly transistorised traumatise traumatised traumatises traumatising travelled traveller travellers travelling travelogue travelogues trialled trialling tricolour tricolours trivialise trivialised trivialises trivialising tumour tumours tunnelled tunnelling tyrannise tyrannised tyrannises tyrannising tyre tyres unauthorised uncivilised underutilised unequalled unfavourable unfavourably unionisation unionise unionised unionises unionising unorganised unravelled unravelling unrecognisable unrecognised unrivalled unsavoury untrammelled urbanisation urbanise urbanised urbanises urbanising utilisable utilisation utilise utilised utilises utilising valour vandalise vandalised vandalises vandalising vaporisation vaporise vaporised vaporises vaporising vapour vapours verbalise verbalised verbalises verbalising victimisation victimise victimised victimises victimising videodisc videodiscs vigour visualisation visualisations visualise visualised visualises visualising vocalisation vocalisations vocalise vocalised vocalises vocalising vulcanised vulgarisation vulgarise vulgarised vulgarises vulgarising waggon waggons watercolour watercolours weaselled weaselling westernisation westernise westernised westernises westernising womanise womanised womaniser womanisers womanises womanising woollen woollens woollies woolly worshipped worshipping worshipper yodelled yodelling yoghourt yoghourts yoghurt yoghurts'.lower().split() us = 'kerb accessorize accessorized accessorizes accessorizing acclimatization acclimatize acclimatized acclimatizes acclimatizing accouterments eon eons aerogram aerograms airplane airplanes esthete esthetes esthetic esthetically esthetics etiology aging aggrandizement agonize agonized agonizes agonizing agonizingly almanac almanacs aluminum amortizable amortization amortizations amortize amortized amortizes amortizing amphitheater amphitheaters anemia anemic anesthesia anesthetic anesthetics anesthetize anesthetized anesthetizes anesthetizing anesthetist anesthetists anesthetize anesthetized anesthetizes anesthetizing analog analogs analyze analyzed analyzes analyzing anglicize anglicized anglicizes anglicizing annualized antagonize antagonized antagonizes antagonizing apologize apologized apologizes apologizing appall appalls appetizer appetizers appetizing appetizingly arbor arbors archeological archeologically archeologist archeologists archeology ardor armor armored armorer armorers armories armory artifact artifacts authorize authorized authorizes authorizing ax backpedaled backpedaling banister banisters baptize baptized baptizes baptizing bastardize bastardized bastardizes bastardizing battleax balk balked balking balks bedeviled bedeviling behavior behavioral behaviorism behaviorist behaviorists behaviors behoove behooved behooves bejeweled belabor belabored belaboring belabors beveled bevies bevy biased biasing binging bougainvillea bougainvilleas bowdlerize bowdlerized bowdlerizes bowdlerizing breathalyze breathalyzed breathalyzer breathalyzers breathalyzes breathalyzing brutalize brutalized brutalizes brutalizing busses bussing cesarean cesareans caliber calibers caliper calipers calisthenics canalize canalized canalizes canalizing cancelation cancelations canceled canceling candor cannibalize cannibalized cannibalizes cannibalizing canonize canonized canonizes canonizing capitalize capitalized capitalizes capitalizing caramelize caramelized caramelizes caramelizing carbonize carbonized carbonizes carbonizing caroled caroling catalog cataloged catalogs cataloging catalyze catalyzed catalyzes catalyzing categorize categorized categorizes categorizing cauterize cauterized cauterizes cauterizing caviled caviling centigram centigrams centiliter centiliters centimeter centimeters centralize centralized centralizes centralizing center centered centerfold centerfolds centerpiece centerpieces centers channeled channeling characterize characterized characterizes characterizing check checkbook checkbooks checkered checks chili chimera chimeras chiseled chiseling circularize circularized circularizes circularizing civilize civilized civilizes civilizing clamor clamored clamoring clamors clangor clarinetist clarinetists collectivize collectivized collectivizes collectivizing colonization colonize colonized colonizer colonizers colonizes colonizing color colorant colorants colored coloreds colorful colorfully coloring colorize colorized colorizes colorizing colorless colors commercialize commercialized commercializes commercializing compartmentalize compartmentalized compartmentalizes compartmentalizing computerize computerized computerizes computerizing conceptualize conceptualized conceptualizes conceptualizing connection connections contextualize contextualized contextualizes contextualizing cozier cozies coziest cozily coziness cozy councilor councilors counseled counseling counselor counselors crenelated criminalize criminalized criminalizes criminalizing criticize criticized criticizes criticizing crueler cruelest crystallization crystallize crystallized crystallizes crystallizing cudgeled cudgeling customize customized customizes customizing cipher ciphers decentralization decentralize decentralized decentralizes decentralizing decriminalization decriminalize decriminalized decriminalizes decriminalizing defense defenseless defenses dehumanization dehumanize dehumanized dehumanizes dehumanizing demeanor demilitarization demilitarize demilitarized demilitarizes demilitarizing demobilization demobilize demobilized demobilizes demobilizing democratization democratize democratized democratizes democratizing demonize demonized demonizes demonizing demoralization demoralize demoralized demoralizes demoralizing denationalization denationalize denationalized denationalizes denationalizing deodorize deodorized deodorizes deodorizing depersonalize depersonalized depersonalizes depersonalizing deputize deputized deputizes deputizing desensitization desensitize desensitized desensitizes desensitizing destabilization destabilize destabilized destabilizes destabilizing dialed dialing dialog dialogs diarrhea digitize digitized digitizes digitizing disk discolor discolored discoloring discolors disks disemboweled disemboweling disfavor disheveled dishonor dishonorable dishonorably dishonored dishonoring dishonors disorganization disorganized distill distills dramatization dramatizations dramatize dramatized dramatizes dramatizing draft draftboard draftboards draftier draftiest drafts draftsman draftsmanship draftsmen draftswoman draftswomen drafty driveled driveling dueled dueling economize economized economizes economizing edema editorialize editorialized editorializes editorializing empathize empathized empathizes empathizing emphasize emphasized emphasizes emphasizing enameled enameling enamored encyclopedia encyclopedias encyclopedic endeavor endeavored endeavoring endeavors energize energized energizes energizing enroll enrolls enthrall enthralls epaulet epaulets epicenter epicenters epilog epilogs epitomize epitomized epitomizes epitomizing equalization equalize equalized equalizer equalizers equalizes equalizing eulogize eulogized eulogizes eulogizing evangelize evangelized evangelizes evangelizing exorcize exorcized exorcizes exorcizing extemporization extemporize extemporized extemporizes extemporizing externalization externalizations externalize externalized externalizes externalizing factorize factorized factorizes factorizing fecal feces familiarization familiarize familiarized familiarizes familiarizing fantasize fantasized fantasizes fantasizing favor favorable favorably favored favoring favorite favorites favoritism favors feminize feminized feminizes feminizing fertilization fertilize fertilized fertilizer fertilizers fertilizes fertilizing fervor fiber fiberglass fibers fictionalization fictionalizations fictionalize fictionalized fictionalizes fictionalizing filet fileted fileting filets finalization finalize finalized finalizes finalizing flutist flutists flavor flavored flavoring flavorings flavorless flavors flavorsome flier flyer fetal fetid fetus fetuses formalization formalize formalized formalizes formalizing fossilization fossilize fossilized fossilizes fossilizing fraternization fraternize fraternized fraternizes fraternizing fulfill fulfillment fulfills funneled funneling galvanize galvanized galvanizes galvanizing gamboled gamboling jail jailbird jailbirds jailbreak jailbreaks jailed jailer jailers jailing jails gasses gage gaged gages gaging generalization generalizations generalize generalized generalizes generalizing ghettoize ghettoized ghettoizes ghettoizing gypsies glamorize glamorized glamorizes glamorizing glamor globalization globalize globalized globalizes globalizing gluing goiter goiters gonorrhea gram grams graveled gray grayed graying grayish grayness grays groveled groveling groin groins grueling gruelingly griffin griffins gynecological gynecologist gynecologists gynecology hematological hematologist hematologists hematology hemoglobin hemophilia hemophiliac hemophiliacs hemorrhage hemorrhaged hemorrhages hemorrhaging hemorrhoids harbor harbored harboring harbors harmonization harmonize harmonized harmonizes harmonizing homeopath homeopathic homeopaths homeopathy homogenize homogenized homogenizes homogenizing honor honorable honorably honored honoring honors hospitalization hospitalize hospitalized hospitalizes hospitalizing humanize humanized humanizes humanizing humor humored humoring humorless humors hybridize hybridized hybridizes hybridizing hypnotize hypnotized hypnotizes hypnotizing hypothesize hypothesized hypothesizes hypothesizing idealization idealize idealized idealizes idealizing idolize idolized idolizes idolizing immobilization immobilize immobilized immobilizer immobilizers immobilizes immobilizing immortalize immortalized immortalizes immortalizing immunization immunize immunized immunizes immunizing impaneled impaneling imperiled imperiling individualize individualized individualizes individualizing industrialize industrialized industrializes industrializing inflection inflections initialize initialized initializes initializing initialed initialing install installment installments installs instill instills institutionalization institutionalize institutionalized institutionalizes institutionalizing intellectualize intellectualized intellectualizes intellectualizing internalization internalize internalized internalizes internalizing internationalization internationalize internationalized internationalizes internationalizing ionization ionize ionized ionizer ionizers ionizes ionizing italicize italicized italicizes italicizing itemize itemized itemizes itemizing jeopardize jeopardized jeopardizes jeopardizing jeweled jeweler jewelers jewelry judgment kilogram kilograms kilometer kilometers labeled labeling labor labored laborer laborers laboring labors lackluster legalization legalize legalized legalizes legalizing legitimize legitimized legitimizes legitimizing leukemia leveled leveler levelers leveling libeled libeling libelous liberalization liberalize liberalized liberalizes liberalizing license licensed licenses licensing likable lionization lionize lionized lionizes lionizing liquidize liquidized liquidizer liquidizers liquidizes liquidizing liter liters localize localized localizes localizing louver louvered louvers luster magnetize magnetized magnetizes magnetizing maneuverability maneuverable maneuver maneuvered maneuvers maneuvering maneuverings marginalization marginalize marginalized marginalizes marginalizing marshaled marshaling marveled marveling marvelous marvelously materialization materialize materialized materializes materializing maximization maximize maximized maximizes maximizing meager mechanization mechanize mechanized mechanizes mechanizing medieval memorialize memorialized memorializes memorializing memorize memorized memorizes memorizing mesmerize mesmerized mesmerizes mesmerizing metabolize metabolized metabolizes metabolizing meter meters micrometer micrometers militarize militarized militarizes militarizing milligram milligrams milliliter milliliters millimeter millimeters miniaturization miniaturize miniaturized miniaturizes miniaturizing minibusses minimize minimized minimizes minimizing misbehavior misdemeanor misdemeanors misspelled miter miters mobilization mobilize mobilized mobilizes mobilizing modeled modeler modelers modeling modernize modernized modernizes modernizing moisturize moisturized moisturizer moisturizers moisturizes moisturizing monolog monologs monopolization monopolize monopolized monopolizes monopolizing moralize moralized moralizes moralizing motorized mold molded molder moldered moldering molders moldier moldiest molding moldings molds moldy molt molted molting molts mustache mustached mustaches mustachioed multicolored nationalization nationalizations nationalize nationalized nationalizes nationalizing naturalization naturalize naturalized naturalizes naturalizing neighbor neighborhood neighborhoods neighboring neighborliness neighborly neighbors neutralization neutralize neutralized neutralizes neutralizing normalization normalize normalized normalizes normalizing odor odorless odors esophagus esophaguses estrogen offense offenses omelet omelets optimize optimized optimizes optimizing organization organizational organizations organize organized organizer organizers organizes organizing orthopedic orthopedics ostracize ostracized ostracizes ostracizing outmaneuver outmaneuvered outmaneuvers outmaneuvering overemphasize overemphasized overemphasizes overemphasizing oxidization oxidize oxidized oxidizes oxidizing pederast pederasts pediatric pediatrician pediatricians pediatrics pedophile pedophiles pedophilia paleolithic paleontologist paleontologists paleontology paneled paneling panelist panelists paralyze paralyzed paralyzes paralyzing parceled parceling parlor parlors particularize particularized particularizes particularizing passivization passivize passivized passivizes passivizing pasteurization pasteurize pasteurized pasteurizes pasteurizing patronize patronized patronizes patronizing patronizingly pedaled pedaling pedestrianization pedestrianize pedestrianized pedestrianizes pedestrianizing penalize penalized penalizes penalizing penciled penciling personalize personalized personalizes personalizing pharmacopeia pharmacopeias philosophize philosophized philosophizes philosophizing filter filters phony plagiarize plagiarized plagiarizes plagiarizing plow plowed plowing plowman plowmen plows plowshare plowshares polarization polarize polarized polarizes polarizing politicization politicize politicized politicizes politicizing popularization popularize popularized popularizes popularizing pouf poufs practice practiced practices practicing presidium presidiums pressurization pressurize pressurized pressurizes pressurizing pretense pretenses primeval prioritization prioritize prioritized prioritizes prioritizing privatization privatizations privatize privatized privatizes privatizing professionalization professionalize professionalized professionalizes professionalizing program programs prolog prologs propagandize propagandized propagandizes propagandizing proselytize proselytized proselytizer proselytizers proselytizes proselytizing psychoanalyze psychoanalyzed psychoanalyzes psychoanalyzing publicize publicized publicizes publicizing pulverization pulverize pulverized pulverizes pulverizing pummel pummeled pajama pajamas pizzazz quarreled quarreling radicalize radicalized radicalizes radicalizing rancor randomize randomized randomizes randomizing rationalization rationalizations rationalize rationalized rationalizes rationalizing raveled raveling realizable realization realizations realize realized realizes realizing recognizable recognizably recognizance recognize recognized recognizes recognizing reconnoiter reconnoitered reconnoiters reconnoitering refueled refueling regularization regularize regularized regularizes regularizing remodeled remodeling remold remolded remolding remolds reorganization reorganizations reorganize reorganized reorganizes reorganizing reveled reveler revelers reveling revitalize revitalized revitalizes revitalizing revolutionize revolutionized revolutionizes revolutionizing rhapsodize rhapsodized rhapsodizes rhapsodizing rigor rigors ritualized rivaled rivaling romanticize romanticized romanticizes romanticizing rumor rumored rumors saber sabers saltpeter sanitize sanitized sanitizes sanitizing satirize satirized satirizes satirizing savior saviors savor savored savories savoring savors savory scandalize scandalized scandalizes scandalizing skeptic skeptical skeptically skepticism skeptics scepter scepters scrutinize scrutinized scrutinizes scrutinizing secularization secularize secularized secularizes secularizing sensationalize sensationalized sensationalizes sensationalizing sensitize sensitized sensitizes sensitizing sentimentalize sentimentalized sentimentalizes sentimentalizing sepulcher sepulchers serialization serializations serialize serialized serializes serializing sermonize sermonized sermonizes sermonizing sheik shoveled shoveling shriveled shriveling signalize signalized signalizes signalizing signaled signaling smolder smoldered smoldering smolders sniveled sniveling snorkeled snorkeling snowplow snowplow socialization socialize socialized socializes socializing sodomize sodomized sodomizes sodomizing solemnize solemnized solemnizes solemnizing somber specialization specializations specialize specialized specializes specializing specter specters spiraled spiraling splendor splendors squirreled squirreling stabilization stabilize stabilized stabilizer stabilizers stabilizes stabilizing standardization standardize standardized standardizes standardizing stenciled stenciling sterilization sterilizations sterilize sterilized sterilizer sterilizers sterilizes sterilizing stigmatization stigmatize stigmatized stigmatizes stigmatizing story stories subsidization subsidize subsidized subsidizer subsidizers subsidizes subsidizing succor succored succoring succors sulfate sulfates sulfide sulfides sulfur sulfurous summarize summarized summarizes summarizing swiveled swiveling symbolize symbolized symbolizes symbolizing sympathize sympathized sympathizer sympathizers sympathizes sympathizing synchronization synchronize synchronized synchronizes synchronizing synthesize synthesized synthesizer synthesizers synthesizes synthesizing siphon siphoned siphoning siphons systematization systematize systematized systematizes systematizing tantalize tantalized tantalizes tantalizing tantalizingly tasseled technicolor temporize temporized temporizes temporizing tenderize tenderized tenderizes tenderizing terrorize terrorized terrorizes terrorizing theater theatergoer theatergoers theaters theorize theorized theorizes theorizing ton tons toweled toweling toxemia tranquilize tranquilized tranquilizer tranquilizers tranquilizes tranquilizing tranquility tranquilize tranquilized tranquilizer tranquilizers tranquilizes tranquilizing tranquility transistorized traumatize traumatized traumatizes traumatizing traveled traveler travelers traveling travelog travelogs trialed trialing tricolor tricolors trivialize trivialized trivializes trivializing tumor tumors tunneled tunneling tyrannize tyrannized tyrannizes tyrannizing tire tires unauthorized uncivilized underutilized unequaled unfavorable unfavorably unionization unionize unionized unionizes unionizing unorganized unraveled unraveling unrecognizable unrecognized unrivaled unsavory untrammeled urbanization urbanize urbanized urbanizes urbanizing utilizable utilization utilize utilized utilizes utilizing valor vandalize vandalized vandalizes vandalizing vaporization vaporize vaporized vaporizes vaporizing vapor vapors verbalize verbalized verbalizes verbalizing victimization victimize victimized victimizes victimizing videodisk videodisks vigor visualization visualizations visualize visualized visualizes visualizing vocalization vocalizations vocalize vocalized vocalizes vocalizing vulcanized vulgarization vulgarize vulgarized vulgarizes vulgarizing wagon wagons watercolor watercolors weaseled weaseling westernization westernize westernized westernizes westernizing womanize womanized womanizer womanizers womanizes womanizing woolen woolens woolies wooly worshiped worshiping worshiper yodeled yodeling yogurt yogurts yogurt yogurts'.lower().split() uk_us = {} us_uk = {} loop_n = 0 for x in UK: ukUS[x] = US[loopN] loop_n += 1 loop_n = 0 for y in US: usUK[y] = UK[loopN] loop_n += 1
s = [[int(i) for i in input().split(' ')] for j in range(3)] n = [s[i][j] for i in range(3) for j in range(3)] all_n = [[8,1,6,3,5,7,4,9,2],[6,1,8,7,5,3,2,9,4],[4,9,2,3,5,7,8,1,6],[2,9,4,7,5,3,6,1,8],[8,3,4,1,5,9,6,7,2],[4,3,8,9,5,1,2,7,6],[6,7,2,1,5,9,8,3,4],[2,7,6,9,5,1,4,3,8]] allsum=[] for l in all_n: summ=0 for i in range(9): summ+=abs(n[i]-l[i]) allsum.append(summ) # print([abs(n[i]-l[i]) for i in range(9)]) # allsum.append(sum([abs(n[i]-l[i]) for i in range(9)])) print(min(allsum))
s = [[int(i) for i in input().split(' ')] for j in range(3)] n = [s[i][j] for i in range(3) for j in range(3)] all_n = [[8, 1, 6, 3, 5, 7, 4, 9, 2], [6, 1, 8, 7, 5, 3, 2, 9, 4], [4, 9, 2, 3, 5, 7, 8, 1, 6], [2, 9, 4, 7, 5, 3, 6, 1, 8], [8, 3, 4, 1, 5, 9, 6, 7, 2], [4, 3, 8, 9, 5, 1, 2, 7, 6], [6, 7, 2, 1, 5, 9, 8, 3, 4], [2, 7, 6, 9, 5, 1, 4, 3, 8]] allsum = [] for l in all_n: summ = 0 for i in range(9): summ += abs(n[i] - l[i]) allsum.append(summ) print(min(allsum))
BUILTIN_ENGINES = {"spark": "feaflow.engine.spark.SparkEngine"} BUILTIN_SOURCES = { "query": "feaflow.source.query.QuerySource", "pandas": "feaflow.source.pandas.PandasDataFrameSource", } BUILTIN_COMPUTES = {"sql": "feaflow.compute.sql.SqlCompute"} BUILTIN_SINKS = { "table": "feaflow.sink.table.TableSink", "redis": "feaflow.sink.redis.RedisSink", "feature_view": "feaflow.sink.feature_view.FeatureViewSink", }
builtin_engines = {'spark': 'feaflow.engine.spark.SparkEngine'} builtin_sources = {'query': 'feaflow.source.query.QuerySource', 'pandas': 'feaflow.source.pandas.PandasDataFrameSource'} builtin_computes = {'sql': 'feaflow.compute.sql.SqlCompute'} builtin_sinks = {'table': 'feaflow.sink.table.TableSink', 'redis': 'feaflow.sink.redis.RedisSink', 'feature_view': 'feaflow.sink.feature_view.FeatureViewSink'}
""" This module contains everything that calls command line calls. """ class Command(object): base_cmd = ['transmission-remote'] args = [] def run_command(self): return subprocess.check_output(self.base_cmd + self.args, stderr=subprocess.STDOUT) class ListCommand(Command): args = ['-l'] class RemoveCommand(Command): def __init__(self, torrent_id): self.args = ['--remove={0}'.format(torrent_id)]
""" This module contains everything that calls command line calls. """ class Command(object): base_cmd = ['transmission-remote'] args = [] def run_command(self): return subprocess.check_output(self.base_cmd + self.args, stderr=subprocess.STDOUT) class Listcommand(Command): args = ['-l'] class Removecommand(Command): def __init__(self, torrent_id): self.args = ['--remove={0}'.format(torrent_id)]
APP_ID = '390093838084850' DOMAIN = 'https://ef1ac6ba.ngrok.io' COMMENTS_CALLBACK = DOMAIN + \ '/webhook_handler/' MESSENGER_CALLBACK = DOMAIN + \ '/webhook_handler/' VERIFY_TOKEN = '19990402' APP_SECRET = 'e3d24fecd0c82e3c558d9cca9c6edad7'
app_id = '390093838084850' domain = 'https://ef1ac6ba.ngrok.io' comments_callback = DOMAIN + '/webhook_handler/' messenger_callback = DOMAIN + '/webhook_handler/' verify_token = '19990402' app_secret = 'e3d24fecd0c82e3c558d9cca9c6edad7'
# Copyright 2017 Ryan D. Williams # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Module containing helper functions for common tasks related to interacting with the FeedLogs DB Functions: add_nulls_to_vals - replace values that evaluate to false with None build_ins_query - builds an insert query """ def add_nulls_to_vals(columns, vals): """Takes a list of columns to be inserted/updated and a value dictionary. Any columns that are not present in the dictionary keys will be added with a None value, translating to Null in the db. Used to help input dictionarys Args: columns (list of str): column names vals: (dict of str): keys = column names, values = their values Returns: dict: where columns not found in vals.keys() are added with a None value """ new_vals = vals.copy() new_vals.update({col: None for col in columns if col not in vals}) return new_vals def build_ins_query(table, columns, returns=None): """Takes a table name, a list of columns and optional colunns to return after the insert is complete Args: table (str): table to insert into columns (list of str): ordered list of column names return (list of str): inserted column values you wish to return Returns: str: formated query """ qry = 'INSERT INTO {table} {columns_str} VALUES {values_str}' qry_strs = { 'columns_str': '(' + ','.join(columns) + ')', 'values_str': '(' + ','.join(('%(' + col + ')s' for col in columns)) + ')' } if returns: qry += ' RETURNING {returns_str}' qry_strs['returns_str'] = '(' + ','.join(returns) + ')' fmtd_qry = qry.format(table=table, **qry_strs) return fmtd_qry
"""Module containing helper functions for common tasks related to interacting with the FeedLogs DB Functions: add_nulls_to_vals - replace values that evaluate to false with None build_ins_query - builds an insert query """ def add_nulls_to_vals(columns, vals): """Takes a list of columns to be inserted/updated and a value dictionary. Any columns that are not present in the dictionary keys will be added with a None value, translating to Null in the db. Used to help input dictionarys Args: columns (list of str): column names vals: (dict of str): keys = column names, values = their values Returns: dict: where columns not found in vals.keys() are added with a None value """ new_vals = vals.copy() new_vals.update({col: None for col in columns if col not in vals}) return new_vals def build_ins_query(table, columns, returns=None): """Takes a table name, a list of columns and optional colunns to return after the insert is complete Args: table (str): table to insert into columns (list of str): ordered list of column names return (list of str): inserted column values you wish to return Returns: str: formated query """ qry = 'INSERT INTO {table} {columns_str} VALUES {values_str}' qry_strs = {'columns_str': '(' + ','.join(columns) + ')', 'values_str': '(' + ','.join(('%(' + col + ')s' for col in columns)) + ')'} if returns: qry += ' RETURNING {returns_str}' qry_strs['returns_str'] = '(' + ','.join(returns) + ')' fmtd_qry = qry.format(table=table, **qry_strs) return fmtd_qry
bind = '0.0.0.0:5000' workers = 1 backlog = 2048 worker_class = "sync" debug = True proc_name = 'gunicorn.proc' pidfile = '/tmp/gunicorn.pid' logfile = '/var/log/gunicorn/debug.log' loglevel = 'error'
bind = '0.0.0.0:5000' workers = 1 backlog = 2048 worker_class = 'sync' debug = True proc_name = 'gunicorn.proc' pidfile = '/tmp/gunicorn.pid' logfile = '/var/log/gunicorn/debug.log' loglevel = 'error'
def fizzbuzz(i): ''' int -> str If i is divisible by 3, return "Fizz". If i is divisible by 5, return "Buzz". If i is divisible by 3 and 5, return "FizzBuzz".''' if i % 3 == 0 and i % 5 == 0: return ("FizzBuzz") elif i % 3 == 0: return ("Fizz") elif i % 5 == 0: return ("Buzz") else: return (str(i)) numlist = range(1, 101) for i in numlist: print(fizzbuzz(i))
def fizzbuzz(i): """ int -> str If i is divisible by 3, return "Fizz". If i is divisible by 5, return "Buzz". If i is divisible by 3 and 5, return "FizzBuzz".""" if i % 3 == 0 and i % 5 == 0: return 'FizzBuzz' elif i % 3 == 0: return 'Fizz' elif i % 5 == 0: return 'Buzz' else: return str(i) numlist = range(1, 101) for i in numlist: print(fizzbuzz(i))
# Configuration file for the Sphinx documentation builder. # -- Project information project = 'ChemW' copyright = '2022, Andrew Philip Freiburger' author = 'Andrew Philip Freiburger' release = '1' version = '0.3.1'
project = 'ChemW' copyright = '2022, Andrew Philip Freiburger' author = 'Andrew Philip Freiburger' release = '1' version = '0.3.1'
""" Quoridor Online Quentin Deschamps, 2020 """ class Game: """Create a game""" def __init__(self, game_id, nb_players): self.game_id = game_id self.nb_players = nb_players self.connected = [False] * nb_players self.names = [''] * nb_players self.run = False self.current_player = -1 self.last_play = '' self.winner = '' self.wanted_restart = [] def add_player(self, num_player): """Add a player""" self.connected[num_player] = True print(f"[Game {self.game_id}]: player {num_player} added") def add_name(self, data): """Add a player's name""" num_player = int(data.split(';')[1]) name = data.split(';')[2] self.names[num_player] = name print(f"[Game {self.game_id}]: {name} added as player {num_player}") def remove_player(self, num_player): """Remove a player""" self.connected[num_player] = False self.names[num_player] = '' if self.nb_players_connected() == 1: self.run = False self.current_player == -1 else: if num_player == self.current_player: self.current_player = self.next_player(self.current_player) self.last_play = ';'.join(['D', str(num_player)]) print(f"[Game {self.game_id}]: player {num_player} removed") def nb_players_connected(self): """Return the number of players connected""" return self.connected.count(True) def players_missing(self): """Return the number of players missing to start""" return self.nb_players - self.nb_players_connected() def ready(self): """Return True if the game can start""" return self.nb_players_connected() == self.nb_players def next_player(self, current): """Return the new current player""" current = (current + 1) % self.nb_players while not self.connected[current]: current = (current + 1) % self.nb_players return current def get_name_current(self): """Return the name of the current player""" return self.names[self.current_player] def start(self): """Start the game""" self.winner = '' self.current_player = self.next_player(-1) self.run = True print(f"[Game {self.game_id}]: started") def play(self, data): """Get a move""" print(f"[Game {self.game_id}]: move {data}") self.last_play = data if data.split(';')[-1] == 'w': print(f"[Game {self.game_id}]: {self.get_name_current()} wins!") self.winner = self.get_name_current() self.current_player = -1 self.run = False self.wanted_restart = [] else: self.current_player = self.next_player(self.current_player) def restart(self, data): """Restart the game if there are enough players""" num_player = int(data.split(';')[1]) self.wanted_restart.append(num_player) print(f"[Game {self.game_id}]: {self.names[num_player]} asked restart", end=' ') print(f"{len(self.wanted_restart)}/{self.nb_players}") if len(self.wanted_restart) == self.nb_players: self.start() class Games: """Manage games""" def __init__(self, nb_players): self.games = {} self.nb_players = nb_players self.num_player = 0 self.game_id = 0 def find_game(self, game_id): """Find a game""" if game_id in self.games: return self.games[game_id] return None def add_game(self): """Create a new game""" if self.game_id not in self.games: self.num_player = 0 self.games[self.game_id] = Game(self.game_id, self.nb_players) print(f"[Game {self.game_id}]: created") def del_game(self, game_id): """Delete a game""" if game_id in self.games: del self.games[game_id] print(f"[Game {game_id}]: closed") if game_id == self.game_id: self.num_player = 0 def accept_player(self): """Accept a player""" if self.game_id not in self.games: self.add_game() self.games[self.game_id].add_player(self.num_player) return self.game_id, self.num_player def launch_game(self): """Lauch a game""" if self.games[self.game_id].ready(): self.games[self.game_id].start() self.game_id += 1 else: self.num_player += 1 def remove_player(self, game_id, num_player): """Remove a player""" game = self.find_game(game_id) if game is not None: game.remove_player(num_player) if not game.run: self.del_game(game_id)
""" Quoridor Online Quentin Deschamps, 2020 """ class Game: """Create a game""" def __init__(self, game_id, nb_players): self.game_id = game_id self.nb_players = nb_players self.connected = [False] * nb_players self.names = [''] * nb_players self.run = False self.current_player = -1 self.last_play = '' self.winner = '' self.wanted_restart = [] def add_player(self, num_player): """Add a player""" self.connected[num_player] = True print(f'[Game {self.game_id}]: player {num_player} added') def add_name(self, data): """Add a player's name""" num_player = int(data.split(';')[1]) name = data.split(';')[2] self.names[num_player] = name print(f'[Game {self.game_id}]: {name} added as player {num_player}') def remove_player(self, num_player): """Remove a player""" self.connected[num_player] = False self.names[num_player] = '' if self.nb_players_connected() == 1: self.run = False self.current_player == -1 elif num_player == self.current_player: self.current_player = self.next_player(self.current_player) self.last_play = ';'.join(['D', str(num_player)]) print(f'[Game {self.game_id}]: player {num_player} removed') def nb_players_connected(self): """Return the number of players connected""" return self.connected.count(True) def players_missing(self): """Return the number of players missing to start""" return self.nb_players - self.nb_players_connected() def ready(self): """Return True if the game can start""" return self.nb_players_connected() == self.nb_players def next_player(self, current): """Return the new current player""" current = (current + 1) % self.nb_players while not self.connected[current]: current = (current + 1) % self.nb_players return current def get_name_current(self): """Return the name of the current player""" return self.names[self.current_player] def start(self): """Start the game""" self.winner = '' self.current_player = self.next_player(-1) self.run = True print(f'[Game {self.game_id}]: started') def play(self, data): """Get a move""" print(f'[Game {self.game_id}]: move {data}') self.last_play = data if data.split(';')[-1] == 'w': print(f'[Game {self.game_id}]: {self.get_name_current()} wins!') self.winner = self.get_name_current() self.current_player = -1 self.run = False self.wanted_restart = [] else: self.current_player = self.next_player(self.current_player) def restart(self, data): """Restart the game if there are enough players""" num_player = int(data.split(';')[1]) self.wanted_restart.append(num_player) print(f'[Game {self.game_id}]: {self.names[num_player]} asked restart', end=' ') print(f'{len(self.wanted_restart)}/{self.nb_players}') if len(self.wanted_restart) == self.nb_players: self.start() class Games: """Manage games""" def __init__(self, nb_players): self.games = {} self.nb_players = nb_players self.num_player = 0 self.game_id = 0 def find_game(self, game_id): """Find a game""" if game_id in self.games: return self.games[game_id] return None def add_game(self): """Create a new game""" if self.game_id not in self.games: self.num_player = 0 self.games[self.game_id] = game(self.game_id, self.nb_players) print(f'[Game {self.game_id}]: created') def del_game(self, game_id): """Delete a game""" if game_id in self.games: del self.games[game_id] print(f'[Game {game_id}]: closed') if game_id == self.game_id: self.num_player = 0 def accept_player(self): """Accept a player""" if self.game_id not in self.games: self.add_game() self.games[self.game_id].add_player(self.num_player) return (self.game_id, self.num_player) def launch_game(self): """Lauch a game""" if self.games[self.game_id].ready(): self.games[self.game_id].start() self.game_id += 1 else: self.num_player += 1 def remove_player(self, game_id, num_player): """Remove a player""" game = self.find_game(game_id) if game is not None: game.remove_player(num_player) if not game.run: self.del_game(game_id)
""" >>> bus1 = HountedBus(['Alice', 'Bill']) >>> bus1.passengers ['Alice', 'Bill'] >>> bus1.pick('Charlie') >>> bus1.drop('Alice') >>> bus1.passengers ['Bill', 'Charlie'] >>> bus2 = HountedBus() >>> bus2.pick('Carrie') >>> bus2.passengers ['Carrie'] >>> bus3 = HountedBus() >>> bus3.passengers ['Carrie'] >>> bus3.pick('Dave') >>> bus2.passengers ['Carrie', 'Dave'] >>> bus2.passengers is bus3.passengers True >>> bus1.passengers ['Bill', 'Charlie'] >>> dir(HountedBus.__init__) # doctest: +ELLIPSIS ['__annotations__', '__call__', ..., '__defaults__', ...] >>> HountedBus.__init__.__defaults__ (['Carrie', 'Dave'],) >>> HountedBus.__init__.__defaults__[0] is bus2.passengers True """ # BEGIN HAUNTED_BUS_CLASS class HountedBus: """A bus model hounted by ghost passengers""" def __init__(self, passengers=[]): # <1> self.passengers = passengers # <2> def pick(self, name): self.passengers.append(name) # <3> def drop(self, name): self.passengers.remove(name) # END HAUNTED_BUS_CLASS
""" >>> bus1 = HountedBus(['Alice', 'Bill']) >>> bus1.passengers ['Alice', 'Bill'] >>> bus1.pick('Charlie') >>> bus1.drop('Alice') >>> bus1.passengers ['Bill', 'Charlie'] >>> bus2 = HountedBus() >>> bus2.pick('Carrie') >>> bus2.passengers ['Carrie'] >>> bus3 = HountedBus() >>> bus3.passengers ['Carrie'] >>> bus3.pick('Dave') >>> bus2.passengers ['Carrie', 'Dave'] >>> bus2.passengers is bus3.passengers True >>> bus1.passengers ['Bill', 'Charlie'] >>> dir(HountedBus.__init__) # doctest: +ELLIPSIS ['__annotations__', '__call__', ..., '__defaults__', ...] >>> HountedBus.__init__.__defaults__ (['Carrie', 'Dave'],) >>> HountedBus.__init__.__defaults__[0] is bus2.passengers True """ class Hountedbus: """A bus model hounted by ghost passengers""" def __init__(self, passengers=[]): self.passengers = passengers def pick(self, name): self.passengers.append(name) def drop(self, name): self.passengers.remove(name)
""" File: caesar.py Name: Isabelle ------------------------------ This program demonstrates the idea of caesar cipher. Users will be asked to input a number to produce shifted ALPHABET as the cipher table. After that, any strings typed in will be encrypted. """ # This constant shows the original order of alphabetic sequence ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def main(): """ User input the secret number and the string. The program will shift ALPHABET as cipher table and then encrypt the string. """ n=int(input('Secret number: ')) s=input("What's the ciphered string? ").upper() new_alphabet=alphabet(n) decipher(s,new_alphabet) def alphabet(n): """ Shift the ALPHABET as cipher table. :param n: int, necessary number to shift ALPHABET as cipher table :return: str, cipher table """ a='' for i in range((26-n),26): a+=ALPHABET[i] for i in range(26-n): a+=ALPHABET[i] return a def decipher(s,x): """ Encrypt the string the user input :param s: str, string being encrypted :param x: str, cipher table """ b='' for i in s: ch=x.find(i) if ch==-1: # When there is ' ' in the string. b+=i else: b+=ALPHABET[ch] print('The deciphered string is: '+b) ##### DO NOT EDIT THE CODE BELOW THIS LINE ##### if __name__ == '__main__': main()
""" File: caesar.py Name: Isabelle ------------------------------ This program demonstrates the idea of caesar cipher. Users will be asked to input a number to produce shifted ALPHABET as the cipher table. After that, any strings typed in will be encrypted. """ alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' def main(): """ User input the secret number and the string. The program will shift ALPHABET as cipher table and then encrypt the string. """ n = int(input('Secret number: ')) s = input("What's the ciphered string? ").upper() new_alphabet = alphabet(n) decipher(s, new_alphabet) def alphabet(n): """ Shift the ALPHABET as cipher table. :param n: int, necessary number to shift ALPHABET as cipher table :return: str, cipher table """ a = '' for i in range(26 - n, 26): a += ALPHABET[i] for i in range(26 - n): a += ALPHABET[i] return a def decipher(s, x): """ Encrypt the string the user input :param s: str, string being encrypted :param x: str, cipher table """ b = '' for i in s: ch = x.find(i) if ch == -1: b += i else: b += ALPHABET[ch] print('The deciphered string is: ' + b) if __name__ == '__main__': main()
#URL: https://www.hackerrank.com/challenges/two-characters/problem def alternate(l, s): chars = list(set(s)) n = len(chars) maxlen = 0 #print(chars) for i in range(n): for j in range(i+1,n): ch1 = chars[i] ch2 = chars[j] tempans = "" ansl = 0 f = True for ch in s: if ch ==ch1: if (ansl==0) or tempans[-1]==ch2: tempans+=ch ansl+=1 else: f= False break elif ch == ch2: if (ansl==0) or tempans[-1]==ch1: tempans+=ch ansl+=1 else: f=False break if f: maxlen = max(maxlen, ansl) return maxlen
def alternate(l, s): chars = list(set(s)) n = len(chars) maxlen = 0 for i in range(n): for j in range(i + 1, n): ch1 = chars[i] ch2 = chars[j] tempans = '' ansl = 0 f = True for ch in s: if ch == ch1: if ansl == 0 or tempans[-1] == ch2: tempans += ch ansl += 1 else: f = False break elif ch == ch2: if ansl == 0 or tempans[-1] == ch1: tempans += ch ansl += 1 else: f = False break if f: maxlen = max(maxlen, ansl) return maxlen
def arithmetic_arranger(problems, answer=False): # check to see if the list is too long num_problems = len(problems) answers_list = [] top_operand = [] operator = [] bottom_operand = [] # calculate answers, create a list of answers # check to see if there are too many problems if num_problems > 5: return "Error: Too many problems." for problem in problems: problem_list = problem.split() # if too many problems, return error if (len(problem_list[0]) > 4) or (len(problem_list[2]) > 4): return "Error: Numbers cannot be more than four digits." # try/except to look for ValueErrors try: if problem_list[1] == '+': result = int(problem_list[0]) + int(problem_list[2]) elif problem_list[1] == '-': result = int(problem_list[0]) - int(problem_list[2]) # return error if wrong operator else: return "Error: Operator must be '+' or '-'." except ValueError: return "Error: Numbers must only contain digits." answers_list.append(str(result)) top_operand.append(problem_list[0]) operator.append(problem_list[1]) bottom_operand.append(problem_list[2]) # determine lengths # get lengths of all operands, append to list, then determine which to use for spacing purposes top_lengths = [] bottom_lengths = [] actual_lengths = [] for value in top_operand: top_lengths.append(len(value)) for value in bottom_operand: bottom_lengths.append(len(value)) # determine which to use for spacing purposes for i in range(0, len(top_lengths)): if top_lengths[i] >= bottom_lengths[i]: actual_lengths.append(top_lengths[i]) else: actual_lengths.append(bottom_lengths[i]) actual_length_int = (int(actual_lengths[i]) + 2) # is for space/operator actual_lengths[i] = actual_length_int # build string arranged_problems = "" # top row i = 0 for value in top_lengths: space_length = actual_lengths[i] - value spacing = " " * space_length arranged_problems = arranged_problems + spacing arranged_problems = arranged_problems + top_operand[i] arranged_problems = arranged_problems + " " i += 1 arranged_problems = arranged_problems.rstrip() arranged_problems = arranged_problems + "\n" # bottom operands and operators i = 0 for value in bottom_lengths: arranged_problems = arranged_problems + operator[i] + " " space_length = (actual_lengths[i] - 2) - value if space_length > 0: spacing = " " * space_length arranged_problems = arranged_problems + spacing arranged_problems = arranged_problems + bottom_operand[i] arranged_problems = arranged_problems + " " i += 1 arranged_problems = arranged_problems.rstrip() arranged_problems = arranged_problems + "\n" # dashes i = 0 for value in actual_lengths: arranged_problems = arranged_problems + ("-" * actual_lengths[i]) arranged_problems = arranged_problems + " " i += 1 arranged_problems = arranged_problems.rstrip() if answer is True: arranged_problems = arranged_problems + "\n" i = 0 for answer in answers_list: space_length = actual_lengths[i] - len(answer) arranged_problems = arranged_problems + (" " * space_length) arranged_problems = arranged_problems + answer arranged_problems = arranged_problems + " " i += 1 arranged_problems = arranged_problems.rstrip() return arranged_problems
def arithmetic_arranger(problems, answer=False): num_problems = len(problems) answers_list = [] top_operand = [] operator = [] bottom_operand = [] if num_problems > 5: return 'Error: Too many problems.' for problem in problems: problem_list = problem.split() if len(problem_list[0]) > 4 or len(problem_list[2]) > 4: return 'Error: Numbers cannot be more than four digits.' try: if problem_list[1] == '+': result = int(problem_list[0]) + int(problem_list[2]) elif problem_list[1] == '-': result = int(problem_list[0]) - int(problem_list[2]) else: return "Error: Operator must be '+' or '-'." except ValueError: return 'Error: Numbers must only contain digits.' answers_list.append(str(result)) top_operand.append(problem_list[0]) operator.append(problem_list[1]) bottom_operand.append(problem_list[2]) top_lengths = [] bottom_lengths = [] actual_lengths = [] for value in top_operand: top_lengths.append(len(value)) for value in bottom_operand: bottom_lengths.append(len(value)) for i in range(0, len(top_lengths)): if top_lengths[i] >= bottom_lengths[i]: actual_lengths.append(top_lengths[i]) else: actual_lengths.append(bottom_lengths[i]) actual_length_int = int(actual_lengths[i]) + 2 actual_lengths[i] = actual_length_int arranged_problems = '' i = 0 for value in top_lengths: space_length = actual_lengths[i] - value spacing = ' ' * space_length arranged_problems = arranged_problems + spacing arranged_problems = arranged_problems + top_operand[i] arranged_problems = arranged_problems + ' ' i += 1 arranged_problems = arranged_problems.rstrip() arranged_problems = arranged_problems + '\n' i = 0 for value in bottom_lengths: arranged_problems = arranged_problems + operator[i] + ' ' space_length = actual_lengths[i] - 2 - value if space_length > 0: spacing = ' ' * space_length arranged_problems = arranged_problems + spacing arranged_problems = arranged_problems + bottom_operand[i] arranged_problems = arranged_problems + ' ' i += 1 arranged_problems = arranged_problems.rstrip() arranged_problems = arranged_problems + '\n' i = 0 for value in actual_lengths: arranged_problems = arranged_problems + '-' * actual_lengths[i] arranged_problems = arranged_problems + ' ' i += 1 arranged_problems = arranged_problems.rstrip() if answer is True: arranged_problems = arranged_problems + '\n' i = 0 for answer in answers_list: space_length = actual_lengths[i] - len(answer) arranged_problems = arranged_problems + ' ' * space_length arranged_problems = arranged_problems + answer arranged_problems = arranged_problems + ' ' i += 1 arranged_problems = arranged_problems.rstrip() return arranged_problems
# # PySNMP MIB module OUTBOUNDTELNET-PRIVATE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OUTBOUNDTELNET-PRIVATE-MIB # Produced by pysmi-0.3.4 at Wed May 1 14:35:45 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, SingleValueConstraint, ConstraintsIntersection, ValueSizeConstraint, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsIntersection", "ValueSizeConstraint", "ConstraintsUnion") switch, = mibBuilder.importSymbols("QUANTA-SWITCH-MIB", "switch") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") MibScalar, MibTable, MibTableRow, MibTableColumn, NotificationType, ObjectIdentity, Unsigned32, Gauge32, MibIdentifier, iso, IpAddress, Counter32, Bits, Integer32, TimeTicks, Counter64, ModuleIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "NotificationType", "ObjectIdentity", "Unsigned32", "Gauge32", "MibIdentifier", "iso", "IpAddress", "Counter32", "Bits", "Integer32", "TimeTicks", "Counter64", "ModuleIdentity") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") outboundTelnetPrivate = ModuleIdentity((1, 3, 6, 1, 4, 1, 7244, 2, 19)) if mibBuilder.loadTexts: outboundTelnetPrivate.setLastUpdated('201108310000Z') if mibBuilder.loadTexts: outboundTelnetPrivate.setOrganization('QCI') if mibBuilder.loadTexts: outboundTelnetPrivate.setContactInfo(' Customer Support Postal: Quanta Computer Inc. 4, Wen Ming 1 St., Kuei Shan Hsiang, Tao Yuan Shien, Taiwan, R.O.C. Tel: +886 3 328 0050 E-Mail: strong.chen@quantatw.com') if mibBuilder.loadTexts: outboundTelnetPrivate.setDescription('The QCI Private MIB for Outbound Telnet') agentOutboundTelnetGroup = MibIdentifier((1, 3, 6, 1, 4, 1, 7244, 2, 19, 1)) agentOutboundTelnetAdminMode = MibScalar((1, 3, 6, 1, 4, 1, 7244, 2, 19, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("enable", 1), ("disable", 2))).clone('enable')).setMaxAccess("readwrite") if mibBuilder.loadTexts: agentOutboundTelnetAdminMode.setStatus('current') if mibBuilder.loadTexts: agentOutboundTelnetAdminMode.setDescription(' Admin-mode of the Outbound Telnet.') agentOutboundTelnetMaxNoOfSessions = MibScalar((1, 3, 6, 1, 4, 1, 7244, 2, 19, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 5)).clone(5)).setMaxAccess("readwrite") if mibBuilder.loadTexts: agentOutboundTelnetMaxNoOfSessions.setStatus('current') if mibBuilder.loadTexts: agentOutboundTelnetMaxNoOfSessions.setDescription(' The maximum no. of Outbound Telnet sessions allowed.') agentOutboundTelnetTimeout = MibScalar((1, 3, 6, 1, 4, 1, 7244, 2, 19, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 160)).clone(5)).setMaxAccess("readwrite") if mibBuilder.loadTexts: agentOutboundTelnetTimeout.setStatus('current') if mibBuilder.loadTexts: agentOutboundTelnetTimeout.setDescription(' The login inactivity timeout value for Outbound Telnet.') mibBuilder.exportSymbols("OUTBOUNDTELNET-PRIVATE-MIB", outboundTelnetPrivate=outboundTelnetPrivate, agentOutboundTelnetAdminMode=agentOutboundTelnetAdminMode, agentOutboundTelnetTimeout=agentOutboundTelnetTimeout, agentOutboundTelnetGroup=agentOutboundTelnetGroup, agentOutboundTelnetMaxNoOfSessions=agentOutboundTelnetMaxNoOfSessions, PYSNMP_MODULE_ID=outboundTelnetPrivate)
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, constraints_intersection, value_size_constraint, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueSizeConstraint', 'ConstraintsUnion') (switch,) = mibBuilder.importSymbols('QUANTA-SWITCH-MIB', 'switch') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (mib_scalar, mib_table, mib_table_row, mib_table_column, notification_type, object_identity, unsigned32, gauge32, mib_identifier, iso, ip_address, counter32, bits, integer32, time_ticks, counter64, module_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'NotificationType', 'ObjectIdentity', 'Unsigned32', 'Gauge32', 'MibIdentifier', 'iso', 'IpAddress', 'Counter32', 'Bits', 'Integer32', 'TimeTicks', 'Counter64', 'ModuleIdentity') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') outbound_telnet_private = module_identity((1, 3, 6, 1, 4, 1, 7244, 2, 19)) if mibBuilder.loadTexts: outboundTelnetPrivate.setLastUpdated('201108310000Z') if mibBuilder.loadTexts: outboundTelnetPrivate.setOrganization('QCI') if mibBuilder.loadTexts: outboundTelnetPrivate.setContactInfo(' Customer Support Postal: Quanta Computer Inc. 4, Wen Ming 1 St., Kuei Shan Hsiang, Tao Yuan Shien, Taiwan, R.O.C. Tel: +886 3 328 0050 E-Mail: strong.chen@quantatw.com') if mibBuilder.loadTexts: outboundTelnetPrivate.setDescription('The QCI Private MIB for Outbound Telnet') agent_outbound_telnet_group = mib_identifier((1, 3, 6, 1, 4, 1, 7244, 2, 19, 1)) agent_outbound_telnet_admin_mode = mib_scalar((1, 3, 6, 1, 4, 1, 7244, 2, 19, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('enable', 1), ('disable', 2))).clone('enable')).setMaxAccess('readwrite') if mibBuilder.loadTexts: agentOutboundTelnetAdminMode.setStatus('current') if mibBuilder.loadTexts: agentOutboundTelnetAdminMode.setDescription(' Admin-mode of the Outbound Telnet.') agent_outbound_telnet_max_no_of_sessions = mib_scalar((1, 3, 6, 1, 4, 1, 7244, 2, 19, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(0, 5)).clone(5)).setMaxAccess('readwrite') if mibBuilder.loadTexts: agentOutboundTelnetMaxNoOfSessions.setStatus('current') if mibBuilder.loadTexts: agentOutboundTelnetMaxNoOfSessions.setDescription(' The maximum no. of Outbound Telnet sessions allowed.') agent_outbound_telnet_timeout = mib_scalar((1, 3, 6, 1, 4, 1, 7244, 2, 19, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(1, 160)).clone(5)).setMaxAccess('readwrite') if mibBuilder.loadTexts: agentOutboundTelnetTimeout.setStatus('current') if mibBuilder.loadTexts: agentOutboundTelnetTimeout.setDescription(' The login inactivity timeout value for Outbound Telnet.') mibBuilder.exportSymbols('OUTBOUNDTELNET-PRIVATE-MIB', outboundTelnetPrivate=outboundTelnetPrivate, agentOutboundTelnetAdminMode=agentOutboundTelnetAdminMode, agentOutboundTelnetTimeout=agentOutboundTelnetTimeout, agentOutboundTelnetGroup=agentOutboundTelnetGroup, agentOutboundTelnetMaxNoOfSessions=agentOutboundTelnetMaxNoOfSessions, PYSNMP_MODULE_ID=outboundTelnetPrivate)
# automatically generated by the FlatBuffers compiler, do not modify # namespace: FBOutput class PassMask(object): _img = 1 _id = 2 _category = 4 _mask = 8 _depth = 16 _normals = 32 _flow = 64
class Passmask(object): _img = 1 _id = 2 _category = 4 _mask = 8 _depth = 16 _normals = 32 _flow = 64
class Config(): def __init__(self): self.api_token = None self.module_name = None self.port = None self.enable_2fa = None self.creds = None self.seen = set() self.verbose = False
class Config: def __init__(self): self.api_token = None self.module_name = None self.port = None self.enable_2fa = None self.creds = None self.seen = set() self.verbose = False
board=[" "]*9 def draw_board(board): print("|----|----|----|") print("| | | |") print("| "+board[0]+"| "+board[1]+" | "+board[2]+" |") print("| | | |") print("|----|----|----|") print("| | | |") print("| "+board[3]+"| "+board[4]+" | "+board[5]+" |") print("| | | |") print("|----|----|----|") print("| | | |") print("| "+board[6]+"| "+board[7]+" | "+board[8]+" |") print("| | | |") print("|----|----|----|") def check_win(player_mark,board): return( (board[0]==board[1]==board[2]==player_mark) or (board[3]==board[4]==board[5]==player_mark) or (board[6]==board[7]==board[8]==player_mark) or (board[0]==board[3]==board[6]==player_mark) or (board[1]==board[4]==board[7]==player_mark) or (board[2]==board[5]==board[8]==player_mark) or (board[0]==board[4]==board[8]==player_mark) or (board[6]==board[4]==board[2]==player_mark) ) def check_draw(board): return " " not in board def duplicate_board(board): dup=[] for j in board: dup.append(j) return dup def test_win_move(board,player_mark,move): bcopy=duplicate_board(board) bcopy[move]=player_mark return check_win(player_mark,bcopy) def win_strategy(board): #If no place is there to win #then it comes here #Usually person wins by playing #in the corners for i in [0,8,2,6]: if board[i]==" ": return i #next best chance is in the middle if board[4]== " ": return 4 for i in [1,3,5,7]: if board[i]==" ": return i def fork_move(board, player_mark, move): #checking ahead in time if that position #can cause a fork move bcopy=duplicate_board(board) bcopy[move]=player_mark #If winning moves that is, #The player or agent plays in that position # 2 places in which he can play to win winning_moves=0 for i in range(0,9): if bcopy[i]==" " and test_win_move(bcopy,player_mark,i): winning_moves+=1 return winning_moves>=2 def get_agent_move(board): #Return agent move #If there exist a move which will make the agent win for i in range(0,9): if board[i]== " " and test_win_move(board,'X',i): return i #Return player win move #Blocks the player from winning for i in range(0,9): if board[i]== " " and test_win_move(board,"O",i): return i #Return position of fork move #Agent to try and make a fork move for i in range(0,9): if board[i]== " " and fork_move(board,"X",i): return i #Return position of fork move #To block the player from making a fork move for i in range(0,9): if board[i]== " " and fork_move(board,"O",i): return i #if none of these positions are available #then return the best postion to place the agent move return win_strategy(board) def tic_tac_toe(): Playing=True while Playing: InGame=True board=[" "]*9 #X is fixed as agent marker #O is fixed as player marker player_mark="X" print("Playing 1st or 2nd??(Enter 1 or 2)") pref=input() if pref=="1": player_mark="O" while InGame: if player_mark=="O": print("Player's turn") move=int(input()) if board[move]!=" ": print("Invalid move") continue else: move=get_agent_move(board) board[move]=player_mark if check_win(player_mark,board): InGame= False draw_board(board) if player_mark=="X": print("Agent wins") else: print("Player wins") continue if check_draw(board): InGame=False draw_board(board) print("Its a draw") continue draw_board(board) if player_mark=="O": player_mark="X" else: player_mark="O" print("Do you want to continue playing??(Y or N)") inp=input() if inp!= "Y" or inp!="y": Playing=False tic_tac_toe()
board = [' '] * 9 def draw_board(board): print('|----|----|----|') print('| | | |') print('| ' + board[0] + '| ' + board[1] + ' | ' + board[2] + ' |') print('| | | |') print('|----|----|----|') print('| | | |') print('| ' + board[3] + '| ' + board[4] + ' | ' + board[5] + ' |') print('| | | |') print('|----|----|----|') print('| | | |') print('| ' + board[6] + '| ' + board[7] + ' | ' + board[8] + ' |') print('| | | |') print('|----|----|----|') def check_win(player_mark, board): return board[0] == board[1] == board[2] == player_mark or board[3] == board[4] == board[5] == player_mark or board[6] == board[7] == board[8] == player_mark or (board[0] == board[3] == board[6] == player_mark) or (board[1] == board[4] == board[7] == player_mark) or (board[2] == board[5] == board[8] == player_mark) or (board[0] == board[4] == board[8] == player_mark) or (board[6] == board[4] == board[2] == player_mark) def check_draw(board): return ' ' not in board def duplicate_board(board): dup = [] for j in board: dup.append(j) return dup def test_win_move(board, player_mark, move): bcopy = duplicate_board(board) bcopy[move] = player_mark return check_win(player_mark, bcopy) def win_strategy(board): for i in [0, 8, 2, 6]: if board[i] == ' ': return i if board[4] == ' ': return 4 for i in [1, 3, 5, 7]: if board[i] == ' ': return i def fork_move(board, player_mark, move): bcopy = duplicate_board(board) bcopy[move] = player_mark winning_moves = 0 for i in range(0, 9): if bcopy[i] == ' ' and test_win_move(bcopy, player_mark, i): winning_moves += 1 return winning_moves >= 2 def get_agent_move(board): for i in range(0, 9): if board[i] == ' ' and test_win_move(board, 'X', i): return i for i in range(0, 9): if board[i] == ' ' and test_win_move(board, 'O', i): return i for i in range(0, 9): if board[i] == ' ' and fork_move(board, 'X', i): return i for i in range(0, 9): if board[i] == ' ' and fork_move(board, 'O', i): return i return win_strategy(board) def tic_tac_toe(): playing = True while Playing: in_game = True board = [' '] * 9 player_mark = 'X' print('Playing 1st or 2nd??(Enter 1 or 2)') pref = input() if pref == '1': player_mark = 'O' while InGame: if player_mark == 'O': print("Player's turn") move = int(input()) if board[move] != ' ': print('Invalid move') continue else: move = get_agent_move(board) board[move] = player_mark if check_win(player_mark, board): in_game = False draw_board(board) if player_mark == 'X': print('Agent wins') else: print('Player wins') continue if check_draw(board): in_game = False draw_board(board) print('Its a draw') continue draw_board(board) if player_mark == 'O': player_mark = 'X' else: player_mark = 'O' print('Do you want to continue playing??(Y or N)') inp = input() if inp != 'Y' or inp != 'y': playing = False tic_tac_toe()
""" Script testing 3.4.1 control from OWASP ASVS 4.0: 'Verify that cookie-based session tokens have the 'Secure' attribute set.' The script will raise an alert if 'Secure' attribute is not present. """ def scan(ps, msg, src): #find "Set-Cookie" header headerCookie = str(msg.getResponseHeader().getHeader("Set-Cookie")) #alert parameters alertRisk= 1 alertConfidence = 2 alertTitle = "3.4.1 Verify that cookie-based session tokens have the 'Secure' attribute set." alertDescription = "The secure attribute is an option that can be set by the application server when sending a new cookie to the user within an HTTP Response. The purpose of the secure attribute is to prevent cookies from being observed by unauthorized parties due to the transmission of the cookie in clear text. To accomplish this goal, browsers which support the secure attribute will only send cookies with the secure attribute when the request is going to an HTTPS page. Said in another way, the browser will not send a cookie with the secure attribute set over an unencrypted HTTP request. By setting the secure attribute, the browser will prevent the transmission of a cookie over an unencrypted channel." url = msg.getRequestHeader().getURI().toString() alertParam = "" alertAttack = "" alertInfo = "https://owasp.org/www-community/controls/SecureCookieAttribute" alertSolution = "Add 'Secure' attribute when sending cookie." alertEvidence = "" cweID = 614 wascID = 0 #if "Set-Cookie" header does not have "secure" attribute, raise alert if ((headerCookie != "None") and "secure" not in headerCookie.lower()): ps.raiseAlert(alertRisk, alertConfidence, alertTitle, alertDescription, url, alertParam, alertAttack, alertInfo, alertSolution, alertEvidence, cweID, wascID, msg);
""" Script testing 3.4.1 control from OWASP ASVS 4.0: 'Verify that cookie-based session tokens have the 'Secure' attribute set.' The script will raise an alert if 'Secure' attribute is not present. """ def scan(ps, msg, src): header_cookie = str(msg.getResponseHeader().getHeader('Set-Cookie')) alert_risk = 1 alert_confidence = 2 alert_title = "3.4.1 Verify that cookie-based session tokens have the 'Secure' attribute set." alert_description = 'The secure attribute is an option that can be set by the application server when sending a new cookie to the user within an HTTP Response. The purpose of the secure attribute is to prevent cookies from being observed by unauthorized parties due to the transmission of the cookie in clear text. To accomplish this goal, browsers which support the secure attribute will only send cookies with the secure attribute when the request is going to an HTTPS page. Said in another way, the browser will not send a cookie with the secure attribute set over an unencrypted HTTP request. By setting the secure attribute, the browser will prevent the transmission of a cookie over an unencrypted channel.' url = msg.getRequestHeader().getURI().toString() alert_param = '' alert_attack = '' alert_info = 'https://owasp.org/www-community/controls/SecureCookieAttribute' alert_solution = "Add 'Secure' attribute when sending cookie." alert_evidence = '' cwe_id = 614 wasc_id = 0 if headerCookie != 'None' and 'secure' not in headerCookie.lower(): ps.raiseAlert(alertRisk, alertConfidence, alertTitle, alertDescription, url, alertParam, alertAttack, alertInfo, alertSolution, alertEvidence, cweID, wascID, msg)
__example_payload__ = "AND 1=1" __type__ = "putting the payload in-between a comment with obfuscation in it" def tamper(payload, **kwargs): return "/*!00000{}*/".format(payload)
__example_payload__ = 'AND 1=1' __type__ = 'putting the payload in-between a comment with obfuscation in it' def tamper(payload, **kwargs): return '/*!00000{}*/'.format(payload)
class Employee: raise_amount = 1.04 employee_Amount = 0 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@companyemail' Employee.employee_Amount += 1 def fullname(self): return '{} {}{}{}'.format(self.first, self.last, self.first) def apply_raise(self): self.pay = int(self.pay * Employee.raise_amount) @classmethod def set_raise_amt(cls, amount): cls.raise_amount = amount emp1 = Employee('herold', 'bob', 500) print(emp1.pay) emp1.apply_raise() print(emp1.pay) print(Employee.employee_Amount) print(emp1.fullname())
class Employee: raise_amount = 1.04 employee__amount = 0 def __init__(self, first, last, pay): self.first = first self.last = last self.pay = pay self.email = first + '.' + last + '@companyemail' Employee.employee_Amount += 1 def fullname(self): return '{} {}{}{}'.format(self.first, self.last, self.first) def apply_raise(self): self.pay = int(self.pay * Employee.raise_amount) @classmethod def set_raise_amt(cls, amount): cls.raise_amount = amount emp1 = employee('herold', 'bob', 500) print(emp1.pay) emp1.apply_raise() print(emp1.pay) print(Employee.employee_Amount) print(emp1.fullname())
class Editor(object): def __init__(self): self.color = '0 143 192' self.visgroupshown = 1 self.visgroupautoshown = 1 def __str__(self): out_str = 'editor\n\t\t{\n' out_str += f'\t\t\t\"color\" \"{self.color}\"\n' out_str += f'\t\t\t\"visgroupshown\" \"{self.visgroupshown}\"\n' out_str += f'\t\t\t\"visgroupautoshown\" \"{self.visgroupautoshown}\"\n' out_str += '\t\t}\n' return out_str
class Editor(object): def __init__(self): self.color = '0 143 192' self.visgroupshown = 1 self.visgroupautoshown = 1 def __str__(self): out_str = 'editor\n\t\t{\n' out_str += f'\t\t\t"color" "{self.color}"\n' out_str += f'\t\t\t"visgroupshown" "{self.visgroupshown}"\n' out_str += f'\t\t\t"visgroupautoshown" "{self.visgroupautoshown}"\n' out_str += '\t\t}\n' return out_str
class SharpSpringException(Exception): pass
class Sharpspringexception(Exception): pass
t = int(input()) for _ in range(t): n = int(input()) s = input() dic = {} for i in s: if i not in dic: dic[i] = 1 else: dic[i] += 1 is_yes = True for key in dic: if(dic[key] % 2 == 1): is_yes = False break if(is_yes): print("YES") else: print("NO")
t = int(input()) for _ in range(t): n = int(input()) s = input() dic = {} for i in s: if i not in dic: dic[i] = 1 else: dic[i] += 1 is_yes = True for key in dic: if dic[key] % 2 == 1: is_yes = False break if is_yes: print('YES') else: print('NO')
# Space: O(l) # Time: O(m * n * l) class Solution: def exist(self, board, word) -> bool: column_length = len(board) row_length = len(board[0]) word_length = len(word) def dfs(x, y, index): if index >= word_length: return True if (not 0 <= x < row_length) or (not 0 <= y < column_length): return False if board[y][x] != word[index]: return False temp = board[y][x] board[y][x] = '*' if dfs(x - 1, y, index + 1): return True if dfs(x + 1, y, index + 1): return True if dfs(x, y - 1, index + 1): return True if dfs(x, y + 1, index + 1): return True board[y][x] = temp for column in range(column_length): for row in range(row_length): if dfs(row, column, 0): return True return False
class Solution: def exist(self, board, word) -> bool: column_length = len(board) row_length = len(board[0]) word_length = len(word) def dfs(x, y, index): if index >= word_length: return True if not 0 <= x < row_length or not 0 <= y < column_length: return False if board[y][x] != word[index]: return False temp = board[y][x] board[y][x] = '*' if dfs(x - 1, y, index + 1): return True if dfs(x + 1, y, index + 1): return True if dfs(x, y - 1, index + 1): return True if dfs(x, y + 1, index + 1): return True board[y][x] = temp for column in range(column_length): for row in range(row_length): if dfs(row, column, 0): return True return False
class User: def __init__(self, login, password): self._login = login self._password = password @property def login(self): return self._login @property def password(self): return self._password class Operation: def __init__(self, a, func, b): self._a = a self._func = func self._b = b def result(): return self._func(a, b)
class User: def __init__(self, login, password): self._login = login self._password = password @property def login(self): return self._login @property def password(self): return self._password class Operation: def __init__(self, a, func, b): self._a = a self._func = func self._b = b def result(): return self._func(a, b)
internCache = {} # XXX: upper bound on size somehow def intern(klass, vm, method, frame): string = frame.get_local(0) value = string._values['value'] if value in internCache: return internCache[value] internCache[value] = string return string
intern_cache = {} def intern(klass, vm, method, frame): string = frame.get_local(0) value = string._values['value'] if value in internCache: return internCache[value] internCache[value] = string return string
for _ in range(int(input())): s = input().split() for i in range(2, len(s)): print(s[i], end=' ') print(s[0]+' '+s[1])
for _ in range(int(input())): s = input().split() for i in range(2, len(s)): print(s[i], end=' ') print(s[0] + ' ' + s[1])
""" return every upper case character from a text """ def only_upper(string): text = "" for char in string: if char.isupper(): text += char return text if __name__ == "__main__": # get cipher from file if unavailable cipher = input("paste the text here: ") if cipher == '': file_location = input("file location: ") with open(file_location, encoding='utf-8') as file: cipher = file.read() print(only_upper(cipher))
""" return every upper case character from a text """ def only_upper(string): text = '' for char in string: if char.isupper(): text += char return text if __name__ == '__main__': cipher = input('paste the text here: ') if cipher == '': file_location = input('file location: ') with open(file_location, encoding='utf-8') as file: cipher = file.read() print(only_upper(cipher))
# https://stepik.org/lesson/5047/step/5?unit=1086 # Sample Input 1: # 8 # 2 # 14 # Sample Output 1: # 14 # 2 # 8 # Sample Input 2: # 23 # 23 # 21 # Sample Output 2: # 23 # 21 # 23 max, min, other = a, b, c = int(input()), int(input()), int(input()) if b > max: max, min = b, a if c > max: max, min, other = c, a, b if (min > other): min, other = other, min print(max, min, other, sep='\n')
(max, min, other) = (a, b, c) = (int(input()), int(input()), int(input())) if b > max: (max, min) = (b, a) if c > max: (max, min, other) = (c, a, b) if min > other: (min, other) = (other, min) print(max, min, other, sep='\n')
p=int(input("Enter the size of list : ")) l=p x=[] while(l): x.append(input("Enter elements : ")) l=l-1 print(x) while(True) : option= int(input("Do you want to :\n1.Pop\n2Remove\n3.Exit\n4.Insert\n5.Append\n6.Search\n7.Sort\n8.Reverse\n9.DecSort ?\n")) if(option == 1): #POP n=int(input("Enter the index you want to pop : ")) x.pop(n) print(x) elif(option == 2): #Remove n=(input("Enter the element you want to remove : ")) x.remove(n) print(x) elif(option == 3): #Exit exit elif(option == 4): #Insert n=int(input("Enter the position : ")) value = input("Enter the element : ") x.insert(n,value) print(x) elif(option == 5): #Append value = input("Enter the element you want to insert : ") x.append(value) print(x) elif (option == 6): #search Index n=input("Enter the element you want to search ? ") if x.index(n) : print("Found at " + str(x.index(n))) else : print("Not Found") elif (option == 7): #Sort x.sort() print(x) elif (option == 8): #Reverse x.reverse() print(x) elif (option == 9): #Decending order x=sorted(x) x.reverse() print(x)
p = int(input('Enter the size of list : ')) l = p x = [] while l: x.append(input('Enter elements : ')) l = l - 1 print(x) while True: option = int(input('Do you want to :\n1.Pop\n2Remove\n3.Exit\n4.Insert\n5.Append\n6.Search\n7.Sort\n8.Reverse\n9.DecSort ?\n')) if option == 1: n = int(input('Enter the index you want to pop : ')) x.pop(n) print(x) elif option == 2: n = input('Enter the element you want to remove : ') x.remove(n) print(x) elif option == 3: exit elif option == 4: n = int(input('Enter the position : ')) value = input('Enter the element : ') x.insert(n, value) print(x) elif option == 5: value = input('Enter the element you want to insert : ') x.append(value) print(x) elif option == 6: n = input('Enter the element you want to search ? ') if x.index(n): print('Found at ' + str(x.index(n))) else: print('Not Found') elif option == 7: x.sort() print(x) elif option == 8: x.reverse() print(x) elif option == 9: x = sorted(x) x.reverse() print(x)
''' Python Code Snippets - stevepython.wordpress.com 149-Convert KMH to MPH Source: https://www.pythonforbeginners.com/code-snippets-source-code/ python-code-convert-kmh-to-mph/ ''' kmh = int(input("Enter km/h: ")) mph = 0.6214 * kmh print ("Speed:", kmh, "KM/H = ", mph, "MPH")
""" Python Code Snippets - stevepython.wordpress.com 149-Convert KMH to MPH Source: https://www.pythonforbeginners.com/code-snippets-source-code/ python-code-convert-kmh-to-mph/ """ kmh = int(input('Enter km/h: ')) mph = 0.6214 * kmh print('Speed:', kmh, 'KM/H = ', mph, 'MPH')
#!/usr/bin/env python # -*- coding: utf-8 -*- opticalIsomers = 2 energy = { 'CBS-QB3': GaussianLog('TS07.log'), 'CCSD(T)-F12/cc-pVTZ-F12': MolproLog('TS07_f12.out'), #'CCSD(T)-F12/cc-pVTZ-F12': -382.96546696009017 } frequencies = GaussianLog('TS07freq.log') rotors = [HinderedRotor(scanLog=ScanLog('scan_0.log'), pivots=[2,4], top=[4,5,6,7], symmetry=3), HinderedRotor(scanLog=ScanLog('scan_1.log'), pivots=[2,8], top=[8,9,10,11], symmetry=3), HinderedRotor(scanLog=ScanLog('scan_2.log'), pivots=[2,1], top=[1,12,13,14,15,16], symmetry=1), ]
optical_isomers = 2 energy = {'CBS-QB3': gaussian_log('TS07.log'), 'CCSD(T)-F12/cc-pVTZ-F12': molpro_log('TS07_f12.out')} frequencies = gaussian_log('TS07freq.log') rotors = [hindered_rotor(scanLog=scan_log('scan_0.log'), pivots=[2, 4], top=[4, 5, 6, 7], symmetry=3), hindered_rotor(scanLog=scan_log('scan_1.log'), pivots=[2, 8], top=[8, 9, 10, 11], symmetry=3), hindered_rotor(scanLog=scan_log('scan_2.log'), pivots=[2, 1], top=[1, 12, 13, 14, 15, 16], symmetry=1)]
class AdditionalInfoMeta(object): """Attributes that can enhance the discoverability of a resource.""" KEY = 'additionalInformation' VALUES_KEYS = ( 'categories', 'copyrightHolder', 'description', 'inLanguage', 'links', 'tags', 'updateFrequency', 'structuredMarkup', 'poseidonHash', 'providerKey', 'workExample' ) REQUIRED_VALUES_KEYS = tuple() class CurationMeta(object): """To normalize the different possible rating attributes after a curation process.""" KEY = 'curation' VALUES_KEYS = ( "rating", "numVotes", "schema", 'isListed' ) REQUIRED_VALUES_KEYS = {'rating', 'numVotes'} class MetadataMain(object): """The main attributes that need to be included in the Asset Metadata.""" KEY = 'main' VALUES_KEYS = { 'author', 'name', 'type', 'dateCreated', 'license', 'price', 'files' } REQUIRED_VALUES_KEYS = {'name', 'dateCreated', 'author', 'license', 'price', 'files'} class Metadata(object): """Every Asset (dataset, algorithm, etc.) in a Nevermined Network has an associated Decentralized Identifier (DID) and DID document / DID Descriptor Object (DDO).""" REQUIRED_SECTIONS = {MetadataMain.KEY} MAIN_SECTIONS = { MetadataMain.KEY: MetadataMain, CurationMeta.KEY: CurationMeta, AdditionalInfoMeta.KEY: AdditionalInfoMeta } @staticmethod def validate(metadata): """Validator of the metadata composition :param metadata: conforming to the Metadata accepted by Nevermined, dict :return: bool """ # validate required sections and their sub items for section_key in Metadata.REQUIRED_SECTIONS: if section_key not in metadata or not metadata[section_key] or not isinstance( metadata[section_key], dict): return False section = Metadata.MAIN_SECTIONS[section_key] section_metadata = metadata[section_key] for subkey in section.REQUIRED_VALUES_KEYS: if subkey not in section_metadata or section_metadata[subkey] is None: return False return True
class Additionalinfometa(object): """Attributes that can enhance the discoverability of a resource.""" key = 'additionalInformation' values_keys = ('categories', 'copyrightHolder', 'description', 'inLanguage', 'links', 'tags', 'updateFrequency', 'structuredMarkup', 'poseidonHash', 'providerKey', 'workExample') required_values_keys = tuple() class Curationmeta(object): """To normalize the different possible rating attributes after a curation process.""" key = 'curation' values_keys = ('rating', 'numVotes', 'schema', 'isListed') required_values_keys = {'rating', 'numVotes'} class Metadatamain(object): """The main attributes that need to be included in the Asset Metadata.""" key = 'main' values_keys = {'author', 'name', 'type', 'dateCreated', 'license', 'price', 'files'} required_values_keys = {'name', 'dateCreated', 'author', 'license', 'price', 'files'} class Metadata(object): """Every Asset (dataset, algorithm, etc.) in a Nevermined Network has an associated Decentralized Identifier (DID) and DID document / DID Descriptor Object (DDO).""" required_sections = {MetadataMain.KEY} main_sections = {MetadataMain.KEY: MetadataMain, CurationMeta.KEY: CurationMeta, AdditionalInfoMeta.KEY: AdditionalInfoMeta} @staticmethod def validate(metadata): """Validator of the metadata composition :param metadata: conforming to the Metadata accepted by Nevermined, dict :return: bool """ for section_key in Metadata.REQUIRED_SECTIONS: if section_key not in metadata or not metadata[section_key] or (not isinstance(metadata[section_key], dict)): return False section = Metadata.MAIN_SECTIONS[section_key] section_metadata = metadata[section_key] for subkey in section.REQUIRED_VALUES_KEYS: if subkey not in section_metadata or section_metadata[subkey] is None: return False return True
def read_list(t): return [t(x) for x in input().split()] def read_line(t): return t(input()) def read_lines(t, N): return [t(input()) for _ in range(N)] for i in range(read_line(int)): N = read_line(int) print(min(read_list(int)) * (N-1))
def read_list(t): return [t(x) for x in input().split()] def read_line(t): return t(input()) def read_lines(t, N): return [t(input()) for _ in range(N)] for i in range(read_line(int)): n = read_line(int) print(min(read_list(int)) * (N - 1))
#assert True == True def mean(num_list): try: mean = sum(num_list)/float(len(num_list)) if isinstance(mean, complex): return NotImplemented return mean except ZeroDivisionError as detail: msg = "\nCannot compute the mean value of an empty list." raise ZeroDivisionError(detail.__str__()+ msg) except TypeError as detail: msg = "\nPlease pass a list of numbers not strings" raise TypeError(detail.__str__()+ msg)
def mean(num_list): try: mean = sum(num_list) / float(len(num_list)) if isinstance(mean, complex): return NotImplemented return mean except ZeroDivisionError as detail: msg = '\nCannot compute the mean value of an empty list.' raise zero_division_error(detail.__str__() + msg) except TypeError as detail: msg = '\nPlease pass a list of numbers not strings' raise type_error(detail.__str__() + msg)
def solution(clothes): style = dict() for i in clothes: if i[1] not in style: style[i[1]]=1 else : style[i[1]]+=1 print(style) answer =1 for i in style.values(): answer*=(i+1) return answer-1
def solution(clothes): style = dict() for i in clothes: if i[1] not in style: style[i[1]] = 1 else: style[i[1]] += 1 print(style) answer = 1 for i in style.values(): answer *= i + 1 return answer - 1
# tunnels at level = 0 #https://www.openstreetmap.org/way/167952621 assert_has_feature( 18, 41903, 101298, "roads", {"kind": "highway", "highway": "motorway", "id": 167952621, "name": "Presidio Pkwy.", "is_tunnel": True, "sort_key": 331}) # http://www.openstreetmap.org/way/89912879 assert_has_feature( 16, 19829, 24234, "roads", {"kind": "major_road", "highway": "trunk", "id": 89912879, "name": "Sullivan Square Underpass", "is_tunnel": True, "sort_key": 329}) #https://www.openstreetmap.org/way/117837633 assert_has_feature( 18, 67234, 97737, "roads", {"kind": "major_road", "highway": "primary", "id": 117837633, "name": "Dixie Hwy.", "is_tunnel": True, "sort_key": 328}) #https://www.openstreetmap.org/way/57782075 assert_has_feature( 18, 67251, 97566, "roads", {"kind": "major_road", "highway": "secondary", "id": 57782075, "name": "S Halsted St.", "is_tunnel": True, "sort_key": 327}) #https://www.openstreetmap.org/way/57708079 assert_has_feature( 18, 67255, 97547, "roads", {"kind": "major_road", "highway": "tertiary", "id": 57708079, "name": "W 74th St.", "is_tunnel": True, "sort_key": 326}) #https://www.openstreetmap.org/way/56393654 assert_has_feature( 18, 67233, 97449, "roads", {"kind": "minor_road", "highway": "residential", "id": 56393654, "name": "S Paulina St.", "is_tunnel": True, "sort_key": 310}) #https://www.openstreetmap.org/way/190835369 assert_has_feature( 18, 67258, 97452, "roads", {"kind": "minor_road", "highway": "service", "id": 190835369, "name": "S Wong Pkwy.", "is_tunnel": True, "sort_key": 308})
assert_has_feature(18, 41903, 101298, 'roads', {'kind': 'highway', 'highway': 'motorway', 'id': 167952621, 'name': 'Presidio Pkwy.', 'is_tunnel': True, 'sort_key': 331}) assert_has_feature(16, 19829, 24234, 'roads', {'kind': 'major_road', 'highway': 'trunk', 'id': 89912879, 'name': 'Sullivan Square Underpass', 'is_tunnel': True, 'sort_key': 329}) assert_has_feature(18, 67234, 97737, 'roads', {'kind': 'major_road', 'highway': 'primary', 'id': 117837633, 'name': 'Dixie Hwy.', 'is_tunnel': True, 'sort_key': 328}) assert_has_feature(18, 67251, 97566, 'roads', {'kind': 'major_road', 'highway': 'secondary', 'id': 57782075, 'name': 'S Halsted St.', 'is_tunnel': True, 'sort_key': 327}) assert_has_feature(18, 67255, 97547, 'roads', {'kind': 'major_road', 'highway': 'tertiary', 'id': 57708079, 'name': 'W 74th St.', 'is_tunnel': True, 'sort_key': 326}) assert_has_feature(18, 67233, 97449, 'roads', {'kind': 'minor_road', 'highway': 'residential', 'id': 56393654, 'name': 'S Paulina St.', 'is_tunnel': True, 'sort_key': 310}) assert_has_feature(18, 67258, 97452, 'roads', {'kind': 'minor_road', 'highway': 'service', 'id': 190835369, 'name': 'S Wong Pkwy.', 'is_tunnel': True, 'sort_key': 308})
''' Kattis - rijeci from fibo(0) = 0, fibo(1) = 1, output the x-1th and xth fibo numbers, x <= 45 Simply use a for loop. Time: O(x), Space: O(1) ''' x = int(input()) a = 1 b = 0 for i in range(x): a, b = b, a+b print(a, b)
""" Kattis - rijeci from fibo(0) = 0, fibo(1) = 1, output the x-1th and xth fibo numbers, x <= 45 Simply use a for loop. Time: O(x), Space: O(1) """ x = int(input()) a = 1 b = 0 for i in range(x): (a, b) = (b, a + b) print(a, b)
"""This module contains class Task for represent single task entity, class TaskStatus""" class TaskStatus: OPENED = 'opened' SOLVED = 'solved' ACTIVATED = 'activated' FAILED = 'failed' class RelatedTaskType: """ This class defines constants which using in related tasks """ BLOCKER = 'blocker' CONTROLLER = 'controller' class Task: """ This class defines single task entity attributes """ def __init__(self, name, key, queue=None, description=None, parent=None, related=None, author=None, responsible: list=None, priority=0, progress=0, start=None, deadline=None, tags=None, reminder=None, creating_time=None): self.name = name self.queue = queue self.description = description self.parent = parent self.sub_tasks = [] self.related = related self.author = author self.priority = priority self.progress = progress self.start = start self.deadline = deadline self.tags = tags self.reminder = reminder self.status = TaskStatus.OPENED self.key = key self.creating_time = creating_time self.editing_time = creating_time if responsible is None: self.responsible = [] else: self.responsible = responsible
"""This module contains class Task for represent single task entity, class TaskStatus""" class Taskstatus: opened = 'opened' solved = 'solved' activated = 'activated' failed = 'failed' class Relatedtasktype: """ This class defines constants which using in related tasks """ blocker = 'blocker' controller = 'controller' class Task: """ This class defines single task entity attributes """ def __init__(self, name, key, queue=None, description=None, parent=None, related=None, author=None, responsible: list=None, priority=0, progress=0, start=None, deadline=None, tags=None, reminder=None, creating_time=None): self.name = name self.queue = queue self.description = description self.parent = parent self.sub_tasks = [] self.related = related self.author = author self.priority = priority self.progress = progress self.start = start self.deadline = deadline self.tags = tags self.reminder = reminder self.status = TaskStatus.OPENED self.key = key self.creating_time = creating_time self.editing_time = creating_time if responsible is None: self.responsible = [] else: self.responsible = responsible
# 1st solution # O(1) time | O(1) space class Solution: def bitwiseComplement(self, n: int) -> int: k = 1 while k < n: k = (k << 1) | 1 return k - n
class Solution: def bitwise_complement(self, n: int) -> int: k = 1 while k < n: k = k << 1 | 1 return k - n
# -*- coding: utf-8 -*- """ The MIT License (MIT) Copyright (c) 2019 Lorenzo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ __all__ = ( "PokemonException", "PokeAPIException", "RateLimited", "NotFound", "Forbidden", "NoMoreItems" ) class PokemonException(Exception): """The base exception for this wrapper.""" class PokeAPIException(PokemonException): """Exception raised when an HTTP request is not successful. Attributes ---------- response: :class:`aiohttp.ClientResponse` The failed HTTP response. status: :class:`int` The HTTP status code. message: :class:`str` A, hopefully, useful exception message.""" def __init__(self, response, message: str): self.response = response self.status = response.status self.message = "API responded with status code {0} {2}: {1}".format(self.status, message, response.reason) super().__init__(self.message) class RateLimited(PokeAPIException): """Exception raised when an HTTP request is equal to 429 TOO MANY REQUESTS. This exception will only raise if you surpass 100 requests per minutes, if you need more requests then that it would be better to host your own API instance. This inherits from :exc:`PokeAPIException`.""" class NotFound(PokeAPIException): """Exception raised when an HTTP request response code is equal to 404 NOT FOUND. This inherits from :exc:`PokeAPIException`.""" class Forbidden(PokeAPIException): """Exception raised when an HTTP request response code is equal to 403 FORBIDDEN. This inherits from :exc:`PokeAPIException`.""" class NoMoreItems(PokemonException): """Exception raised when an AsyncIterator is empty. This is usually catched to stop the iteration, unless you directly use the :meth:`AsyncPaginationIterator.next` method you shouldn't worry about it too much. .. versionadded:: 0.1.0a"""
""" The MIT License (MIT) Copyright (c) 2019 Lorenzo Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ __all__ = ('PokemonException', 'PokeAPIException', 'RateLimited', 'NotFound', 'Forbidden', 'NoMoreItems') class Pokemonexception(Exception): """The base exception for this wrapper.""" class Pokeapiexception(PokemonException): """Exception raised when an HTTP request is not successful. Attributes ---------- response: :class:`aiohttp.ClientResponse` The failed HTTP response. status: :class:`int` The HTTP status code. message: :class:`str` A, hopefully, useful exception message.""" def __init__(self, response, message: str): self.response = response self.status = response.status self.message = 'API responded with status code {0} {2}: {1}'.format(self.status, message, response.reason) super().__init__(self.message) class Ratelimited(PokeAPIException): """Exception raised when an HTTP request is equal to 429 TOO MANY REQUESTS. This exception will only raise if you surpass 100 requests per minutes, if you need more requests then that it would be better to host your own API instance. This inherits from :exc:`PokeAPIException`.""" class Notfound(PokeAPIException): """Exception raised when an HTTP request response code is equal to 404 NOT FOUND. This inherits from :exc:`PokeAPIException`.""" class Forbidden(PokeAPIException): """Exception raised when an HTTP request response code is equal to 403 FORBIDDEN. This inherits from :exc:`PokeAPIException`.""" class Nomoreitems(PokemonException): """Exception raised when an AsyncIterator is empty. This is usually catched to stop the iteration, unless you directly use the :meth:`AsyncPaginationIterator.next` method you shouldn't worry about it too much. .. versionadded:: 0.1.0a"""
""" https://leetcode.com/problems/find-smallest-letter-greater-than-target/ Given a list of sorted characters letters containing only lowercase letters, and given a target letter target, find the smallest element in the list that is larger than the given target. Letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], the answer is 'a'. Examples: Input: letters = ["c", "f", "j"] target = "a" Output: "c" Input: letters = ["c", "f", "j"] target = "c" Output: "f" Input: letters = ["c", "f", "j"] target = "d" Output: "f" Input: letters = ["c", "f", "j"] target = "g" Output: "j" Input: letters = ["c", "f", "j"] target = "j" Output: "c" Input: letters = ["c", "f", "j"] target = "k" Output: "c" Note: letters has a length in range [2, 10000]. letters consists of lowercase letters, and contains at least 2 unique letters. target is a lowercase letter. """ # time complexity: O(n), space complexity: O(1) class Solution: def nextGreatestLetter(self, letters: List[str], target: str) -> str: if target < letters[0]: return letters[0] elif target >= letters[-1]: return letters[0] else: # letter[0] <= target < letter[-1] for i in range(len(letters) - 1): if letters[i] <= target < letters[i + 1]: return letters[i + 1]
""" https://leetcode.com/problems/find-smallest-letter-greater-than-target/ Given a list of sorted characters letters containing only lowercase letters, and given a target letter target, find the smallest element in the list that is larger than the given target. Letters also wrap around. For example, if the target is target = 'z' and letters = ['a', 'b'], the answer is 'a'. Examples: Input: letters = ["c", "f", "j"] target = "a" Output: "c" Input: letters = ["c", "f", "j"] target = "c" Output: "f" Input: letters = ["c", "f", "j"] target = "d" Output: "f" Input: letters = ["c", "f", "j"] target = "g" Output: "j" Input: letters = ["c", "f", "j"] target = "j" Output: "c" Input: letters = ["c", "f", "j"] target = "k" Output: "c" Note: letters has a length in range [2, 10000]. letters consists of lowercase letters, and contains at least 2 unique letters. target is a lowercase letter. """ class Solution: def next_greatest_letter(self, letters: List[str], target: str) -> str: if target < letters[0]: return letters[0] elif target >= letters[-1]: return letters[0] else: for i in range(len(letters) - 1): if letters[i] <= target < letters[i + 1]: return letters[i + 1]
"""88. Lowest Common Ancestor of a Binary Tree Assume two nodes are exist in tree.""" """ Definition of TreeNode: class TreeNode: def __init__(self, val): self.val = val self.left, self.right = None, None """ class Solution: """ @param: root: The root of the binary search tree. @param: A: A TreeNode in a Binary. @param: B: A TreeNode in a Binary. @return: Return the least common ancestor(LCA) of the two nodes. """ def lowestCommonAncestor(self, root, A, B): # write your code here ### Practice: return self.dfs(root, A, B) def dfs(self, node, a, b): if not node: return None if node == a or node == b: return node left = self.dfs(node.left) right = self.dfs(node.right) if not left and not right: return None if left and right: return node return left or right ## if not root: return None if root == A or root == B: return root left = self.lowestCommonAncestor(root.left, A, B) right = self.lowestCommonAncestor(root.right, A, B) if left and right: return root if left or right: return left or right return None
"""88. Lowest Common Ancestor of a Binary Tree Assume two nodes are exist in tree.""" '\nDefinition of TreeNode:\nclass TreeNode:\n def __init__(self, val):\n self.val = val\n self.left, self.right = None, None\n' class Solution: """ @param: root: The root of the binary search tree. @param: A: A TreeNode in a Binary. @param: B: A TreeNode in a Binary. @return: Return the least common ancestor(LCA) of the two nodes. """ def lowest_common_ancestor(self, root, A, B): return self.dfs(root, A, B) def dfs(self, node, a, b): if not node: return None if node == a or node == b: return node left = self.dfs(node.left) right = self.dfs(node.right) if not left and (not right): return None if left and right: return node return left or right if not root: return None if root == A or root == B: return root left = self.lowestCommonAncestor(root.left, A, B) right = self.lowestCommonAncestor(root.right, A, B) if left and right: return root if left or right: return left or right return None
""" Configuration for defining the datastore. """ MAX_KEY_LEN = 32 # characters MAX_VALUE_SIZE = 16 * 1024 # 16 Kbytes MAX_LOCAL_STORAGE_SIZE = 1 * 1024 * 1024 * 1024 # 1 GB LOCAL_STORAGE_PREPEND_PATH = "/tmp" # this will be prepended to the file path provided
""" Configuration for defining the datastore. """ max_key_len = 32 max_value_size = 16 * 1024 max_local_storage_size = 1 * 1024 * 1024 * 1024 local_storage_prepend_path = '/tmp'
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] for n in range(1, 12, 1): n = int(input()) print(months[n - 1]) break
months = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'] for n in range(1, 12, 1): n = int(input()) print(months[n - 1]) break
def add_mod(x: int, y: int, modulo: int = 32) -> int: """ Modular addition :param x: :param y: :param modulo: :return: """ return (x + y) & ((1 << modulo) - 1) def left_circ_shift(x: int, shift: int, n_bits: int) -> int: """ Does a left binary circular shift on the number x of n_bits bits :param x: A number :param shift: The number of bits to shift :param n_bits: The number of bits of x :return: The shifted result """ mask = (1 << n_bits) - 1 # Trick to create a ones mask of n bits x_base = (x << shift) & mask # Keep it in the n_bits range return x_base | (x >> (n_bits - shift)) # Add the out of bounds bits def right_circ_shift(x: int, shift: int, n_bits: int) -> int: """ Does a right binary circular shift on the number x of n_bits bits :param x: A number :param shift: The number of bits to shift :param n_bits: The number of bits of x :return: The shifted result """ mask = (1 << n_bits) - 1 # Trick to create a ones mask of n bits x_base = x >> shift return x_base | (x << (n_bits - shift) & mask) def merge_bytes(payload_list: list) -> int: """ Gives an 8 bytes value from a byte list :param payload_list: Byte list (max size is 8) :return: """ while len(payload_list) < 8: payload_list.append(0x00) result = payload_list[0] for i in range(1, 8): result = (result << 8) | payload_list[i] return result def split_bytes(payload: int) -> bytearray: """ Gives a byte list of an 8 bytes value :param payload: The 8 bytes value :return: """ payload_list = bytearray() for i in range(8): payload_list.insert(0, (payload >> (8 * i)) & 0xFF) # Extract bytes by shifting right and masking return payload_list
def add_mod(x: int, y: int, modulo: int=32) -> int: """ Modular addition :param x: :param y: :param modulo: :return: """ return x + y & (1 << modulo) - 1 def left_circ_shift(x: int, shift: int, n_bits: int) -> int: """ Does a left binary circular shift on the number x of n_bits bits :param x: A number :param shift: The number of bits to shift :param n_bits: The number of bits of x :return: The shifted result """ mask = (1 << n_bits) - 1 x_base = x << shift & mask return x_base | x >> n_bits - shift def right_circ_shift(x: int, shift: int, n_bits: int) -> int: """ Does a right binary circular shift on the number x of n_bits bits :param x: A number :param shift: The number of bits to shift :param n_bits: The number of bits of x :return: The shifted result """ mask = (1 << n_bits) - 1 x_base = x >> shift return x_base | x << n_bits - shift & mask def merge_bytes(payload_list: list) -> int: """ Gives an 8 bytes value from a byte list :param payload_list: Byte list (max size is 8) :return: """ while len(payload_list) < 8: payload_list.append(0) result = payload_list[0] for i in range(1, 8): result = result << 8 | payload_list[i] return result def split_bytes(payload: int) -> bytearray: """ Gives a byte list of an 8 bytes value :param payload: The 8 bytes value :return: """ payload_list = bytearray() for i in range(8): payload_list.insert(0, payload >> 8 * i & 255) return payload_list
# Utility class used for string processing def HasText(line, values): retval = False found = 0 for data in values: if data in line: found += 1 if found == len(values): retval = True return retval def TextAfter(line, values): retval = "" if HasText(line, values): loc = 0 for data in values: end = line.find(data, 0) + len(data) if end > loc: loc = end retval = line[loc+1:] return retval
def has_text(line, values): retval = False found = 0 for data in values: if data in line: found += 1 if found == len(values): retval = True return retval def text_after(line, values): retval = '' if has_text(line, values): loc = 0 for data in values: end = line.find(data, 0) + len(data) if end > loc: loc = end retval = line[loc + 1:] return retval
# razbi n, ki je 5000 mestno stevilo na 100 50 mestnih stevilk in najdi prvih 10 stevk vsote teh 100-tih stevil sez = [37107287533902102798797998220837590246510135740250,46376937677490009712648124896970078050417018260538,74324986199524741059474233309513058123726617309629,91942213363574161572522430563301811072406154908250,23067588207539346171171980310421047513778063246676,89261670696623633820136378418383684178734361726757,28112879812849979408065481931592621691275889832738,44274228917432520321923589422876796487670272189318,47451445736001306439091167216856844588711603153276,70386486105843025439939619828917593665686757934951,62176457141856560629502157223196586755079324193331,64906352462741904929101432445813822663347944758178,92575867718337217661963751590579239728245598838407,58203565325359399008402633568948830189458628227828,80181199384826282014278194139940567587151170094390,35398664372827112653829987240784473053190104293586,86515506006295864861532075273371959191420517255829,71693888707715466499115593487603532921714970056938,54370070576826684624621495650076471787294438377604,53282654108756828443191190634694037855217779295145,36123272525000296071075082563815656710885258350721,45876576172410976447339110607218265236877223636045,17423706905851860660448207621209813287860733969412,81142660418086830619328460811191061556940512689692,51934325451728388641918047049293215058642563049483,62467221648435076201727918039944693004732956340691,15732444386908125794514089057706229429197107928209,55037687525678773091862540744969844508330393682126,18336384825330154686196124348767681297534375946515,80386287592878490201521685554828717201219257766954,78182833757993103614740356856449095527097864797581,16726320100436897842553539920931837441497806860984,48403098129077791799088218795327364475675590848030,87086987551392711854517078544161852424320693150332,59959406895756536782107074926966537676326235447210,69793950679652694742597709739166693763042633987085,41052684708299085211399427365734116182760315001271,65378607361501080857009149939512557028198746004375,35829035317434717326932123578154982629742552737307,94953759765105305946966067683156574377167401875275,88902802571733229619176668713819931811048770190271,25267680276078003013678680992525463401061632866526,36270218540497705585629946580636237993140746255962,24074486908231174977792365466257246923322810917141,91430288197103288597806669760892938638285025333403,34413065578016127815921815005561868836468420090470,23053081172816430487623791969842487255036638784583,11487696932154902810424020138335124462181441773470,63783299490636259666498587618221225225512486764533,67720186971698544312419572409913959008952310058822,95548255300263520781532296796249481641953868218774,76085327132285723110424803456124867697064507995236,37774242535411291684276865538926205024910326572967,23701913275725675285653248258265463092207058596522,29798860272258331913126375147341994889534765745501,18495701454879288984856827726077713721403798879715,38298203783031473527721580348144513491373226651381,34829543829199918180278916522431027392251122869539,40957953066405232632538044100059654939159879593635,29746152185502371307642255121183693803580388584903,41698116222072977186158236678424689157993532961922,62467957194401269043877107275048102390895523597457,23189706772547915061505504953922979530901129967519,86188088225875314529584099251203829009407770775672,11306739708304724483816533873502340845647058077308,82959174767140363198008187129011875491310547126581,97623331044818386269515456334926366572897563400500,42846280183517070527831839425882145521227251250327,55121603546981200581762165212827652751691296897789,32238195734329339946437501907836945765883352399886,75506164965184775180738168837861091527357929701337,62177842752192623401942399639168044983993173312731,32924185707147349566916674687634660915035914677504,99518671430235219628894890102423325116913619626622,73267460800591547471830798392868535206946944540724,76841822524674417161514036427982273348055556214818,97142617910342598647204516893989422179826088076852,87783646182799346313767754307809363333018982642090,10848802521674670883215120185883543223812876952786,71329612474782464538636993009049310363619763878039,62184073572399794223406235393808339651327408011116,66627891981488087797941876876144230030984490851411,60661826293682836764744779239180335110989069790714,85786944089552990653640447425576083659976645795096,66024396409905389607120198219976047599490197230297,64913982680032973156037120041377903785566085089252,16730939319872750275468906903707539413042652315011,94809377245048795150954100921645863754710598436791,78639167021187492431995700641917969777599028300699,15368713711936614952811305876380278410754449733078,40789923115535562561142322423255033685442488917353,44889911501440648020369068063960672322193204149535,41503128880339536053299340368006977710650566631954,81234880673210146739058568557934581403627822703280,82616570773948327592232845941706525094512325230608,22918802058777319719839450180888072429661980811197,77158542502016545090413245809786882778948721859617,72107838435069186155435662884062257473692284509516,20849603980134001723930671666823555245252804609722,53503534226472524250874054075591789781264330331690] def prva_deset_mestna(sez): vsota = sum(sez) return int(str(vsota)[:10]) print(prva_deset_mestna(sez)) 5537376230
sez = [37107287533902102798797998220837590246510135740250, 46376937677490009712648124896970078050417018260538, 74324986199524741059474233309513058123726617309629, 91942213363574161572522430563301811072406154908250, 23067588207539346171171980310421047513778063246676, 89261670696623633820136378418383684178734361726757, 28112879812849979408065481931592621691275889832738, 44274228917432520321923589422876796487670272189318, 47451445736001306439091167216856844588711603153276, 70386486105843025439939619828917593665686757934951, 62176457141856560629502157223196586755079324193331, 64906352462741904929101432445813822663347944758178, 92575867718337217661963751590579239728245598838407, 58203565325359399008402633568948830189458628227828, 80181199384826282014278194139940567587151170094390, 35398664372827112653829987240784473053190104293586, 86515506006295864861532075273371959191420517255829, 71693888707715466499115593487603532921714970056938, 54370070576826684624621495650076471787294438377604, 53282654108756828443191190634694037855217779295145, 36123272525000296071075082563815656710885258350721, 45876576172410976447339110607218265236877223636045, 17423706905851860660448207621209813287860733969412, 81142660418086830619328460811191061556940512689692, 51934325451728388641918047049293215058642563049483, 62467221648435076201727918039944693004732956340691, 15732444386908125794514089057706229429197107928209, 55037687525678773091862540744969844508330393682126, 18336384825330154686196124348767681297534375946515, 80386287592878490201521685554828717201219257766954, 78182833757993103614740356856449095527097864797581, 16726320100436897842553539920931837441497806860984, 48403098129077791799088218795327364475675590848030, 87086987551392711854517078544161852424320693150332, 59959406895756536782107074926966537676326235447210, 69793950679652694742597709739166693763042633987085, 41052684708299085211399427365734116182760315001271, 65378607361501080857009149939512557028198746004375, 35829035317434717326932123578154982629742552737307, 94953759765105305946966067683156574377167401875275, 88902802571733229619176668713819931811048770190271, 25267680276078003013678680992525463401061632866526, 36270218540497705585629946580636237993140746255962, 24074486908231174977792365466257246923322810917141, 91430288197103288597806669760892938638285025333403, 34413065578016127815921815005561868836468420090470, 23053081172816430487623791969842487255036638784583, 11487696932154902810424020138335124462181441773470, 63783299490636259666498587618221225225512486764533, 67720186971698544312419572409913959008952310058822, 95548255300263520781532296796249481641953868218774, 76085327132285723110424803456124867697064507995236, 37774242535411291684276865538926205024910326572967, 23701913275725675285653248258265463092207058596522, 29798860272258331913126375147341994889534765745501, 18495701454879288984856827726077713721403798879715, 38298203783031473527721580348144513491373226651381, 34829543829199918180278916522431027392251122869539, 40957953066405232632538044100059654939159879593635, 29746152185502371307642255121183693803580388584903, 41698116222072977186158236678424689157993532961922, 62467957194401269043877107275048102390895523597457, 23189706772547915061505504953922979530901129967519, 86188088225875314529584099251203829009407770775672, 11306739708304724483816533873502340845647058077308, 82959174767140363198008187129011875491310547126581, 97623331044818386269515456334926366572897563400500, 42846280183517070527831839425882145521227251250327, 55121603546981200581762165212827652751691296897789, 32238195734329339946437501907836945765883352399886, 75506164965184775180738168837861091527357929701337, 62177842752192623401942399639168044983993173312731, 32924185707147349566916674687634660915035914677504, 99518671430235219628894890102423325116913619626622, 73267460800591547471830798392868535206946944540724, 76841822524674417161514036427982273348055556214818, 97142617910342598647204516893989422179826088076852, 87783646182799346313767754307809363333018982642090, 10848802521674670883215120185883543223812876952786, 71329612474782464538636993009049310363619763878039, 62184073572399794223406235393808339651327408011116, 66627891981488087797941876876144230030984490851411, 60661826293682836764744779239180335110989069790714, 85786944089552990653640447425576083659976645795096, 66024396409905389607120198219976047599490197230297, 64913982680032973156037120041377903785566085089252, 16730939319872750275468906903707539413042652315011, 94809377245048795150954100921645863754710598436791, 78639167021187492431995700641917969777599028300699, 15368713711936614952811305876380278410754449733078, 40789923115535562561142322423255033685442488917353, 44889911501440648020369068063960672322193204149535, 41503128880339536053299340368006977710650566631954, 81234880673210146739058568557934581403627822703280, 82616570773948327592232845941706525094512325230608, 22918802058777319719839450180888072429661980811197, 77158542502016545090413245809786882778948721859617, 72107838435069186155435662884062257473692284509516, 20849603980134001723930671666823555245252804609722, 53503534226472524250874054075591789781264330331690] def prva_deset_mestna(sez): vsota = sum(sez) return int(str(vsota)[:10]) print(prva_deset_mestna(sez)) 5537376230
""" Represents the domain of a variable, i.e. the possible values that each variable may assign. """ class Domain: # ================================================================== # Constructors # ================================================================== def __init__ ( self, value_or_values ): self.values = [] if type( value_or_values ) is int: self.values.append( value_or_values ) else: self.values = value_or_values self.modified = False def copy ( self, values ): self.values = values # ================================================================== # Accessors # ================================================================== # Checks if value exists within the domain def contains ( self, v ): return v in self.values # Returns number of values in the domain def size ( self ): return len(self.values) # Returns true if no values are contained in the domain def isEmpty ( self ): return not self.values # Returns whether or not the domain has been modified def isModified ( self ): return self.modified # ================================================================== # Modifiers # ================================================================== # Adds a value to the domain def add ( self, num ): if num not in self.values: self.values.append( num ) # Remove a value from the domain def remove ( self, num ): if num in self.values: self.modified = True self.values.remove( num ) return True else: return False # Sets the modified flag def setModified ( self, modified ): self.modified = modified # ================================================================== # String representation # ================================================================== def __str__ ( self ): output = "{" for i in range(len(self.values) - 1): output += str(self.values[i]) + ", " try: output += str(self.values[-1]) except: pass output += "}" return output
""" Represents the domain of a variable, i.e. the possible values that each variable may assign. """ class Domain: def __init__(self, value_or_values): self.values = [] if type(value_or_values) is int: self.values.append(value_or_values) else: self.values = value_or_values self.modified = False def copy(self, values): self.values = values def contains(self, v): return v in self.values def size(self): return len(self.values) def is_empty(self): return not self.values def is_modified(self): return self.modified def add(self, num): if num not in self.values: self.values.append(num) def remove(self, num): if num in self.values: self.modified = True self.values.remove(num) return True else: return False def set_modified(self, modified): self.modified = modified def __str__(self): output = '{' for i in range(len(self.values) - 1): output += str(self.values[i]) + ', ' try: output += str(self.values[-1]) except: pass output += '}' return output
""" approximations using histograms """ class Interval: def __init__(self, low, up): if low > up: raise Exception("Cannot create interval: low must be smaller or equal than up") self.low = low self.up = up def __len__(self): return self.up - self.low def contains(self, c): return self.low <= c <= self.up def intersect(self, interval): if interval.low > self.up or self.low > interval.up: return None return Interval(max(self.low, interval.low), min(self.up, interval.up)) class Histogram: def __init__(self): self.intervals = [] def add_interval(self, low, up, elements): """ Adds a new bucket to the histogram. :param low: lower bound :param up: upper bound :param elements: number of elements :return: self """ self.intervals.append((Interval(low, up), elements)) return self def approx_equals_constant_verbose(histogram, c): numerator = [] denominator = [elements for _, elements in histogram.intervals] for interval, elements in histogram.intervals: if interval.contains(c): numerator.append(elements) result = sum(numerator) / sum(denominator) return f'\\frac{{ {" + ".join(map(str, numerator))} }}{{ {" + ".join(map(str, denominator))} }} = {result:.4f}', result def approx_greater_constant_verbose(histogram, c): numerator_tex = [] numerator = [] denominator = [elements for _, elements in histogram.intervals] for interval, elements in histogram.intervals: if interval.contains(c): numerator_tex.append(f'\\frac{{ {interval.up} - {c} }}{{ {interval.up} - {interval.low} }} \\cdot {elements}') numerator.append(((interval.up - c) / len(interval)) * elements) elif interval.low > c: numerator_tex.append(f'{elements}') numerator.append(elements) result = sum(numerator) / sum(denominator) return f'\\frac{{ {" + ".join(numerator_tex)} }}{{ {" + ".join(map(str, denominator))} }} = {result:.4f}', result def approx_join_verbose(hist1, hist2): numerator_tex = [] numerator = [] denominator_h1 = [elements for _, elements in hist1.intervals] denominator_h2 = [elements for _, elements in hist2.intervals] for i1, elements1 in hist1.intervals: for i2, elements2 in hist2.intervals: iprime = i1.intersect(i2) if iprime is None: continue numerator_tex.append( f'\\frac{{ {len(iprime)} }}{{ {len(i1)} }} \\cdot {elements1} \\cdot ' f'\\frac{{ {len(iprime)} }}{{ {len(i2)} }} \\cdot {elements2}' ) numerator.append(((len(iprime) / len(i1)) * elements1) * ((len(iprime) / len(i2)) * elements2)) result = sum(numerator) / (sum(denominator_h1) * sum(denominator_h2)) return f'\\frac{{ {" + ".join(numerator_tex)} }}' \ f'{{ \\left( {" + ".join(map(str, denominator_h1))} \\right) \\cdot ' \ f'\\left( {" + ".join(map(str, denominator_h2))} \\right) }} '\ f' = {result:.4f}', result
""" approximations using histograms """ class Interval: def __init__(self, low, up): if low > up: raise exception('Cannot create interval: low must be smaller or equal than up') self.low = low self.up = up def __len__(self): return self.up - self.low def contains(self, c): return self.low <= c <= self.up def intersect(self, interval): if interval.low > self.up or self.low > interval.up: return None return interval(max(self.low, interval.low), min(self.up, interval.up)) class Histogram: def __init__(self): self.intervals = [] def add_interval(self, low, up, elements): """ Adds a new bucket to the histogram. :param low: lower bound :param up: upper bound :param elements: number of elements :return: self """ self.intervals.append((interval(low, up), elements)) return self def approx_equals_constant_verbose(histogram, c): numerator = [] denominator = [elements for (_, elements) in histogram.intervals] for (interval, elements) in histogram.intervals: if interval.contains(c): numerator.append(elements) result = sum(numerator) / sum(denominator) return (f"\\frac{{ {' + '.join(map(str, numerator))} }}{{ {' + '.join(map(str, denominator))} }} = {result:.4f}", result) def approx_greater_constant_verbose(histogram, c): numerator_tex = [] numerator = [] denominator = [elements for (_, elements) in histogram.intervals] for (interval, elements) in histogram.intervals: if interval.contains(c): numerator_tex.append(f'\\frac{{ {interval.up} - {c} }}{{ {interval.up} - {interval.low} }} \\cdot {elements}') numerator.append((interval.up - c) / len(interval) * elements) elif interval.low > c: numerator_tex.append(f'{elements}') numerator.append(elements) result = sum(numerator) / sum(denominator) return (f"\\frac{{ {' + '.join(numerator_tex)} }}{{ {' + '.join(map(str, denominator))} }} = {result:.4f}", result) def approx_join_verbose(hist1, hist2): numerator_tex = [] numerator = [] denominator_h1 = [elements for (_, elements) in hist1.intervals] denominator_h2 = [elements for (_, elements) in hist2.intervals] for (i1, elements1) in hist1.intervals: for (i2, elements2) in hist2.intervals: iprime = i1.intersect(i2) if iprime is None: continue numerator_tex.append(f'\\frac{{ {len(iprime)} }}{{ {len(i1)} }} \\cdot {elements1} \\cdot \\frac{{ {len(iprime)} }}{{ {len(i2)} }} \\cdot {elements2}') numerator.append(len(iprime) / len(i1) * elements1 * (len(iprime) / len(i2) * elements2)) result = sum(numerator) / (sum(denominator_h1) * sum(denominator_h2)) return (f"\\frac{{ {' + '.join(numerator_tex)} }}{{ \\left( {' + '.join(map(str, denominator_h1))} \\right) \\cdot \\left( {' + '.join(map(str, denominator_h2))} \\right) }} = {result:.4f}", result)
async def run(plugin, ctx, channel): plugin.db.configs.update(ctx.guild.id, "message_logging", True) plugin.db.configs.update(ctx.guild.id, "message_log_channel", f"{channel.id}") await ctx.send(plugin.t(ctx.guild, "enabled_module_channel", _emote="YES", module="Message Logging", channel=channel.mention))
async def run(plugin, ctx, channel): plugin.db.configs.update(ctx.guild.id, 'message_logging', True) plugin.db.configs.update(ctx.guild.id, 'message_log_channel', f'{channel.id}') await ctx.send(plugin.t(ctx.guild, 'enabled_module_channel', _emote='YES', module='Message Logging', channel=channel.mention))
# Copyright 2014 Hewlett-Packard Development Company, L.P. # # Licensed under the Apache License, Version 2.0 (the "License"); you may # not use this file except in compliance with the License. You may obtain # a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the # License for the specific language governing permissions and limitations # under the License. """Exception Class for proliantutils module.""" class ProliantUtilsException(Exception): """Parent class for all Proliantutils exceptions.""" pass class InvalidInputError(Exception): message = "Invalid Input: %(reason)s" class IloError(ProliantUtilsException): """Base Exception. This exception is used when a problem is encountered in executing an operation on the iLO. """ def __init__(self, message, errorcode=None): super(IloError, self).__init__(message) class IloClientInternalError(IloError): """Internal Error from IloClient. This exception is raised when iLO client library fails to communicate properly with the iLO. """ def __init__(self, message, errorcode=None): super(IloError, self).__init__(message) class IloCommandNotSupportedError(IloError): """Command not supported on the platform. This exception is raised when iLO client library fails to communicate properly with the iLO """ def __init__(self, message, errorcode=None): super(IloError, self).__init__(message) class IloLoginFailError(IloError): """iLO Login Failed. This exception is used to communicate a login failure to the caller. """ messages = ['User login name was not found', 'Login failed', 'Login credentials rejected'] statuses = [0x005f, 0x000a] message = 'Authorization Failed' def __init__(self, message, errorcode=None): super(IloError, self).__init__(message) class IloConnectionError(IloError): """Cannot connect to iLO. This exception is used to communicate an HTTP connection error from the iLO to the caller. """ def __init__(self, message): super(IloConnectionError, self).__init__(message) # This is not merged with generic InvalidInputError because # of backward-compatibility reasons. If we changed this, # use-cases of excepting 'IloError' to catch 'IloInvalidInputError' # will be broken. class IloInvalidInputError(IloError): """Invalid Input passed. This exception is used when invalid inputs are passed to the APIs exposed by this module. """ def __init__(self, message): super(IloInvalidInputError, self).__init__(message) class HPSSAException(ProliantUtilsException): message = "An exception occured in hpssa module" def __init__(self, message=None, **kwargs): if not message: message = self.message message = message % kwargs super(HPSSAException, self).__init__(message) class PhysicalDisksNotFoundError(HPSSAException): message = ("Not enough physical disks were found to create logical disk " "of size %(size_gb)s GB and raid level %(raid_level)s") class HPSSAOperationError(HPSSAException): message = ("An error was encountered while doing hpssa configuration: " "%(reason)s.")
"""Exception Class for proliantutils module.""" class Proliantutilsexception(Exception): """Parent class for all Proliantutils exceptions.""" pass class Invalidinputerror(Exception): message = 'Invalid Input: %(reason)s' class Iloerror(ProliantUtilsException): """Base Exception. This exception is used when a problem is encountered in executing an operation on the iLO. """ def __init__(self, message, errorcode=None): super(IloError, self).__init__(message) class Iloclientinternalerror(IloError): """Internal Error from IloClient. This exception is raised when iLO client library fails to communicate properly with the iLO. """ def __init__(self, message, errorcode=None): super(IloError, self).__init__(message) class Ilocommandnotsupportederror(IloError): """Command not supported on the platform. This exception is raised when iLO client library fails to communicate properly with the iLO """ def __init__(self, message, errorcode=None): super(IloError, self).__init__(message) class Ilologinfailerror(IloError): """iLO Login Failed. This exception is used to communicate a login failure to the caller. """ messages = ['User login name was not found', 'Login failed', 'Login credentials rejected'] statuses = [95, 10] message = 'Authorization Failed' def __init__(self, message, errorcode=None): super(IloError, self).__init__(message) class Iloconnectionerror(IloError): """Cannot connect to iLO. This exception is used to communicate an HTTP connection error from the iLO to the caller. """ def __init__(self, message): super(IloConnectionError, self).__init__(message) class Iloinvalidinputerror(IloError): """Invalid Input passed. This exception is used when invalid inputs are passed to the APIs exposed by this module. """ def __init__(self, message): super(IloInvalidInputError, self).__init__(message) class Hpssaexception(ProliantUtilsException): message = 'An exception occured in hpssa module' def __init__(self, message=None, **kwargs): if not message: message = self.message message = message % kwargs super(HPSSAException, self).__init__(message) class Physicaldisksnotfounderror(HPSSAException): message = 'Not enough physical disks were found to create logical disk of size %(size_gb)s GB and raid level %(raid_level)s' class Hpssaoperationerror(HPSSAException): message = 'An error was encountered while doing hpssa configuration: %(reason)s.'
def exist(board, word): """ Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. :param board: :param word: :return: """ if not board: return False for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == word[0]: if helper(board, i, j, word): return True return False def helper(board, word, i, j): # Recursive process for DFS search if len(word) == 1: # Reach the end, return True return True for next_start in [[i - 1, j], [i + 1, j], [i, j - 1], [i, j + 1]]: board[i][j] = None if 0 <= next_start[0] < len(board) and 0 <= next_start[1] < len(board[0]): if board[next_start[0]][next_start[1]] == word[1]: if helper(board, word[1:], next_start[0], next_start[1]): return True board[i][j] = word[0] return False
def exist(board, word): """ Given a 2D board and a word, find if the word exists in the grid. The word can be constructed from letters of sequentially adjacent cell, where "adjacent" cells are those horizontally or vertically neighboring. The same letter cell may not be used more than once. :param board: :param word: :return: """ if not board: return False for i in range(len(board)): for j in range(len(board[0])): if board[i][j] == word[0]: if helper(board, i, j, word): return True return False def helper(board, word, i, j): if len(word) == 1: return True for next_start in [[i - 1, j], [i + 1, j], [i, j - 1], [i, j + 1]]: board[i][j] = None if 0 <= next_start[0] < len(board) and 0 <= next_start[1] < len(board[0]): if board[next_start[0]][next_start[1]] == word[1]: if helper(board, word[1:], next_start[0], next_start[1]): return True board[i][j] = word[0] return False
class TwoSum: def __init__(self): """ Initialize your data structure here. """ self.numberCount = defaultdict(int) def add(self, number: int) -> None: """ Add the number to an internal data structure.. """ self.numberCount[number] += 1 def find(self, value: int) -> bool: """ Find if there exists any pair of numbers which sum is equal to the value. """ for number in self.numberCount.keys(): complementNumber = value - number if complementNumber == number: if self.numberCount[number] > 1: return True else: if complementNumber in self.numberCount: return True return False # Your TwoSum object will be instantiated and called as such: # obj = TwoSum() # obj.add(number) # param_2 = obj.find(value)
class Twosum: def __init__(self): """ Initialize your data structure here. """ self.numberCount = defaultdict(int) def add(self, number: int) -> None: """ Add the number to an internal data structure.. """ self.numberCount[number] += 1 def find(self, value: int) -> bool: """ Find if there exists any pair of numbers which sum is equal to the value. """ for number in self.numberCount.keys(): complement_number = value - number if complementNumber == number: if self.numberCount[number] > 1: return True elif complementNumber in self.numberCount: return True return False
### --- ### --- ### --- ### #! While structure: #` 1. The while statement starts with the while keyword, followed bu a test condition, and ends with a colon (:). #` 2. The loop body contains the code that gets repeated at each step of the loop. Each line is indented four spaces. #$ Example: n = 10 while n < 20: print(n) n = n + 1 #. infinite loop while n <= 10: print(n)
n = 10 while n < 20: print(n) n = n + 1 while n <= 10: print(n)
class Solution: def maxScore(self, s: str) -> int: """String. Running time: O(n) where n == len(s). """ res = 0 ones = 0 for i in s: if i == '1': ones += 1 z, o = 0, 0 for i in s[:-1]: if i == '0': z += 1 else: o += 1 res = max(res, z + ones - o) return res
class Solution: def max_score(self, s: str) -> int: """String. Running time: O(n) where n == len(s). """ res = 0 ones = 0 for i in s: if i == '1': ones += 1 (z, o) = (0, 0) for i in s[:-1]: if i == '0': z += 1 else: o += 1 res = max(res, z + ones - o) return res
class EndpointSolver(object): def __init__(self, env, charms): self.env = env self.charms = charms # Relation endpoint match logic def solve(self, ep_a, ep_b): service_a, charm_a, endpoints_a = self._parse_endpoints(ep_a) service_b, charm_b, endpoints_b = self._parse_endpoints(ep_b) pairs = self._select_endpoint_pairs(endpoints_a, endpoints_b) return service_a, service_b, pairs return service_a, pairs[0], service_b, pairs[1] def _check_endpoints_match(self, ep_a, ep_b): if ep_a['interface'] != ep_b['interface']: return False if ep_a['role'] == 'requirer' and ep_b['role'] == 'provider': return True elif ep_a['role'] == 'provider' and ep_b['role'] == 'requirer': return True elif ep_a['role'] == 'peer' and ep_b['role'] == 'peer': if ep_a['service'] == ep_b['service']: return True return False def _select_endpoint_pairs(self, eps_a, eps_b): pairs = [] for ep_a in eps_a: for ep_b in eps_b: if self._check_endpoints_match(ep_a, ep_b): scope = 'global' if (ep_a['scope'] == 'container' or ep_b['scope'] == 'container'): scope = 'container' pairs.append((ep_a, ep_b, scope)) return pairs def _parse_endpoints(self, descriptor): if ':' in descriptor: svc_name, rel_name = descriptor.split(u":") else: svc_name, rel_name = unicode(descriptor), None svc = self.env.env_get_service(svc_name) charm = self.charms.get(svc.charm_url) endpoints = [] found = False for ep in charm.endpoints: ep['service'] = svc_name if rel_name: if ep['name'] == rel_name: found = True endpoints.append(ep) break else: endpoints.append(ep) if rel_name and not found: raise EnvError({'Error': '%s rel endpoint not valid' % descriptor}) return svc, charm, endpoints
class Endpointsolver(object): def __init__(self, env, charms): self.env = env self.charms = charms def solve(self, ep_a, ep_b): (service_a, charm_a, endpoints_a) = self._parse_endpoints(ep_a) (service_b, charm_b, endpoints_b) = self._parse_endpoints(ep_b) pairs = self._select_endpoint_pairs(endpoints_a, endpoints_b) return (service_a, service_b, pairs) return (service_a, pairs[0], service_b, pairs[1]) def _check_endpoints_match(self, ep_a, ep_b): if ep_a['interface'] != ep_b['interface']: return False if ep_a['role'] == 'requirer' and ep_b['role'] == 'provider': return True elif ep_a['role'] == 'provider' and ep_b['role'] == 'requirer': return True elif ep_a['role'] == 'peer' and ep_b['role'] == 'peer': if ep_a['service'] == ep_b['service']: return True return False def _select_endpoint_pairs(self, eps_a, eps_b): pairs = [] for ep_a in eps_a: for ep_b in eps_b: if self._check_endpoints_match(ep_a, ep_b): scope = 'global' if ep_a['scope'] == 'container' or ep_b['scope'] == 'container': scope = 'container' pairs.append((ep_a, ep_b, scope)) return pairs def _parse_endpoints(self, descriptor): if ':' in descriptor: (svc_name, rel_name) = descriptor.split(u':') else: (svc_name, rel_name) = (unicode(descriptor), None) svc = self.env.env_get_service(svc_name) charm = self.charms.get(svc.charm_url) endpoints = [] found = False for ep in charm.endpoints: ep['service'] = svc_name if rel_name: if ep['name'] == rel_name: found = True endpoints.append(ep) break else: endpoints.append(ep) if rel_name and (not found): raise env_error({'Error': '%s rel endpoint not valid' % descriptor}) return (svc, charm, endpoints)
# -*- encoding: utf-8 -*- def _single_action_str(self): return '/'.join(list(iter(self))) def _multi_action_str(_): cmd_actions = [ str(arg) for arg in [ RUN_OPT_NAME, STOP_OPT_NAME, ENABLE_OPTS_NAME, ENABLE_OPTS_NAME, ] ] return ', '.join(cmd_actions) frozenset_single_action_opts = type( 'frozenset_argv_action_opts', (frozenset,), {'__str__': _single_action_str}, ) frozenset_multiple_action_opts = type( 'frozenset_argv_action_opts', (frozenset,), {'__str__': _multi_action_str}, ) RUN_OPT_NAME = 'run' START_OPT_NAME = 'start' STOP_OPT_NAME = 'stop' ENABLE_OPT_NAME = 'en' ENABLE_OPT_NAME_ALIAS = 'enable' ENABLE_OPTS_NAME = frozenset_single_action_opts( {ENABLE_OPT_NAME, ENABLE_OPT_NAME_ALIAS}, ) DISABLE_OPT_NAME = 'dis' DISABLE_OPT_NAME_ALIAS = 'disable' DISABLE_OPTS_NAME = frozenset_single_action_opts( {DISABLE_OPT_NAME, DISABLE_OPT_NAME_ALIAS}, ) ARGS_ACTION_OPTS = frozenset_multiple_action_opts( {RUN_OPT_NAME} | {STOP_OPT_NAME} | ENABLE_OPTS_NAME | DISABLE_OPTS_NAME, ) ALL = 'all'
def _single_action_str(self): return '/'.join(list(iter(self))) def _multi_action_str(_): cmd_actions = [str(arg) for arg in [RUN_OPT_NAME, STOP_OPT_NAME, ENABLE_OPTS_NAME, ENABLE_OPTS_NAME]] return ', '.join(cmd_actions) frozenset_single_action_opts = type('frozenset_argv_action_opts', (frozenset,), {'__str__': _single_action_str}) frozenset_multiple_action_opts = type('frozenset_argv_action_opts', (frozenset,), {'__str__': _multi_action_str}) run_opt_name = 'run' start_opt_name = 'start' stop_opt_name = 'stop' enable_opt_name = 'en' enable_opt_name_alias = 'enable' enable_opts_name = frozenset_single_action_opts({ENABLE_OPT_NAME, ENABLE_OPT_NAME_ALIAS}) disable_opt_name = 'dis' disable_opt_name_alias = 'disable' disable_opts_name = frozenset_single_action_opts({DISABLE_OPT_NAME, DISABLE_OPT_NAME_ALIAS}) args_action_opts = frozenset_multiple_action_opts({RUN_OPT_NAME} | {STOP_OPT_NAME} | ENABLE_OPTS_NAME | DISABLE_OPTS_NAME) all = 'all'
rosha = bet_log[-1] bet_log = []
rosha = bet_log[-1] bet_log = []
# # PySNMP MIB module CISCO-LWAPP-REAP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-LWAPP-REAP-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:49:14 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # OctetString, Integer, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "OctetString", "Integer", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, ConstraintsUnion, ValueSizeConstraint, SingleValueConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "ConstraintsUnion", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsIntersection") cLApSysMacAddress, = mibBuilder.importSymbols("CISCO-LWAPP-AP-MIB", "cLApSysMacAddress") cLWlanIndex, = mibBuilder.importSymbols("CISCO-LWAPP-WLAN-MIB", "cLWlanIndex") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") SnmpAdminString, = mibBuilder.importSymbols("SNMP-FRAMEWORK-MIB", "SnmpAdminString") ObjectGroup, NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "NotificationGroup", "ModuleCompliance") MibScalar, MibTable, MibTableRow, MibTableColumn, ModuleIdentity, Unsigned32, Counter32, Gauge32, IpAddress, Counter64, Integer32, MibIdentifier, iso, ObjectIdentity, Bits, NotificationType, TimeTicks = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ModuleIdentity", "Unsigned32", "Counter32", "Gauge32", "IpAddress", "Counter64", "Integer32", "MibIdentifier", "iso", "ObjectIdentity", "Bits", "NotificationType", "TimeTicks") TextualConvention, RowStatus, TruthValue, StorageType, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "RowStatus", "TruthValue", "StorageType", "DisplayString") ciscoLwappReapMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 517)) ciscoLwappReapMIB.setRevisions(('2010-10-06 00:00', '2010-02-06 00:00', '2007-11-01 00:00', '2007-04-19 00:00', '2006-04-19 00:00',)) if mibBuilder.loadTexts: ciscoLwappReapMIB.setLastUpdated('201010060000Z') if mibBuilder.loadTexts: ciscoLwappReapMIB.setOrganization('Cisco Systems Inc.') ciscoLwappReapMIBNotifs = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 0)) ciscoLwappReapMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 1)) ciscoLwappReapMIBConform = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 2)) ciscoLwappReapWlanConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 1)) ciscoLwappReapApConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2)) ciscoLwappReapGroupConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3)) cLReapWlanConfigTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 1, 1), ) if mibBuilder.loadTexts: cLReapWlanConfigTable.setStatus('current') cLReapWlanConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-LWAPP-WLAN-MIB", "cLWlanIndex")) if mibBuilder.loadTexts: cLReapWlanConfigEntry.setStatus('current') cLReapWlanEnLocalSwitching = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 1, 1, 1, 1), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cLReapWlanEnLocalSwitching.setStatus('current') cLReapWlanClientIpLearnEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 1, 1, 1, 2), TruthValue().clone('true')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cLReapWlanClientIpLearnEnable.setStatus('current') cLReapWlanApAuth = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 1, 1, 1, 3), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cLReapWlanApAuth.setStatus('current') cLReapApConfigTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1), ) if mibBuilder.loadTexts: cLReapApConfigTable.setStatus('current') cLReapApConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1, 1), ).setIndexNames((0, "CISCO-LWAPP-AP-MIB", "cLApSysMacAddress")) if mibBuilder.loadTexts: cLReapApConfigEntry.setStatus('current') cLReapApNativeVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4095)).clone(1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: cLReapApNativeVlanId.setStatus('current') cLReapApVlanEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1, 1, 2), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cLReapApVlanEnable.setStatus('current') cLReapHomeApEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1, 1, 3), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cLReapHomeApEnable.setStatus('current') cLReapApLeastLatencyJoinEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1, 1, 4), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cLReapApLeastLatencyJoinEnable.setStatus('current') cLReapHomeApLocalSsidReset = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1, 1, 5), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: cLReapHomeApLocalSsidReset.setStatus('current') cLReapApVlanIdTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 2), ) if mibBuilder.loadTexts: cLReapApVlanIdTable.setStatus('current') cLReapApVlanIdEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 2, 1), ).setIndexNames((0, "CISCO-LWAPP-AP-MIB", "cLApSysMacAddress"), (0, "CISCO-LWAPP-WLAN-MIB", "cLWlanIndex")) if mibBuilder.loadTexts: cLReapApVlanIdEntry.setStatus('current') cLReapApVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 2, 1, 1), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(1, 4095)).clone(1)).setMaxAccess("readwrite") if mibBuilder.loadTexts: cLReapApVlanId.setStatus('current') cLReapGroupConfigTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1), ) if mibBuilder.loadTexts: cLReapGroupConfigTable.setStatus('current') cLReapGroupConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1), ).setIndexNames((0, "CISCO-LWAPP-REAP-MIB", "cLReapGroupName")) if mibBuilder.loadTexts: cLReapGroupConfigEntry.setStatus('current') cLReapGroupName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 1), SnmpAdminString()) if mibBuilder.loadTexts: cLReapGroupName.setStatus('current') cLReapGroupPrimaryRadiusIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 2), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cLReapGroupPrimaryRadiusIndex.setStatus('current') cLReapGroupSecondaryRadiusIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 3), Unsigned32()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cLReapGroupSecondaryRadiusIndex.setStatus('current') cLReapGroupStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 4), StorageType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cLReapGroupStorageType.setStatus('current') cLReapGroupRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 5), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cLReapGroupRowStatus.setStatus('current') cLReapGroupRadiusPacTimeout = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 6), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(2, 4095)).clone(10)).setUnits('days').setMaxAccess("readcreate") if mibBuilder.loadTexts: cLReapGroupRadiusPacTimeout.setStatus('deprecated') cLReapGroupRadiusAuthorityId = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate") if mibBuilder.loadTexts: cLReapGroupRadiusAuthorityId.setStatus('current') cLReapGroupRadiusAuthorityInfo = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 8), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate") if mibBuilder.loadTexts: cLReapGroupRadiusAuthorityInfo.setStatus('current') cLReapGroupRadiusServerKey = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 9), OctetString().subtype(subtypeSpec=ValueSizeConstraint(1, 32)).clone('****')).setMaxAccess("readcreate") if mibBuilder.loadTexts: cLReapGroupRadiusServerKey.setStatus('current') cLReapGroupRadiusIgnoreKey = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 10), TruthValue().clone('true')).setMaxAccess("readcreate") if mibBuilder.loadTexts: cLReapGroupRadiusIgnoreKey.setStatus('current') cLReapGroupRadiusEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 11), TruthValue().clone('false')).setMaxAccess("readcreate") if mibBuilder.loadTexts: cLReapGroupRadiusEnable.setStatus('current') cLReapGroupRadiusLeapEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 12), TruthValue().clone('false')).setMaxAccess("readcreate") if mibBuilder.loadTexts: cLReapGroupRadiusLeapEnable.setStatus('current') cLReapGroupRadiusEapFastEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 13), TruthValue().clone('false')).setMaxAccess("readcreate") if mibBuilder.loadTexts: cLReapGroupRadiusEapFastEnable.setStatus('current') cLReapGroupRadiusPacTimeoutCtrl = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 14), Unsigned32().subtype(subtypeSpec=ValueRangeConstraint(0, 4095)).clone(10)).setUnits('seconds').setMaxAccess("readcreate") if mibBuilder.loadTexts: cLReapGroupRadiusPacTimeoutCtrl.setStatus('current') cLReapGroupApConfigTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 2), ) if mibBuilder.loadTexts: cLReapGroupApConfigTable.setStatus('current') cLReapGroupApConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 2, 1), ).setIndexNames((0, "CISCO-LWAPP-REAP-MIB", "cLReapGroupName"), (0, "CISCO-LWAPP-AP-MIB", "cLApSysMacAddress")) if mibBuilder.loadTexts: cLReapGroupApConfigEntry.setStatus('current') cLReapGroupApStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 2, 1, 1), StorageType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cLReapGroupApStorageType.setStatus('current') cLReapGroupApRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 2, 1, 2), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cLReapGroupApRowStatus.setStatus('current') cLReapGroupUserConfigTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 3), ) if mibBuilder.loadTexts: cLReapGroupUserConfigTable.setStatus('current') cLReapGroupUserConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 3, 1), ).setIndexNames((0, "CISCO-LWAPP-REAP-MIB", "cLReapGroupName"), (0, "CISCO-LWAPP-REAP-MIB", "cLReapGroupUserName")) if mibBuilder.loadTexts: cLReapGroupUserConfigEntry.setStatus('current') cLReapGroupUserName = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 3, 1, 1), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 24))) if mibBuilder.loadTexts: cLReapGroupUserName.setStatus('current') cLReapGroupUserPassword = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 3, 1, 2), SnmpAdminString().subtype(subtypeSpec=ValueSizeConstraint(1, 64))).setMaxAccess("readcreate") if mibBuilder.loadTexts: cLReapGroupUserPassword.setStatus('current') cLReapGroupUserStorageType = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 3, 1, 3), StorageType()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cLReapGroupUserStorageType.setStatus('current') cLReapGroupUserRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 3, 1, 4), RowStatus()).setMaxAccess("readcreate") if mibBuilder.loadTexts: cLReapGroupUserRowStatus.setStatus('current') ciscoLwappReapMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1)) ciscoLwappReapMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2)) ciscoLwappReapMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1, 1)).setObjects(("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapWlanConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapApConfigGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappReapMIBCompliance = ciscoLwappReapMIBCompliance.setStatus('deprecated') ciscoLwappReapMIBComplianceRev1 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1, 2)).setObjects(("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapWlanConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapApConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappReapMIBComplianceRev1 = ciscoLwappReapMIBComplianceRev1.setStatus('deprecated') ciscoLwappReapMIBComplianceRev2 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1, 3)).setObjects(("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapWlanConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapApConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappReapMIBComplianceRev2 = ciscoLwappReapMIBComplianceRev2.setStatus('deprecated') ciscoLwappReapMIBComplianceRev3 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1, 4)).setObjects(("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapWlanConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapApConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigRadiusGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigUserAuthGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapApConfigGroupHomeAp")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappReapMIBComplianceRev3 = ciscoLwappReapMIBComplianceRev3.setStatus('deprecated') ciscoLwappReapMIBComplianceRev4 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1, 5)).setObjects(("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapWlanConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapApConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigUserAuthGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapApConfigGroupHomeAp"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigRadiusGroup1")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappReapMIBComplianceRev4 = ciscoLwappReapMIBComplianceRev4.setStatus('deprecated') ciscoLwappReapMIBComplianceRev5 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1, 6)).setObjects(("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapWlanConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapApConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigUserAuthGroup"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapApConfigGroupHomeAp"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapGroupConfigRadiusGroup1"), ("CISCO-LWAPP-REAP-MIB", "ciscoLwappReapWlanConfigGroupSup1")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappReapMIBComplianceRev5 = ciscoLwappReapMIBComplianceRev5.setStatus('current') ciscoLwappReapWlanConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 1)).setObjects(("CISCO-LWAPP-REAP-MIB", "cLReapWlanEnLocalSwitching")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappReapWlanConfigGroup = ciscoLwappReapWlanConfigGroup.setStatus('current') ciscoLwappReapApConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 2)).setObjects(("CISCO-LWAPP-REAP-MIB", "cLReapApNativeVlanId"), ("CISCO-LWAPP-REAP-MIB", "cLReapApVlanId"), ("CISCO-LWAPP-REAP-MIB", "cLReapApVlanEnable")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappReapApConfigGroup = ciscoLwappReapApConfigGroup.setStatus('current') ciscoLwappReapGroupConfigGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 3)).setObjects(("CISCO-LWAPP-REAP-MIB", "cLReapGroupPrimaryRadiusIndex"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupSecondaryRadiusIndex"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupStorageType"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRowStatus"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupApStorageType"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupApRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappReapGroupConfigGroup = ciscoLwappReapGroupConfigGroup.setStatus('current') ciscoLwappReapGroupConfigRadiusGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 4)).setObjects(("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusPacTimeout"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusAuthorityId"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusAuthorityInfo"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusServerKey"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusIgnoreKey"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusEnable"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusLeapEnable"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusEapFastEnable")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappReapGroupConfigRadiusGroup = ciscoLwappReapGroupConfigRadiusGroup.setStatus('deprecated') ciscoLwappReapGroupConfigUserAuthGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 5)).setObjects(("CISCO-LWAPP-REAP-MIB", "cLReapGroupUserPassword"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupUserStorageType"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupUserRowStatus")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappReapGroupConfigUserAuthGroup = ciscoLwappReapGroupConfigUserAuthGroup.setStatus('current') ciscoLwappReapApConfigGroupHomeAp = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 6)).setObjects(("CISCO-LWAPP-REAP-MIB", "cLReapHomeApEnable"), ("CISCO-LWAPP-REAP-MIB", "cLReapApLeastLatencyJoinEnable"), ("CISCO-LWAPP-REAP-MIB", "cLReapWlanClientIpLearnEnable"), ("CISCO-LWAPP-REAP-MIB", "cLReapHomeApLocalSsidReset")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappReapApConfigGroupHomeAp = ciscoLwappReapApConfigGroupHomeAp.setStatus('current') ciscoLwappReapGroupConfigRadiusGroup1 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 7)).setObjects(("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusAuthorityId"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusAuthorityInfo"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusServerKey"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusIgnoreKey"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusEnable"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusLeapEnable"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusEapFastEnable"), ("CISCO-LWAPP-REAP-MIB", "cLReapGroupRadiusPacTimeoutCtrl")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappReapGroupConfigRadiusGroup1 = ciscoLwappReapGroupConfigRadiusGroup1.setStatus('current') ciscoLwappReapWlanConfigGroupSup1 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 8)).setObjects(("CISCO-LWAPP-REAP-MIB", "cLReapWlanApAuth")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoLwappReapWlanConfigGroupSup1 = ciscoLwappReapWlanConfigGroupSup1.setStatus('current') mibBuilder.exportSymbols("CISCO-LWAPP-REAP-MIB", cLReapGroupRadiusIgnoreKey=cLReapGroupRadiusIgnoreKey, cLReapGroupUserName=cLReapGroupUserName, cLReapApNativeVlanId=cLReapApNativeVlanId, cLReapWlanEnLocalSwitching=cLReapWlanEnLocalSwitching, cLReapGroupRadiusEnable=cLReapGroupRadiusEnable, cLReapGroupUserStorageType=cLReapGroupUserStorageType, ciscoLwappReapMIBComplianceRev1=ciscoLwappReapMIBComplianceRev1, cLReapGroupName=cLReapGroupName, ciscoLwappReapApConfig=ciscoLwappReapApConfig, cLReapApConfigEntry=cLReapApConfigEntry, cLReapGroupRadiusPacTimeout=cLReapGroupRadiusPacTimeout, cLReapApVlanId=cLReapApVlanId, cLReapGroupUserConfigEntry=cLReapGroupUserConfigEntry, cLReapGroupApRowStatus=cLReapGroupApRowStatus, PYSNMP_MODULE_ID=ciscoLwappReapMIB, ciscoLwappReapMIBComplianceRev4=ciscoLwappReapMIBComplianceRev4, ciscoLwappReapWlanConfigGroup=ciscoLwappReapWlanConfigGroup, ciscoLwappReapGroupConfigUserAuthGroup=ciscoLwappReapGroupConfigUserAuthGroup, ciscoLwappReapGroupConfigRadiusGroup1=ciscoLwappReapGroupConfigRadiusGroup1, cLReapGroupRadiusPacTimeoutCtrl=cLReapGroupRadiusPacTimeoutCtrl, cLReapGroupApConfigTable=cLReapGroupApConfigTable, cLReapWlanClientIpLearnEnable=cLReapWlanClientIpLearnEnable, cLReapApVlanIdTable=cLReapApVlanIdTable, cLReapGroupApConfigEntry=cLReapGroupApConfigEntry, cLReapGroupRadiusEapFastEnable=cLReapGroupRadiusEapFastEnable, cLReapGroupUserRowStatus=cLReapGroupUserRowStatus, cLReapApConfigTable=cLReapApConfigTable, ciscoLwappReapMIBGroups=ciscoLwappReapMIBGroups, cLReapGroupRadiusAuthorityId=cLReapGroupRadiusAuthorityId, ciscoLwappReapGroupConfigGroup=ciscoLwappReapGroupConfigGroup, cLReapWlanConfigTable=cLReapWlanConfigTable, cLReapHomeApEnable=cLReapHomeApEnable, cLReapGroupConfigTable=cLReapGroupConfigTable, ciscoLwappReapApConfigGroupHomeAp=ciscoLwappReapApConfigGroupHomeAp, cLReapGroupRadiusLeapEnable=cLReapGroupRadiusLeapEnable, ciscoLwappReapMIBNotifs=ciscoLwappReapMIBNotifs, cLReapApVlanIdEntry=cLReapApVlanIdEntry, cLReapGroupRadiusServerKey=cLReapGroupRadiusServerKey, ciscoLwappReapApConfigGroup=ciscoLwappReapApConfigGroup, cLReapWlanConfigEntry=cLReapWlanConfigEntry, cLReapGroupSecondaryRadiusIndex=cLReapGroupSecondaryRadiusIndex, ciscoLwappReapMIBObjects=ciscoLwappReapMIBObjects, cLReapHomeApLocalSsidReset=cLReapHomeApLocalSsidReset, ciscoLwappReapMIBComplianceRev2=ciscoLwappReapMIBComplianceRev2, ciscoLwappReapMIBComplianceRev5=ciscoLwappReapMIBComplianceRev5, ciscoLwappReapMIBConform=ciscoLwappReapMIBConform, cLReapGroupPrimaryRadiusIndex=cLReapGroupPrimaryRadiusIndex, ciscoLwappReapWlanConfigGroupSup1=ciscoLwappReapWlanConfigGroupSup1, cLReapGroupUserConfigTable=cLReapGroupUserConfigTable, cLReapGroupStorageType=cLReapGroupStorageType, ciscoLwappReapGroupConfigRadiusGroup=ciscoLwappReapGroupConfigRadiusGroup, ciscoLwappReapGroupConfig=ciscoLwappReapGroupConfig, cLReapApLeastLatencyJoinEnable=cLReapApLeastLatencyJoinEnable, ciscoLwappReapMIB=ciscoLwappReapMIB, cLReapWlanApAuth=cLReapWlanApAuth, ciscoLwappReapMIBCompliances=ciscoLwappReapMIBCompliances, cLReapGroupConfigEntry=cLReapGroupConfigEntry, ciscoLwappReapWlanConfig=ciscoLwappReapWlanConfig, ciscoLwappReapMIBCompliance=ciscoLwappReapMIBCompliance, cLReapGroupRowStatus=cLReapGroupRowStatus, cLReapGroupApStorageType=cLReapGroupApStorageType, cLReapGroupUserPassword=cLReapGroupUserPassword, ciscoLwappReapMIBComplianceRev3=ciscoLwappReapMIBComplianceRev3, cLReapApVlanEnable=cLReapApVlanEnable, cLReapGroupRadiusAuthorityInfo=cLReapGroupRadiusAuthorityInfo)
(octet_string, integer, object_identifier) = mibBuilder.importSymbols('ASN1', 'OctetString', 'Integer', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, constraints_union, value_size_constraint, single_value_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'ConstraintsUnion', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsIntersection') (c_l_ap_sys_mac_address,) = mibBuilder.importSymbols('CISCO-LWAPP-AP-MIB', 'cLApSysMacAddress') (c_l_wlan_index,) = mibBuilder.importSymbols('CISCO-LWAPP-WLAN-MIB', 'cLWlanIndex') (cisco_mgmt,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoMgmt') (snmp_admin_string,) = mibBuilder.importSymbols('SNMP-FRAMEWORK-MIB', 'SnmpAdminString') (object_group, notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'ObjectGroup', 'NotificationGroup', 'ModuleCompliance') (mib_scalar, mib_table, mib_table_row, mib_table_column, module_identity, unsigned32, counter32, gauge32, ip_address, counter64, integer32, mib_identifier, iso, object_identity, bits, notification_type, time_ticks) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'ModuleIdentity', 'Unsigned32', 'Counter32', 'Gauge32', 'IpAddress', 'Counter64', 'Integer32', 'MibIdentifier', 'iso', 'ObjectIdentity', 'Bits', 'NotificationType', 'TimeTicks') (textual_convention, row_status, truth_value, storage_type, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'RowStatus', 'TruthValue', 'StorageType', 'DisplayString') cisco_lwapp_reap_mib = module_identity((1, 3, 6, 1, 4, 1, 9, 9, 517)) ciscoLwappReapMIB.setRevisions(('2010-10-06 00:00', '2010-02-06 00:00', '2007-11-01 00:00', '2007-04-19 00:00', '2006-04-19 00:00')) if mibBuilder.loadTexts: ciscoLwappReapMIB.setLastUpdated('201010060000Z') if mibBuilder.loadTexts: ciscoLwappReapMIB.setOrganization('Cisco Systems Inc.') cisco_lwapp_reap_mib_notifs = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 0)) cisco_lwapp_reap_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 1)) cisco_lwapp_reap_mib_conform = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 2)) cisco_lwapp_reap_wlan_config = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 1)) cisco_lwapp_reap_ap_config = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2)) cisco_lwapp_reap_group_config = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3)) c_l_reap_wlan_config_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 1, 1)) if mibBuilder.loadTexts: cLReapWlanConfigTable.setStatus('current') c_l_reap_wlan_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 1, 1, 1)).setIndexNames((0, 'CISCO-LWAPP-WLAN-MIB', 'cLWlanIndex')) if mibBuilder.loadTexts: cLReapWlanConfigEntry.setStatus('current') c_l_reap_wlan_en_local_switching = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 1, 1, 1, 1), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: cLReapWlanEnLocalSwitching.setStatus('current') c_l_reap_wlan_client_ip_learn_enable = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 1, 1, 1, 2), truth_value().clone('true')).setMaxAccess('readwrite') if mibBuilder.loadTexts: cLReapWlanClientIpLearnEnable.setStatus('current') c_l_reap_wlan_ap_auth = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 1, 1, 1, 3), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: cLReapWlanApAuth.setStatus('current') c_l_reap_ap_config_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1)) if mibBuilder.loadTexts: cLReapApConfigTable.setStatus('current') c_l_reap_ap_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1, 1)).setIndexNames((0, 'CISCO-LWAPP-AP-MIB', 'cLApSysMacAddress')) if mibBuilder.loadTexts: cLReapApConfigEntry.setStatus('current') c_l_reap_ap_native_vlan_id = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 4095)).clone(1)).setMaxAccess('readwrite') if mibBuilder.loadTexts: cLReapApNativeVlanId.setStatus('current') c_l_reap_ap_vlan_enable = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1, 1, 2), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: cLReapApVlanEnable.setStatus('current') c_l_reap_home_ap_enable = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1, 1, 3), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: cLReapHomeApEnable.setStatus('current') c_l_reap_ap_least_latency_join_enable = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1, 1, 4), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: cLReapApLeastLatencyJoinEnable.setStatus('current') c_l_reap_home_ap_local_ssid_reset = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 1, 1, 5), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: cLReapHomeApLocalSsidReset.setStatus('current') c_l_reap_ap_vlan_id_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 2)) if mibBuilder.loadTexts: cLReapApVlanIdTable.setStatus('current') c_l_reap_ap_vlan_id_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 2, 1)).setIndexNames((0, 'CISCO-LWAPP-AP-MIB', 'cLApSysMacAddress'), (0, 'CISCO-LWAPP-WLAN-MIB', 'cLWlanIndex')) if mibBuilder.loadTexts: cLReapApVlanIdEntry.setStatus('current') c_l_reap_ap_vlan_id = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 2, 2, 1, 1), unsigned32().subtype(subtypeSpec=value_range_constraint(1, 4095)).clone(1)).setMaxAccess('readwrite') if mibBuilder.loadTexts: cLReapApVlanId.setStatus('current') c_l_reap_group_config_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1)) if mibBuilder.loadTexts: cLReapGroupConfigTable.setStatus('current') c_l_reap_group_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1)).setIndexNames((0, 'CISCO-LWAPP-REAP-MIB', 'cLReapGroupName')) if mibBuilder.loadTexts: cLReapGroupConfigEntry.setStatus('current') c_l_reap_group_name = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 1), snmp_admin_string()) if mibBuilder.loadTexts: cLReapGroupName.setStatus('current') c_l_reap_group_primary_radius_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 2), unsigned32()).setMaxAccess('readcreate') if mibBuilder.loadTexts: cLReapGroupPrimaryRadiusIndex.setStatus('current') c_l_reap_group_secondary_radius_index = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 3), unsigned32()).setMaxAccess('readcreate') if mibBuilder.loadTexts: cLReapGroupSecondaryRadiusIndex.setStatus('current') c_l_reap_group_storage_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 4), storage_type()).setMaxAccess('readcreate') if mibBuilder.loadTexts: cLReapGroupStorageType.setStatus('current') c_l_reap_group_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 5), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: cLReapGroupRowStatus.setStatus('current') c_l_reap_group_radius_pac_timeout = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 6), unsigned32().subtype(subtypeSpec=value_range_constraint(2, 4095)).clone(10)).setUnits('days').setMaxAccess('readcreate') if mibBuilder.loadTexts: cLReapGroupRadiusPacTimeout.setStatus('deprecated') c_l_reap_group_radius_authority_id = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 7), octet_string().subtype(subtypeSpec=value_size_constraint(0, 32))).setMaxAccess('readcreate') if mibBuilder.loadTexts: cLReapGroupRadiusAuthorityId.setStatus('current') c_l_reap_group_radius_authority_info = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 8), octet_string().subtype(subtypeSpec=value_size_constraint(0, 32))).setMaxAccess('readcreate') if mibBuilder.loadTexts: cLReapGroupRadiusAuthorityInfo.setStatus('current') c_l_reap_group_radius_server_key = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 9), octet_string().subtype(subtypeSpec=value_size_constraint(1, 32)).clone('****')).setMaxAccess('readcreate') if mibBuilder.loadTexts: cLReapGroupRadiusServerKey.setStatus('current') c_l_reap_group_radius_ignore_key = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 10), truth_value().clone('true')).setMaxAccess('readcreate') if mibBuilder.loadTexts: cLReapGroupRadiusIgnoreKey.setStatus('current') c_l_reap_group_radius_enable = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 11), truth_value().clone('false')).setMaxAccess('readcreate') if mibBuilder.loadTexts: cLReapGroupRadiusEnable.setStatus('current') c_l_reap_group_radius_leap_enable = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 12), truth_value().clone('false')).setMaxAccess('readcreate') if mibBuilder.loadTexts: cLReapGroupRadiusLeapEnable.setStatus('current') c_l_reap_group_radius_eap_fast_enable = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 13), truth_value().clone('false')).setMaxAccess('readcreate') if mibBuilder.loadTexts: cLReapGroupRadiusEapFastEnable.setStatus('current') c_l_reap_group_radius_pac_timeout_ctrl = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 1, 1, 14), unsigned32().subtype(subtypeSpec=value_range_constraint(0, 4095)).clone(10)).setUnits('seconds').setMaxAccess('readcreate') if mibBuilder.loadTexts: cLReapGroupRadiusPacTimeoutCtrl.setStatus('current') c_l_reap_group_ap_config_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 2)) if mibBuilder.loadTexts: cLReapGroupApConfigTable.setStatus('current') c_l_reap_group_ap_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 2, 1)).setIndexNames((0, 'CISCO-LWAPP-REAP-MIB', 'cLReapGroupName'), (0, 'CISCO-LWAPP-AP-MIB', 'cLApSysMacAddress')) if mibBuilder.loadTexts: cLReapGroupApConfigEntry.setStatus('current') c_l_reap_group_ap_storage_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 2, 1, 1), storage_type()).setMaxAccess('readcreate') if mibBuilder.loadTexts: cLReapGroupApStorageType.setStatus('current') c_l_reap_group_ap_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 2, 1, 2), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: cLReapGroupApRowStatus.setStatus('current') c_l_reap_group_user_config_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 3)) if mibBuilder.loadTexts: cLReapGroupUserConfigTable.setStatus('current') c_l_reap_group_user_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 3, 1)).setIndexNames((0, 'CISCO-LWAPP-REAP-MIB', 'cLReapGroupName'), (0, 'CISCO-LWAPP-REAP-MIB', 'cLReapGroupUserName')) if mibBuilder.loadTexts: cLReapGroupUserConfigEntry.setStatus('current') c_l_reap_group_user_name = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 3, 1, 1), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(1, 24))) if mibBuilder.loadTexts: cLReapGroupUserName.setStatus('current') c_l_reap_group_user_password = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 3, 1, 2), snmp_admin_string().subtype(subtypeSpec=value_size_constraint(1, 64))).setMaxAccess('readcreate') if mibBuilder.loadTexts: cLReapGroupUserPassword.setStatus('current') c_l_reap_group_user_storage_type = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 3, 1, 3), storage_type()).setMaxAccess('readcreate') if mibBuilder.loadTexts: cLReapGroupUserStorageType.setStatus('current') c_l_reap_group_user_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 517, 1, 3, 3, 1, 4), row_status()).setMaxAccess('readcreate') if mibBuilder.loadTexts: cLReapGroupUserRowStatus.setStatus('current') cisco_lwapp_reap_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1)) cisco_lwapp_reap_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2)) cisco_lwapp_reap_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1, 1)).setObjects(('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapWlanConfigGroup'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapApConfigGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_lwapp_reap_mib_compliance = ciscoLwappReapMIBCompliance.setStatus('deprecated') cisco_lwapp_reap_mib_compliance_rev1 = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1, 2)).setObjects(('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapWlanConfigGroup'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapApConfigGroup'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapGroupConfigGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_lwapp_reap_mib_compliance_rev1 = ciscoLwappReapMIBComplianceRev1.setStatus('deprecated') cisco_lwapp_reap_mib_compliance_rev2 = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1, 3)).setObjects(('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapWlanConfigGroup'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapApConfigGroup'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapGroupConfigGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_lwapp_reap_mib_compliance_rev2 = ciscoLwappReapMIBComplianceRev2.setStatus('deprecated') cisco_lwapp_reap_mib_compliance_rev3 = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1, 4)).setObjects(('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapWlanConfigGroup'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapApConfigGroup'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapGroupConfigGroup'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapGroupConfigRadiusGroup'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapGroupConfigUserAuthGroup'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapApConfigGroupHomeAp')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_lwapp_reap_mib_compliance_rev3 = ciscoLwappReapMIBComplianceRev3.setStatus('deprecated') cisco_lwapp_reap_mib_compliance_rev4 = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1, 5)).setObjects(('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapWlanConfigGroup'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapApConfigGroup'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapGroupConfigGroup'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapGroupConfigUserAuthGroup'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapApConfigGroupHomeAp'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapGroupConfigRadiusGroup1')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_lwapp_reap_mib_compliance_rev4 = ciscoLwappReapMIBComplianceRev4.setStatus('deprecated') cisco_lwapp_reap_mib_compliance_rev5 = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 1, 6)).setObjects(('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapWlanConfigGroup'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapApConfigGroup'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapGroupConfigGroup'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapGroupConfigUserAuthGroup'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapApConfigGroupHomeAp'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapGroupConfigRadiusGroup1'), ('CISCO-LWAPP-REAP-MIB', 'ciscoLwappReapWlanConfigGroupSup1')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_lwapp_reap_mib_compliance_rev5 = ciscoLwappReapMIBComplianceRev5.setStatus('current') cisco_lwapp_reap_wlan_config_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 1)).setObjects(('CISCO-LWAPP-REAP-MIB', 'cLReapWlanEnLocalSwitching')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_lwapp_reap_wlan_config_group = ciscoLwappReapWlanConfigGroup.setStatus('current') cisco_lwapp_reap_ap_config_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 2)).setObjects(('CISCO-LWAPP-REAP-MIB', 'cLReapApNativeVlanId'), ('CISCO-LWAPP-REAP-MIB', 'cLReapApVlanId'), ('CISCO-LWAPP-REAP-MIB', 'cLReapApVlanEnable')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_lwapp_reap_ap_config_group = ciscoLwappReapApConfigGroup.setStatus('current') cisco_lwapp_reap_group_config_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 3)).setObjects(('CISCO-LWAPP-REAP-MIB', 'cLReapGroupPrimaryRadiusIndex'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupSecondaryRadiusIndex'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupStorageType'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupRowStatus'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupApStorageType'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupApRowStatus')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_lwapp_reap_group_config_group = ciscoLwappReapGroupConfigGroup.setStatus('current') cisco_lwapp_reap_group_config_radius_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 4)).setObjects(('CISCO-LWAPP-REAP-MIB', 'cLReapGroupRadiusPacTimeout'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupRadiusAuthorityId'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupRadiusAuthorityInfo'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupRadiusServerKey'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupRadiusIgnoreKey'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupRadiusEnable'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupRadiusLeapEnable'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupRadiusEapFastEnable')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_lwapp_reap_group_config_radius_group = ciscoLwappReapGroupConfigRadiusGroup.setStatus('deprecated') cisco_lwapp_reap_group_config_user_auth_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 5)).setObjects(('CISCO-LWAPP-REAP-MIB', 'cLReapGroupUserPassword'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupUserStorageType'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupUserRowStatus')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_lwapp_reap_group_config_user_auth_group = ciscoLwappReapGroupConfigUserAuthGroup.setStatus('current') cisco_lwapp_reap_ap_config_group_home_ap = object_group((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 6)).setObjects(('CISCO-LWAPP-REAP-MIB', 'cLReapHomeApEnable'), ('CISCO-LWAPP-REAP-MIB', 'cLReapApLeastLatencyJoinEnable'), ('CISCO-LWAPP-REAP-MIB', 'cLReapWlanClientIpLearnEnable'), ('CISCO-LWAPP-REAP-MIB', 'cLReapHomeApLocalSsidReset')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_lwapp_reap_ap_config_group_home_ap = ciscoLwappReapApConfigGroupHomeAp.setStatus('current') cisco_lwapp_reap_group_config_radius_group1 = object_group((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 7)).setObjects(('CISCO-LWAPP-REAP-MIB', 'cLReapGroupRadiusAuthorityId'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupRadiusAuthorityInfo'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupRadiusServerKey'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupRadiusIgnoreKey'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupRadiusEnable'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupRadiusLeapEnable'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupRadiusEapFastEnable'), ('CISCO-LWAPP-REAP-MIB', 'cLReapGroupRadiusPacTimeoutCtrl')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_lwapp_reap_group_config_radius_group1 = ciscoLwappReapGroupConfigRadiusGroup1.setStatus('current') cisco_lwapp_reap_wlan_config_group_sup1 = object_group((1, 3, 6, 1, 4, 1, 9, 9, 517, 2, 2, 8)).setObjects(('CISCO-LWAPP-REAP-MIB', 'cLReapWlanApAuth')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_lwapp_reap_wlan_config_group_sup1 = ciscoLwappReapWlanConfigGroupSup1.setStatus('current') mibBuilder.exportSymbols('CISCO-LWAPP-REAP-MIB', cLReapGroupRadiusIgnoreKey=cLReapGroupRadiusIgnoreKey, cLReapGroupUserName=cLReapGroupUserName, cLReapApNativeVlanId=cLReapApNativeVlanId, cLReapWlanEnLocalSwitching=cLReapWlanEnLocalSwitching, cLReapGroupRadiusEnable=cLReapGroupRadiusEnable, cLReapGroupUserStorageType=cLReapGroupUserStorageType, ciscoLwappReapMIBComplianceRev1=ciscoLwappReapMIBComplianceRev1, cLReapGroupName=cLReapGroupName, ciscoLwappReapApConfig=ciscoLwappReapApConfig, cLReapApConfigEntry=cLReapApConfigEntry, cLReapGroupRadiusPacTimeout=cLReapGroupRadiusPacTimeout, cLReapApVlanId=cLReapApVlanId, cLReapGroupUserConfigEntry=cLReapGroupUserConfigEntry, cLReapGroupApRowStatus=cLReapGroupApRowStatus, PYSNMP_MODULE_ID=ciscoLwappReapMIB, ciscoLwappReapMIBComplianceRev4=ciscoLwappReapMIBComplianceRev4, ciscoLwappReapWlanConfigGroup=ciscoLwappReapWlanConfigGroup, ciscoLwappReapGroupConfigUserAuthGroup=ciscoLwappReapGroupConfigUserAuthGroup, ciscoLwappReapGroupConfigRadiusGroup1=ciscoLwappReapGroupConfigRadiusGroup1, cLReapGroupRadiusPacTimeoutCtrl=cLReapGroupRadiusPacTimeoutCtrl, cLReapGroupApConfigTable=cLReapGroupApConfigTable, cLReapWlanClientIpLearnEnable=cLReapWlanClientIpLearnEnable, cLReapApVlanIdTable=cLReapApVlanIdTable, cLReapGroupApConfigEntry=cLReapGroupApConfigEntry, cLReapGroupRadiusEapFastEnable=cLReapGroupRadiusEapFastEnable, cLReapGroupUserRowStatus=cLReapGroupUserRowStatus, cLReapApConfigTable=cLReapApConfigTable, ciscoLwappReapMIBGroups=ciscoLwappReapMIBGroups, cLReapGroupRadiusAuthorityId=cLReapGroupRadiusAuthorityId, ciscoLwappReapGroupConfigGroup=ciscoLwappReapGroupConfigGroup, cLReapWlanConfigTable=cLReapWlanConfigTable, cLReapHomeApEnable=cLReapHomeApEnable, cLReapGroupConfigTable=cLReapGroupConfigTable, ciscoLwappReapApConfigGroupHomeAp=ciscoLwappReapApConfigGroupHomeAp, cLReapGroupRadiusLeapEnable=cLReapGroupRadiusLeapEnable, ciscoLwappReapMIBNotifs=ciscoLwappReapMIBNotifs, cLReapApVlanIdEntry=cLReapApVlanIdEntry, cLReapGroupRadiusServerKey=cLReapGroupRadiusServerKey, ciscoLwappReapApConfigGroup=ciscoLwappReapApConfigGroup, cLReapWlanConfigEntry=cLReapWlanConfigEntry, cLReapGroupSecondaryRadiusIndex=cLReapGroupSecondaryRadiusIndex, ciscoLwappReapMIBObjects=ciscoLwappReapMIBObjects, cLReapHomeApLocalSsidReset=cLReapHomeApLocalSsidReset, ciscoLwappReapMIBComplianceRev2=ciscoLwappReapMIBComplianceRev2, ciscoLwappReapMIBComplianceRev5=ciscoLwappReapMIBComplianceRev5, ciscoLwappReapMIBConform=ciscoLwappReapMIBConform, cLReapGroupPrimaryRadiusIndex=cLReapGroupPrimaryRadiusIndex, ciscoLwappReapWlanConfigGroupSup1=ciscoLwappReapWlanConfigGroupSup1, cLReapGroupUserConfigTable=cLReapGroupUserConfigTable, cLReapGroupStorageType=cLReapGroupStorageType, ciscoLwappReapGroupConfigRadiusGroup=ciscoLwappReapGroupConfigRadiusGroup, ciscoLwappReapGroupConfig=ciscoLwappReapGroupConfig, cLReapApLeastLatencyJoinEnable=cLReapApLeastLatencyJoinEnable, ciscoLwappReapMIB=ciscoLwappReapMIB, cLReapWlanApAuth=cLReapWlanApAuth, ciscoLwappReapMIBCompliances=ciscoLwappReapMIBCompliances, cLReapGroupConfigEntry=cLReapGroupConfigEntry, ciscoLwappReapWlanConfig=ciscoLwappReapWlanConfig, ciscoLwappReapMIBCompliance=ciscoLwappReapMIBCompliance, cLReapGroupRowStatus=cLReapGroupRowStatus, cLReapGroupApStorageType=cLReapGroupApStorageType, cLReapGroupUserPassword=cLReapGroupUserPassword, ciscoLwappReapMIBComplianceRev3=ciscoLwappReapMIBComplianceRev3, cLReapApVlanEnable=cLReapApVlanEnable, cLReapGroupRadiusAuthorityInfo=cLReapGroupRadiusAuthorityInfo)
number = 15 while True: number += 1 last_digit = str(number)[-1:] if last_digit != '6': continue small = int(number / 10) large = int('6' + str(small)) if large % number == 0: print('--') print(str(number) + ' || ' + str(small) + ' : ' + str(large)) print('Division: ' + str(int(large / number))) if int(large / number) == 4: print('Answer: ' + str(number)) break
number = 15 while True: number += 1 last_digit = str(number)[-1:] if last_digit != '6': continue small = int(number / 10) large = int('6' + str(small)) if large % number == 0: print('--') print(str(number) + ' || ' + str(small) + ' : ' + str(large)) print('Division: ' + str(int(large / number))) if int(large / number) == 4: print('Answer: ' + str(number)) break
fake_users_db = { "typo11": { "username": "typo11", "full_name": "Tammy Cacablanka", "email": "tammy@localhost.com", "disabled": False, "hashed_password": "$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW" }, "typo12": { "username": "typo12", "full_name": "Sammy Cacablanka", "email": "master@localhost.com", "disabled": True, "hashed_password": "fakehashedsecret2" } }
fake_users_db = {'typo11': {'username': 'typo11', 'full_name': 'Tammy Cacablanka', 'email': 'tammy@localhost.com', 'disabled': False, 'hashed_password': '$2b$12$EixZaYVK1fsbw1ZfbX3OXePaWxn96p36WQoeG6Lruj3vjPGga31lW'}, 'typo12': {'username': 'typo12', 'full_name': 'Sammy Cacablanka', 'email': 'master@localhost.com', 'disabled': True, 'hashed_password': 'fakehashedsecret2'}}
""" DSC20 WI22 HW05 Name: William Trang PID: A16679845 """ # begin helper methods def ceil(x): """ Simulation to math.ceil No doctest needed """ if int(x) != x: return int(x) + 1 return int(x) def log(x): """ Simulation to math.log with base e No doctests needed """ n = 1e10 return n * ((x ** (1/n)) - 1) # end helper methods # Question1 def db_calc(dynamic, inst_mult): """ Given a musical dynamic abbreviation as a string and a multiplier inst_mult for louder and softer instruments as a float, compute the intial decibel level based on distance from the instrument. Parameters: dynamic: Abbreviation of music dynamic. inst_mult: Multiplier for louder/softer instruments. Returns: Function that computes intial decibel level of instrument for a given distance. >>> snare_1 = db_calc('ff', 1.2) >>> snare_1(0) 126 >>> snare_1(10) 80 >>> snare_1(50) 48 >>> db_calc('loud', 1)(35) Traceback (most recent call last): ... AssertionError >>> db_calc('pp', 1.200001)(50) Traceback (most recent call last): ... AssertionError # Add AT LEAST 3 doctests below, DO NOT delete this line >>> snare_2 = db_calc('p', 1.3) Traceback (most recent call last): ... AssertionError >>> snare_3 = db_calc('pp', 1) >>> snare_3(10) 0 >>> snare_4 = db_calc('pp', 'cha') Traceback (most recent call last): ... AssertionError """ assert isinstance(dynamic, str) assert isinstance(inst_mult, (float, int)) assert (inst_mult >= .8) and (inst_mult <= 1.2) db = {'pp': 30, 'p': 45, 'mp': 60, 'mf': 75, 'f': 90, 'ff': 105} assert dynamic in db db_init = db[dynamic] * inst_mult def db_level(distance): """ Computes the observed decibel level given a distance away from the instrument. Parameters: distance: Distance away from the instrument as an integer. Returns: Decibel level for given distance from instrument as an integer. """ assert isinstance(distance, int) assert distance >= 0 if distance == 0: return round(db_init) level = db_init - 20 * log(distance) if level < 0: return 0 return round(level) return db_level # Question2 def next_move(file_names, decision): """ Takes in a filepath containing constestant names and decisions, and a final decision to make. Returns a message for the contestants whose decisions match the final decisions. Parameters: file_names: Path to file containing names and decisions. decision: Final decision that determines which contestants are sent messages. Returns: Function that creates message for contestants that match the final decision. >>> message_to_students = next_move("files/names.txt", "h") >>> mess = message_to_students("Never give up!") >>> print(mess) Dear I! Unfortunately, it is time to go home. Never give up! >>> message_to_students = next_move("files/names.txt", "s") >>> mess = message_to_students("San Diego, Earth.") >>> print(mess) Dear A, C, E, G, K! We are happy to announce that you can move to the next round. It will be held at San Diego, Earth. # Add AT LEAST 3 doctests below, DO NOT delete this line >>> message_2 = next_move('files/names2.txt', 'h') >>> mess2 = message_2('It is all good.') >>> print(mess2) Dear Will, M! Unfortunately, it is time to go home. It is all good. >>> message_2 = next_move('files/names2.txt', 's') >>> mess2 = message_2('Yay!') >>> print(mess2) Dear Zhi! We are happy to announce that you can move to the next round. It will be held at Yay! >>> mess2 = message_2('MOS114') >>> print(mess2) Dear Zhi! We are happy to announce that you can move to the next round. It will be held at MOS114 """ f_name = 0 dec_index = 3 name_list = [] tmp = '' with open(file_names, 'r') as f: for line in f: tmp = line.split(',') if tmp[dec_index].strip().lower() == decision.lower(): name_list.append(tmp[f_name]) def final_message(message): """ Creates and returns a string final_message based on an inputted message. Parameters: message: Custom message to send to participants matching the decision. Returns: A predetermined string message along with the custom message to send. """ output_str = 'Dear ' + ', '.join(name_list) + '!\n' if decision == 's': output_str += 'We are happy to announce that you can \ move to the next round.\nIt will be held at \ ' + message else: output_str += 'Unfortunately, it is time to go home. ' + message return output_str return final_message # Question3 def forge(filepath): """ Reads a given filepath containing names and votes with votes being 1 and 0, and changes people's votes in the file to make the majority vote what is desired. Parameters: filepath: Path to file containing names and votes. Returns: Function that forges votes in the file. >>> forge('files/vote1.txt')(0) >>> with open('files/vote1.txt', 'r') as outfile1: ... print(outfile1.read().strip()) Jerry,0 Larry,0 Colin,0 Scott,0 Jianming,0 Huaning,1 Amy,1 Elvy,1 >>> forge('files/vote2.txt')(0) >>> with open('files/vote2.txt', 'r') as outfile2: ... print(outfile2.read().strip()) Jerry,0 Larry,0 Colin,0 Scott,1 Jianming,0 Huaning,1 Amy,1 Elvy,0 >>> forge('files/vote3.txt')(1) >>> with open('files/vote3.txt', 'r') as outfile3: ... print(outfile3.read().strip()) Jerry,1 Larry,1 Colin,1 Scott,0 # Add AT LEAST 3 doctests below, DO NOT delete this line >>> forge('files/vote4.txt')(1) >>> with open('files/vote4.txt', 'r') as outfile4: ... print(outfile4.read().strip()) Will,1 Zhi,1 TL,1 DJ,0 Rj,0 RD,1 >>> forge('files/vote5.txt')(0) >>> with open('files/vote5.txt', 'r') as outfile5: ... print(outfile5.read().strip()) Will,0 Zhi,0 TL,1 DJ,0 Rj,0 RD,1 >>> forge('files/vote6.txt')(1) >>> with open('files/vote6.txt', 'r') as outfile6: ... print(outfile6.read().strip()) Will,1 """ votes = {0: 0, 1: 0} vote_index = 1 name_index = 0 with open(filepath, 'r') as f: for line in f: votes[int(line.split(',')[vote_index])] += 1 majority = int((votes[0] + votes[1]) / 2) + 1 def change_votes(wanted): """ Takes in a vote that is the desired result of the voting process. Write to the file to make the wanted vote the majority vote. Parameters: wanted: The desired majority in the voting process. """ votes_to_change = majority - votes[wanted] new_votes = '' with open(filepath, 'r') as f: for line in f: if votes_to_change > 0: if int(line.split(',')[vote_index]) != int(wanted): new_votes += line.split(',')[name_index] + \ ',' + str(wanted) + '\n' votes_to_change -= 1 else: new_votes += line else: new_votes += line with open(filepath, 'w') as f: f.write(new_votes) return change_votes # Question4.1 def number_of_adults_1(lst, age = 18): """ Takes in a list of integers containing ages and an age threshold, and returns the number of adults needed to supervise people below the age threshold. Each adult can supervise three people. Parameters: lst: List containing ages of people as integers. age: Age threshold where people no longer need supervision. Default value is 18. Returns: Number of adults needed to supervise people under the age threshold. >>> number_of_adults_1([1,2,3,4,5,6,7]) 3 >>> number_of_adults_1([1,2,3,4,5,6,7], 5) 2 >>> number_of_adults_1([1,2,3,4,5,6,7], age = 2) 1 # Add AT LEAST 3 doctests below, DO NOT delete this line >>> number_of_adults_1([18, 20, 19, 90]) 0 >>> number_of_adults_1([1,2,3,4,5,6,7], 2) 1 >>> number_of_adults_1([]) 0 """ adults_per_kid = 3 return ceil(len([ages for ages in lst if ages < age]) / adults_per_kid) # Question4.2 def number_of_adults_2(*args): """ Takes in positional arguments of integer ages, and returns the number of adults needed to supervise people below the age threshold which is 18. One adult can supervise three people. Parameters: *args: Positional arguments that designate age. Returns: Number of adults needed to supervise people below eighteen years old. >>> number_of_adults_2(1,2,3,4,5,6,7) 3 >>> number_of_adults_2(10,20,13,4) 1 >>> number_of_adults_2(19, 20) 0 # Add AT LEAST 3 doctests below, DO NOT delete this line >>> number_of_adults_2(1,2,3,4,5,6,7,8,9,10,19) 4 >>> number_of_adults_2(10) 1 >>> number_of_adults_2(0) 1 """ adults_per_kid = 3 age_threshold = 18 return ceil(len([ages for ages in args \ if ages < age_threshold]) / adults_per_kid) # Question4.3 def number_of_adults_3(*args, age = 18): """ Takes in positional arguments of integer ages, and returns the number of adults needed to supervise people below the given age threshold. One adult can supervise three people. Parameters: *args: Positional arguments that designate age. age: Age threshold where people no longer need supervision. Default value is 18. Returns: Number of adults needed to supervise people below age threshold. >>> number_of_adults_3(1,2,3,4,5,6,7) 3 >>> number_of_adults_3(1,2,3,4,5,6,7, age = 5) 2 >>> number_of_adults_3(1,2,3,4,5,6,7, age = 2) 1 # Add AT LEAST 3 doctests below, DO NOT delete this line >>> number_of_adults_3(19,19,20,20,31) 0 >>> number_of_adults_3(1,2,3,4,5,6,7, 5) 3 >>> number_of_adults_3(19,20,21, age = 42) 1 """ adults_per_kid = 3 return ceil(len([ages for ages in args if ages < age]) / adults_per_kid) # Question5 def school_trip(age_limit, **kwargs): """ Given a set of keyword arguments with key being each class and the values being ages in the class, return a dictionary where keys are classes and values are the number of adults needed to supervise the people in the class. Kids below the age limit need supervision and adults can supervise up to 3 kids. Parameters: age_limit: Age threshold where people no longer need supervision. **kwargs: Keyword arguments where key is class and values are a list of ages in the class. Returns: Dictionary where keys are classes and values are number of adults needed to supervise the class. >>> school_trip(14, class1=[1,2,3], class2 =[4,5,6,7], class3=[15,16]) {'class1': 1, 'class2': 2, 'class3': 0} >>> school_trip(14, class1=[21,3], class2 =[41,1,2,24,6], class3=[30,3,1,7,88]) {'class1': 1, 'class2': 1, 'class3': 1} >>> school_trip(100, class1=[21,3], class2 =[41,1000,2,24,6], class3=[3,1,7,88]) {'class1': 1, 'class2': 2, 'class3': 2} # Add AT LEAST 3 doctests below, DO NOT delete this line >>> school_trip(2, class2=[2,2,2], class3=[3,3,3,3,3,3,3], class4=[4,4,4]) {'class2': 0, 'class3': 0, 'class4': 0} >>> school_trip(11, class1=[12,13,14,15], class2=[10,10,10,11]) {'class1': 0, 'class2': 1} >>> school_trip(15, class1=[12,13,14,15], \ class2=[10,10,10,11,12,13,14,14,14,14]) {'class1': 1, 'class2': 4} """ trip = [] for keys, values in kwargs.items(): trip.append((keys, number_of_adults_3(*values, age = age_limit))) return dict(trip) # Question6 def rearrange_args(*args, **kwargs): """ Given positional arguments and keyword arguments, return a list of tuples containing the type of argument and number of the argument as well as its value. Parameters: *args: Random positional arguments. **kwargs: Random keyword arguments. Returns: List of tuples where the first value of the tuple is the type of argument with its number and the second value is the value of the argument. Keyword arguments' first value also contains the key of the keyword argument. >>> rearrange_args(10, False, player1=[25, 30], player2=[5, 50]) [('positional_0', 10), ('positional_1', False), \ ('keyword_0_player1', [25, 30]), ('keyword_1_player2', [5, 50])] >>> rearrange_args('L', 'A', 'N', 'G', L='O', I='S') [('positional_0', 'L'), ('positional_1', 'A'), ('positional_2', 'N'), \ ('positional_3', 'G'), ('keyword_0_L', 'O'), ('keyword_1_I', 'S')] >>> rearrange_args(no_positional=True) [('keyword_0_no_positional', True)] # Add AT LEAST 3 doctests below, DO NOT delete this line >>> rearrange_args(11, 'no_kw') [('positional_0', 11), ('positional_1', 'no_kw')] >>> rearrange_args(11, keyW = 'MONKEY!!!!') [('positional_0', 11), ('keyword_0_keyW', 'MONKEY!!!!')] >>> rearrange_args(keyW = 4.0, d11='C') [('keyword_0_keyW', 4.0), ('keyword_1_d11', 'C')] """ key_index = 0 val_index = 1 return [('positional_' + str(count), arg) for count, arg\ in list(enumerate(args))] + [('keyword_' + str(num) + '_' + \ str(dic[key_index]), dic[val_index]) \ for num, dic in enumerate(kwargs.items())]
""" DSC20 WI22 HW05 Name: William Trang PID: A16679845 """ def ceil(x): """ Simulation to math.ceil No doctest needed """ if int(x) != x: return int(x) + 1 return int(x) def log(x): """ Simulation to math.log with base e No doctests needed """ n = 10000000000.0 return n * (x ** (1 / n) - 1) def db_calc(dynamic, inst_mult): """ Given a musical dynamic abbreviation as a string and a multiplier inst_mult for louder and softer instruments as a float, compute the intial decibel level based on distance from the instrument. Parameters: dynamic: Abbreviation of music dynamic. inst_mult: Multiplier for louder/softer instruments. Returns: Function that computes intial decibel level of instrument for a given distance. >>> snare_1 = db_calc('ff', 1.2) >>> snare_1(0) 126 >>> snare_1(10) 80 >>> snare_1(50) 48 >>> db_calc('loud', 1)(35) Traceback (most recent call last): ... AssertionError >>> db_calc('pp', 1.200001)(50) Traceback (most recent call last): ... AssertionError # Add AT LEAST 3 doctests below, DO NOT delete this line >>> snare_2 = db_calc('p', 1.3) Traceback (most recent call last): ... AssertionError >>> snare_3 = db_calc('pp', 1) >>> snare_3(10) 0 >>> snare_4 = db_calc('pp', 'cha') Traceback (most recent call last): ... AssertionError """ assert isinstance(dynamic, str) assert isinstance(inst_mult, (float, int)) assert inst_mult >= 0.8 and inst_mult <= 1.2 db = {'pp': 30, 'p': 45, 'mp': 60, 'mf': 75, 'f': 90, 'ff': 105} assert dynamic in db db_init = db[dynamic] * inst_mult def db_level(distance): """ Computes the observed decibel level given a distance away from the instrument. Parameters: distance: Distance away from the instrument as an integer. Returns: Decibel level for given distance from instrument as an integer. """ assert isinstance(distance, int) assert distance >= 0 if distance == 0: return round(db_init) level = db_init - 20 * log(distance) if level < 0: return 0 return round(level) return db_level def next_move(file_names, decision): """ Takes in a filepath containing constestant names and decisions, and a final decision to make. Returns a message for the contestants whose decisions match the final decisions. Parameters: file_names: Path to file containing names and decisions. decision: Final decision that determines which contestants are sent messages. Returns: Function that creates message for contestants that match the final decision. >>> message_to_students = next_move("files/names.txt", "h") >>> mess = message_to_students("Never give up!") >>> print(mess) Dear I! Unfortunately, it is time to go home. Never give up! >>> message_to_students = next_move("files/names.txt", "s") >>> mess = message_to_students("San Diego, Earth.") >>> print(mess) Dear A, C, E, G, K! We are happy to announce that you can move to the next round. It will be held at San Diego, Earth. # Add AT LEAST 3 doctests below, DO NOT delete this line >>> message_2 = next_move('files/names2.txt', 'h') >>> mess2 = message_2('It is all good.') >>> print(mess2) Dear Will, M! Unfortunately, it is time to go home. It is all good. >>> message_2 = next_move('files/names2.txt', 's') >>> mess2 = message_2('Yay!') >>> print(mess2) Dear Zhi! We are happy to announce that you can move to the next round. It will be held at Yay! >>> mess2 = message_2('MOS114') >>> print(mess2) Dear Zhi! We are happy to announce that you can move to the next round. It will be held at MOS114 """ f_name = 0 dec_index = 3 name_list = [] tmp = '' with open(file_names, 'r') as f: for line in f: tmp = line.split(',') if tmp[dec_index].strip().lower() == decision.lower(): name_list.append(tmp[f_name]) def final_message(message): """ Creates and returns a string final_message based on an inputted message. Parameters: message: Custom message to send to participants matching the decision. Returns: A predetermined string message along with the custom message to send. """ output_str = 'Dear ' + ', '.join(name_list) + '!\n' if decision == 's': output_str += 'We are happy to announce that you can move to the next round.\nIt will be held at ' + message else: output_str += 'Unfortunately, it is time to go home. ' + message return output_str return final_message def forge(filepath): """ Reads a given filepath containing names and votes with votes being 1 and 0, and changes people's votes in the file to make the majority vote what is desired. Parameters: filepath: Path to file containing names and votes. Returns: Function that forges votes in the file. >>> forge('files/vote1.txt')(0) >>> with open('files/vote1.txt', 'r') as outfile1: ... print(outfile1.read().strip()) Jerry,0 Larry,0 Colin,0 Scott,0 Jianming,0 Huaning,1 Amy,1 Elvy,1 >>> forge('files/vote2.txt')(0) >>> with open('files/vote2.txt', 'r') as outfile2: ... print(outfile2.read().strip()) Jerry,0 Larry,0 Colin,0 Scott,1 Jianming,0 Huaning,1 Amy,1 Elvy,0 >>> forge('files/vote3.txt')(1) >>> with open('files/vote3.txt', 'r') as outfile3: ... print(outfile3.read().strip()) Jerry,1 Larry,1 Colin,1 Scott,0 # Add AT LEAST 3 doctests below, DO NOT delete this line >>> forge('files/vote4.txt')(1) >>> with open('files/vote4.txt', 'r') as outfile4: ... print(outfile4.read().strip()) Will,1 Zhi,1 TL,1 DJ,0 Rj,0 RD,1 >>> forge('files/vote5.txt')(0) >>> with open('files/vote5.txt', 'r') as outfile5: ... print(outfile5.read().strip()) Will,0 Zhi,0 TL,1 DJ,0 Rj,0 RD,1 >>> forge('files/vote6.txt')(1) >>> with open('files/vote6.txt', 'r') as outfile6: ... print(outfile6.read().strip()) Will,1 """ votes = {0: 0, 1: 0} vote_index = 1 name_index = 0 with open(filepath, 'r') as f: for line in f: votes[int(line.split(',')[vote_index])] += 1 majority = int((votes[0] + votes[1]) / 2) + 1 def change_votes(wanted): """ Takes in a vote that is the desired result of the voting process. Write to the file to make the wanted vote the majority vote. Parameters: wanted: The desired majority in the voting process. """ votes_to_change = majority - votes[wanted] new_votes = '' with open(filepath, 'r') as f: for line in f: if votes_to_change > 0: if int(line.split(',')[vote_index]) != int(wanted): new_votes += line.split(',')[name_index] + ',' + str(wanted) + '\n' votes_to_change -= 1 else: new_votes += line else: new_votes += line with open(filepath, 'w') as f: f.write(new_votes) return change_votes def number_of_adults_1(lst, age=18): """ Takes in a list of integers containing ages and an age threshold, and returns the number of adults needed to supervise people below the age threshold. Each adult can supervise three people. Parameters: lst: List containing ages of people as integers. age: Age threshold where people no longer need supervision. Default value is 18. Returns: Number of adults needed to supervise people under the age threshold. >>> number_of_adults_1([1,2,3,4,5,6,7]) 3 >>> number_of_adults_1([1,2,3,4,5,6,7], 5) 2 >>> number_of_adults_1([1,2,3,4,5,6,7], age = 2) 1 # Add AT LEAST 3 doctests below, DO NOT delete this line >>> number_of_adults_1([18, 20, 19, 90]) 0 >>> number_of_adults_1([1,2,3,4,5,6,7], 2) 1 >>> number_of_adults_1([]) 0 """ adults_per_kid = 3 return ceil(len([ages for ages in lst if ages < age]) / adults_per_kid) def number_of_adults_2(*args): """ Takes in positional arguments of integer ages, and returns the number of adults needed to supervise people below the age threshold which is 18. One adult can supervise three people. Parameters: *args: Positional arguments that designate age. Returns: Number of adults needed to supervise people below eighteen years old. >>> number_of_adults_2(1,2,3,4,5,6,7) 3 >>> number_of_adults_2(10,20,13,4) 1 >>> number_of_adults_2(19, 20) 0 # Add AT LEAST 3 doctests below, DO NOT delete this line >>> number_of_adults_2(1,2,3,4,5,6,7,8,9,10,19) 4 >>> number_of_adults_2(10) 1 >>> number_of_adults_2(0) 1 """ adults_per_kid = 3 age_threshold = 18 return ceil(len([ages for ages in args if ages < age_threshold]) / adults_per_kid) def number_of_adults_3(*args, age=18): """ Takes in positional arguments of integer ages, and returns the number of adults needed to supervise people below the given age threshold. One adult can supervise three people. Parameters: *args: Positional arguments that designate age. age: Age threshold where people no longer need supervision. Default value is 18. Returns: Number of adults needed to supervise people below age threshold. >>> number_of_adults_3(1,2,3,4,5,6,7) 3 >>> number_of_adults_3(1,2,3,4,5,6,7, age = 5) 2 >>> number_of_adults_3(1,2,3,4,5,6,7, age = 2) 1 # Add AT LEAST 3 doctests below, DO NOT delete this line >>> number_of_adults_3(19,19,20,20,31) 0 >>> number_of_adults_3(1,2,3,4,5,6,7, 5) 3 >>> number_of_adults_3(19,20,21, age = 42) 1 """ adults_per_kid = 3 return ceil(len([ages for ages in args if ages < age]) / adults_per_kid) def school_trip(age_limit, **kwargs): """ Given a set of keyword arguments with key being each class and the values being ages in the class, return a dictionary where keys are classes and values are the number of adults needed to supervise the people in the class. Kids below the age limit need supervision and adults can supervise up to 3 kids. Parameters: age_limit: Age threshold where people no longer need supervision. **kwargs: Keyword arguments where key is class and values are a list of ages in the class. Returns: Dictionary where keys are classes and values are number of adults needed to supervise the class. >>> school_trip(14, class1=[1,2,3], class2 =[4,5,6,7], class3=[15,16]) {'class1': 1, 'class2': 2, 'class3': 0} >>> school_trip(14, class1=[21,3], class2 =[41,1,2,24,6], class3=[30,3,1,7,88]) {'class1': 1, 'class2': 1, 'class3': 1} >>> school_trip(100, class1=[21,3], class2 =[41,1000,2,24,6], class3=[3,1,7,88]) {'class1': 1, 'class2': 2, 'class3': 2} # Add AT LEAST 3 doctests below, DO NOT delete this line >>> school_trip(2, class2=[2,2,2], class3=[3,3,3,3,3,3,3], class4=[4,4,4]) {'class2': 0, 'class3': 0, 'class4': 0} >>> school_trip(11, class1=[12,13,14,15], class2=[10,10,10,11]) {'class1': 0, 'class2': 1} >>> school_trip(15, class1=[12,13,14,15], class2=[10,10,10,11,12,13,14,14,14,14]) {'class1': 1, 'class2': 4} """ trip = [] for (keys, values) in kwargs.items(): trip.append((keys, number_of_adults_3(*values, age=age_limit))) return dict(trip) def rearrange_args(*args, **kwargs): """ Given positional arguments and keyword arguments, return a list of tuples containing the type of argument and number of the argument as well as its value. Parameters: *args: Random positional arguments. **kwargs: Random keyword arguments. Returns: List of tuples where the first value of the tuple is the type of argument with its number and the second value is the value of the argument. Keyword arguments' first value also contains the key of the keyword argument. >>> rearrange_args(10, False, player1=[25, 30], player2=[5, 50]) [('positional_0', 10), ('positional_1', False), ('keyword_0_player1', [25, 30]), ('keyword_1_player2', [5, 50])] >>> rearrange_args('L', 'A', 'N', 'G', L='O', I='S') [('positional_0', 'L'), ('positional_1', 'A'), ('positional_2', 'N'), ('positional_3', 'G'), ('keyword_0_L', 'O'), ('keyword_1_I', 'S')] >>> rearrange_args(no_positional=True) [('keyword_0_no_positional', True)] # Add AT LEAST 3 doctests below, DO NOT delete this line >>> rearrange_args(11, 'no_kw') [('positional_0', 11), ('positional_1', 'no_kw')] >>> rearrange_args(11, keyW = 'MONKEY!!!!') [('positional_0', 11), ('keyword_0_keyW', 'MONKEY!!!!')] >>> rearrange_args(keyW = 4.0, d11='C') [('keyword_0_keyW', 4.0), ('keyword_1_d11', 'C')] """ key_index = 0 val_index = 1 return [('positional_' + str(count), arg) for (count, arg) in list(enumerate(args))] + [('keyword_' + str(num) + '_' + str(dic[key_index]), dic[val_index]) for (num, dic) in enumerate(kwargs.items())]
# Aidan Conlon - 27 March 2019 # This is the solution to Problem 6 # Write a program that takes a user input string and outputs every second word. UserInput = input("Please enter a string of text:") # Print to screen the comment and take a value entered by the user. for i, word in enumerate(UserInput.split()): # Use a for loop to pull each word from the sentence using a split function if i %2 == 0: # if i is divisible by 2 with no carry then it is the 1st, 3rd, 5th word etc. in the entered sentence. print("%s" % (word), sep=' ', end=' ') # Print the string given the value of word (for this iteration of i), usng concatenation of each word seperated by a space quit() # Quit the program
user_input = input('Please enter a string of text:') for (i, word) in enumerate(UserInput.split()): if i % 2 == 0: print('%s' % word, sep=' ', end=' ') quit()
# THIS IS STATIC WEEKDAYS = { 0: "Monday", 1: "Tuesday", 2: "Wednesday", 3: "Thursday", 4: "Friday", 5: "Saturday", 6: "Sunday" } CLASS_MAP = { 1: "Art", 2: "Geography", 3: "Science" } ENTRIES = { "Monday": { 1: { "class_name": CLASS_MAP[1], "meeting_time": [9,10], "meeting_link": "zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1" }, 2: { "class_name": CLASS_MAP[2], "meeting_time": [10,12], "meeting_link": "zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1" }, 3: { "class_name": CLASS_MAP[3], "meeting_time": [12,13], "meeting_link": "zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1" } }, "Tuesday": { 1: { "class_name": CLASS_MAP[2], "meeting_time": [11,12], "meeting_link": "zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1" }, }, "Wednesday": { 1: { "class_name": CLASS_MAP[3], "meeting_time": [12,13], "meeting_link": "zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1" } }, "Thursday": { 1: { "class_name": CLASS_MAP[1], "meeting_time": [14,15], "meeting_link": "zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1" }, 2: { "class_name": CLASS_MAP[2], "meeting_time": [17,18], "meeting_link": "zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1" } }, "Friday": {}, }
weekdays = {0: 'Monday', 1: 'Tuesday', 2: 'Wednesday', 3: 'Thursday', 4: 'Friday', 5: 'Saturday', 6: 'Sunday'} class_map = {1: 'Art', 2: 'Geography', 3: 'Science'} entries = {'Monday': {1: {'class_name': CLASS_MAP[1], 'meeting_time': [9, 10], 'meeting_link': 'zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1'}, 2: {'class_name': CLASS_MAP[2], 'meeting_time': [10, 12], 'meeting_link': 'zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1'}, 3: {'class_name': CLASS_MAP[3], 'meeting_time': [12, 13], 'meeting_link': 'zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1'}}, 'Tuesday': {1: {'class_name': CLASS_MAP[2], 'meeting_time': [11, 12], 'meeting_link': 'zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1'}}, 'Wednesday': {1: {'class_name': CLASS_MAP[3], 'meeting_time': [12, 13], 'meeting_link': 'zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1'}}, 'Thursday': {1: {'class_name': CLASS_MAP[1], 'meeting_time': [14, 15], 'meeting_link': 'zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1'}, 2: {'class_name': CLASS_MAP[2], 'meeting_time': [17, 18], 'meeting_link': 'zoommtg://port-ac-uk.zoom.us/join?action=join&confno=5453452341&pwd=c8j88912u391n8m2d98sumd98u1'}}, 'Friday': {}}
# -*- coding: utf-8 -*- def test_search_all(slack_time): assert slack_time.search.all def test_search_files(slack_time): assert slack_time.search.files def test_search_messages(slack_time): assert slack_time.search.messages
def test_search_all(slack_time): assert slack_time.search.all def test_search_files(slack_time): assert slack_time.search.files def test_search_messages(slack_time): assert slack_time.search.messages
class SegmentTreeNode: def __init__(self, start, end, max): self.start, self.end, self.max = start, end, max self.left, self.right = None, None class Solution: """ @param root: The root of segment tree. @param index: index. @param value: value @return: nothing """ def modify(self, root, index, value): if root.start == root.end and root.start == index : root.max = value return mid = (root.start+root.end)//2 if index>mid : self.modify(root.right,index,value) else : self.modify(root.left,index,value) root.max = max(root.left.max,root.right.max)
class Segmenttreenode: def __init__(self, start, end, max): (self.start, self.end, self.max) = (start, end, max) (self.left, self.right) = (None, None) class Solution: """ @param root: The root of segment tree. @param index: index. @param value: value @return: nothing """ def modify(self, root, index, value): if root.start == root.end and root.start == index: root.max = value return mid = (root.start + root.end) // 2 if index > mid: self.modify(root.right, index, value) else: self.modify(root.left, index, value) root.max = max(root.left.max, root.right.max)
class RssItem: """A class used to represent an RSS post""" def __init__(self, title, description, link, pub_date): self.title = title self.description = description self.link = link self.pub_date = pub_date
class Rssitem: """A class used to represent an RSS post""" def __init__(self, title, description, link, pub_date): self.title = title self.description = description self.link = link self.pub_date = pub_date
# Copyright 2014 The Chromium Authors. All rights reserved. # Use of this source code is governed by a BSD-style license that can be # found in the LICENSE file. # Pre-caching steps used internally by the IDL compiler # # Design doc: http://www.chromium.org/developers/design-documents/idl-build { 'includes': [ 'scripts.gypi', '../bindings.gypi', '../templates/templates.gypi', ], 'targets': [ ################################################################################ { # This separate pre-caching step is required to use lex/parse table caching # in PLY, since PLY itself does not check if the cache is valid, and may end # up using a stale cache if this step hasn't been run to update it. # # This action's dependencies *is* the cache validation. # # GN version: //third_party/WebKit/Source/bindings/scripts:cached_lex_yacc_tables 'target_name': 'cached_lex_yacc_tables', 'type': 'none', 'actions': [{ 'action_name': 'cache_lex_yacc_tables', 'inputs': [ '<@(idl_lexer_parser_files)', ], 'outputs': [ '<(bindings_scripts_output_dir)/lextab.py', '<(bindings_scripts_output_dir)/parsetab.pickle', ], 'action': [ 'python', 'blink_idl_parser.py', '<(bindings_scripts_output_dir)', ], 'message': 'Caching PLY lex & yacc lex/parse tables', }], }, ################################################################################ { # A separate pre-caching step is *required* to use bytecode caching in # Jinja (which improves speed significantly), as the bytecode cache is # not concurrency-safe on write; details in code_generator_v8.py. # # GN version: //third_party/WebKit/Source/bindings/scripts:cached_jinja_templates 'target_name': 'cached_jinja_templates', 'type': 'none', 'actions': [{ 'action_name': 'cache_jinja_templates', 'inputs': [ '<@(jinja_module_files)', 'code_generator_v8.py', '<@(code_generator_template_files)', ], 'outputs': [ '<(bindings_scripts_output_dir)/cached_jinja_templates.stamp', # Dummy to track dependency ], 'action': [ 'python', 'code_generator_v8.py', '<(bindings_scripts_output_dir)', '<(bindings_scripts_output_dir)/cached_jinja_templates.stamp', ], 'message': 'Caching bytecode of Jinja templates', }], }, ################################################################################ ], # targets }
{'includes': ['scripts.gypi', '../bindings.gypi', '../templates/templates.gypi'], 'targets': [{'target_name': 'cached_lex_yacc_tables', 'type': 'none', 'actions': [{'action_name': 'cache_lex_yacc_tables', 'inputs': ['<@(idl_lexer_parser_files)'], 'outputs': ['<(bindings_scripts_output_dir)/lextab.py', '<(bindings_scripts_output_dir)/parsetab.pickle'], 'action': ['python', 'blink_idl_parser.py', '<(bindings_scripts_output_dir)'], 'message': 'Caching PLY lex & yacc lex/parse tables'}]}, {'target_name': 'cached_jinja_templates', 'type': 'none', 'actions': [{'action_name': 'cache_jinja_templates', 'inputs': ['<@(jinja_module_files)', 'code_generator_v8.py', '<@(code_generator_template_files)'], 'outputs': ['<(bindings_scripts_output_dir)/cached_jinja_templates.stamp'], 'action': ['python', 'code_generator_v8.py', '<(bindings_scripts_output_dir)', '<(bindings_scripts_output_dir)/cached_jinja_templates.stamp'], 'message': 'Caching bytecode of Jinja templates'}]}]}
# automatically generated by the FlatBuffers compiler, do not modify # namespace: enums class DateGenerationRule(object): Backward = 0 CDS = 1 Forward = 2 OldCDS = 3 ThirdWednesday = 4 Twentieth = 5 TwentiethIMM = 6 Zero = 7
class Dategenerationrule(object): backward = 0 cds = 1 forward = 2 old_cds = 3 third_wednesday = 4 twentieth = 5 twentieth_imm = 6 zero = 7
n=int(input("Enter a number:")) print("The number is",n) sum=0 while(n>0 or sum>9): if(n==0): n=sum sum=0 sum=sum+n%10 n=n//10 print(f"sum of the digits is:", sum) if(sum==1): print("it is a magic number") else: print("It is not a magic number")
n = int(input('Enter a number:')) print('The number is', n) sum = 0 while n > 0 or sum > 9: if n == 0: n = sum sum = 0 sum = sum + n % 10 n = n // 10 print(f'sum of the digits is:', sum) if sum == 1: print('it is a magic number') else: print('It is not a magic number')
# https://docs.python.org/3/library/exceptions.html class person: def __init__(self, age, name): if type(age)!=int: raise Exception("Invaild Age: {}".format(age)) if age<0: raise Exception("Invaild Age: {}".format(age)) if type(name)!=str: raise Exception("Name not string: {}".format(name)) self.name=name self.age=age x=person("-9", 1243)
class Person: def __init__(self, age, name): if type(age) != int: raise exception('Invaild Age: {}'.format(age)) if age < 0: raise exception('Invaild Age: {}'.format(age)) if type(name) != str: raise exception('Name not string: {}'.format(name)) self.name = name self.age = age x = person('-9', 1243)
#Exercise! #Display the image below to the right hand side where the 0 is going to be ' ', # and the 1 is going to be '*'. This will reveal an image! picture = [ [0,0,0,1,0,0,0], [0,0,1,1,1,0,0], [0,1,1,1,1,1,0], [1,1,1,1,1,1,1], [0,0,0,1,0,0,0], [0,0,0,1,0,0,0] ] #version 1 # for y_list in picture: # row_image = "" # for x in y_list: # if x: # row_image += "*" # else: # row_image += " " # print(row_image) #version 2 fill = "*" space = " " empty = "" for row in picture: for pixel in row: if pixel: #overwrite the end to "" instead of new line for print function print(fill, end=empty) else: print(space, end=empty) #new line after each row print(empty)
picture = [[0, 0, 0, 1, 0, 0, 0], [0, 0, 1, 1, 1, 0, 0], [0, 1, 1, 1, 1, 1, 0], [1, 1, 1, 1, 1, 1, 1], [0, 0, 0, 1, 0, 0, 0], [0, 0, 0, 1, 0, 0, 0]] fill = '*' space = ' ' empty = '' for row in picture: for pixel in row: if pixel: print(fill, end=empty) else: print(space, end=empty) print(empty)