content
stringlengths
7
1.05M
# https://www.geeksforgeeks.org/partition-a-set-into-two-subsets-such-that-the-difference-of-subset-sums-is-minimum/ def helper(arr, n, path, s): if n == 0: return abs((s - path) - path) return min( helper(arr, n-1, path+arr[n], s), helper(arr, n-1, path, s) ) def solve(arr): n = len(arr) s = sum(arr) dp = [ [False] * (s+1) for _ in range(n+1) ] for i in range(n+1): dp[i][0] = True for i in range(1, s+1): dp[0][i] = False for i in range(1, n+1): for j in range(1, s+1): dp[i][j] = dp[i-1][j] if arr[i-1] <= j: dp[i][j] = dp[i][j] or dp[i-1][j-arr[i-1]] diff = float('inf') for j in range(s//2, -1, -1): if dp[n][j]: diff = s - 2*j break return diff assert 1 == solve([1, 6, 11, 5]) assert 1 == solve([3, 1, 4, 2, 2, 1])
## Shortest Word ## 7 kyu ## https://www.codewars.com/kata/57cebe1dc6fdc20c57000ac9 def find_short(s): # your code here return sorted([len(word) for word in s.split()])[0]
nums = 34 coins= [1,2,5,10] temp = nums dp = [float("inf") for _ in range(nums)] dp[0] = 0 for i in range(1,nums): for j in range(len(coins)): if(coins[j] <= nums): dp[i] = min(dp[i], dp[i-coins[j]]+1) print(dp) print(dp[nums-1])
model_name_mapping = { 'baseline': 'Baseline', # dnn 'single_regression_2': 'SingleRegression_a', 'single_regression_11': 'SingleRegression_b', 'single_classification_22': 'SingleClassification_a', 'single_classification_42': 'SingleClassification_b', 'multi_classification_15': 'MultiClassification_a', 'multi_classification_18': 'MultiClassification_b', 'vanilla_lstm_8': 'LSTM_a', 'vanilla_lstm_19': 'LSTM_b', # random forest 'random_forest_12': 'RandomForest_a', 'random_forest_13': 'RandomForest_b', 'random_forest_14': 'RandomForest_c', 'random_forest_24': 'RandomForest_d', 'random_forest_25': 'RandomForest_e', 'random_forest_72': 'RandomForest_f', 'random_forest_96': 'RandomForest_g', 'random_forest_97': 'RandomForest_h', # irv 'irv_5': 'IRV_a', 'irv_10': 'IRV_b', 'irv_20': 'IRV_c', 'irv_40': 'IRV_d', 'irv_80': 'IRV_e', # docking 'dockscore_hybrid': 'Docking_hybrid', 'dockscore_fred': 'Docking_fred', 'dockscore_dock6': 'Docking_dock6', 'dockscore_rdockint': 'Docking_rdockint', 'dockscore_rdocktot': 'Docking_rdocktot', 'dockscore_surflex': 'Docking_surflex', 'dockscore_ad4': 'Docking_ad4', 'dockscore_plants': 'Docking_plants', 'dockscore_smina': 'Docking_smina', 'consensus_dockscore_max': 'ConsensusDocking_max', 'consensus_bcs_efr1_opt': 'ConsensusDocking_efr1_opt', 'consensus_bcs_rocauc_opt': 'ConsensusDocking_rocauc_opt', 'consensus_dockscore_median': 'ConsensusDocking_median', 'consensus_dockscore_mean': 'ConsensusDocking_mean', }
class QueryContinueDragEventArgs(RoutedEventArgs): """ Contains arguments for the System.Windows.DragDrop.QueryContinueDrag event. """ Action=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets or sets the current status of the associated drag-and-drop operation. Get: Action(self: QueryContinueDragEventArgs) -> DragAction Set: Action(self: QueryContinueDragEventArgs)=value """ EscapePressed=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets a Boolean value indicating whether the ESC key has been pressed. Get: EscapePressed(self: QueryContinueDragEventArgs) -> bool """ KeyStates=property(lambda self: object(),lambda self,v: None,lambda self: None) """Gets a flag enumeration indicating the current state of the SHIFT,CTRL,and ALT keys,as well as the state of the mouse buttons. Get: KeyStates(self: QueryContinueDragEventArgs) -> DragDropKeyStates """
def isfirstwordtitle(txt): allchars = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',' '] for char in allchars: if txt.startswith(char): return True return False def islower(txt,checknum=0): txt = txt.replace(' ','') allchars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',' '] if checknum == 0: for char in txt: checknum += 1 for char2 in range(0,checknum): char1 = txt[char2] for char in allchars: if char1 == char: c = True break else: c = False if not c: return False return True def istitle(txt,count=0): txt = txt.replace(' ','') txt = txt.split() counter = 0 if count == 0: for item in txt: count += 1 else: count -= 1 for item in txt: if counter > count: del txt[counter] counter += 1 for word in txt: if not isfirstwordtitle(word): return False return True def isupper(txt,checknum=0): allchars = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z',' '] txt = txt.replace(' ','') if checknum == 0: for char in txt: checknum += 1 for char2 in range(0,checknum): char1 = txt[char2] for char in allchars: if char1 == char: c = True break else: c=False if not c: return False return True def getupper(txt): line = 0 allchars = ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'] upperline = [] for char in txt: line += 1 if char in allchars: upperline.append(line) else: if not char in ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z']: raise SyntaxError(f'Unknown Character at character {str(line)}.') if str(upperline) != '[]': return upperline def getlower(txt): line = 0 allchars = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] lowerline = [] for char in txt: line += 1 if char in allchars: lowerline.append(line) else: if not char in ['A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z']: raise SyntaxError(f'Unknown Character at character {str(line)}.') if str(lowerline) != '[]': return lowerline
# Checks if all characters of a string are alphanumeric (a-z, A-Z and 0-9). c = "qA2" print(c.isalnum()) # Checks if all the characters of a string are alphabetical (a-z and A-Z). print(c.isalpha()) # Checks if all characters in a string are digits. print(c.isdigit()) # Checks if all characters in a string are lowercase print(c.islower()) # Checks if all characters of a string are uppercase print(c.isupper()) def is_al_num(s): return s.isalnum() def alpha(s): return s.isalpha() def run_method_for_each_char(s): print(any([char.isalnum() for char in s])) print(any([char.isalpha() for char in s])) print(any([char.isdigit() for char in s])) print(any([char.islower() for char in s])) print(any([char.isupper() for char in s])) if __name__ == "__main__": run_method_for_each_char(c)
names = ['Christopher', 'Susan'] index = 0 while index < len(names): print(names[index]) # 조건을 바꿈!! index = index + 1
""" 438. Find All Anagrams in a String Example 1: Input: s: "cbaebabacd" p: "abc" Output: [0, 6] Explanation: The substring with start index = 0 is "cba", which is an anagram of "abc". The substring with start index = 6 is "bac", which is an anagram of "abc". Example 2: Input: s: "abab" p: "ab" Output: [0, 1, 2] Explanation: The substring with start index = 0 is "ab", which is an anagram of "ab". The substring with start index = 1 is "ba", which is an anagram of "ab". The substring with start index = 2 is "ab", which is an anagram of "ab". """ # sliding window 用count记录p中出现次数, count = 0, append res class Solution: def findAnagrams(self, s, p): """ :type s: str :type p: str :rtype: List[int] """ lenn = count = len(p) res = [] dic = collections.Counter(p) for i, v in enumerate(s): start= i - lenn + 1 if dic[v] > 0: count -=1 dic[v]-=1 if count == 0: res.append(start) if start>=0: dic[s[start]]+=1 if dic[s[start]] > 0: count += 1 return res #sliding window 用 two pointer, 一个map,只有在比较对象中出现过得加减, 如果two pointer之间距离 ==p的长度 append to res class Solution: def findAnagrams(self, s, p): """ :type s: str :type p: str :rtype: List[int] """ lenn, j = len(p), 0 res = [] dic = collections.Counter(p) for i, v in enumerate(s): if v in dic: dic[v]-=1 while dic[v] < 0: dic[s[j]]+=1 j+=1 if dic[v] == 0 and i - j == lenn - 1: res.append(j) else: while j <= i: if s[j] in dic: dic[s[j]]+=1 j+=1 return res #sliding window 用 two pointer, 一个map, 所有字母相加减, 如果two pointer之间距离 ==p的长度 append to res class Solution: def findAnagrams(self, s, p): lenn, j = len(p), 0 res = [] dic = collections.Counter(p) for i, v in enumerate(s): dic[v]-=1 while j<=i and dic[v] < 0: dic[s[j]]+=1 j+=1 if i - j == lenn - 1: res.append(j) return res
"""modular.py Modular arithmetic helpers """ def modular_multiply(A, B, C): """Finds `(A * B) mod C` This is equivalent to: `(A mod C * B mod C) mod C` https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/modular-multiplication https://www.khanacademy.org/computing/computer-science/cryptography/modarithmetic/a/the-quotient-remainder-theorem """ a_mod_c = A % C b_mod_c = B % C result = (a_mod_c * b_mod_c) % C return result
# STRING: nome print('Camilli', type('Camilli')) # INT: idade print(17, type(17)) # # ALTURA: float print(1.58, type(1.58)) # É MAIOR DE IDADE: bool print(bool(17 > 18))
# -*- coding: utf-8 -*- class ClassTest: def __init__(self, value1, value2): self.value1 = value1 self._value2 = value2 @property def value2(self): return self._value2 @value2.setter def value2(self, value): self._value2 = value
s=0 tot =0 for c in range(1, 500, 2): if (c % 3) == 0: s += c tot += 1 print(s) print(tot)
#!/usr/bin/python3 for a in range(1, 400): for b in range(1, 400): c = (1000 - a) - b if a < b < c: if a**2 + b**2 == c**2: print(a * b * c)
# 向文件添加两行字符串 f = open('hello.txt', 'a') # 打开(文本+追加模式) f.write('Fine, thanks.\n') f.write('And you?\n') f.close() # 关闭
# Advent of Code - Day 8 - Part Two def result(data): digits = { 2: 1, 4: 4, 3: 7, 7: 8 } count = 0 for line in data: a, b = line.split(' | ') for word in b.split(' '): x = len(word) if digits.get(x): count += 1 return count
# coding: utf-8 """ According http://www.iliassociation.org/documents/industry/POF%20specs%20V3_2%20January%202005.pdf Газпром 2-2.3-919-2015 """ class Error(Exception): """ Feature Class exception """ class MagnetType: # pylint: disable=too-few-public-methods,no-init """ Magnet system types """ MFL = 'MFL' # lengthwise TFI = 'TFI' # diametral CAL = 'CAL' # caliper class FeatureClass: # pylint: disable=too-few-public-methods,no-init """ class for given geometry parameters """ AXGR = 'AXGR' # Axial Grooving (продольная канавка) AXSL = 'AXSL' # Axial Slotting (продольная щель) CIGR = 'CIGR' # Circumferential Grooving (поперечная канавка) CISL = 'CISL' # Circumferential Slotting (поперечная щель) GENE = 'GENE' # General (обширный) PINH = 'PINH' # Pinhole (язва) PITT = 'PITT' # Pitting (каверна) MIN_PERCENT = { # пороги обнаружения в % от толщины стенки трубы MagnetType.MFL: { FeatureClass.GENE: 5, FeatureClass.PITT: 10, FeatureClass.PINH: 20, FeatureClass.AXGR: 20, FeatureClass.CIGR: 8, FeatureClass.CISL: 8, }, MagnetType.TFI: { FeatureClass.GENE: 5, FeatureClass.PITT: 10, FeatureClass.PINH: 20, FeatureClass.CIGR: 20, FeatureClass.AXGR: 8, FeatureClass.AXSL: 8, }, } LIMITS = { MagnetType.MFL: { FeatureClass.GENE: lambda thick, length, width, depth: ( lim(length, 0, 30), # точность по длине, мм -/+ lim(width, 0, 30), # точность по ширине, мм -/+ lim_z(depth, thick, 0.1), # точность по глубине, мм -/+ ), FeatureClass.PITT: lambda thick, length, width, depth: ( lim(length, 0, 20), lim(width, 0, 30), lim_z(depth, thick, 0.1), ), FeatureClass.PINH: lambda thick, length, width, depth: ( lim(length, 0, 15), lim(width, thick, 30), lim_z(depth, thick, 0.2), ), FeatureClass.AXGR: lambda thick, length, width, depth: ( lim(length, 0, 20), lim(width, 0, 30), lim_z(depth, thick, 0.2), ), FeatureClass.CIGR: lambda thick, length, width, depth: ( lim(length, 0, 20), lim(width, thick, 30), lim_z(depth, thick, 0.15), ), FeatureClass.CISL: lambda thick, length, width, depth: ( lim(length, 0, 20), lim(width, thick, 30), lim_z(depth, thick, 0.15), ), }, MagnetType.TFI: { FeatureClass.GENE: lambda thick, length, width, depth: ( lim(length, 0, 30), lim(width, 0, 30), lim_z(depth, thick, 0.1), ), FeatureClass.PITT: lambda thick, length, width, depth: ( lim(length, 0, 30), lim(width, 0, 20), lim_z(depth, thick, 0.1), ), FeatureClass.PINH: lambda thick, length, width, depth: ( lim(length, thick, 30), lim(width, 0, 15), lim_z(depth, thick, 0.2), ), FeatureClass.CIGR: lambda thick, length, width, depth: ( lim(length, 0, 30), lim(width, 0, 20), lim_z(depth, thick, 0.2), ), FeatureClass.AXGR: lambda thick, length, width, depth: ( lim(length, 0, 30), lim(width, 0, 20), lim_z(depth, thick, 0.15), ), FeatureClass.AXSL: lambda thick, length, width, depth: ( lim(length, 0, 30), lim(width, 0, 20), lim_z(depth, thick, 0.15), ), }, } def lim_z(depth, thick, val): """ limits for depth """ return (depth - val * thick, depth + val * thick) def lim(size, thick, val): """ limits for width/length """ return (size - (thick + val), size + (thick + val)) def size_class(length, width, thick): """ calculate feature class for given parameters """ if not all([width, length, thick]): raise Error("Wrong FeatureClass params. l={} w={} t={}".format(length, width, thick)) size1 = thick if size1 < 10: size1 = 10 size3 = 3 * size1 size6 = 6 * size1 lwr = float(length) / float(width) if (width >= size3) and (length >= size3): ret = FeatureClass.GENE elif ( (size6 > width >= size1) and (size6 > length >= size1) and (2.0 > lwr > 0.5) ) and not (width >= size3 <= length): ret = FeatureClass.PITT elif (size3 > width >= size1) and (lwr >= 2.0): ret = FeatureClass.AXGR elif (size3 > length >= size1) and (lwr <= 0.5): ret = FeatureClass.CIGR elif (size1 > width > 0) and (size1 > length > 0): ret = FeatureClass.PINH elif length >= size1 > width > 0: ret = FeatureClass.AXSL elif width >= size1 > length > 0: ret = FeatureClass.CISL else: raise Error("Wrong FeatureClass params. l={} w={} t={}".format(length, width, thick)) return ret def is_detectable(sizes, thick, magnet_type=MagnetType.MFL): """ return True if defekt with given sizes on wallthick more than minimal percent """ length, width, depth = sizes cls = size_class(length, width, thick) min_percent = MIN_PERCENT[magnet_type] if cls not in min_percent: return False if depth < 0: # through hole depth = thick return int(round(depth * 100.0 / thick, 0)) >= min_percent[cls] def is_in_limits(calcked, real, thick, magnet_type=MagnetType.MFL): """ return tuple from 3 boolean items, that represent limits by length, width, depth """ limits = LIMITS[magnet_type] cls = size_class(real[0], real[1], thick) if cls not in limits: raise Error("Defect with params {} has class '{}'. Not applicable for method '{}'".format( real, cls, magnet_type )) length, width, depth = calcked limits_length, limits_width, limits_depth = limits[cls](thick, *real) return ( limits_length[0] <= length <= limits_length[1], limits_width[0] <= width <= limits_width[1], limits_depth[0] <= depth <= limits_depth[1], )
def staircase(n): num_dict = dict({}) return staircase_faster(n, num_dict) def staircase_faster(n, num_dict): if n == 1: output = 1 elif n == 2: output = 2 elif n == 3: output = 4 else: if (n - 1) in num_dict: first_output = num_dict[n - 1] else: first_output = staircase_faster(n - 1, num_dict) if (n - 2) in num_dict: second_output = num_dict[n - 2] else: second_output = staircase_faster(n - 2, num_dict) if (n - 3) in num_dict: third_output = num_dict[n - 3] else: third_output = staircase_faster(n - 3, num_dict) output = first_output + second_output + third_output num_dict[n] = output; return output
""" Code taken from fsl.py https://git.fmrib.ox.ac.uk/fsl/fslpy Copyright 2016-2017 University of Oxford, Oxford, UK. 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 isNoisyComponent(labels, signalLabels=None): """Given a set of component labels, returns ``True`` if the component is ultimately classified as noise, ``False`` otherwise. :arg signalLabels: Labels which are deemed signal. If a component has no labels in this list, it is deemed noise. Defaults to ``['Signal', 'Unknown']``. """ if signalLabels is None: signalLabels = ['signal', 'unknown'] signalLabels = [l.lower() for l in signalLabels] labels = [l.lower() for l in labels] noise = not any([sl in labels for sl in signalLabels]) return noise def saveLabelFile(allLabels, filename, dirname=None, listBad=True, signalLabels=None): """Saves the given classification labels to the specified file. The classifications are saved in the format described in the :func:`loadLabelFile` method. :arg allLabels: A list of lists, one list for each component, where each list contains the labels for the corresponding component. :arg filename: Name of the file to which the labels should be saved. :arg dirname: If provided, is output as the first line of the file. Intended to be a relative path to the MELODIC analysis directory with which this label file is associated. If not provided, a ``'.'`` is output as the first line. :arg listBad: If ``True`` (the default), the last line of the file will contain a comma separated list of components which are deemed 'noisy' (see :func:`isNoisyComponent`). :arg signalLabels: Labels which should be deemed 'signal' - see the :func:`isNoisyComponent` function. """ lines = [] noisyComps = [] # The first line - the melodic directory name if dirname is None: dirname = '.' lines.append(dirname) for i, labels in enumerate(allLabels): comp = i + 1 noise = isNoisyComponent(labels, signalLabels) labels = [l.replace(',', '_') for l in labels] tokens = [str(comp)] + labels + [str(noise)] lines.append(', '.join(tokens)) if noise: noisyComps.append(comp) if listBad: lines.append('[' + ', '.join([str(c) for c in noisyComps]) + ']') with open(filename, 'wt') as f: f.write('\n'.join(lines) + '\n')
def firstNonRepeatingCharacter(string): """ This function takes a string and find the first character in the string which is non-repeating. This implementation is of O(n) time complexity and O(1) space complexity where n is the length of the string and all chars in the string are lowecase that is why only 26 key value pairs in the hash table which is of O(1) space complexity. args: -------------- string (str) : a string of lowercase characters output: -------------- index (int): index of first character in the string which is non repeating """ # make a dictionary with each char in string as key and occurrence as value charOccurrence = {} for char in string: charOccurrence[char] = charOccurrence.get(char, 0) + 1 # iterate through the string and find lowest index which has occurrence 1 for i in range(len(string)): if charOccurrence[string[i]] == 1: return i return -1
#三种求 5!+ 4!+ 3!+ 2!+ 1!之和的方法 def cross(n): result = 1 while n > 1: result *= n n -= 1 return result sum = 0 for i in range(1,6): sum += cross(i) print(sum) sum = 0 a = 1 for i in range(1, 6): a *= i sum += a print(sum) print(cross(6)) def cross(n): if n == 1: return 1 if n >= 1: return n * cross(n-1) sum = 0 for i in range(1,6): sum += cross(i) print(sum)
if __name__ == "__main__": primes = [2, 3, 5, 7, 11, 13, 17, 19] s = 1 m = 1 for i in range(1, 21): if i in primes: s *= i m *= i elif m % i == 0: pass elif m % i != 0: j = m while True: j += s if j % i == 0: m = j s = j break print(m)
# Program to push , pop and display elements of a stack st = [] r = [] def push(): print('--STACK--') x = int(input('Book_No: ')) y = input('Book_Name: ') r = [x, y] st.append(r) def display(): if len(st) > 0: for i in range(len(st)-1, -1, -1): print(st[i]) else: print('Underflow') def pop(): if st[0] == (): print('Underflow!') else: p = int(input('Index of element to pop: ')) r.pop(p) print(f'Element popped is {r} from {st} with position {p}') while True: ch = int(input('Enter choice: ')) if ch == 1: m = int(input('Enter no. of elements: ')) for i in range(m): push() elif ch == 2: display() elif ch == 3: pop() elif ch == 4: exit() else: print('Invalid choice!')
class SiteConfig(dict): def update(self, d, **kwargs): filtered_d = {k: v for k, v in d.items() if v is not None} super().update(filtered_d, **kwargs) @staticmethod def default(): return SiteConfig( { "depth": 5, "delay": 1.5, "ua": "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36", "following": "", "selenium": False, } )
contoh_list = [1, 'dua', 3, 4.0, 5] print(contoh_list[0]) print(contoh_list[3]) contoh_list = [1, 'dua', 3, 4.0, 5] contoh_list[3] = 'empat' print(contoh_list[3])
# -*- coding: utf-8 -*- # this file is released under public domain and you can use without limitations ######################################################################### ## Customize your APP title, subtitle and menus here ######################################################################### response.logo = A(B('QualityPost'),XML('&trade;&nbsp;'), _class="brand",_href="http://www.qualitypost.com.mx/") #response.title = request.application.replace('_',' ').title() response.title = 'Asignacion Interactiva de Mensajes' response.subtitle = 'Cliente: ' ## read more at http://dev.w3.org/html5/markup/meta.name.html response.meta.author = 'Armando Hernandez <ahernandez@lettershopmexico.com>' response.meta.keywords = 'web2py, python, framework' response.meta.generator = 'Web2py Web Framework' ## your http://google.com/analytics id response.google_analytics_id = None ######################################################################### ## this is the main application menu add/remove items as required ######################################################################### response.menu = [ (T('Home'), False, URL('default', 'index'), []) ] if "auth" in locals(): auth.wikimenu()
# spaceobj.py # A space object. # Basically, anything that exists on the starmap. NONETYPE = 0 FLEETTYPE = 1 STARTYPE = 2 class SpaceObj: name = "" x = 0 y = 0 # This is often a class variable... sprite = () def __init__( s ): pass def moveTo( s, x, y ): s.x = x s.y = y def getLocation( s ): return (s.x, s.y) def prepareSprite( self ): self.sprite.setAnim( 0 ) # There has GOT TO BE A BETTER WAY!!! def getType( s ): return NONETYPE def draw( s, surface, screenx, screeny, screenw, screenh ): minx = screenx maxx = screenx + screenw miny = screeny maxy = screeny + screenh # So if you override getLocation() (like fleet.py does), you can # make something act like it's somewhere it isn't, without # overriding this function. locx, locy = s.getLocation() if (locx >= minx and locx < maxx) and (locy >= miny and locy < maxy): objx = locx - screenx - (s.sprite.getW() / 2) objy = locy - screeny - (s.sprite.getH() / 2) s.prepareSprite() s.sprite.draw( surface, objx, objy )
x = y = direction = 0 moves = open('input.txt', 'r').readline().strip().split(', ') for move in moves: if move[0] == 'L': if direction == 0: direction = 3 else: direction -= 1 elif move[0] == 'R': if direction == 3: direction = 0 else: direction += 1 dist = int(''.join(move[1:])) if direction == 0: y -= dist elif direction == 1: x += dist elif direction == 2: y += dist elif direction == 3: x -= dist print(abs(x) + abs(y)) input()
with open('input.txt') as f: lines = f.readlines() count = 0 prevSum = 0 for i in range(len(lines)): if i + 3 > len(lines): break newSum = int(lines[i]) + int(lines[i + 1]) + int(lines[i + 2]) if prevSum != 0: if newSum > prevSum: count += 1 prevSum = newSum print(count)
TOKEN_LIST = [ #kovan ['ethereum', '42', 'eth', '0x0000000000000000000000000000000000000000', 18], ['ethereum', '42', 'usdt', '0xd85476c906b5301e8e9eb58d174a6f96b9dfc5ee', 6], ['ethereum', '42', 'usdc', '0xb7a4f3e9097c08da09517b5ab877f7a917224ede', 6], ['ethereum', '42', 'dai', '0xc4375b7de8af5a38a93548eb8453a498222c4ff2', 18], ['arweave', '99', 'pia', 'n05LTiuWcAYjizXAu-ghegaWjL89anZ6VdvuHcU6dno', 18], ['arweave', '99', 'vrt', 'usjm4PCxUd5mtaon7zc97-dt-3qf67yPyqgzLnLqk5A', 18], ['arweave', '99', 'xyz', 'mzvUgNc8YFk0w5K5H7c8pyT-FC5Y_ba0r7_8766Kx74', 18], ['arweave', '99', 'ardrive', '-8A6RexFkpfWwuyVO98wzSFZh0d6VJuI-buTJvlwOJQ', 18], ['arweave,ethereum', '0,42', 'ar', 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA,0xcc9141efa8c20c7df0778748255b1487957811be', 12], ['moonbase', '1287', 'dev', '0x0000000000000000000000000000000000000000', 18], ['moonbase', '1287', 'zlk', '0x322f069e9b8b554f3fb43cefcb0c7b3222242f0e', 18], #mainnet ['ethereum', '1', 'eth', '0x0000000000000000000000000000000000000000', 18], ['ethereum', '1', 'usdt', '0xdac17f958d2ee523a2206206994597c13d831ec7', 6], ['ethereum', '1', 'wbtc', '0x2260fac5e5542a773aa44fbcfedf7c193bc2c599', 8], ['ethereum', '1', 'usdc', '0xa0b86991c6218b36c1d19d4a2e9eb0ce3606eb48', 6], ['ethereum', '1', 'dai', '0x6b175474e89094c44da98b954eedeac495271d0f', 18], ['ethereum', '1', 'uni', '0x1f9840a85d5af5bf1d1762f925bdaddc4201f984', 18], ['ethereum', '1', 'sos', '0x3b484b82567a09e2588a13d54d032153f0c0aee0', 18], ['ethereum', '1', 'bank', '0x2d94aa3e47d9d5024503ca8491fce9a2fb4da198', 18], ['ethereum', '1', 'dodo', '0x43dfc4159d86f3a37a5a4b3d4580b888ad7d4ddd', 18], ['ethereum', '1', 'mask', '0x69af81e73a73b40adf4f3d4223cd9b1ece623074', 18], ['moonbeam', '1284', 'zlk', '0x3fd9b6c9a24e09f67b7b706d72864aebb439100c', 18], ['moonbeam', '1284', 'glmr', '0x0000000000000000000000000000000000000000', 18], ['arweave,ethereum', '0,1', 'ar', 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA,0x4fadc7a98f2dc96510e42dd1a74141eeae0c1543', 12], ['arweave', '0', 'ardrive', '-8A6RexFkpfWwuyVO98wzSFZh0d6VJuI-buTJvlwOJQ', 18], ['arweave', '0', 'vrt', 'usjm4PCxUd5mtaon7zc97-dt-3qf67yPyqgzLnLqk5A', 18], ] def get_token_id(chain_type, chain_id, token_symbol): for token in TOKEN_LIST: if token[0] == chain_type and token[1] == chain_id and token[2] == token_symbol: return token[3] def get_token_decimal(chain_type, chain_id, token_symbol): for token in TOKEN_LIST: if token[0] == chain_type and token[1] == chain_id and token[2] == token_symbol: return token[4] def get_token_tag(chain_type, chain_id, token_symbol, token_id=''): if not token_id: token_id = get_token_id(chain_type, chain_id, token_symbol) return '-'.join([chain_type, token_symbol, token_id])
# -*- coding: utf-8 -*- """ Created on Tue May 25 11:16:49 2021 @author: SST-Lab """ class XBank: loggedinCounter = 0 def _init_(self, atmpin, theaccountbalance, thename): self.atmpin = theatmpin self.accountbalance = theaccountbalance self.name = thename XBank.loggedinCounter = XBank.loggedinCounter + 1 def CollectMoney(self, amounttowithdraw): if(amounttowithdraw > self.accountbalance): print(f"Sorry we are not able to process at this time") else: print(f"Collect your cash...Thanks for banking with XBank") def ChangePin(self, newPin): self.atmpin = newPin print(f"Your pin has been changed...Thanks for banking with XBank") @classmethod def No0fCustomersLoggedin (cls): print(f"we have total of" + str(XBank.loggedinCounter) + "that have logged in") f = open("C: \\Users\\SST-LAB\\Desktop\\database.txt",'r') #print(f.readline()) password = [] accountB = [] name = [] breaker = [] for x in f: breaker = x.split(' ') password.append(breaker[0]) accountB.append(breaker[1]) name.append(breaker[2]) break print("enter your pin.....") pasw = input() if(pasw == password[0]): customer = XBank(password[0],accountB[0],name[0])
def linear_search(list, target): """ Returns the index position of the target if found, else returns None """ for i in range(0, len(list)): if list[i] == target: return i return None def verify(index): if index is not None: print("Target is found at index: ", index) else: print("Target is not found in the list") one_to_ten = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] result = linear_search(one_to_ten, 2) verify(result)
# coding=utf-8 # # @lc app=leetcode id=830 lang=python # # [830] Positions of Large Groups # # https://leetcode.com/problems/positions-of-large-groups/description/ # # algorithms # Easy (47.46%) # Likes: 224 # Dislikes: 56 # Total Accepted: 29.6K # Total Submissions: 61.5K # Testcase Example: '"abbxxxxzzy"' # # In a string S of lowercase letters, these letters form consecutive groups of # the same character. # # For example, a string like S = "abbxxxxzyy" has the groups "a", "bb", "xxxx", # "z" and "yy". # # Call a group large if it has 3 or more characters.  We would like the # starting and ending positions of every large group. # # The final answer should be in lexicographic order. # # # # Example 1: # # # Input: "abbxxxxzzy" # Output: [[3,6]] # Explanation: "xxxx" is the single large group with starting 3 and ending # positions 6. # # # Example 2: # # # Input: "abc" # Output: [] # Explanation: We have "a","b" and "c" but no large group. # # # Example 3: # # # Input: "abcdddeeeeaabbbcd" # Output: [[3,5],[6,9],[12,14]] # # # # Note:  1 <= S.length <= 1000 # # class Solution(object): def _largeGroupPositions(self, S): """ :type S: str :rtype: List[List[int]] """ last = None index = 1 result = [] for i, s in enumerate(S): if s == last: index += 1 else: if index >= 3: result.append([i-index, i-1]) index = 1 last = s if s == last: index += 1 if index > 3: result.append([i - index + 2, i]) return result def largeGroupPositions(self, S): """ :type S: str :rtype: List[List[int]] """ if len(S) < 3: return [] index = 1 count = 1 result = [] while index < len(S): if S[index] == S[index-1]: count += 1 else: if count >= 3: result.append([index-count, index-1]) count = 1 index += 1 if count >= 3: result.append([index-count, index-1]) return result # if __name__ == '__main__': # s = Solution() # print s.largeGroupPositions("abbxxxxzzy") # print s.largeGroupPositions("abc") # print s.largeGroupPositions("abcdddeeeeaabbbcd") # print s.largeGroupPositions("aaaaaaa") # print s.largeGroupPositions("aaa")
DEBIAN = 'debian' CENTOS = 'centos' OPENSUSE = 'opensuse' UBUNTU = 'ubuntu'
print('====== EX 024 ======') cid = str(input('Em que cidade você nasceu? ')).lower().split() print('santo' in cid)
# Quest 01 num = int(input("Digite um número: ")) positivo = num > 0 negativo = num < 0 neutro = num == 0 if (positivo): print("Positivo") elif(negativo): print("Negativo") else: print("Neutro")
#MenuTitle: Make bottom left node first # -*- coding: utf-8 -*- __doc__=""" Makes the bottom left node in each path the first node in all masters """ def left(x): return x.position.x def bottom(x): return x.position.y layers = Glyphs.font.selectedLayers for aLayer in layers: for idx, thisLayer in enumerate(aLayer.parent.layers): for p in thisLayer.paths: oncurves = filter(lambda n: n.type != "offcurve", list(p.nodes)) n = sorted(sorted(oncurves, key = bottom),key=left)[0] n.makeNodeFirst()
class Solution(object): def nextPermutation(self, nums): """ :type nums: List[int] :rtype: void Do not return anything, modify nums in-place instead. """ # find the longest non-decreasing suffix in nums right = len(nums) - 1 while right >= 1 and nums[right] <= nums[right - 1]: right -= 1 if right == 0: return self.reverse(nums, 0, len(nums) - 1) # find pivot pivot = right - 1 # find rightmost succesor for i in xrange(len(nums) - 1, pivot, -1): if nums[i] > nums[pivot]: succesor = i break # swap pivot and succesor nums[pivot], nums[succesor] = nums[succesor], nums[pivot] # reverse the suffix self.reverse(nums, pivot + 1, len(nums) - 1) def reverse(self, nums, l, r): """ reverse nums[l:r] :type nums: List[int] :type l: int :type r: int :rtype None """ while l < r: nums[l], nums[r] = nums[r], nums[l] l += 1 r -= 1
cand1 = 0 cand2 = 0 cand3 = 0 eleitores = int(input('Digite a quantidade de eleitores: ')) print('Para votar no Candidato 1 digite [1]\nPara votar no Candidato 2 digite [2]\nPara votar no Candidato 3 digite [3]') for cont in range(0, eleitores): voto = str(input('Digite seu voto: ')) if voto == '1': cand1 += 1 if voto == '2': cand2 += 1 if voto == '3': cand3 += 1 print('O resultado foi: \nO Candidato 1 recebeu {} votos;\nO Candidato 2 recebeu {} votos;\nO Candidato 3 recebeu {} votos.'.format(cand1, cand2, cand3))
qq = (input('Digite algo qualquer: ')) print('O tipo da palavra digitado é', type(qq)) print('O valor dela são digitos?', qq.isdigit()) print('O valor dela são númericos?', qq.isnumeric()) print('O valor dela são letras?', qq.isalpha()) print('O valor dela são alfanúmericos?', qq.isalnum()) print('O valor dela são apenas espaços?', qq.isspace()) print('O valor dela são maiúsculas?', qq.isupper()) print('O valor dela são minusclas?', qq.islower())
# ---------------------------------------------------------------------- # Copyright (c) Microsoft Corporation. # All rights reserved. # ---------------------------------------------------------------------- # TODO: Consider just inheriting from Python's set type -MPL class SymbolSet: def __init__(self): self._symbol_set_collection = set() @property def size(self): return len(self._symbol_set_collection) def add(self, new_symbol): self._symbol_set_collection.add(new_symbol) def merge(self, sym_set): if sym_set is not None: self._symbol_set_collection = self._symbol_set_collection.union(sym_set) def copy(self): return self._symbol_set_collection.copy() def __iter__(self): return iter(self._symbol_set_collection)
fix = {'5':'S', '0':'O', '1':'I'} def correct(s): return "".join(fix.get(c, c) for c in s)
def config_step_task(name, task_name, task_params=[], on_failure='TERMINATE_CLUSTER'): """ Returns a Python dict representing the step. :param name: semantic name of the task :param task_name: task name, identifies executable :param task_params: task parameters :param on_failure: either "CONTINUE" or "TERMINATE_CLUSTER" :return: """ return { 'Name': name, 'ActionOnFailure': on_failure, 'HadoopJarStep': { 'Jar': 'command-runner.jar', 'Args': ['/usr/local/bin/{task_name}'.format(task_name=task_name)] + task_params } }
#!/usr/bin/python3 def test_erc165_support(nft): erc165_interface_id = "0x01ffc9a7" assert nft.supportsInterface(erc165_interface_id) is True def test_erc721_support(nft): erc721_interface_id = "0x80ac58cd" assert nft.supportsInterface(erc721_interface_id) is True
def fatorial(_numero = 1, show = False): resultado = 1 for item in range(1, _numero + 1): resultado *= item if show: texto = '' for item in reversed(range(1, _numero + 1)): texto += '{} '.format(item) if item == 1: texto += '= {}'.format(resultado) else: texto += 'x ' else: texto = '{}'.format(resultado) return texto print(fatorial(5, True)) print(fatorial(5, False)) print(fatorial())
""" Management of OpenStack Keystone Roles ====================================== .. versionadded:: 2018.3.0 :depends: shade :configuration: see :py:mod:`salt.modules.keystoneng` for setup instructions Example States .. code-block:: yaml create role: keystone_role.present: - name: role1 delete role: keystone_role.absent: - name: role1 create role with optional params: keystone_role.present: - name: role1 - description: 'my group' """ __virtualname__ = "keystone_role" def __virtual__(): if "keystoneng.role_get" in __salt__: return __virtualname__ return ( False, "The keystoneng execution module failed to load: shade python module is not" " available", ) def present(name, auth=None, **kwargs): """ Ensure an role exists name Name of the role description An arbitrary description of the role """ ret = {"name": name, "changes": {}, "result": True, "comment": ""} kwargs = __utils__["args.clean_kwargs"](**kwargs) __salt__["keystoneng.setup_clouds"](auth) kwargs["name"] = name role = __salt__["keystoneng.role_get"](**kwargs) if not role: if __opts__["test"] is True: ret["result"] = None ret["changes"] = kwargs ret["comment"] = "Role will be created." return ret role = __salt__["keystoneng.role_create"](**kwargs) ret["changes"]["id"] = role.id ret["changes"]["name"] = role.name ret["comment"] = "Created role" return ret # NOTE(SamYaple): Update support pending https://review.openstack.org/#/c/496992/ return ret def absent(name, auth=None, **kwargs): """ Ensure role does not exist name Name of the role """ ret = {"name": name, "changes": {}, "result": True, "comment": ""} __salt__["keystoneng.setup_clouds"](auth) kwargs["name"] = name role = __salt__["keystoneng.role_get"](**kwargs) if role: if __opts__["test"] is True: ret["result"] = None ret["changes"] = {"id": role.id} ret["comment"] = "Role will be deleted." return ret __salt__["keystoneng.role_delete"](name=role) ret["changes"]["id"] = role.id ret["comment"] = "Deleted role" return ret
BLACK = '\x1b[0;30m' RED = '\x1b[0;31m' GREEN = '\x1b[0;32m' BROWN = '\x1b[0;33m' BLUE = '\x1b[0;34m' PURPLE = '\x1b[0;35m' CYAN = '\x1b[0;36m' LIGHT_GRAY = '\x1b[0;37m' DARK_GRAY = '\x1b[1;30m' LIGHT_RED = '\x1b[1;31m' LIGHT_GREEN = '\x1b[1;32m' YELLOW = '\x1b[1;33m' LIGHT_BLUE = '\x1b[1;34m' LIGHT_PURPLE = '\x1b[1;35m' LIGHT_CYAN = '\x1b[1;36m' WHITE = '\x1b[1;37m' NONE = '\x1b[0m'
""" Assignment 8 1. Write a function that will return True if the passed-in number is even, and False if it is odd. 2. Write a second function that will call the first with values 0-6 and print each result on a new line. 3. Invoke the second function. The signature of the first function should be: `is_even(num: int) -> bool` The signature of the second function should be: `test_is_even() -> None` """ # Answer def is_even(num: int) -> bool: return num % 2 == 0 def test_is_even() -> None: for i in range(7): print(is_even(i)) test_is_even()
authentication = { "type": "object", "properties": { "access": { "type": "object", "properties": { "token": { "type": "object", "properties": { "id": { "type": "string" }, }, "required": ["id"], }, "serviceCatalog": { "type": "array", }, }, "required": ["token", "serviceCatalog", ], }, }, "required": ["access", ], }
class Node: def __init__(self, value): self.value = value self.next = None class Queue: def __init__(self): self.front = None self.rear = None def enqueue(self, data): node = Node(data) if self.rear: self.rear.next = node self.rear = node else: self.front = node self.rear = node def dequeue(self): temp = self.front if self.is_empty(): raise AttributeError ('Queue is empty') else: self.front = self.front.next temp.next = None if self.front == None: self.rear = None return temp.value def peek(self): try: return self.front.value except AttributeError: raise AttributeError ('Queue is empty') def is_empty(self): if self.rear == None and self.front == None : return True else: return False def print_(self): temp = self.front str = '' while temp: str += f'{temp.value} - > ' temp = temp.next return str class Stack: def __init__(self): self.top = None def push(self, data): node = Node(data) if self.top: node.next = self.top self.top = node def pop(self): if not self.top : raise AttributeError ('Queue is empty') else: temp = self.top self.top = self.top.next temp.next = None return temp.value def peek(self): if not self.is_empty(): return self.top.value else : raise AttributeError ('Queue is empty') def is_empty(self): if not self.top: return True else: return False if __name__ == "__main__": stack = Stack() # print('check when initlize the stack ',stack.is_empty()) # stack.push(5) # stack.push(6) # stack.push('cat') # print(stack.peek()) # print('check after adding some items ',stack.is_empty()) # stack.pop() # stack.pop() # print(stack.peek()) # print('check after pop() some items ',stack.is_empty()) # stack.pop() # print(stack.peek()) # print('check after pop() all items ',stack.is_empty()) # print(stack.is_empty()) # stack.push(5) # stack.push(6) # stack.push('cat') # stack.pop() # stack.pop() # stack.pop() # print(stack.is_empty()) queue = Queue() queue.enqueue(4) queue.enqueue(5) # queue.enqueue(5) # queue.enqueue(77) # queue.dequeue() # print(queue.print_())
""" # requests : 웹 사이트에 접속, 데이터를 받아오는 역할 # * 페이지 보기를 했을때 나오는 코드로 이용 # BeautifulSoup : 데이터를 HTML로 해석하는 역할 # 선행지식 : HTML에 대한 이해, CSS Selector를 만드는 방법 # 요소검사를 통해 확인할 수 있는 소스코드 or 업데이트되는 환경일 때 1) selennium : 웹 브라우저 자체를 컨트롤해서 Crawling(실시간으로 업데이트된 것을 가져오기 위해) * 요소를 선택해서 사용자의 동작을 흉내낸다. : 클릭, 키보드 입력 * 이때는 선택자) xpath, css * 우클릭해서 copy를 하면 된다 그러나 selector에서 지원되지 않는 문법이 있으므로 카피하는것은 비추천 * xpath는 그냥 2) BeatuifulSoup : 얻은 데이터를 HTML로 해석 request : selenium : 컨트롤해야 하기때문에 request보다 느리다 페이지 이동을해도 페이지가 새로고침이 안되면 처음부터 다 불러와놓고 일부분만 보여준다거나 실시간으로 가져온다거나 둘중 하나이다 풀링 : 우리가 서버로 조회하는것 푸슁 : 서버가 우리에게 전달해주는것 days를 눌렀을떄 Headers로 보면 requestURL로 보면 링크가 있는데 어가면 막혀있다 * reffer로 막아놓았다 확인하는 방법은 소스코드에서 아무 태그의 링크를 해당 URL로 바꿔보면 알수있다 """
class Customer: def __init__(self, name, age, phone_no, address): self.name = name self.age = age self.phone_no = phone_no self.address = address def view_details(self): print(self.name, self.age, self.phone_no) print(self.address.get_door_no(), self.address.get_street(), self.address.get_pincode()) class Address: def __init__(self, door_no, street, pincode): self.__door_no = door_no self.__street = street self.__pincode = pincode def get_door_no(self): return self.__door_no def get_street(self): return self.__street def get_pincode(self): return self.__pincode def set_door_no(self, value): self.__door_no = value def set_street(self, value): self.__street = value def set_pincode(self, value): self.__pincode = value def update_address(self): pass add1 = Address(123, "5th Lane", 56001) cus1 = Customer("Jack", 24, 1234, add1) cus1.view_details()
#!/usr/bin/env python3 # https://abc054.contest.atcoder.jp/tasks/abc054_a a, b = map(int, input().split()) if a == b: print('Draw') elif a == 1: print('Alice') elif b == 1: print('Bob') elif a > b: print('Alice') else: print('Bob')
#获取参数异常 class ArgmentError(Exception): def __init__(self, expression, message): self.expression = expression self.message = message #读取配置文件异常 class SettingFileError(Exception): def __init__(self, expression, message): self.expression = expression self.message = message class DataBaseError(Exception): def __init__(self, expression, message): self.expression = expression self.message = message
class NoQueueError(Exception): pass class JobError(RuntimeError): pass class TimeoutError(JobError): pass class CrashError(JobError): pass
# ------------------------------ # 33. Search in Rotated Sorted Array # # Description: # Suppose an array sorted in ascending order is rotated at some pivot unknown to you beforehand. # # (i.e., 0 1 2 4 5 6 7 might become 4 5 6 7 0 1 2). # You are given a target value to search. If found in the array return its index, otherwise return -1. # # You may assume no duplicate exists in the array. # # # Version: 1.0 # 10/22/17 by Jianfa # ------------------------------ class Solution(object): def search(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ if not nums: return -1 if target not in nums: return -1 left = 0 right = len(nums) - 1 while left < right: mid = (left + right) / 2 if (nums[0] > target) ^ (nums[0] > nums[mid]) ^ (target > nums[mid]): left = mid + 1 else: right = mid return left if target == nums[left] else -1 # Used for test if __name__ == "__main__": test = Solution() nums = [3,4,5,1,2] print(test.search(nums, 5)) # ------------------------------ # Summary: # Idea from https://leetcode.com/problems/search-in-rotated-sorted-array/discuss/14419/Pretty-short-C%2B%2BJavaRubyPython # There are three conditions need to be thought: nums[0] > target? nums[0] > nums[mid]? target > nums[mid]? # If exactly two of them are true, then target should be at left side. # Using XOR to distinguish.
# Encoding and Decoding in Python 3.x a = 'Harshit' # initialize byte object. c = b'Harshit' # using encode() to encode string d = a.encode('ASCII') if (d == c): print("Encoding successful.") else: print("Encoding unsuccessful. :( ") # Similarly, decode() is the inverse process. # decode() will convert byte to string.
#!/usr/bin/env python3 # -*- coding: utf-8 -*- __author__ = 'ipetrash' # SOURCE: Design Patterns: Proxy - Заместитель # SOURCE: https://ru.wikipedia.org/wiki/Заместитель_(шаблон_проектирования) class IMath: """Интерфейс для прокси и реального субъекта""" def add(self, x, y): raise NotImplementedError() def sub(self, x, y): raise NotImplementedError() def mul(self, x, y): raise NotImplementedError() def div(self, x, y): raise NotImplementedError() class Math(IMath): """Реальный субъект""" def add(self, x, y): return x + y def sub(self, x, y): return x - y def mul(self, x, y): return x * y def div(self, x, y): return x / y class MathProxy(IMath): """Прокси""" def __init__(self): self.math = None # Быстрые операции - не требуют реального субъекта def add(self, x, y): return x + y def sub(self, x, y): return x - y # Медленная операция - требует создания реального субъекта def mul(self, x, y): if not self.math: self.math = Math() return self.math.mul(x, y) def div(self, x, y): if y == 0: return float('inf') # Вернуть positive infinity if not self.math: self.math = Math() return self.math.div(x, y) if __name__ == '__main__': p = MathProxy() x, y = 4, 2 print('4 + 2 =', p.add(x, y)) print('4 - 2 =', p.sub(x, y)) print('4 * 2 =', p.mul(x, y)) print('4 / 2 =', p.div(x, y))
#! /usr/bin/env python3 """ --- besspin-ci.py is the CI entry to the BESSPIN program. --- This file provide the combinations of CI files generated. --- Every combination is represented as a set of tuples. Each tuple represents one setting and its possible values. Each "values" should be a tuple. Please note that a 1-element tuple should be: ('element',) """ backupBesspinAMI = { 'ImageId' : 'ami-067bd21562d1f150e', 'CreationDate' : '2021-05-19T20:09:51.000Z', 'OwnerId' : '363527286999'} # Please update occasionally. Used by ./utils.getBesspinAMI() instead of erring. ciAWSqueue = 'https://sqs.us-west-2.amazonaws.com/845509001885/ssith-fett-target-ci-develop-pipeline-PipelineSQSQueue-1IOF3D3BU1MEP.fifo' ciAWSbucket = 'ssith-fett-target-ci-develop' ciAWSqueueTesting = 'https://sqs.us-west-2.amazonaws.com/363527286999/aws-test-suite-queue.fifo' ciAWSbucketTesting = 'aws-test-suite-bucket' commonDefaults = { ('openConsole',('No',)), ('gdbDebug',('No',)), ('useCustomHwTarget',('No',)), ('useCustomTargetIp',('No',)), ('useCustomQemu',('No',)), ('useCustomOsImage',('No',)), ('useCustomProcessor',('No',)), ('remoteTargetIp',('172.31.30.56',)) } commonDefaultsFETT = { ('mode',('fettTest',)) } commonDefaultsCWEs = { ('mode',('evaluateSecurityTests',)), ('vulClasses', ('[bufferErrors, PPAC, resourceManagement, informationLeakage, numericErrors, hardwareSoC, injection]',)), ('checkAgainstValidScores',('Yes',)), ('useCustomScoring',('No',)), ('useCustomCompiling',('No',)), ('computeNaiveCWEsTally',('Yes',)), ('computeBesspinScale',('Yes',)), ('FreeRTOStimeout',(10,)), ('runAllTests',('Yes',)), ('runUnixMultitaskingTests',('Yes',)), ('instancesPerTestPart',(1,)) } unixDefaultsCWEs = commonDefaultsCWEs.union({ ('nTests',(150,)), ('cross-compiler',('GCC','Clang',)), # If cross-compiler is Clang, linker will be over-written to LLD ('linker',('GCC',)), }) freertosDefaultsCWEs = commonDefaultsCWEs.union({ ('nTests',(60,)) }) unixDefaults = commonDefaults.union({ ('useCustomCredentials',('yes',)), ('userName',('researcher',)), ('userPasswordHash',('$6$xcnc07LxM26Xq$VBAn8.ZfCzEf5MEpftSsCndDaxfPs5gXWjdrvrHcSA6O6eRoV5etd9V8E.BE0/q4P8pGOz96Nav3PPuXOktmv.',)), ('buildApps',('no',)), ('rootUserAccess',('yes',)) }) gfe_unixOnPremDefaults = unixDefaults.union({ ('binarySource',('GFE',)), ('elfLoader',('netboot',)), ('sourceVariant',('default',)) }) gfe_unixAwsDefaults = unixDefaults.union({ ('binarySource',('GFE',)), ('elfLoader',('JTAG',)), ('sourceVariant',('default',)), ('target',('awsf1',)) }) gfe_unixAllTargets_onprem = gfe_unixOnPremDefaults.union({ ('processor',('chisel_p2', 'bluespec_p2',)), ('target',('qemu', 'vcu118',)), ('osImage',('FreeBSD', 'debian',)) }) gfe_unixDevPR_onprem = gfe_unixOnPremDefaults.union({ ('processor',('chisel_p2',)), ('target',('vcu118',)), ('osImage',('FreeBSD', 'debian',)) }) gfe_debianDevPR_aws = gfe_unixAwsDefaults.union({ ('processor',('chisel_p2',)), ('osImage',('debian',)) }) gfe_freebsdDevPR_aws = gfe_unixAwsDefaults.union({ ('processor',('bluespec_p2',)), ('osImage',('FreeBSD',)) }) mit_unixDevPR_aws = unixDefaults.union({ ('binarySource',('MIT',)), ('elfLoader',('JTAG',)), ('sourceVariant',('default',)), ('processor',('bluespec_p2',)), ('target',('awsf1',)), ('osImage',('debian',)) }) lmco_unixDevPR_aws = unixDefaults.union({ ('binarySource',('LMCO',)), ('elfLoader',('JTAG',)), ('sourceVariant',('default',)), ('processor',('chisel_p2',)), ('target',('awsf1',)), ('osImage',('debian',)) }) sri_cambridge_unixDevPR_aws = unixDefaults.union({ ('binarySource',('SRI-Cambridge',)), ('elfLoader',('JTAG',)), ('sourceVariant',('default','purecap','temporal',)), ('processor',('bluespec_p2',)), ('target',('awsf1',)), ('osImage',('FreeBSD',)) }) freertosDefaults = commonDefaults.union({ ('osImage',('FreeRTOS',)), ('elfLoader',('JTAG',)), ('sourceVariant',('default',)), ('freertosFatFs',('default',)) }) gfe_freertosAllTargets_onprem = freertosDefaults.union({ ('binarySource',('GFE',)), ('processor',('chisel_p1',)), ('target',('vcu118',)), ('cross-compiler',('GCC','Clang',)), ('linker',('GCC',)), ('buildApps',('yes',)) }) gfe_freertosDevPR_onprem = gfe_freertosAllTargets_onprem gfe_freertosDevPR_aws = freertosDefaults.union({ ('binarySource',('GFE',)), ('processor',('chisel_p1',)), ('target',('awsf1',)), ('cross-compiler',('GCC','Clang',)), ('linker',('GCC',)), # If cross-compiler is Clang, linker will be over-written to LLD ('buildApps',('yes',)) }) lmco_freertosDevPR_aws = freertosDefaults.union({ ('binarySource',('LMCO',)), ('processor',('chisel_p1',)), ('target',('awsf1',)), ('cross-compiler',('GCC',)), ('linker',('GCC',)), # If cross-compiler is Clang, linker will be over-written to LLD ('buildApps',('yes',)) }) michigan_freertosDevPR_aws = freertosDefaults.union({ ('binarySource',('Michigan',)), ('processor',('chisel_p1',)), ('target',('awsf1',)), ('buildApps',('no',)) }) appSets = { 'runPeriodic' : { 'OnPrem' : { 'fett' : { 'gfe_freertos' : gfe_freertosAllTargets_onprem.union(commonDefaultsFETT), 'gfe_unix' : gfe_unixAllTargets_onprem.union(commonDefaultsFETT) }, 'cwe' : { 'gfe_freertos' : gfe_freertosAllTargets_onprem.union(freertosDefaultsCWEs), 'gfe_unix' : gfe_unixAllTargets_onprem.union(unixDefaultsCWEs) } } }, 'runDevPR' : { 'OnPrem' : { 'fett' : { 'gfe_freertos' : gfe_freertosDevPR_onprem.union(commonDefaultsFETT), 'gfe_unix' : gfe_unixDevPR_onprem.union(commonDefaultsFETT) }, 'cwe' : { 'gfe_freertos' : gfe_freertosDevPR_onprem.union(freertosDefaultsCWEs), 'gfe_unix' : gfe_unixDevPR_onprem.union(unixDefaultsCWEs) } }, 'aws' : { 'fett' : { 'gfe_debian' : gfe_debianDevPR_aws.union(commonDefaultsFETT), 'gfe_freebsd' : gfe_freebsdDevPR_aws.union(commonDefaultsFETT), 'gfe_freertos' : gfe_freertosDevPR_aws.union(commonDefaultsFETT), 'lmco_freertos' : lmco_freertosDevPR_aws.union(commonDefaultsFETT), 'michigan_freertos' : michigan_freertosDevPR_aws.union(commonDefaultsFETT), 'mit_unix' : mit_unixDevPR_aws.union(commonDefaultsFETT), 'lmco_unix' : lmco_unixDevPR_aws.union(commonDefaultsFETT), 'sri-cambridge_unix' : sri_cambridge_unixDevPR_aws.union(commonDefaultsFETT) }, 'cwe' : { 'gfe_debian' : gfe_debianDevPR_aws.union(unixDefaultsCWEs), 'gfe_freebsd' : gfe_freebsdDevPR_aws.union(unixDefaultsCWEs), 'gfe_freertos' : gfe_freertosDevPR_aws.union(freertosDefaultsCWEs) } } } } appSets['runRelease'] = appSets['runPeriodic']
''' Verify correct field and URL verification behavior for not and nocase modifiers. ''' # @file # # Copyright 2021, Verizon Media # SPDX-License-Identifier: Apache-2.0 # Test.Summary = ''' Verify correct field and URL verification behavior for equals, absent, present, contains, prefix, and suffix with not, nocase, and both not and nocase modifiers ''' # # Test 1: Verify field verification in a YAML replay file. # Each combinaton of test type, not/as, and case/nocase, and positive/negative result # are tested for client, and a mixture for server # r = Test.AddTestRun("Verify 'not' and 'nocase' directives work for a single HTTP transaction") client = r.AddClientProcess("client1", "replay_files/not_nocase.yaml") server = r.AddServerProcess("server1", "replay_files/not_nocase.yaml") proxy = r.AddProxyProcess( "proxy1", listen_port=client.Variables.http_port, server_port=server.Variables.http_port) server.Streams.stdout += Testers.ContainsExpression( 'Not Equals Success: Different. Key: "5", Field Name: "host", Correct Value: "le.on", Actual Value: "example.one"', 'Validation should be happy that "le.on" is not equal to "example.one".') server.Streams.stdout += Testers.ContainsExpression( 'Not Presence Success: Absent. Key: "5", Field Name: "x-test-absent"', 'Validation should be happy that "X-Test-Absent" has no value.') server.Streams.stdout += Testers.ContainsExpression( 'Not Absence Success: Present. Key: "5", Field Name: "x-test-present", Value: "It\'s there"', 'Validation should be happy that "X-Test-Present" has a value.') server.Streams.stdout += Testers.ContainsExpression( 'Not Contains Success: Not Found. Key: "5", Field Name: "host", Required Value: "leo", Actual Value: "example.one"', 'Validation should be happy that "leo" is not contained in "example.one".') server.Streams.stdout += Testers.ContainsExpression( 'Not Prefix Success: Not Found. Key: "5", Field Name: "x-test-request", Required Value: "equ", Actual Value: "RequestData"', 'Validation should be happy that "equ" does not prefix "RequestData".') server.Streams.stdout += Testers.ContainsExpression( 'Not Suffix Success: Not Found. Key: "5", Field Name: "x-test-present", Required Value: "It\'s", Actual Value: "It\'s there"', 'Validation should be happy that "It\'s" does not suffix "It\'s there".') server.Streams.stdout += Testers.ContainsExpression( 'No Case Equals Success: Key: "5", Field Name: "host", Required Value: "EXAMpLE.ONE", Value: "example.one"', 'Validation should be happy that "EXAMpLE.ONE" nocase equals "example.one".') server.Streams.stdout += Testers.ContainsExpression( 'No Case Contains Success: Key: "5", Field Name: "host", Required Value: "Le.ON", Value: "example.one"', 'Validation should be happy that "Le.ON" is nocase contained in "example.one".') server.Streams.stdout += Testers.ContainsExpression( 'No Case Prefix Success: Key: "5", Field Name: "x-test-request", Required Value: "rEQ", Value: "RequestData"', 'Validation should be happy that "rEQ" nocase prefixes "RequestData".') server.Streams.stdout += Testers.ContainsExpression( 'No Case Suffix Success: Key: "5", Field Name: "x-test-present", Required Value: "heRe", Value: "It\'s there"', 'Validation should be happy that "heRe" nocase suffixes "It\'s there".') server.Streams.stdout += Testers.ContainsExpression( 'Not No Case Equals Success: Different. Key: "5", Field Name: "host", Correct Value: "example.ON", Actual Value: "example.one"', 'Validation should be happy that "le.on" does not nocase equal "example.one".') server.Streams.stdout += Testers.ContainsExpression( 'Not No Case Contains Success: Not Found. Key: "5", Field Name: "host", Required Value: "U", Actual Value: "example.one"', 'Validation should be happy that "leo" is not nocase contained in "example.one".') server.Streams.stdout += Testers.ContainsExpression( 'Not No Case Prefix Success: Not Found. Key: "5", Field Name: "x-test-request", Required Value: "EQU", Actual Value: "RequestData"', 'Validation should be happy that "equ" does not nocase prefix "RequestData".') server.Streams.stdout += Testers.ContainsExpression( 'Not No Case Suffix Success: Not Found. Key: "5", Field Name: "x-test-present", Required Value: "hre", Actual Value: "It\'s there"', 'Validation should be happy that "hre" does not nocase suffix "It\'s there".') server.Streams.stdout += Testers.ContainsExpression( 'Not Equals Violation: Key: "5", Field Name: "host", Value: "example.one"', 'Validation should complain that "example.on" equals "example.one".') server.Streams.stdout += Testers.ContainsExpression( 'Not Presence Violation: Key: "5", Field Name: "x-test-present", Value: "It\'s there"', 'Validation should complain that "X-Test-Present" has a value.') server.Streams.stdout += Testers.ContainsExpression( 'Not Absence Violation: Key: "5", Field Name: "x-test-absent"', 'Validation should complain that "X-Test-Absent" has no value.') server.Streams.stdout += Testers.ContainsExpression( 'Not Contains Violation: Key: "5", Field Name: "host", Required Value: "le.on", Value: "example.one"', 'Validation should complain that "le.on" is contained in "example.one".') server.Streams.stdout += Testers.ContainsExpression( 'Not Prefix Violation: Key: "5", Field Name: "x-test-request", Required Value: "Req", Value: "RequestData"', 'Validation should complain that "Req" prefixes "RequestData".') server.Streams.stdout += Testers.ContainsExpression( 'Not Suffix Violation: Key: "5", Field Name: "x-test-present", Required Value: "there", Value: "It\'s there"', 'Validation should complain that "there" suffixes "It\'s there".') server.Streams.stdout += Testers.ContainsExpression( 'No Case Equals Violation: Different. Key: "5", Field Name: "host", Correct Value: "EXAMPLE.ON", Actual Value: "example.one"', 'Validation should complain that "EXAMPL.ON" does not nocase equal "example.one".') server.Streams.stdout += Testers.ContainsExpression( 'No Case Contains Violation: Not Found. Key: "5", Field Name: "host", Required Value: "LE..On", Actual Value: "example.one"', 'Validation should complain that "LE..On" is not nocase contained in "example.one".') server.Streams.stdout += Testers.ContainsExpression( 'No Case Prefix Violation: Not Found. Key: "5", Field Name: "x-test-request", Required Value: "-TE", Actual Value: "RequestData"', 'Validation should complain that "-TE" does not nocase prefix "RequestData".') server.Streams.stdout += Testers.ContainsExpression( 'No Case Suffix Violation: Not Found. Key: "5", Field Name: "x-test-present", Required Value: "THER", Actual Value: "It\'s there"', 'Validation should complain that "THER" does not nocase suffix "It\'s there".') server.Streams.stdout += Testers.ContainsExpression( 'Not No Case Equals Violation: Key: "5", Field Name: "host", Required Value: "Example.one", Value: "example.one"', 'Validation should complain that "Example.one" nocase equals "example.one".') server.Streams.stdout += Testers.ContainsExpression( 'Not No Case Contains Violation: Key: "5", Field Name: "host", Required Value: "le.oN", Value: "example.one"', 'Validation should complain that "le.oN" is nocase contained in "example.one".') server.Streams.stdout += Testers.ContainsExpression( 'Not No Case Prefix Violation: Key: "5", Field Name: "x-test-request", Required Value: "req", Value: "RequestData"', 'Validation should complain that "req" nocase prefixes "RequestData".') server.Streams.stdout += Testers.ContainsExpression( 'Not No Case Suffix Violation: Key: "5", Field Name: "x-test-present", Required Value: "eRE", Value: "It\'s there"', 'Validation should complain that "eRE" nocase suffixes "It\'s there".') server.Streams.stdout = Testers.ContainsExpression( 'Not No Case Contains Violation: Key: "5", URI Part: "path", Required Value: "iG/S", Value: "/config/settings.yaml"', 'Validation should complain that "iG/S" is nocase contained in the path.') client.Streams.stdout += Testers.ContainsExpression( 'Not Equals Success: Different. Key: "5", Field Name: "content-type", Correct Value: "text", Actual Value: "text/html"', 'Validation should be happy that "text" does not equal "text/html".') client.Streams.stdout += Testers.ContainsExpression( 'Not Presence Violation: Key: "5", Field Name: "set-cookie", Value: "ABCD"', 'Validation should complain that "set-cookie" is present.') client.Streams.stdout += Testers.ContainsExpression( 'Not Absence Violation: Key: "5", Field Name: "fake-cookie"', 'Validation should complain that "fake-cookie" is absent.') client.Streams.stdout += Testers.ContainsExpression( 'Not No Case Contains Violation: Key: "5", Field Name: "content-type", Required Value: "Tex", Value: "text/html"', 'Validation should complain that "Tex" is nocase contained in "text/html".') client.Streams.stdout += Testers.ContainsExpression( 'Not No Case Prefix Success: Absent. Key: "5", Field Name: "fake-cookie", Required Value: "B"', 'Validation should be happy that "B" does not nocase prefix a nonexistent header.') client.Streams.stdout += Testers.ContainsExpression( 'No Case Suffix Success: Key: "5", Field Name: "content-type", Required Value: "L", Value: "text/html"', 'Validation should be happy that "L" nocase suffixes "text/html".') client.Streams.stdout += Testers.ContainsExpression( 'Not Prefix Success: Not Found. Key: "5", Field Name: "multiple", Required Values: "Abc" "DEF", Received Values: "abc" "DEF"', 'Validation should be happy that "Abc" does not prefix "abc", even though "DEF" prefixes "DEF".') client.Streams.stdout += Testers.ContainsExpression( 'Not No Case Equals Violation: Key: "5", Field Name: "multiple", Required Values: "Abc" "DEF", Values: "abc" "DEF"', 'Validation should complain that each required value nocase equals the corresponding received value.') client.ReturnCode = 1 server.ReturnCode = 1
#!/usr/bin/python3 """ Class Square creation module A Blueprint for squares """ class Square: """Set the class square""" def __init__(self, size=0): """Iniatiate Attributes for Square class. Args: size: integer with size of the square. """ self.__size = size @property def size(self): """Get the private size value. Return: self._size: value of size """ return self.__size @size.setter def size(self, value): """Set size into class object. Args: value: size to check Raises: ValueError: if size is lesser than 0. TypeError: if size is not an integer. """ if type(value) is int: if value < 0: raise ValueError("size must be >= 0") self.__size = value else: raise TypeError("size must be an integer") def area(self): """Square Area method. Return: The Area of the square. """ return self.__size ** 2
# Python API for using CAPI 3 core files from VUnit # Authors: # Unai Martinez-Corral # # Copyright 2021 Unai Martinez-Corral <unai.martinezcorral@ehu.eus> # # 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. # # SPDX-License-Identifier: Apache-2.0 def AddCoreFilesets(vunitHandle, core, filesets): """ Add the sources of some filesets from a CAPI 3 compliant core, into a VUnit handle through VUnit's API (``add_library`` and ``add_source_files``). :param vunitHandle: handle to the VUnit object instance. :param core: CAPI 3 compliant object (coming from LoadCoreFile). :param filesets: name of the filesets to be added into the VUnit handle. """ _root = core.FILE_PATH.parent _defaultLib = "VUnitUserLib" _sources = {_defaultLib: []} for fsetname in filesets: if fsetname in core.filesets: fset = core.filesets[fsetname] _lib = _defaultLib if fset.logical_name == "" else fset.logical_name if _lib not in _sources: _sources[_lib] = [] _sources[_lib] += [_root / fset.path / fstr for fstr in fset.files] for _lib, _files in _sources.items(): vunitHandle.add_library(_lib).add_source_files(_files)
"""Welcome to FIRESONG, the FIRst Extragalactic Simulation Of Neutrinos and Gamma-rays""" __author__ = 'C.F. Tung, T. Glauch, M. Larson, A. Pizzuto, R. Reimann, I. Taboada' __email__ = '' __version__ = '1.8' __all__ = ['Firesong', 'Evolution', 'distance', 'FluxPDF', 'input_out', 'Luminosity', 'sampling', 'Legend']
# ------------------------------ # 1027. Longest Arithmetic Sequence # # Description: # Given an array A of integers, return the length of the longest arithmetic subsequence in A. # Recall that a subsequence of A is a list A[i_1], A[i_2], ..., A[i_k] with 0 <= i_1 < i_2 < # ... < i_k <= A.length - 1, and that a sequence B is arithmetic if B[i+1] - B[i] are all the # same value (for 0 <= i < B.length - 1). # # Example 1: # Input: [3,6,9,12] # Output: 4 # Explanation: # The whole array is an arithmetic sequence with steps of length = 3. # # Example 2: # Input: [9,4,7,2,10] # Output: 3 # Explanation: # The longest arithmetic subsequence is [4,7,10]. # # Example 3: # Input: [20,1,15,3,10,5,8] # Output: 4 # Explanation: # The longest arithmetic subsequence is [20,15,10,5]. # # Note: # 2 <= A.length <= 2000 # 0 <= A[i] <= 10000 # # Version: 1.0 # 11/03/19 by Jianfa # ------------------------------ class Solution: def longestArithSeqLength(self, A: List[int]) -> int: dp = {} # dp[(index, diff)] is the length of longest arithmetic subsequence ending at index with difference diff for i in range(len(A)): for j in range(i+1, len(A)): dp[j, A[j] - A[i]] = dp.get((i, A[j] - A[i]), 1) + 1 # get((i, A[j] - A[i]), 1) the 1 is for the single element length return max(dp.values()) # Used for testing if __name__ == "__main__": test = Solution() # ------------------------------ # Summary: # DP solution from: https://leetcode.com/problems/longest-arithmetic-sequence/discuss/274611/JavaC%2B%2BPython-DP # # O(N^2) time, O(N^2) space
products = {} command = input() while command != "statistics": command = input() while command != "statistics": tokens = command.split(": ") product = tokens[0] quantity = int(tokens[1]) if product not in products: products[product] = 0 products[product] += quantity print("Products in stock:") for(product, quantity) in products.items(): print(f"- {product}: {quantity}") print(f"Total Products: {len(products.keys())}") print(f"Total Quantity: {sum(products.values())}")
DEBUG = False ALLOWED_HOSTS = ['*'] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db1', 'USER': 'alex', 'PASSWORD': 'asdewqr1', 'HOST': 'localhost', # Set to empty string for localhost. 'PORT': '', # Set to empty string for default. } }
#!/usr/bin/env python # -*- encoding: utf-8 -*- # Copyright (c) 2002-2020 "Neo4j," # Neo4j Sweden AB [http://neo4j.com] # # This file is part of Neo4j. # # 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. """ This module contains the core driver exceptions. """ class ProtocolError(Exception): """ Raised when an unexpected or unsupported protocol event occurs. """ class ServiceUnavailable(Exception): """ Raised when no database service is available. """ class IncompleteCommitError(Exception): """ Raised when a disconnection occurs while still waiting for a commit response. For non-idempotent write transactions, this leaves the data in an unknown state with regard to whether the transaction completed successfully or not. """ class SecurityError(Exception): """ Raised when an action is denied due to security settings. """ class CypherError(Exception): """ Raised when the Cypher engine returns an error to the client. """ message = None code = None classification = None category = None title = None metadata = None @classmethod def hydrate(cls, message=None, code=None, **metadata): message = message or "An unknown error occurred." code = code or "Neo.DatabaseError.General.UnknownError" try: _, classification, category, title = code.split(".") except ValueError: classification = "DatabaseError" category = "General" title = "UnknownError" error_class = cls._extract_error_class(classification, code) inst = error_class(message) inst.message = message inst.code = code inst.classification = classification inst.category = category inst.title = title inst.metadata = metadata return inst @classmethod def _extract_error_class(cls, classification, code): if classification == "ClientError": try: return client_errors[code] except KeyError: return ClientError elif classification == "TransientError": try: return transient_errors[code] except KeyError: return TransientError elif classification == "DatabaseError": return DatabaseError else: return cls class ClientError(CypherError): """ The Client sent a bad request - changing the request might yield a successful outcome. """ class DatabaseError(CypherError): """ The database failed to service the request. """ class TransientError(CypherError): """ The database cannot service the request right now, retrying later might yield a successful outcome. """ class DatabaseUnavailableError(TransientError): """ """ class ConstraintError(ClientError): """ """ class CypherSyntaxError(ClientError): """ """ class CypherTypeError(ClientError): """ """ class NotALeaderError(ClientError): """ """ class Forbidden(ClientError, SecurityError): """ """ class ForbiddenOnReadOnlyDatabaseError(Forbidden): """ """ class AuthError(ClientError, SecurityError): """ Raised when authentication failure occurs. """ client_errors = { # ConstraintError "Neo.ClientError.Schema.ConstraintValidationFailed": ConstraintError, "Neo.ClientError.Schema.ConstraintViolation": ConstraintError, "Neo.ClientError.Statement.ConstraintVerificationFailed": ConstraintError, "Neo.ClientError.Statement.ConstraintViolation": ConstraintError, # CypherSyntaxError "Neo.ClientError.Statement.InvalidSyntax": CypherSyntaxError, "Neo.ClientError.Statement.SyntaxError": CypherSyntaxError, # CypherTypeError "Neo.ClientError.Procedure.TypeError": CypherTypeError, "Neo.ClientError.Statement.InvalidType": CypherTypeError, "Neo.ClientError.Statement.TypeError": CypherTypeError, # Forbidden "Neo.ClientError.General.ForbiddenOnReadOnlyDatabase": ForbiddenOnReadOnlyDatabaseError, "Neo.ClientError.General.ReadOnly": Forbidden, "Neo.ClientError.Schema.ForbiddenOnConstraintIndex": Forbidden, "Neo.ClientError.Schema.IndexBelongsToConstraint": Forbidden, "Neo.ClientError.Security.Forbidden": Forbidden, "Neo.ClientError.Transaction.ForbiddenDueToTransactionType": Forbidden, # AuthError "Neo.ClientError.Security.AuthorizationFailed": AuthError, "Neo.ClientError.Security.Unauthorized": AuthError, # NotALeaderError "Neo.ClientError.Cluster.NotALeader": NotALeaderError } transient_errors = { # DatabaseUnavailableError "Neo.TransientError.General.DatabaseUnavailable": DatabaseUnavailableError } class SessionExpired(Exception): """ Raised when no a session is no longer able to fulfil the purpose described by its original parameters. """ def __init__(self, session, *args, **kwargs): super(SessionExpired, self).__init__(session, *args, **kwargs) class TransactionError(Exception): """ Raised when an error occurs while using a transaction. """ def __init__(self, transaction, *args, **kwargs): super(TransactionError, self).__init__(*args, **kwargs) self.transaction = transaction
""" `segment_regexes`: make sure a string is segmented at either the start or end of the matching group(s) """ newline = { 'name': 'newline', 'regex': r'\n', 'at': 'end' } ellipsis = { 'name': 'ellipsis', 'regex': r'…(?![\!\?\..?!])', 'at': 'end' } after_semicolon = { 'name': 'after_semicolon', 'regex': r' *;', 'at': 'end' } """ `prevent_regexes`: make sure a string is not segmented at characters that fall within the matching group(s) """ liberal_url = { # ref. https://gist.github.com/gruber/249502#gistcomment-1328838 'name': 'liberal_url', 'regex': r'\b((?:[a-z][\w\-]+:(?:\/{1,3}|[a-z0-9%])|www\d{0,3}[.]|[a-z0-9.\-]+[.][a-z]{2,4}\/)(?:[^\s()<>]|\((?:[^\s()<>]|(?:\([^\s()<>]+\)))*\))+(?:\((?:[^\s()<>]|(?:\([^\s()<>]+\)))*\)|[^\s`!()\[\]{};:\'".,<>?«»“”‘’]))' } period_followed_by_lowercase = { 'name': 'period_followed_by_lowercase', 'regex': r'\.(?= *[a-z])' }
class Dummy: def __str__(self) -> str: return "dummy" d1 = Dummy() print(d1)
""" Problem 1 - https://adventofcode.com/2020/day/2 Part 1 - Given a list of password and conditions the passwords have to fulfill, return the number of passwords that fulfill the conditions Part 2 - Same as part 1 with different conditions """ # Set up the input with open('input-02122020.txt', 'r') as file: s = file.readlines() # Solution to part 1 def valid_1(password, lower, upper, letter): """ Takes in a password and checks if it is valid """ l_count = 0 for char in password: if char == letter: l_count += 1 if int(lower) <= l_count <= int(upper): return 1 else: return 0 def solve_1(passw): valid = 0 for p in passw: password = p.split()[-1] lower = p.split('-')[0] upper = p.split()[0].split('-')[-1] letter = p.split(':')[0][-1] valid += valid_1(password, lower, upper, letter) return valid ans_1 = solve_1(s) print(ans_1) # Answer was 418 # Solution to part 2 def valid_2(password, lower, upper, letter): """ Takes in a password and checks if it is valid """ if password[lower] == letter and password[upper] != letter: return 1 elif password[lower] != letter and password[upper] == letter: return 1 else: return 0 def solve_2(passw): valid = 0 for p in passw: password = p.split()[-1] lower = int(p.split('-')[0]) - 1 upper = int(p.split()[0].split('-')[-1]) - 1 letter = p.split(':')[0][-1] valid += valid_2(password, lower, upper, letter) return valid ans_2 = solve_2(s) print(ans_2) # Answer was 616
""" Last one was a bit easy. Let's ramp it up a tad :) This challenge is close to the real deal. Some of you may get it here. Solve the equation for X. Example For string = "99X=1(mod 8)", the output should be breakDown3(string) = 3. "99X=1(mod 8)". To solve this equation, first you must reduce the left side. Make it as small as possible without being negative by decreasing it by mod. So, for example 99X would reduce to 3x. Now your expression should look like this: 3X=1(mod 8). Now that the left side is done, we switch focus to the right side. If we mod by 8, we can safely add or subtract 8 to get the same answer, so we add 8 to the number on the right until we get a number evenly divisible by the left number. So 3X=1(mod 8) goes to 3x=9(mod 8). 9 is evenly divided by 3, so we stop there. Our final step is to isolate X, so we divide 9 by 3 leaving us with X=3. """ def breakDown3(s): l, r, m = map(int, re.findall("\d+", s)) while r % l: r += m return r / l
_use_time = True try: _start_time = datetime.utcnow().timestamp() except Exception: _use_time = False
# -*- coding: Latin-1 -*- ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## # infinity.py # -------------------------------- # Copyright (c) 2005 # Jean-Sébastien BOLDUC # Hans Vangheluwe # McGill University (Montréal) # -------------------------------- # # - Singleton class "Inf" and unique instance "INFINITY" --- # stands for infinity (to use in time advance function) # ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## INFINITY OBJECT --- ADDED 04/04/2005 ## more comparison operators -- HV 12/11/2006 ## ## mul and rmul added -- Eugene 14/11/2006 ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## class Infty(object): """Singleton class: the single instance "INFINITY" stands for infinity.""" __instantiated = False def __init__(self): if self.__instantiated: raise NotImplementedError("singleton class already instantiated") self.__instantiatiated = True def __deepcopy__(self, memo): return self def __add__(self, other): """ INFINITY + x = INFINITY """ return self def __sub__(self, other): """ INFINITY - x = INFINITY (if x != INF), or NaN (if x == INFINITY) """ if other == self: raise ValueError("INFINITY - INFINITY gives NaN (not defined)") return self def __mul__(self, other): """ INFINITY * x = INFINITY """ return self def __radd__(self, other): """ x + INFINITY = INFINITY """ return self def __rsub__(self, other): """ x - INFINITY = -INFINITY (if x != INFINITY), or NaN (if x == INFINITY) """ if other == self: raise ValueError("INFINITY - INFINITY gives NaN (not defined)") raise ValueError("x - INFINITY gives MINUS_INFINITY (not defined)") def __rmul__(self, other): """ x * INFINITY = INFINITY """ return self def __abs__(self): """ abs(INFINITY) = INFINITY -- absolute value """ return self # def __cmp__(self, other): # if other is self: # return 0 # else: # return 1 def __eq__(self, other): if other is self: return True else: return False def __ne__(self, other): if other is self: return False else: return True def __lt__(self, other): return False def __le__(self, other): if other is self: return True else: return False def __gt__(self, other): if other is self: return False else: return True def __ge__(self, other): return True def __str__(self): return "+INFINITY" # Instantiate singleton: INFINITY = Infty()
# -*- coding: utf-8 -*- """ sphinxcontrib.websupport.version ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ :copyright: Copyright 2007-2018 by the Sphinx team, see README. :license: BSD, see LICENSE for details. """ __version__ = '1.1.0' __version_info__ = tuple(map(int, __version__.split('.')))
class ErrorCode(object): ERROR_001_REQUIRED_FIELD_NOT_NULL = '001' ERROR_002_PAGE_SIZE_LARGE_THAN_0 = '002' ERROR_003_PAGE_LARGE_THAN_0 = '003' ERROR_004_FIELD_VALUE_INVALID = '004' ERROR_005_ORDER_VALUE_INVALID = '005' ERROR_006_SEARCH_PARAMS_INVALID = '006' ERROR_040_UNAUTHORIZED = '040' ERROR_042_FILE_NOT_NULL = '042' ERROR_045_FORMAT_FILE = '045' ERROR_046_STANDARDIZED = '046' ERROR_051_SEARCH_PARAM_TYPE_FAIL = '051' ERROR_061_COMPANY_NOT_FOUND = '061' ERROR_091_DEPARTMENT_ID_NOT_EXISTS = '091' ERROR_092_COMPANY_ID_IS_REQUIRED = '092' ERROR_093_DEPARTMENT_DUPLICATE = '093' ERROR_094_DEPARTMENT_PARENT_NOT_EXISTS = '094' ERROR_095_CAN_NOT_DISABLE_DEPARTMENT_HAVE_STAFF = '095' ERROR_096_CAN_NOT_DISABLE_DEPARTMENT_WHEN_CHILD_HAVE_STAFF = '096' ERROR_097_STAFF_AND_DEPARTMENT_NOT_SAME_COMPANY = '097' ERROR_098_ROLE_TITLE_NOT_BELONG_TO_DEPARTMENT = '098' ERROR_099_PARENT_ID_BELONG_TO_CHILD_DEPARTMENT = '099' ERROR_100_CAN_NOT_UPDATE_DEPARTMENT_COMPANY = '100' ERROR_100_FILE_TOO_LARGE = '100' ERROR_101_NOT_CONNECT_MinIO = '101' ERROR_101_ROLE_TITLE_DELETED = '101' ERROR_102_STAFF_ID_DUPLICATE = '102' ERROR_103_PARENT_DEPARTMENT_NOT_BELONG_TO_COMPANY = '103' ERROR_104_PARENT_DEPARTMENT_INACTIVE = '104' ERROR_105_STAFF_BELONG_TO_OTHER_DEPARTMENT = '105' ERROR_106_STAFF_INACTIVE = '106' ERROR_107_DEPARTMENT_INACTIVE = '107' ERROR_108_PARENT_NOT_YOURSELF = '108' ERROR_120_INCORRECT_EMAIL_OR_PASSWORD = '120' ERROR_121_EMAIL_NOT_FOUND = '121' ERROR_122_EMAIL_ALREADY_EXISTS = '122' ERROR_123_UNACTIVE_USER = '123' ERROR_126_EMAIL_COMPANY_INVALID = '126' ERROR_128_IDENTITY_CARD = '128' ERROR_129_MANAGER_ID_INVALID = "129" ERROR_130_MANAGER_NOT_FOUND = '130' ERROR_132_PHONE_NUMBER_INVALID = '132' ERROR_134_STAFF_ID_NOT_FOUND = '134' ERROR_135_STAFF_CODE_DUPLICATE = '135' ERROR_136_MANAGER_ID_BELONG_CHILDREN = '136' ERROR_137_MANAGER_CANNOT_INACTIVE = '137' ERROR_139_FILE_WRONG_TEMPLATE = '139' ERROR_160_EXISTS_TEAM = "160" ERROR_161_TEAM_ID_NOT_FOUND = "161" ERROR_162_STAFF_AND_TEAM_NOT_BELONG_SAME_COMPANY = '162' ERROR_163_TEAM_NAME_TOO_LONG = '163' ERROR_164_CANNOT_DELETE_TEAM = '164' ERROR_190_ROLE_EXISTS = '190' ERROR_191_ROLE_ID_DOES_NOT_EXITS = '191' ERROR_192_DEPARTMENT_NOT_BELONG_TO_COMPANY = '192' ERROR_193_CAN_NOT_DISABLE_ROLE_TILE = '193' ERROR_194_CAN_NOT_UPDATE_ROLE_TILE_DEPARTMENT = '194' ERROR_195_CAN_NOT_UPDATE_ROLE_TILE_COMPANY = '195' ERROR_196_CAN_NOT_CREATE_SAME_ROLE_TILE_IN_A_DEPARTMENT = '196' ERROR_197_CAN_NOT_ACTIVE_ROLE_TILE_IN_DEPARTMENT_INACTIVE = '197' ERROR_992_ERROR = '992' ERROR_999_SERVER = '999' class ErrorMessage(object): MESSAGE_001_REQUIRED_FIELD_NOT_NULL = 'Các trường thông tin bắt buộc không được bỏ trống' MESSAGE_002_PAGE_SIZE_LARGE_THAN_0 = 'Số lượng phần tử trong trang tìm kiếm phải lớn hơn 0 và nhỏ hơn 1000' MESSAGE_003_PAGE_LARGE_THAN_0 = 'Số thứ tự của trang hiện tại phải lớn hơn hoặc bằng 0' MESSAGE_004_FIELD_VALUE_INVALID = 'Trường dữ liệu không hợp lệ' MESSAGE_005_ORDER_VALUE_INVALID = 'Chiều sắp xếp phải là "desc" hoặc "asc"' MESSAGE_006_SEARCH_PARAMS_INVALID = 'Các trường tìm kiếm không hợp lệ' MESSAGE_040_UNAUTHORIZED = 'unauthorized' MESSAGE_041 = 'Định dạng tệp tải lên chỉ bao gồm jpg, png, pdf, xlsx, xls, svg, pdf, doc, docx, rar, zip' MESSAGE_042_FILE_NOT_NULL = 'Tệp tải lên không được bỏ trống' MESSAGE_045_FORMAT_FILE = 'File không tồn tại, hoặc không đúng định dạng' MESSAGE_046_STANDARDIZED = 'Tên file không hợp lệ, không thể chuẩn hóa' MESSAGE_051_SEARCH_PARAM_TYPE_FAIL = 'Search param: Type phải là tree hoặc list' MESSAGE_061_COMPANY_NOT_FOUND = 'ID company không tồn tại trong hệ thống' MESSAGE_091_DEPARTMENT_ID_NOT_EXISTS = 'ID của phòng ban không tồn tại trong hệ thống' MESSAGE_092_COMPANY_ID_IS_REQUIRED = 'ID của company không được để trống' MESSAGE_093_DEPARTMENT_DUPLICATE = 'Tên phòng ban đã tồn tại' MESSAGE_094_DEPARTMENT_PARENT_NOT_EXISTS = 'ID của phòng ban cấp trên không tồn tại trong hệ thống' MESSAGE_095_CAN_NOT_DISABLE_DEPARTMENT_HAVE_STAFF = 'Không được phép xóa phòng ban đang có nhân viên' MESSAGE_096_CAN_NOT_DISABLE_DEPARTMENT_WHEN_CHILD_HAVE_STAFF = 'Không thể xóa phòng ban do các phòng ban trực thuộc đang có nhân viên' MESSAGE_097_STAFF_AND_DEPARTMENT_NOT_SAME_COMPANY = 'Nhân viên và phòng ban không thuộc cùng công ty' MESSAGE_098_ROLE_TITLE_NOT_BELONG_TO_DEPARTMENT = 'Role_title không thuộc phòng ban' MESSAGE_099_PARENT_ID_BELONG_TO_CHILD_DEPARTMENT = 'Không thể update vì parent_id thuộc danh sách các department cấp dưới' MESSAGE_100_CAN_NOT_UPDATE_DEPARTMENT_COMPANY = 'Không thể update company_id của phòng ban' MESSAGE_100_FILE_TOO_LARGE = 'Dung lượng file quá lớn' MESSAGE_101_NOT_CONNECT_MinIO = 'Không thể kết nối tới MinIO' MESSAGE_101_ROLE_TITLE_DELETED = 'Role_title đã khóa' MESSAGE_102_STAFF_ID_DUPLICATE = 'Staff_id bị duplicate' MESSAGE_103_PARENT_DEPARTMENT_NOT_BELONG_TO_COMPANY = 'Parent_id không thuộc company' MESSAGE_104_PARENT_DEPARTMENT_INACTIVE = 'Parent_id đã bị khóa' MESSAGE_105_STAFF_BELONG_TO_OTHER_DEPARTMENT = 'Staff đã thuộc department khác - staff_id = ' MESSAGE_106_STAFF_INACTIVE = 'Staff đã bị inactive staff_id = ' MESSAGE_107_DEPARTMENT_INACTIVE = 'Phòng ban đã bị inactive' MESSAGE_108_PARENT_NOT_YOURSELF = 'Không thể tự thêm parent là chính mình' MESSAGE_120_INCORRECT_EMAIL_OR_PASSWORD = 'Incorrect email or password' MESSAGE_121_EMAIL_NOT_FOUND = 'Email nhân viên chưa có trong hệ thống' MESSAGE_122_EMAIL_ALREADY_EXISTS = 'Email already exists' MESSAGE_123_UNACTIVE_USER = 'User inactive' MESSAGE_128_IDENTITY_CARD = 'Số chứng minh thư không hợp lệ( 9 số hoặc 12 số)' MESSAGE_129_MANAGER_ID_INVALID = 'Manager không thuộc công ty của nhân viên' MESSAGE_130_MANAGER_NOT_FOUND = "Manager ID không tồn tại trên hệ thống" MESSAGE_132_PHONE_NUMBER_INVALID = "phone number phải bắt đầu bằng 0, độ dài tối đa 12 chữ số, tối thiểu 10 chữ số" MESSAGE_134_STAFF_ID_NOT_FOUND = "Id của staff không tồn tại" MESSAGE_135_STAFF_CODE_DUPLICATE = "Mã nhân viên trùng nhau" MESSAGE_136_MANAGER_ID_BELONG_CHILDREN = 'Không thể update vì manager_id thuộc danh sách các nhân viên cấp dưới' MESSAGE_137_MANAGER_CANNOT_INACTIVE = 'Không thể inactive nhân viên vì nhân viên đang là người quản lý' MESSAGE_139_FILE_WRONG_TEMPLATE = 'File không đúng template' MESSAGE_160_EXISTS_TEAM = "Tên team đã tồn tại trên hệ thống" MESSAGE_161_TEAM_ID_NOT_FOUND = "Không tìm thấy id team" MESSAGE_162_STAFF_AND_TEAM_NOT_BELONG_SAME_COMPANY = "Nhân viên và nhóm không cùng công ty" MESSAGE_163_TEAM_NAME_TOO_LONG = 'Tên team dài hơn 255 ký tự' MESSAGE_164_CANNOT_DELETE_TEAM = 'Không thể xóa nhóm đang có nhân viên' MESSAGE_190_ROLE_EXISTS = 'Tên role title đã tồn tại' MESSAGE_126_EMAIL_COMPANY_INVALID = "email công ty và email đăng ký không phù hợp" MESSAGE_191_ROLE_ID_DOES_NOT_EXITS = 'role title id không tồn tại' MESSAGE_192_DEPARTMENT_NOT_BELONG_TO_COMPANY = 'Phòng ban không thuộc trong công ty' MESSAGE_193_CAN_NOT_DISABLE_ROLE_TILE = 'Không thể khóa vì job title đang gắn với nhân viên trong phòng ban' MESSAGE_194_CAN_NOT_UPDATE_ROLE_TILE_DEPARTMENT = 'Không thể cập nhật phòng ban của job title đã tồn tại' MESSAGE_195_CAN_NOT_UPDATE_ROLE_TILE_COMPANY = 'Không thể cập nhật công ty của job title đã tồn tại' MESSAGE_196_CAN_NOT_CREATE_SAME_ROLE_TILE_IN_A_DEPARTMENT = 'Role title name đã tồn tại trong phòng ban' MESSAGE_197_CAN_NOT_ACTIVE_ROLE_TILE_IN_DEPARTMENT_INACTIVE = 'Không thể kích hoạt role_title trong phòng ban đã khóa' MESSAGE_992_ERROR = 'có lỗi xảy ra, vui lòng liên hệ admin' MESSAGE_999_SERVER = "Hệ thống đang bảo trì, quý khách vui lòng thử lại sau" error_code = ErrorCode() message = ErrorMessage()
""" Painonhallintasovelluksen pääohjelma Huolehtii syötteen lukemisesta ja tulosten näyttämisestä """ # Kirjastojen ja modulien lataukset # Pääohjelman omat luokat, funktiot ja kirjastokomponenttien alustukset # Pääohjelman ikuinen silmukka jatketaan = 'K' while True: while virhekoodi != 0: paino_str = input('Paino kiloina: ') pituus_str = input('Pituus metreinä: ') ika_str = input('ikä vuosina: ') sukupuoli_str = input('Nainen 0, Mies 1: ') jatketaan = input('Haluatko jatkaa K/e? ') # TODO: tee rutiini oletusarvolle K if jatketaan != 'K': break
# -*- coding: utf-8 -*- extensions = ['sphinx.ext.viewcode'] master_doc = 'index' exclude_patterns = ['_build'] viewcode_follow_imported_members = False
#!/usr/bin/env python # encoding: utf-8 __all__ = ['gcd'] def gcd(a, b): """Compute gcd(a,b) :param a: first number :param b: second number :returns: the gcd """ pos_a, _a = (a >= 0), abs(a) pos_b, _b = (b >= 0), abs(b) gcd_sgn = (-1 + 2*(pos_a or pos_b)) if _a > _b: c = _a % _b else: c = _b % _a if c == 0: return gcd_sgn * min(_a,_b) elif _a == 1: return gcd_sgn * _b elif _b == 1: return gcd_sgn * _a else: return gcd_sgn * gcd(min(_a,_b), c) if __name__ == '__main__': print(gcd(3, 15)) print(gcd(3, 15)) print(gcd(-15, -3)) print(gcd(-3, -12)) # ----------------------------- # Reglages pour 'vim' # vim:set autoindent expandtab tabstop=4 shiftwidth=4: # cursor: 16 del
''' Anti-palindrome strings You are given a string containing only lowercase alphabets. You can swap two adjacent characters any number of times (including 0). A string is called anti-palindrome if it is not a palindrome. If it is possible to make a string anti-palindrome, then find the lexicographically smallest anti-palindrome. Otherwise, print . Input format The first line contains a single integer denoting the number of test cases. The description of test cases follows. Each line contains a string of lower case alphabets only. Output format For each test case, print the answer in a new line. Constraints contains only lowercase alphabets. SAMPLE INPUT 4 bpc pp deep zyx SAMPLE OUTPUT bcp -1 deep xyz Explanation In the first test case, you can create "bcp" which is not a palindrome and it is a lexicographically-smallest string. In the second test case, you cannot form any anti palindrome. ''' for _ in range(int(input())): x=list(input()) if x[::]==x[::-1]: print(-1) else: print(''.join(sorted(x)))
""" all opcodes Python3.6.0 """ # general NOP = 9 POP_TOP = 1 ROT_TWO = 2 ROT_THREE = 3 DUP_TOP = 4 DUP_TOP_TWO = 5 # one operand UNARY_POSITIVE = 10 UNARY_NEGATIVE = 11 UNARY_NOT = 12 UNARY_INVERT = 15 GET_ITER = 68 GET_YIELD_FROM_ITER = 69 # two operand BINARY_POWER = 19 BINARY_MULTIPLY = 20 BINARY_MATRIX_MULTIPLY = 16 BINARY_FLOOR_DIVIDE = 26 BINARY_TRUE_DIVIDE = 27 BINARY_MODULO = 22 BINARY_ADD = 23 BINARY_SUBTRACT = 24 BINARY_SUBSCR = 25 BINARY_LSHIFT = 62 BINARY_RSHIFT = 63 BINARY_AND = 64 BINARY_XOR = 65 BINARY_OR = 66 # inplace INPLACE_POWER = 67 INPLACE_MULTIPLY = 57 INPLACE_MATRIX_MULTIPLY = 17 INPLACE_FLOOR_DIVIDE = 28 INPLACE_TRUE_DIVIDE = 29 INPLACE_MODULO = 59 INPLACE_ADD = 55 INPLACE_SUBTRACT = 56 STORE_SUBSCR = 60 DELETE_SUBSCR = 61 INPLACE_LSHIFT = 75 INPLACE_RSHIFT = 76 INPLACE_AND = 77 INPLACE_XOR = 78 INPLACE_OR = 79 # coroutine (not implemented) GET_AWAITABLE = 73 GET_AITER = 50 GET_ANEXT = 51 BEFORE_ASYNC_WITH = 52 SETUP_ASYNC_WITH = 154 # loop FOR_ITER = 93 SETUP_LOOP = 120 # Distance to target address BREAK_LOOP = 80 CONTINUE_LOOP = 119 # Target address # comprehension SET_ADD = 146 LIST_APPEND = 145 MAP_ADD = 147 # return RETURN_VALUE = 83 YIELD_VALUE = 86 YIELD_FROM = 72 SETUP_ANNOTATIONS = 85 # context SETUP_WITH = 143 WITH_CLEANUP_START = 81 WITH_CLEANUP_FINISH = 82 # import IMPORT_STAR = 84 IMPORT_NAME = 108 # Index in name list IMPORT_FROM = 109 # Index in name list # block stack POP_BLOCK = 87 SETUP_EXCEPT = 121 # "" SETUP_FINALLY = 122 # "" POP_EXCEPT = 89 END_FINALLY = 88 # variable STORE_NAME = 90 # Index in name list DELETE_NAME = 91 # "" UNPACK_SEQUENCE = 92 # Number of tuple items UNPACK_EX = 94 STORE_ATTR = 95 # Index in name list DELETE_ATTR = 96 # "" STORE_GLOBAL = 97 # "" DELETE_GLOBAL = 98 # "" # load LOAD_CONST = 100 # Index in const list LOAD_NAME = 101 # Index in name list LOAD_ATTR = 106 # Index in name list LOAD_GLOBAL = 116 # Index in name list LOAD_FAST = 124 # Local variable number STORE_FAST = 125 # Local variable number DELETE_FAST = 126 # Local variable number # build object BUILD_TUPLE = 102 # Number of tuple items BUILD_LIST = 103 # Number of list items BUILD_SET = 104 # Number of set items BUILD_MAP = 105 # Number of dict entries BUILD_CONST_KEY_MAP = 156 BUILD_STRING = 157 BUILD_TUPLE_UNPACK = 152 BUILD_LIST_UNPACK = 149 BUILD_MAP_UNPACK = 150 BUILD_SET_UNPACK = 153 BUILD_MAP_UNPACK_WITH_CALL = 151 BUILD_TUPLE_UNPACK_WITH_CALL = 158 # bool COMPARE_OP = 107 # Comparison operator # counter JUMP_FORWARD = 110 # Number of bytes to skip POP_JUMP_IF_TRUE = 115 # "" POP_JUMP_IF_FALSE = 114 # "" JUMP_IF_TRUE_OR_POP = 112 # "" JUMP_IF_FALSE_OR_POP = 111 # Target byte offset from beginning of code JUMP_ABSOLUTE = 113 # "" # exception RAISE_VARARGS = 130 # Number of raise arguments (1, 2, or 3) # function CALL_FUNCTION = 131 # #args MAKE_FUNCTION = 132 # Flags BUILD_SLICE = 133 # Number of items LOAD_CLOSURE = 135 LOAD_DEREF = 136 STORE_DEREF = 137 DELETE_DEREF = 138 CALL_FUNCTION_KW = 141 # #args + #kwargs CALL_FUNCTION_EX = 142 # Flags LOAD_CLASSDEREF = 148 # others PRINT_EXPR = 70 LOAD_BUILD_CLASS = 71 HAVE_ARGUMENT = 90 # Opcodes from here have an argument: EXTENDED_ARG = 144 FORMAT_VALUE = 155
## 020 Valid Parentheses ## Given a string containing just the characters '(', ')', '{', '}', '[' and ']', ## determine if the input</br> string is valid. ## The brackets must close in the correct order, "()" and "()[]{}" are all valid ## but "(]" and "([)]" are not. class Solution: def isValid(self, s): """ :type s: str :rtype: bool """ test = list() for key, val in enumerate(s): if val in ['(', '{', '[']: test.append(val) elif len(test) == 0: return False else: c = test.pop() if {')':'(', '}':'{', ']':'['}[val] != c: #这是一个字典索引 return False if len(test) == 0: return True else: return False
def bom_populate(bom): bom.components.new( name="s1", description="HPE ML30 INTEL, 4U Tower, 8 HD's fit inside, 1 gbit dual", cost=378, rackspace_u=0, cru=0, sru=0, hru=0, mru=0, su_perc=50, cu_perc=50, power=150, ) bom.components.new( name="s2", description="HPE ML110 INTEL, 4U Tower, 8 HD's fit inside, 1 gbit dual", cost=454, rackspace_u=4, cru=0, sru=0, hru=0, mru=0, su_perc=90, cu_perc=10, power=150, ) bom.components.new(name="margin", description="margin per node for threefold and its partners", power=0, cost=500) bom.components.new( name="hd12", description="HPE 12TB SATA 6G Midline 7.2K LFF (6-8 watt)", cost=350, hru=12000, power=10, su_perc=100 ) bom.components.new( name="intel1", description="Intel Xeon E-2224 (3.4GHz/4-core/71W) (4 logical cores)", cost=296, cru=4, power=80, cu_perc=100, passmark=8202, ) bom.components.new( name="intel2", description="Intel Xeon-Silver 4208 (2.1GHz/8-core/85W) (16 logical cores)", cost=576, cru=16, power=85, cu_perc=100, passmark=13867, ) bom.components.new( name="intel3", description="Intel Xeon-Silver 4216 (2.1GHz/16-core/100W) (32 logical cores)", cost=1041, cru=16, power=100, cu_perc=100, passmark=20656, ) bom.components.new(name="ssd1", description="960 GB HPE SSD", cost=180, sru=1920, power=10, su_perc=100) bom.components.new(name="mem16_ecc", description="mem 16", cost=98, mru=16, power=8, cu_perc=100) bom.components.new(name="mem32_ecc", description="mem 32", cost=220, mru=32, power=8, cu_perc=100) #bom.components.new(name="sas_contr", description="HPE Smart Array E208i-p SR Gen10 (8 Internal Lanes/No Cache)", cost=60, power=20, su_perc=100) #bom.components.new(name="power_supply", description="350 Power Supply", cost=16, power=0, cu_perc=50, su_perc=50) #bom.components.new(name="sas_cable", description="sas cable kit", cost=33, power=0, su_perc=100) #bom.components.new(name="front_fan", description="front fan kit", cost=44, power=0, cu_perc=50, su_perc=50) bom.components.new( name="ng2", description="48 ports 10 gbit + 4 ports 10 gbit sfp: fs.com + cables", cost=1, power=100, rackspace_u=1, ) # create the template ml30 d = bom.devices.new(name="hpe_compute_tower_ml30") d.components.new(name="s1", nr=1) d.components.new(name="intel1", nr=1) d.components.new(name="hd12", nr=2) d.components.new(name="mem16_ecc", nr=1) d.components.new(name="ssd1", nr=1) #d.components.new(name="sas_contr", nr=1) #d.components.new(name="power_supply", nr=1) #d.components.new(name="sas_cable", nr=1) #d.components.new(name="front_fan", nr=1) # create the template ml110 8core d = bom.devices.new(name="hpe_compute_tower_ml110_8") d.components.new(name="s2", nr=1) d.components.new(name="intel2", nr=1) d.components.new(name="hd12", nr=2) d.components.new(name="mem32_ecc", nr=2) d.components.new(name="ssd1", nr=1) #d.components.new(name="sas_contr", nr=1) #d.components.new(name="power_supply", nr=1) # create the template ml110 16core d = bom.devices.new(name="hpe_compute_tower_ml110_16") d.components.new(name="s2", nr=1) d.components.new(name="intel3", nr=1) d.components.new(name="hd12", nr=2) d.components.new(name="mem32_ecc", nr=2) d.components.new(name="ssd1", nr=1) #d.components.new(name="sas_contr", nr=1) #d.components.new(name="power_supply", nr=1) d = bom.devices.new(name="switch_48") d.components.new(name="ng2", nr=1) return bom
class Model: def to_dict(self): return NotImplementedError class User(Model): def to_dict(self): return {} class UserID(Model): def to_dict(self): return {} class UserAuth(Model): def to_dict(self): return {}
# @file dsc_processor_plugin # Plugin for for parsing DSCs ## # Copyright (c) Microsoft Corporation # # SPDX-License-Identifier: BSD-2-Clause-Patent ## class IDscProcessorPlugin(object): ## # does the transform on the DSC # # @param dsc - the in-memory model of the DSC # @param thebuilder - UefiBuild object to get env information # # @return 0 for success NonZero for error. ## def do_transform(self, dsc, thebuilder): return 0 ## # gets the level that this transform operates at # # @param thebuilder - UefiBuild object to get env information # # @return 0 for the most generic level ## def get_level(self, thebuilder): return 0
def q2(stop_value): first, second = 0, 1 i = 0 while first < stop_value: print(f"{i}th term is: {first}") first, second = first + second, first i += 1 if __name__ == "__main__": n = 20 q2(n)
def titulo(): print('~' * 80) print('{:^80}'.format('Sistema Interativo PyHelp')) print('~' * 80) def leia_comando(): comando = str(input( '> Insira o comando que deseja obter ajuda: ("fim" para encerrar) ')).lower().strip() return comando def imprimir_manual(_comando): try: print() help(_comando) print() except: pass def encerramento(): print('-' * 80) print('{:^80}'.format('Obrigado por utilizar o PyHelp!')) print('-' * 80) while True: titulo() comando = leia_comando() imprimir_manual(comando) if comando == 'fim': encerramento() break
class Status: """ If you create a custom Status symbol, please keep in mind that all statuses are registered globally and that can cause name collisions. However, it's an intended use case for your checks to be able to yield custom statuses. Interpreters of the check protocol will have to skip statuses unknown to them or treat them in an otherwise non-fatal fashion. """ def __new__(cls, name, weight=0): """ Don't create two instances with same name. >>> a = Status('PASS') >>> a <Status hello> >>> b = Status('PASS') >>> b <Status hello> >>> b is a True >>> b == a True """ instance = cls.__instances.get(name, None) if instance is None: instance = cls.__instances[name] = super(Status, cls).__new__(cls) setattr(instance, '_Status__name', name) setattr(instance, '_Status__weight', weight) return instance __instances = {} def __str__(self): return f'<Status {self.__name}>' @property def name(self): return self.__name @property def weight(self): return self.__weight def __gt__(self, other): return self.weight > other.weight def __ge__(self, other): return self.weight >= other.weight def __lt__(self, other): return self.weight < other.weight def __le__(self, other): return self.weight <= other.weight __repr__ = __str__ # Status messages of the check runner protocol # Structuring statuses # * begin with "START" and "END" # * have weights < 0 # * START statuses have even weight, corresponding END statuses have odd # weights, such that START.weight + 1 == END.weight # * the bigger the weight the bigger is the structure, structuring on a macro-level # * different structures can have the same weights, if they occur on the same level # * ENDCHECK is the biggest structuring status # # Log statuses # * have weights >= 0 # * the more important the status the bigger the weight # * ERROR has the biggest weight # * PASS is the lowest status a check can have, # i.e.: a check run must at least yield one log that is >= PASS # # From all the statuses that can occur within a check, the "worst" one # is defining for the check overall status: # ERROR > FAIL > WARN > INFO > SKIP > PASS > DEBUG # Anything from WARN to PASS does not make a check fail. # A result < PASS creates an ERROR. That means, DEBUG is not a valid # result of a check, nor is any of the structuring statuses. # A check with SKIP can't (MUST NOT) create any other event. # Log statuses # only between STARTCHECK and ENDCHECK: DEBUG = Status('DEBUG', 0) # Silent by default PASS = Status('PASS', 1) SKIP = Status('SKIP', 2) # SKIP is heavier than PASS because it's likely more interesting to # see what got skipped, to reveal blind spots. INFO = Status('INFO', 3) WARN = Status('WARN', 4) # A check that results in WARN may indicate a problem, but also may be OK. FAIL = Status('FAIL', 5) # A FAIL is a problem detected in the font or family. ERROR = Status('ERROR', 6) # Something a programmer must fix. It will make a check fail as well. # Start of the suite of checks. Must be always the first message, even in async mode. # Message is the full execution order of the whole profile START = Status('START', -6) # Only between START and before the first SECTIONSUMMARY and END # Message is None. STARTCHECK = Status('STARTCHECK', -2) # Ends the last check started by STARTCHECK. # Message the the result status of the whole check, one of PASS, SKIP, FAIL, ERROR. ENDCHECK = Status('ENDCHECK', -1) # After the last ENDCHECK one SECTIONSUMMARY for each section before END. # Message is a tuple of: # * the actual execution order of the section in the check runner session # as reported. Especially in async mode, the order can differ significantly # from the actual order of checks in the session. # * a Counter dictionary where the keys are Status.name of # the ENDCHECK message. If serialized, some existing statuses may not be # in the counter because they never occurred in the section. SECTIONSUMMARY = Status('SECTIONSUMMARY', -3) # End of the suite of checks. Must be always the last message, even in async mode. # Message is a counter as described in SECTIONSUMMARY, but with the collected # results of all checks in all sections. END = Status('END', -5)
"""Detects and configures the local Python. Add the following to your WORKSPACE FILE: ```python python_configure(name = "cpython37", interpreter = "python3.7") ``` Args: name: A unique name for this workspace rule. interpreter: interpreter used to config this workspace """ def _tpl(repository_ctx, tpl, substitutions = {}, out = None): if not out: out = tpl repository_ctx.template( out, Label("//third_party/cpython:%s.tpl" % tpl), substitutions, ) def _fail(msg): """Output failure message when auto configuration fails.""" red = "\033[0;31m" no_color = "\033[0m" fail("%sPython Configuration Error:%s %s\n" % (red, no_color, msg)) def _execute( repository_ctx, cmdline, error_msg = None, error_details = None, empty_stdout_fine = False, environment = {}): """Executes an arbitrary shell command. Args: repository_ctx: the repository_ctx object cmdline: list of strings, the command to execute error_msg: string, a summary of the error if the command fails error_details: string, details about the error or steps to fix it empty_stdout_fine: bool, if True, an empty stdout result is fine, otherwise it's an error environment: environment variables passed to repository_ctx.execute Return: the result of repository_ctx.execute(cmdline) """ result = repository_ctx.execute(cmdline, environment = environment) if result.stderr or not (empty_stdout_fine or result.stdout): _fail("\n".join([ error_msg.strip() if error_msg else "Repository command failed", result.stderr.strip(), error_details if error_details else "", ])) return result def _get_bin(repository_ctx, bin_name): """Gets the bin path.""" bin_path = repository_ctx.which(bin_name) if bin_path != None: return str(bin_path) _fail("Cannot find %s in PATH" % bin_name) def _get_python_include(repository_ctx, python_bin): """Gets the python include path.""" result = _execute( repository_ctx, [ python_bin, "-c", "from __future__ import print_function;" + "from distutils import sysconfig;" + "print(sysconfig.get_python_inc())", ], error_msg = "Problem getting python include path.", ) return repository_ctx.path(result.stdout.splitlines()[0]) def _get_python_import_lib_path(repository_ctx, python_bin): """Get Python import library""" result = _execute( repository_ctx, [ python_bin, "-c", "from __future__ import print_function;" + "from distutils import sysconfig; import os; " + 'print(os.path.join(*sysconfig.get_config_vars("LIBDIR", "LDLIBRARY")))', ], error_msg = "Problem getting python import library.", ) return repository_ctx.path(result.stdout.splitlines()[0]) def _get_python_version(repository_ctx, python_bin): """Get Python import library""" result = _execute( repository_ctx, [ python_bin, "-c", "from __future__ import print_function;" + "import sys;" + "print(sys.version_info[0]);" + "print(sys.version_info[1])", ], error_msg = "Problem getting python versiony.", ) return [int(v) for v in result.stdout.splitlines()] def _get_python_config_flags(repository_ctx, python_config_bin, flags): result = _execute( repository_ctx, [ python_config_bin, flags, ], error_msg = "Problem getting python-config %s." % flags, ).stdout.splitlines()[0] return ",\n ".join([ '"%s"' % flag for flag in result.split(" ") if not flag.startswith("-I") ]) def _python_autoconf_impl(repository_ctx): """Implementation of the python_autoconf repository rule. Creates the repository containing files set up to build with Python. """ python_bin = _get_bin(repository_ctx, repository_ctx.attr.interpreter) python_include = _get_python_include(repository_ctx, python_bin) python_import_lib = _get_python_import_lib_path(repository_ctx, python_bin) python_version = _get_python_version(repository_ctx, python_bin) if repository_ctx.attr.devel: python_config_bin = _get_bin(repository_ctx, repository_ctx.attr.interpreter + "-config") python_cflags = _get_python_config_flags(repository_ctx, python_config_bin, "--cflags") python_ldflags = _get_python_config_flags(repository_ctx, python_config_bin, "--ldflags") if python_version[0] > 2: python_extension_suffix = _get_python_config_flags(repository_ctx, python_config_bin, "--extension-suffix") else: python_extension_suffix = '".so"' repository_ctx.symlink(python_bin, "python") repository_ctx.symlink(python_include, "include") repository_ctx.symlink(python_import_lib, "lib/" + python_import_lib.basename) _tpl(repository_ctx, "BUILD") _tpl(repository_ctx, "defs.bzl", substitutions = { "%{CPYTHON}": repository_ctx.name, "%{CFLAGS}": python_cflags, "%{LDFLAGS}": python_ldflags, "%{EXTENSION_SUFFIX}": python_extension_suffix, }) python_configure = repository_rule( attrs = { "interpreter": attr.string(), "devel": attr.bool(default = False, doc = "Add support for compiling python extension"), }, implementation = _python_autoconf_impl, configure = True, local = True, )
# Mu Lung Dojo Bulletin Board (2091006) | Mu Lung Temple (250000100) dojo = 925020000 response = sm.sendAskYesNo("Would you like to go to Mu Lung Dojo?") if response: sm.setReturnField() sm.setReturnPortal(0) sm.warp(dojo)
# -------------- # Code starts here class_1 = ['Geoffrey Hinton', 'Andrew Ng', 'Sebastian Raschka', 'Yoshua Bengio'] class_2 = ['Hilary Mason', 'Carla Gentry', 'Corinna Cortes'] new_class = class_1 + class_2 print(new_class) new_class.append('Peter Warden') print(new_class) new_class.remove('Carla Gentry') print(new_class) # Code ends here # -------------- # Code starts here courses= {'Math': 65, 'English': 70, 'History': 80, 'French': 70, 'Science': 60} print(courses) total= sum(courses.values()) print(total) percentage = total / 500 * 100 print(percentage) # Code ends here # -------------- # Code starts here mathematics= {'Geoffrey Hinton':78, 'Andrew Ng':95, 'Sebastian Raschka':65, 'Yoshua Bengio':50, 'Hilary Mason':70, 'Corinna Cortes':66, 'Peter Warden':75} topper= max(mathematics,key = mathematics.get) print(topper) # Code ends here # -------------- # Given string topper = 'andrew ng' # Code starts here first_name,last_name = topper.split( ) full_name = last_name + ' ' + first_name certificate_name = full_name.upper() print(certificate_name) #print(first_name) #print(last_name) # Code ends here
""" Spark mllib Algorithms -> Classification regression clustering topic modelling. etc. workflows -> feature transformations pipelines evaluations hyperparameter tuning utilities -> Distributed math libraries statistics functions """ # Normalize -> maps data from original range to range of 0 to 1 # Advantage of Normalization is large range values and small range values are brough to common range and that is 0 to 1. # Standardize -> Maps data from origninal range to range -1 to 1 # mean is 0 # normally distributed with standard deviation of 1 # Used when features have different scales and # ML algorithms assume a normal distribution. # Patitioning -> Maps data value from continuous values to buckets # Deciles and percentiles ane examples of buckets # useful when you want to work with groups of values # instead of a continuous range of values. # TEXT: TOkeniziong -> list of words. # TEXT: TF-IDF -> Maps text from a single, typically long strings to a vector of frequencies of each word relative to a text. # TF-IDF assumes infrequently used workds are more useful to classify text. ##### NORMALIZING
badge_icon = 'app.icns' icon_locations = { 'LBRY.app': (115, 164), 'Applications': (387, 164) } background='dmg_background.png' default_view='icon-view' symlinks = { 'Applications': '/Applications' } window_rect=((200, 200), (500, 320)) files = [ 'LBRY.app' ] icon_size=128
# -*- coding: utf-8 -*- """ Created on Mon Jun 11 01:37:09 2018 @author: sushy """ secretWord = 'apple' lettersGuessed = ['e', 'i', 'k', 'p', 'r', 's'] def getGuessedWord(sW, lG): ''' sW: string, the word the user is guessing lG: list, what letters have been guessed so far returns: string, comprised of letters and underscores that represents what letters in secretWord have been guessed so far. ''' #first want to create a list with all the letters in secret word, so we can change certain letters letters = [] for c in sW: letters.append(c) #then for each letter that was not in letters guessed change that to an underscore for i in range(len(letters)): if letters[i] not in lG: letters[i] = ' _ ' #then we want to return the string version of letters return ''.join(letters) print(getGuessedWord(secretWord, lettersGuessed))
# # PySNMP MIB module TPT-TPA-HARDWARE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/TPT-TPA-HARDWARE-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:26:46 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) # ObjectIdentifier, Integer, OctetString = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "Integer", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection", "SingleValueConstraint") InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") Counter32, Counter64, Gauge32, TimeTicks, MibIdentifier, ModuleIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, ObjectIdentity, Bits, IpAddress, iso, Integer32, NotificationType, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "Counter32", "Counter64", "Gauge32", "TimeTicks", "MibIdentifier", "ModuleIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "ObjectIdentity", "Bits", "IpAddress", "iso", "Integer32", "NotificationType", "Unsigned32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") tpt_tpa_objs, tpt_tpa_eventsV2, tpt_tpa_unkparams = mibBuilder.importSymbols("TPT-TPAMIBS-MIB", "tpt-tpa-objs", "tpt-tpa-eventsV2", "tpt-tpa-unkparams") tpt_tpa_hardware_objs = ModuleIdentity((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3)).setLabel("tpt-tpa-hardware-objs") tpt_tpa_hardware_objs.setRevisions(('2016-05-25 18:54',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: tpt_tpa_hardware_objs.setRevisionsDescriptions(('Updated copyright information. Minor MIB syntax fixes.',)) if mibBuilder.loadTexts: tpt_tpa_hardware_objs.setLastUpdated('201605251854Z') if mibBuilder.loadTexts: tpt_tpa_hardware_objs.setOrganization('Trend Micro, Inc.') if mibBuilder.loadTexts: tpt_tpa_hardware_objs.setContactInfo('www.trendmicro.com') if mibBuilder.loadTexts: tpt_tpa_hardware_objs.setDescription("Hardware definition of a TPA and its components. Copyright (C) 2016 Trend Micro Incorporated. All Rights Reserved. Trend Micro makes no warranty of any kind with regard to this material, including, but not limited to, the implied warranties of merchantability and fitness for a particular purpose. Trend Micro shall not be liable for errors contained herein or for incidental or consequential damages in connection with the furnishing, performance, or use of this material. This document contains proprietary information, which is protected by copyright. No part of this document may be photocopied, reproduced, or translated into another language without the prior written consent of Trend Micro. The information is provided 'as is' without warranty of any kind and is subject to change without notice. The only warranties for Trend Micro products and services are set forth in the express warranty statements accompanying such products and services. Nothing herein should be construed as constituting an additional warranty. Trend Micro shall not be liable for technical or editorial errors or omissions contained herein. TippingPoint(R), the TippingPoint logo, and Digital Vaccine(R) are registered trademarks of Trend Micro. All other company and product names may be trademarks of their respective holders. All rights reserved. This document contains confidential information, trade secrets or both, which are the property of Trend Micro. No part of this documentation may be reproduced in any form or by any means or used to make any derivative work (such as translation, transformation, or adaptation) without written permission from Trend Micro or one of its subsidiaries. All other company and product names may be trademarks of their respective holders. ") class ManagedElementType(TextualConvention, Integer32): description = 'Type of a managed base hardware element (slot, port, power supply, fan, etc.) on a device.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24)) namedValues = NamedValues(("unequip", 0), ("chassis", 1), ("backplane", 2), ("controller", 3), ("network-interface", 4), ("network-interface-bcomm", 5), ("network-processor", 6), ("feature-card", 7), ("gige-port", 8), ("ten-base-t-port", 9), ("hundred-base-t-port", 10), ("sonet-atm-port", 11), ("sonet-pos-port", 12), ("sonet-pos-srp-port", 13), ("sdh-atm-port", 14), ("sdh-pos-port", 15), ("sdh-pos-srp-port", 16), ("power-supply", 17), ("power-supply-sub-unit", 18), ("fan-controller", 19), ("fan-sub-unit", 20), ("power-entry-module", 21), ("vnam-port", 22), ("ten-gige-port", 23), ("forty-gige-port", 24)) class ConfigRedundancy(TextualConvention, Integer32): description = 'An indication of whether a hardware slot is empty, stand-alone, or part of a redundant pair.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4)) namedValues = NamedValues(("unconfigured", 0), ("simplex", 1), ("duplex", 2), ("loadshare", 3), ("autonomous", 4)) class HardwareState(TextualConvention, Integer32): description = 'The high-level hardware state (active, initializing, standby, etc.).' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9)) namedValues = NamedValues(("oos", 0), ("initialize", 1), ("act", 2), ("stby", 3), ("dgn", 4), ("lpbk", 5), ("act-faf", 6), ("stby-faf", 7), ("act-dgrd", 8), ("stby-dgrd", 9)) class HardwareStateQual(TextualConvention, Integer32): description = 'Further qualification/detail on the high-level hardware state.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29)) namedValues = NamedValues(("port-clear", 0), ("degraded", 1), ("port-los", 2), ("port-lof", 3), ("port-oof", 4), ("port-lop", 5), ("port-signal-degrade", 6), ("port-signal-failure", 7), ("port-ais-p", 8), ("port-ais-l", 9), ("port-rdi", 10), ("port-forced", 11), ("port-lockout", 12), ("yellow-alarm", 13), ("red-alarm", 14), ("parity-err", 15), ("crc-err", 16), ("unequipped-slot", 17), ("blade-pull", 18), ("blade-insert", 19), ("blade-slot-mismatch", 20), ("init-failure", 21), ("parent-oos", 22), ("removed", 23), ("no-info", 24), ("over-temp-alarm", 25), ("under-temp-alarm", 26), ("port-ool", 27), ("port-ool-clear", 28), ("inhibit", 29)) class ExtendedSlot(TextualConvention, Integer32): description = 'An identifier of either a slot or a hardware component. Slot numbers, slot11 to slot14 are valid on NX device, and refer to slot1 to slot4 on that device.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16)) namedValues = NamedValues(("slot1", 1), ("slot2", 2), ("slot3", 3), ("slot4", 4), ("slot5", 5), ("slot6", 6), ("slot7", 7), ("slot8", 8), ("shelf", 9), ("pem", 10), ("power-supply", 11), ("fan", 12), ("slot11", 13), ("slot12", 14), ("slot13", 15), ("slot14", 16)) class LineType(TextualConvention, Integer32): description = 'An indication of whether a port is copper or optical.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 21, 22, 23)) namedValues = NamedValues(("undefined", 0), ("copper", 21), ("optical", 22), ("copper-sfp", 23)) class DuplexState(TextualConvention, Integer32): description = 'An indication of whether a port is running in full or half duplex mode.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2)) namedValues = NamedValues(("unknown", 0), ("half", 1), ("full", 2)) class SfpQualifier(TextualConvention, Integer32): description = 'SFP qualifier value. These combines both the compliance codes for the 1G SFP and 10G SFP+, and transmitter technology for the 40G QSFP+ and 10G XFP transceivers.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29)) namedValues = NamedValues(("sfp-not-applicable", 0), ("sfp-10g-base-er", 1), ("sfp-10g-base-lrm", 2), ("sfp-10g-base-lr", 3), ("sfp-10g-base-sr", 4), ("sfp-base-px", 5), ("sfp-base-bx10", 6), ("sfp-100base-fx", 7), ("sfp-100base-lx-lx10", 8), ("sfp-1000base-t", 9), ("sfp-1000base-cx", 10), ("sfp-1000base-lx", 11), ("sfp-1000base-sx", 12), ("sfp-850-nm-vcsel", 13), ("sfp-1310-nm-vcsel", 14), ("sfp-1550-nm-vcsel", 15), ("sfp-1310-nm-fp", 16), ("sfp-1310-nm-dfb", 17), ("sfp-1550-nm-dfb", 18), ("sfp-1310-nm-eml", 19), ("sfp-1550-nm-eml", 20), ("sfp-copper-or-others", 21), ("sfp-1490-nm-dfb", 22), ("sfp-copper-cable-unequalized", 23), ("sfp-absent", 24), ("sfp-plus-absent", 25), ("qsfp-plus-absent", 26), ("sfp-xfp-absent", 27), ("sfp-10g-dac", 28), ("sfp-10g-dao", 29)) hw_slotTable = MibTable((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1), ).setLabel("hw-slotTable") if mibBuilder.loadTexts: hw_slotTable.setStatus('current') if mibBuilder.loadTexts: hw_slotTable.setDescription('Table of slots/ports on the device.') hw_slotEntry = MibTableRow((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1), ).setLabel("hw-slotEntry").setIndexNames((0, "TPT-TPA-HARDWARE-MIB", "slotNumber"), (0, "TPT-TPA-HARDWARE-MIB", "slotPort")) if mibBuilder.loadTexts: hw_slotEntry.setStatus('current') if mibBuilder.loadTexts: hw_slotEntry.setDescription('An entry in the slot/port table. Rows cannot be created or deleted.') slotNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotNumber.setStatus('current') if mibBuilder.loadTexts: slotNumber.setDescription('Slot number for this hardware element.') slotPort = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 2), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotPort.setStatus('current') if mibBuilder.loadTexts: slotPort.setDescription('Port number for this hardware element (0 refers to the board).') slotType = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 3), ManagedElementType()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotType.setStatus('current') if mibBuilder.loadTexts: slotType.setDescription('Type of hardware element corresponding to slot/port.') slotCfgType = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 4), ConfigRedundancy()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotCfgType.setStatus('current') if mibBuilder.loadTexts: slotCfgType.setDescription('The configuration/redundancy of a hardware element.') slotRunState = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 5), HardwareState()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotRunState.setStatus('current') if mibBuilder.loadTexts: slotRunState.setDescription('The high-level hardware state (active, initializing, standby, etc.).') slotQualifier1 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 6), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotQualifier1.setStatus('current') if mibBuilder.loadTexts: slotQualifier1.setDescription('Further qualification/detail on the high-level hardware state.') slotQualifier2 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 7), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotQualifier2.setStatus('current') if mibBuilder.loadTexts: slotQualifier2.setDescription('Further qualification/detail on the high-level hardware state.') slotQualifier3 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 8), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotQualifier3.setStatus('current') if mibBuilder.loadTexts: slotQualifier3.setDescription('Further qualification/detail on the high-level hardware state.') slotQualifier4 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 9), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotQualifier4.setStatus('current') if mibBuilder.loadTexts: slotQualifier4.setDescription('Further qualification/detail on the high-level hardware state.') slotStartTime = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 10), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotStartTime.setStatus('current') if mibBuilder.loadTexts: slotStartTime.setDescription('The time (seconds) at which this hardware element was powered up.') slotVendorID = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 11), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotVendorID.setStatus('current') if mibBuilder.loadTexts: slotVendorID.setDescription('The identifying number of the vendor of this hardware.') slotDeviceID = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 12), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotDeviceID.setStatus('current') if mibBuilder.loadTexts: slotDeviceID.setDescription('The PCI bus device ID for this slot.') slotProductID = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 13), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: slotProductID.setStatus('current') if mibBuilder.loadTexts: slotProductID.setDescription('Versioning and other inventory information for this hardware element.') slotFPGAVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 14), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotFPGAVersion.setStatus('current') if mibBuilder.loadTexts: slotFPGAVersion.setDescription('The version of the TPT FPGA chip on this hardware.') slotInterface = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 15), InterfaceIndex()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotInterface.setStatus('current') if mibBuilder.loadTexts: slotInterface.setDescription('The entry in the IF-MIB interface table that corresponds to this port.') slotLineType = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 16), LineType()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotLineType.setStatus('current') if mibBuilder.loadTexts: slotLineType.setDescription('The line type (e.g., copper or optical) of the port.') slotDuplexState = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 17), DuplexState()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotDuplexState.setStatus('current') if mibBuilder.loadTexts: slotDuplexState.setDescription('The current duplex state (full or half) of the port.') slotPhysical = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 18), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotPhysical.setStatus('current') if mibBuilder.loadTexts: slotPhysical.setDescription('Physical port number for this hardware element (0 if not a port).') slotSfpQualifier1 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 19), SfpQualifier()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotSfpQualifier1.setStatus('current') if mibBuilder.loadTexts: slotSfpQualifier1.setDescription('Type of the SFP transceiver') slotSfpQualifier2 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 1, 1, 20), SfpQualifier()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotSfpQualifier2.setStatus('current') if mibBuilder.loadTexts: slotSfpQualifier2.setDescription('Type of the SFP transceiver. This is applicable to the dual speed transceivers, and this variable will have value of the second speed supported by those transceivers. For single-speed transceivers, the value will be not applicable.') hw_chasTable = MibTable((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 2), ).setLabel("hw-chasTable") if mibBuilder.loadTexts: hw_chasTable.setStatus('current') if mibBuilder.loadTexts: hw_chasTable.setDescription('Table of chassis data for the device. Represented as a table with one row, and that row is the same as that for other managed elements.') hw_chasEntry = MibTableRow((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 2, 1), ).setLabel("hw-chasEntry").setIndexNames((0, "TPT-TPA-HARDWARE-MIB", "chasNumber")) if mibBuilder.loadTexts: hw_chasEntry.setStatus('current') if mibBuilder.loadTexts: hw_chasEntry.setDescription('An entry in the chassis table. Rows cannot be created or deleted.') chasNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 2, 1, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: chasNumber.setStatus('current') if mibBuilder.loadTexts: chasNumber.setDescription('Number for this entry in the chassis table. Should always be 0.') chasType = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 2, 1, 3), ManagedElementType()).setMaxAccess("readonly") if mibBuilder.loadTexts: chasType.setStatus('current') if mibBuilder.loadTexts: chasType.setDescription('Type of hardware element -- should always be chassis or unequip.') chasCfgType = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 2, 1, 4), ConfigRedundancy()).setMaxAccess("readonly") if mibBuilder.loadTexts: chasCfgType.setStatus('current') if mibBuilder.loadTexts: chasCfgType.setDescription('The configuration/redundancy of a hardware element.') chasRunState = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 2, 1, 5), HardwareState()).setMaxAccess("readonly") if mibBuilder.loadTexts: chasRunState.setStatus('current') if mibBuilder.loadTexts: chasRunState.setDescription('The high-level hardware state (active, initializing, standby, etc.).') chasQualifier1 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 2, 1, 6), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: chasQualifier1.setStatus('current') if mibBuilder.loadTexts: chasQualifier1.setDescription('Further qualification/detail on the high-level hardware state.') chasQualifier2 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 2, 1, 7), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: chasQualifier2.setStatus('current') if mibBuilder.loadTexts: chasQualifier2.setDescription('Further qualification/detail on the high-level hardware state.') chasQualifier3 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 2, 1, 8), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: chasQualifier3.setStatus('current') if mibBuilder.loadTexts: chasQualifier3.setDescription('Further qualification/detail on the high-level hardware state.') chasQualifier4 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 2, 1, 9), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: chasQualifier4.setStatus('current') if mibBuilder.loadTexts: chasQualifier4.setDescription('Further qualification/detail on the high-level hardware state.') chasStartTime = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 2, 1, 10), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: chasStartTime.setStatus('current') if mibBuilder.loadTexts: chasStartTime.setDescription('The time (seconds) at which the hardware element was powered up.') chasVendorID = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 2, 1, 11), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: chasVendorID.setStatus('current') if mibBuilder.loadTexts: chasVendorID.setDescription('The identifying number of the vendor of this hardware.') chasDeviceID = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 2, 1, 12), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: chasDeviceID.setStatus('current') if mibBuilder.loadTexts: chasDeviceID.setDescription('An identifying number specific to this device.') chasProductID = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 2, 1, 13), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: chasProductID.setStatus('current') if mibBuilder.loadTexts: chasProductID.setDescription('Versioning and other inventory information for this hardware element.') chasFPGAVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 2, 1, 14), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: chasFPGAVersion.setStatus('current') if mibBuilder.loadTexts: chasFPGAVersion.setDescription('The version of the TPT FPGA chip on this hardware.') hw_fanTable = MibTable((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 3), ).setLabel("hw-fanTable") if mibBuilder.loadTexts: hw_fanTable.setStatus('current') if mibBuilder.loadTexts: hw_fanTable.setDescription('Table of fans on the device.') hw_fanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 3, 1), ).setLabel("hw-fanEntry").setIndexNames((0, "TPT-TPA-HARDWARE-MIB", "fanSubunit")) if mibBuilder.loadTexts: hw_fanEntry.setStatus('current') if mibBuilder.loadTexts: hw_fanEntry.setDescription('An entry in the fan table. Rows cannot be created or deleted.') fanSubunit = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 3, 1, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fanSubunit.setStatus('current') if mibBuilder.loadTexts: fanSubunit.setDescription('Number of fan sub-unit (0 for controller).') fanType = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 3, 1, 3), ManagedElementType()).setMaxAccess("readonly") if mibBuilder.loadTexts: fanType.setStatus('current') if mibBuilder.loadTexts: fanType.setDescription('Type of hardware element -- should always be fan or unequip.') fanCfgType = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 3, 1, 4), ConfigRedundancy()).setMaxAccess("readonly") if mibBuilder.loadTexts: fanCfgType.setStatus('current') if mibBuilder.loadTexts: fanCfgType.setDescription('The configuration/redundancy of a hardware element.') fanRunState = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 3, 1, 5), HardwareState()).setMaxAccess("readonly") if mibBuilder.loadTexts: fanRunState.setStatus('current') if mibBuilder.loadTexts: fanRunState.setDescription('The high-level hardware state (active, initializing, standby, etc.).') fanQualifier1 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 3, 1, 6), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: fanQualifier1.setStatus('current') if mibBuilder.loadTexts: fanQualifier1.setDescription('Further qualification/detail on the high-level hardware state.') fanQualifier2 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 3, 1, 7), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: fanQualifier2.setStatus('current') if mibBuilder.loadTexts: fanQualifier2.setDescription('Further qualification/detail on the high-level hardware state.') fanQualifier3 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 3, 1, 8), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: fanQualifier3.setStatus('current') if mibBuilder.loadTexts: fanQualifier3.setDescription('Further qualification/detail on the high-level hardware state.') fanQualifier4 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 3, 1, 9), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: fanQualifier4.setStatus('current') if mibBuilder.loadTexts: fanQualifier4.setDescription('Further qualification/detail on the high-level hardware state.') fanStartTime = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 3, 1, 10), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fanStartTime.setStatus('current') if mibBuilder.loadTexts: fanStartTime.setDescription('The time (seconds) at which the hardware element was powered up.') fanVendorID = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 3, 1, 11), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fanVendorID.setStatus('current') if mibBuilder.loadTexts: fanVendorID.setDescription('The identifying number of the vendor of this hardware.') fanDeviceID = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 3, 1, 12), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fanDeviceID.setStatus('current') if mibBuilder.loadTexts: fanDeviceID.setDescription('An identifying number specific to this device.') fanProductID = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 3, 1, 13), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: fanProductID.setStatus('current') if mibBuilder.loadTexts: fanProductID.setDescription('Versioning and other inventory information for this hardware element.') fanFPGAVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 3, 1, 14), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: fanFPGAVersion.setStatus('current') if mibBuilder.loadTexts: fanFPGAVersion.setDescription('The version of the TPT FPGA chip on this hardware.') hw_psTable = MibTable((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 4), ).setLabel("hw-psTable") if mibBuilder.loadTexts: hw_psTable.setStatus('current') if mibBuilder.loadTexts: hw_psTable.setDescription('Table of power supplies on the device.') hw_psEntry = MibTableRow((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 4, 1), ).setLabel("hw-psEntry").setIndexNames((0, "TPT-TPA-HARDWARE-MIB", "psSubunit")) if mibBuilder.loadTexts: hw_psEntry.setStatus('current') if mibBuilder.loadTexts: hw_psEntry.setDescription('An entry in the power supply table. Rows cannot be created or deleted.') psSubunit = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 4, 1, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: psSubunit.setStatus('current') if mibBuilder.loadTexts: psSubunit.setDescription('Number of power supply sub-unit (0 for controller).') psType = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 4, 1, 3), ManagedElementType()).setMaxAccess("readonly") if mibBuilder.loadTexts: psType.setStatus('current') if mibBuilder.loadTexts: psType.setDescription('Type of hardware element -- should always be power-supply or unequip.') psCfgType = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 4, 1, 4), ConfigRedundancy()).setMaxAccess("readonly") if mibBuilder.loadTexts: psCfgType.setStatus('current') if mibBuilder.loadTexts: psCfgType.setDescription('The configuration/redundancy of a hardware element.') psRunState = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 4, 1, 5), HardwareState()).setMaxAccess("readonly") if mibBuilder.loadTexts: psRunState.setStatus('current') if mibBuilder.loadTexts: psRunState.setDescription('The high-level hardware state (active, initializing, standby, etc.).') psQualifier1 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 4, 1, 6), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: psQualifier1.setStatus('current') if mibBuilder.loadTexts: psQualifier1.setDescription('Further qualification/detail on the high-level hardware state.') psQualifier2 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 4, 1, 7), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: psQualifier2.setStatus('current') if mibBuilder.loadTexts: psQualifier2.setDescription('Further qualification/detail on the high-level hardware state.') psQualifier3 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 4, 1, 8), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: psQualifier3.setStatus('current') if mibBuilder.loadTexts: psQualifier3.setDescription('Further qualification/detail on the high-level hardware state.') psQualifier4 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 4, 1, 9), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: psQualifier4.setStatus('current') if mibBuilder.loadTexts: psQualifier4.setDescription('Further qualification/detail on the high-level hardware state.') psStartTime = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 4, 1, 10), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: psStartTime.setStatus('current') if mibBuilder.loadTexts: psStartTime.setDescription('The time (seconds) at which the hardware element was powered up.') psVendorID = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 4, 1, 11), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: psVendorID.setStatus('current') if mibBuilder.loadTexts: psVendorID.setDescription('The identifying number of the vendor of this hardware.') psDeviceID = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 4, 1, 12), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: psDeviceID.setStatus('current') if mibBuilder.loadTexts: psDeviceID.setDescription('An identifying number specific to this device.') psProductID = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 4, 1, 13), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: psProductID.setStatus('current') if mibBuilder.loadTexts: psProductID.setDescription('Versioning and other inventory information for this hardware element.') psFPGAVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 4, 1, 14), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: psFPGAVersion.setStatus('current') if mibBuilder.loadTexts: psFPGAVersion.setDescription('The version of the TPT FPGA chip on this hardware.') hw_pemTable = MibTable((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 5), ).setLabel("hw-pemTable") if mibBuilder.loadTexts: hw_pemTable.setStatus('current') if mibBuilder.loadTexts: hw_pemTable.setDescription('Table of power entry modules on the device.') hw_pemEntry = MibTableRow((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 5, 1), ).setLabel("hw-pemEntry").setIndexNames((0, "TPT-TPA-HARDWARE-MIB", "pemSubunit")) if mibBuilder.loadTexts: hw_pemEntry.setStatus('current') if mibBuilder.loadTexts: hw_pemEntry.setDescription('An entry in the power supply table. Rows cannot be created or deleted.') pemSubunit = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 5, 1, 1), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pemSubunit.setStatus('current') if mibBuilder.loadTexts: pemSubunit.setDescription('Number of power entry module sub-unit (0 for controller).') pemType = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 5, 1, 3), ManagedElementType()).setMaxAccess("readonly") if mibBuilder.loadTexts: pemType.setStatus('current') if mibBuilder.loadTexts: pemType.setDescription('Type of hardware element -- should always be pem or unequip.') pemCfgType = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 5, 1, 4), ConfigRedundancy()).setMaxAccess("readonly") if mibBuilder.loadTexts: pemCfgType.setStatus('current') if mibBuilder.loadTexts: pemCfgType.setDescription('The configuration/redundancy of a hardware element.') pemRunState = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 5, 1, 5), HardwareState()).setMaxAccess("readonly") if mibBuilder.loadTexts: pemRunState.setStatus('current') if mibBuilder.loadTexts: pemRunState.setDescription('The high-level hardware state (active, initializing, standby, etc.).') pemQualifier1 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 5, 1, 6), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: pemQualifier1.setStatus('current') if mibBuilder.loadTexts: pemQualifier1.setDescription('Further qualification/detail on the high-level hardware state.') pemQualifier2 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 5, 1, 7), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: pemQualifier2.setStatus('current') if mibBuilder.loadTexts: pemQualifier2.setDescription('Further qualification/detail on the high-level hardware state.') pemQualifier3 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 5, 1, 8), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: pemQualifier3.setStatus('current') if mibBuilder.loadTexts: pemQualifier3.setDescription('Further qualification/detail on the high-level hardware state.') pemQualifier4 = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 5, 1, 9), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: pemQualifier4.setStatus('current') if mibBuilder.loadTexts: pemQualifier4.setDescription('Further qualification/detail on the high-level hardware state.') pemStartTime = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 5, 1, 10), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pemStartTime.setStatus('current') if mibBuilder.loadTexts: pemStartTime.setDescription('The time (seconds) at which the hardware element was powered up.') pemVendorID = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 5, 1, 11), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pemVendorID.setStatus('current') if mibBuilder.loadTexts: pemVendorID.setDescription('The identifying number of the vendor of this hardware.') pemDeviceID = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 5, 1, 12), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pemDeviceID.setStatus('current') if mibBuilder.loadTexts: pemDeviceID.setDescription('An identifying number specific to this device.') pemProductID = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 5, 1, 13), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: pemProductID.setStatus('current') if mibBuilder.loadTexts: pemProductID.setDescription('Versioning and other inventory information for this hardware element.') pemFPGAVersion = MibTableColumn((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 5, 1, 14), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: pemFPGAVersion.setStatus('current') if mibBuilder.loadTexts: pemFPGAVersion.setDescription('The version of the TPT FPGA chip on this hardware.') hw_numSlots = MibScalar((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 6), Unsigned32()).setLabel("hw-numSlots").setMaxAccess("readonly") if mibBuilder.loadTexts: hw_numSlots.setStatus('current') if mibBuilder.loadTexts: hw_numSlots.setDescription('The number of slots for this device.') hw_numFans = MibScalar((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 7), Unsigned32()).setLabel("hw-numFans").setMaxAccess("readonly") if mibBuilder.loadTexts: hw_numFans.setStatus('current') if mibBuilder.loadTexts: hw_numFans.setDescription('The number of fan subunits for this device.') hw_numPowerSupplies = MibScalar((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 8), Unsigned32()).setLabel("hw-numPowerSupplies").setMaxAccess("readonly") if mibBuilder.loadTexts: hw_numPowerSupplies.setStatus('current') if mibBuilder.loadTexts: hw_numPowerSupplies.setDescription('The number of power supply subunits for this device.') hw_numPEMs = MibScalar((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 9), Unsigned32()).setLabel("hw-numPEMs").setMaxAccess("readonly") if mibBuilder.loadTexts: hw_numPEMs.setStatus('current') if mibBuilder.loadTexts: hw_numPEMs.setDescription('The number of PEM subunits for this device.') hw_certificateNumber = MibScalar((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 10), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 30))).setLabel("hw-certificateNumber").setMaxAccess("readonly") if mibBuilder.loadTexts: hw_certificateNumber.setStatus('current') if mibBuilder.loadTexts: hw_certificateNumber.setDescription('The hardware certficate number of the device.') hw_serialNumber = MibScalar((1, 3, 6, 1, 4, 1, 10734, 3, 3, 2, 3, 11), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 30))).setLabel("hw-serialNumber").setMaxAccess("readonly") if mibBuilder.loadTexts: hw_serialNumber.setStatus('current') if mibBuilder.loadTexts: hw_serialNumber.setDescription('The hardware serial number of the device.') tptHardwareNotifyDeviceID = MibScalar((1, 3, 6, 1, 4, 1, 10734, 3, 3, 3, 1, 1), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 40))).setMaxAccess("readonly") if mibBuilder.loadTexts: tptHardwareNotifyDeviceID.setStatus('current') if mibBuilder.loadTexts: tptHardwareNotifyDeviceID.setDescription('The unique identifier of the device sending this notification.') tptHardwareNotifySlot = MibScalar((1, 3, 6, 1, 4, 1, 10734, 3, 3, 3, 1, 2), ExtendedSlot()).setMaxAccess("readonly") if mibBuilder.loadTexts: tptHardwareNotifySlot.setStatus('current') if mibBuilder.loadTexts: tptHardwareNotifySlot.setDescription('The slot of the hardware whose state has changed. If the hardware element is not a board, this value identifies it as a chassis, fan, power supply, PEM, etc.') tptHardwareNotifyPort = MibScalar((1, 3, 6, 1, 4, 1, 10734, 3, 3, 3, 1, 3), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: tptHardwareNotifyPort.setStatus('current') if mibBuilder.loadTexts: tptHardwareNotifyPort.setDescription('The port or sub-unit number of the hardware whose state has changed. Zero for a board, chassis, fan controller, power supply, or power entry module.') tptHardwareNotifyMeType = MibScalar((1, 3, 6, 1, 4, 1, 10734, 3, 3, 3, 1, 4), ManagedElementType()).setMaxAccess("readonly") if mibBuilder.loadTexts: tptHardwareNotifyMeType.setStatus('current') if mibBuilder.loadTexts: tptHardwareNotifyMeType.setDescription('The type of the managed element (e.g., backplane, controller, power supply, fan, etc.) whose state has changed.') tptHardwareNotifyCfgType = MibScalar((1, 3, 6, 1, 4, 1, 10734, 3, 3, 3, 1, 5), ConfigRedundancy()).setMaxAccess("readonly") if mibBuilder.loadTexts: tptHardwareNotifyCfgType.setStatus('current') if mibBuilder.loadTexts: tptHardwareNotifyCfgType.setDescription('The configuration/redundancy of the hardware whose state has changed.') tptHardwareNotifyHlState = MibScalar((1, 3, 6, 1, 4, 1, 10734, 3, 3, 3, 1, 6), HardwareState()).setMaxAccess("readonly") if mibBuilder.loadTexts: tptHardwareNotifyHlState.setStatus('current') if mibBuilder.loadTexts: tptHardwareNotifyHlState.setDescription('The high-level hardware state (active, initializing, standby, etc.).') tptHardwareNotifyHlStateQual = MibScalar((1, 3, 6, 1, 4, 1, 10734, 3, 3, 3, 1, 7), HardwareStateQual()).setMaxAccess("readonly") if mibBuilder.loadTexts: tptHardwareNotifyHlStateQual.setStatus('current') if mibBuilder.loadTexts: tptHardwareNotifyHlStateQual.setDescription('Further qualification/detail on the high-level state.') tptHardwareNotify = NotificationType((1, 3, 6, 1, 4, 1, 10734, 3, 3, 3, 0, 7)).setObjects(("TPT-TPA-HARDWARE-MIB", "tptHardwareNotifyDeviceID"), ("TPT-TPA-HARDWARE-MIB", "tptHardwareNotifySlot"), ("TPT-TPA-HARDWARE-MIB", "tptHardwareNotifyPort"), ("TPT-TPA-HARDWARE-MIB", "tptHardwareNotifyMeType"), ("TPT-TPA-HARDWARE-MIB", "tptHardwareNotifyCfgType"), ("TPT-TPA-HARDWARE-MIB", "tptHardwareNotifyHlState"), ("TPT-TPA-HARDWARE-MIB", "tptHardwareNotifyHlStateQual")) if mibBuilder.loadTexts: tptHardwareNotify.setStatus('current') if mibBuilder.loadTexts: tptHardwareNotify.setDescription('Notification: Used to inform the management station of changes in hardware state on the device.') mibBuilder.exportSymbols("TPT-TPA-HARDWARE-MIB", slotVendorID=slotVendorID, hw_pemTable=hw_pemTable, hw_slotTable=hw_slotTable, tptHardwareNotifyPort=tptHardwareNotifyPort, slotInterface=slotInterface, slotNumber=slotNumber, chasQualifier1=chasQualifier1, PYSNMP_MODULE_ID=tpt_tpa_hardware_objs, hw_slotEntry=hw_slotEntry, chasQualifier3=chasQualifier3, hw_fanEntry=hw_fanEntry, tptHardwareNotifySlot=tptHardwareNotifySlot, hw_psEntry=hw_psEntry, chasCfgType=chasCfgType, chasQualifier4=chasQualifier4, psFPGAVersion=psFPGAVersion, fanRunState=fanRunState, LineType=LineType, chasQualifier2=chasQualifier2, hw_fanTable=hw_fanTable, hw_numSlots=hw_numSlots, slotQualifier2=slotQualifier2, fanVendorID=fanVendorID, psSubunit=psSubunit, ConfigRedundancy=ConfigRedundancy, fanType=fanType, DuplexState=DuplexState, slotPhysical=slotPhysical, fanCfgType=fanCfgType, fanProductID=fanProductID, pemCfgType=pemCfgType, pemQualifier2=pemQualifier2, tptHardwareNotifyMeType=tptHardwareNotifyMeType, slotProductID=slotProductID, chasNumber=chasNumber, chasDeviceID=chasDeviceID, pemType=pemType, pemDeviceID=pemDeviceID, hw_psTable=hw_psTable, slotQualifier1=slotQualifier1, tptHardwareNotifyDeviceID=tptHardwareNotifyDeviceID, fanQualifier3=fanQualifier3, slotDeviceID=slotDeviceID, pemVendorID=pemVendorID, psQualifier1=psQualifier1, psQualifier3=psQualifier3, HardwareStateQual=HardwareStateQual, hw_pemEntry=hw_pemEntry, fanQualifier2=fanQualifier2, slotType=slotType, fanFPGAVersion=fanFPGAVersion, chasRunState=chasRunState, pemSubunit=pemSubunit, chasType=chasType, fanStartTime=fanStartTime, fanQualifier4=fanQualifier4, slotDuplexState=slotDuplexState, tptHardwareNotify=tptHardwareNotify, hw_numPEMs=hw_numPEMs, slotQualifier4=slotQualifier4, chasProductID=chasProductID, tptHardwareNotifyHlStateQual=tptHardwareNotifyHlStateQual, hw_serialNumber=hw_serialNumber, pemStartTime=pemStartTime, slotFPGAVersion=slotFPGAVersion, chasVendorID=chasVendorID, pemQualifier4=pemQualifier4, fanQualifier1=fanQualifier1, chasStartTime=chasStartTime, hw_certificateNumber=hw_certificateNumber, psStartTime=psStartTime, pemFPGAVersion=pemFPGAVersion, psDeviceID=psDeviceID, fanSubunit=fanSubunit, slotLineType=slotLineType, slotPort=slotPort, pemQualifier3=pemQualifier3, SfpQualifier=SfpQualifier, tptHardwareNotifyCfgType=tptHardwareNotifyCfgType, psProductID=psProductID, pemProductID=pemProductID, pemQualifier1=pemQualifier1, slotRunState=slotRunState, fanDeviceID=fanDeviceID, ExtendedSlot=ExtendedSlot, psVendorID=psVendorID, psRunState=psRunState, hw_chasEntry=hw_chasEntry, psQualifier4=psQualifier4, HardwareState=HardwareState, ManagedElementType=ManagedElementType, psCfgType=psCfgType, slotSfpQualifier1=slotSfpQualifier1, hw_chasTable=hw_chasTable, psQualifier2=psQualifier2, hw_numFans=hw_numFans, tptHardwareNotifyHlState=tptHardwareNotifyHlState, tpt_tpa_hardware_objs=tpt_tpa_hardware_objs, chasFPGAVersion=chasFPGAVersion, pemRunState=pemRunState, slotQualifier3=slotQualifier3, slotCfgType=slotCfgType, hw_numPowerSupplies=hw_numPowerSupplies, psType=psType, slotSfpQualifier2=slotSfpQualifier2, slotStartTime=slotStartTime)
class Solution: def criticalConnections(self, n: int, connections: List[List[int]]) -> List[List[int]]: INF = 1000000 lows = [INF] * n ranks = [INF] * n graph = collections.defaultdict(list) for u, v in connections: graph[u].append(v) graph[v].append(u) self.time = 0 def dfs(node, parent): lows[node] = self.time ranks[node] = self.time self.time += 1 for nei in graph[node]: if ranks[nei] == INF: dfs(nei, node) for nei in graph[node]: if nei != parent: lows[node] = min(lows[node], lows[nei]) dfs(0, -1) ans = [] for u, v in connections: if lows[v] > ranks[u] or lows[u] > ranks[v]: ans.append([u, v]) return ans
# mode: run # ticket: 593 # tag: property, decorator my_property = property class Prop(object): """ >>> p = Prop() >>> p.prop GETTING 'None' >>> p.prop = 1 SETTING '1' (previously: 'None') >>> p.prop GETTING '1' 1 >>> p.prop = 2 SETTING '2' (previously: '1') >>> p.prop GETTING '2' 2 >>> del p.prop DELETING (previously: '2') >>> p.my_prop GETTING 'my_prop' 389 """ _value = None @property def prop(self): print("GETTING '%s'" % self._value) return self._value @prop.setter def prop(self, value): print("SETTING '%s' (previously: '%s')" % (value, self._value)) self._value = value @prop.deleter def prop(self): print("DELETING (previously: '%s')" % self._value) self._value = None @my_property def my_prop(self): print("GETTING 'my_prop'") return 389
l = [83, 85, 78, 123, 77, 52, 57, 53, 45, 102, 52, 110, 33, 125] flag = "" for c in l: flag += chr(c) print(flag)
class ServerObj: """Server class""" def __init__(self): self._name = '' self._totalPhysicalMemory = 0 self._freePhysicalMemory = 0 self._disks = [] @property def name(self): return self._name @name.setter def name(self, n): self._name = n @property def os(self): return self._os @os.setter def os(self, o): self._os = o @property def totalPhysicalMemory(self): return self._totalPhysicalMemory @totalPhysicalMemory.setter def totalPhysicalMemory(self, tpm): self._totalPhysicalMemory = tpm @property def freePhysicalMemory(self): return self._freePhysicalMemory @freePhysicalMemory.setter def freePhysicalMemory(self, fpm): self._freePhysicalMemory = fpm @property def disks(self): return self._disks @disks.setter def disks(self, d): self._disks = d
l,S1,final=[],[],[] S=input('Enter the numbers: ') S1=S.split() for i in S1: l.append(int(i)) final=str("['"+str(l)+"']") print(final)
# Permutation def permutation_rec(a): if len(a) == 0: return [] if len(a) == 1: return [a] l = [] for i in range(len(a)): x = a[:i] + a[i+1:] for j in permutation_rec(x): str2 = a[i] + j l.append(str2) return l count = 0 for r in permutation_rec('chip'): count += 1 print(count, r)