content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
""" 14 / 14 test cases passed. Runtime: 40 ms Memory Usage: 15.1 MB """ class Solution: def minMutation(self, start: str, end: str, bank: List[str]) -> int: used, bank = set(), set(bank) if end not in bank: return -1 # current gene, steps que = collections.deque([(start, 0)]) while que: cur, step = que.popleft() if cur == end: return step for gene in bank: diff = 0 for i in range(len(gene)): if cur[i] != gene[i]: diff += 1 if diff == 1 and gene not in used: used.add(gene) que.append((gene, step + 1)) return -1
""" 14 / 14 test cases passed. Runtime: 40 ms Memory Usage: 15.1 MB """ class Solution: def min_mutation(self, start: str, end: str, bank: List[str]) -> int: (used, bank) = (set(), set(bank)) if end not in bank: return -1 que = collections.deque([(start, 0)]) while que: (cur, step) = que.popleft() if cur == end: return step for gene in bank: diff = 0 for i in range(len(gene)): if cur[i] != gene[i]: diff += 1 if diff == 1 and gene not in used: used.add(gene) que.append((gene, step + 1)) return -1
# -*- coding: utf-8 -*- """Version information for this package.""" __version__ = "4.10.9" VERSION: str = __version__ """Version of package.""" __url__ = "https://github.com/Axonius/axonius_api_client" URL: str = __url__ """URL of package.""" __author__ = "Axonius" AUTHOR: str = __author__ """Auth of package.""" __title__ = "axonius_api_client" TITLE: str = __title__ """Title of package.""" __project__ = "axonius_api_client" PROJECT: str = __project__ """Name of package.""" __author_email__ = "support@axonius.com" AUTHOR_EMAIL: str = __author_email__ """Author email of package.""" __description__ = "Axonius API client for Python" DESCRIPTION: str = __description__ """Description of package.""" __docs__ = "https://axonius-api-client.readthedocs.io/en/latest/" DOCS: str = __docs__ """Link to the documentation for this package.""" __license__ = "MIT" LICENSE: str = __license__ """License of package.""" __copyright__ = "Copyright Axonius 2021" COPYRIGHT: str = __copyright__ """Copyright of package."""
"""Version information for this package.""" __version__ = '4.10.9' version: str = __version__ 'Version of package.' __url__ = 'https://github.com/Axonius/axonius_api_client' url: str = __url__ 'URL of package.' __author__ = 'Axonius' author: str = __author__ 'Auth of package.' __title__ = 'axonius_api_client' title: str = __title__ 'Title of package.' __project__ = 'axonius_api_client' project: str = __project__ 'Name of package.' __author_email__ = 'support@axonius.com' author_email: str = __author_email__ 'Author email of package.' __description__ = 'Axonius API client for Python' description: str = __description__ 'Description of package.' __docs__ = 'https://axonius-api-client.readthedocs.io/en/latest/' docs: str = __docs__ 'Link to the documentation for this package.' __license__ = 'MIT' license: str = __license__ 'License of package.' __copyright__ = 'Copyright Axonius 2021' copyright: str = __copyright__ 'Copyright of package.'
# Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def minDepth(self, root): # DFS def solve(node, level): if not node: return level - 1 elif node.left and node.right: return min(solve(node.left, level+1), solve(node.right, level+1)) else: return max(solve(node.left, level+1), solve(node.right, level+1)) return solve(root, 1)
class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def min_depth(self, root): def solve(node, level): if not node: return level - 1 elif node.left and node.right: return min(solve(node.left, level + 1), solve(node.right, level + 1)) else: return max(solve(node.left, level + 1), solve(node.right, level + 1)) return solve(root, 1)
def is_polygon(way): """Checks if the way is a polygon. Args way: the osmium.osm.Way to check. Returns: True if the way is a polygon, False otherwise. Note: The geometry shape can still be invalid (e.g. self-intersecting). """ if not way.is_closed(): return False if len(way.nodes) < 4: return False return True
def is_polygon(way): """Checks if the way is a polygon. Args way: the osmium.osm.Way to check. Returns: True if the way is a polygon, False otherwise. Note: The geometry shape can still be invalid (e.g. self-intersecting). """ if not way.is_closed(): return False if len(way.nodes) < 4: return False return True
class Room: def __init__(self): pass def intro_text(self): raise NotImplementedError() def adjacent_moves(self): pass def available_actions(self): pass class StartingRoom(Room): def __init__(self, ): super().__init__() def intro_text(self): return """You find yourself in a cave with a flickering torch on the wall. You can make out four paths, each equally foreboding. """ class EmptyCavePath(Room): def intro_text(self): return """ Another unremarkable part of the cave. You must forge onwards. """
class Room: def __init__(self): pass def intro_text(self): raise not_implemented_error() def adjacent_moves(self): pass def available_actions(self): pass class Startingroom(Room): def __init__(self): super().__init__() def intro_text(self): return 'You find yourself in a cave with a flickering torch on the wall.\n You can make out four paths, each equally foreboding.\n ' class Emptycavepath(Room): def intro_text(self): return '\n Another unremarkable part of the cave. You must forge onwards.\n '
list1, list2 = [123, 567, 343, 611], [456, 700, 200] print("Max value element : ", max(list1)) print("Max value element : ", max(list2)) print("min value element : ", min(list1)) print("min value element : ", min(list2))
(list1, list2) = ([123, 567, 343, 611], [456, 700, 200]) print('Max value element : ', max(list1)) print('Max value element : ', max(list2)) print('min value element : ', min(list1)) print('min value element : ', min(list2))
# splitting_list_elements.py print(""" {original_code} json_data = ["abc", "bcd/chg", "sdf", "bvd", "wer/ewe", "sbc & osc"] separators = ['/', '&', 'and'] title = [] for i in json_data: k = 0 while k < len(separators): if separators[k] in i: t = i.split(separators[k]) title.extend(t) break else: k += 1 if k == 3: title.append(i) print(title) """) # modified code - looks pythonic json_data = ["abc", "bcd/chg", "sdf", "bvd", "wer/ewe", "sbc & osc"] separators = ['/', '&', 'and'] title = [] for i in json_data: for separator in separators: if separator in i: t = i.split(separator) title.extend(t) break else: # if any of the separators are not found in the data, just append it title.append(i) title = [element.strip() for element in title] print(title) print(""" In the above code, for-else clause is used. If the 2nd for-loop exits without break, only then else part will be executed. wrt to above example, if for-loop exits without break, it means in the current word there are no separators. """)
print('\n{original_code}\njson_data = ["abc", "bcd/chg", "sdf", "bvd", "wer/ewe", "sbc & osc"]\nseparators = [\'/\', \'&\', \'and\']\ntitle = []\n\nfor i in json_data:\n k = 0\n while k < len(separators):\n if separators[k] in i:\n t = i.split(separators[k])\n title.extend(t)\n break\n else:\n k += 1\n if k == 3:\n title.append(i)\nprint(title)\n') json_data = ['abc', 'bcd/chg', 'sdf', 'bvd', 'wer/ewe', 'sbc & osc'] separators = ['/', '&', 'and'] title = [] for i in json_data: for separator in separators: if separator in i: t = i.split(separator) title.extend(t) break else: title.append(i) title = [element.strip() for element in title] print(title) print('\nIn the above code, for-else clause is used. If the 2nd for-loop exits without break, only then else part will be executed.\nwrt to above example, if for-loop exits without break, it means in the current word there are no separators.\n')
def seq(hub, low, running): ''' Return the sequence map that should be used to execute the lowstate The sequence needs to identify: 1. recursive requisites 2. what chunks are free to run 3. Bahavior augments for the next chunk to run ''' ret = {} for ind, chunk in enumerate(low): tag = hub.idem.tools.gen_tag(chunk) if tag in running: # Already ran this one, don't add it to the sequence continue ret[ind] = {'chunk': chunk, 'reqrets': [], 'unmet': set()} for req in hub.idem.RMAP: if req in chunk: for rdef in chunk[req]: if not isinstance(rdef, dict): # TODO: Error check continue state = next(iter(rdef)) name = rdef[state] r_chunks = hub.idem.tools.get_chunks(low, state, name) if not r_chunks: ret[ind]['errors'].append(f'Requisite {req} {state}:{name} not found') for r_chunk in r_chunks: r_tag = hub.idem.tools.gen_tag(r_chunk) if r_tag in running: reqret = { 'req': req, 'name': name, 'state': state, 'r_tag': r_tag, 'ret': running[r_tag], } # it has been run, check the rules ret[ind]['reqrets'].append(reqret) else: ret[ind]['unmet'].add(r_tag) return ret
def seq(hub, low, running): """ Return the sequence map that should be used to execute the lowstate The sequence needs to identify: 1. recursive requisites 2. what chunks are free to run 3. Bahavior augments for the next chunk to run """ ret = {} for (ind, chunk) in enumerate(low): tag = hub.idem.tools.gen_tag(chunk) if tag in running: continue ret[ind] = {'chunk': chunk, 'reqrets': [], 'unmet': set()} for req in hub.idem.RMAP: if req in chunk: for rdef in chunk[req]: if not isinstance(rdef, dict): continue state = next(iter(rdef)) name = rdef[state] r_chunks = hub.idem.tools.get_chunks(low, state, name) if not r_chunks: ret[ind]['errors'].append(f'Requisite {req} {state}:{name} not found') for r_chunk in r_chunks: r_tag = hub.idem.tools.gen_tag(r_chunk) if r_tag in running: reqret = {'req': req, 'name': name, 'state': state, 'r_tag': r_tag, 'ret': running[r_tag]} ret[ind]['reqrets'].append(reqret) else: ret[ind]['unmet'].add(r_tag) return ret
#!/usr/bin/env python3 # Day 6: Queue Reconstruction by Height # # Suppose you have a random list of people standing in a queue. Each person is # described by a pair of integers (h, k), where h is the height of the person # and k is the number of people in front of this person who have a height # greater than or equal to h. Write an algorithm to reconstruct the queue. # # Note: # - The number of people is less than 1,100. class Solution: def reconstructQueue(self, people: [[int]]) -> [[int]]: # Convenience functions for clarity height = lambda person: person[0] taller_in_front = lambda person: person[1] # Sort the input by height descending and number of taller persons in # front ascending sorted_people = sorted(people, key = lambda person: (-height(person), taller_in_front(person))) # Insert into the queue at the correct position queue = [] for person in sorted_people: queue.insert(taller_in_front(person), person) return queue # Test assert Solution().reconstructQueue([[7,0], [4,4], [7,1], [5,0], [6,1], [5,2]]) == [[5,0], [7,0], [5,2], [6,1], [4,4], [7,1]]
class Solution: def reconstruct_queue(self, people: [[int]]) -> [[int]]: height = lambda person: person[0] taller_in_front = lambda person: person[1] sorted_people = sorted(people, key=lambda person: (-height(person), taller_in_front(person))) queue = [] for person in sorted_people: queue.insert(taller_in_front(person), person) return queue assert solution().reconstructQueue([[7, 0], [4, 4], [7, 1], [5, 0], [6, 1], [5, 2]]) == [[5, 0], [7, 0], [5, 2], [6, 1], [4, 4], [7, 1]]
""" Descriptions Advantages: Tab auto complete. Historical log to archieve. Edit with in a line. Use $run to call external python script. Support system cmds. Support pylab module. Debug Python code and profiler. """ """ cmds for ipython ipython --pylab quit() %logstart ls %run -i 1_12_vector_add.py 1000 %run -d 1_12_vector_add.py 1000 %run -p 1_12_vector_add.py 1000 %hist """
""" Descriptions Advantages: Tab auto complete. Historical log to archieve. Edit with in a line. Use $run to call external python script. Support system cmds. Support pylab module. Debug Python code and profiler. """ '\ncmds for ipython\n ipython --pylab\n quit()\n %logstart\n ls\n %run -i 1_12_vector_add.py 1000\n %run -d 1_12_vector_add.py 1000\n %run -p 1_12_vector_add.py 1000\n %hist\n'
class Tool: pass class Documentation(Tool): pass class Frustration(Tool): pass class Dwf(Documentation, Frustration, Tool): pass
class Tool: pass class Documentation(Tool): pass class Frustration(Tool): pass class Dwf(Documentation, Frustration, Tool): pass
class roiData: def __init__(self, roistates, numberOfROIs, dicomsPath=None): self.layers = [] self.roistates = [] self.dicomsPath=dicomsPath self.originalLenght = len(roistates) self.numberOfROIs = numberOfROIs for i, roistate in enumerate(roistates): if roistate: self.layers.append(i) self.roistates.append(roistate)
class Roidata: def __init__(self, roistates, numberOfROIs, dicomsPath=None): self.layers = [] self.roistates = [] self.dicomsPath = dicomsPath self.originalLenght = len(roistates) self.numberOfROIs = numberOfROIs for (i, roistate) in enumerate(roistates): if roistate: self.layers.append(i) self.roistates.append(roistate)
def stringify(token): if token.orth_ == 'I': return token.orth_ elif token.is_quote and token.i != 0 and token.nbor(-1).is_space: return ' ' + token.orth_ elif token.ent_type_ == '': return token.lower_ else: return token.orth_ def parse_stack(token): stack = [] if token.n_lefts + token.n_rights > 0: stack.append(token.dep_) child = token parent = child.head while parent != child: stack.append(parent.dep_) child = parent parent = child.head if len(stack) == 0: return [''] return stack def is_full_sentence(span): subject_present = False verb_present = False for token in span: if token.dep_ == 'nsubj': subject_present = True if token.pos_ == 'VERB': verb_present = True if subject_present and verb_present: return True return False def closing_punct(sent): final_word = sent[-1:] if len([q for q in sent if q == '"']) % 2 != 0: sent += '"' if not (final_word == '.' or final_word == '!' or final_word == '?' or final_word == '"' or final_word == "'"): return sent + '.' return sent def parse_complexity(span): return len(set([parse_stack(t)[0] for t in span])) def add_symbol_balance(doc): balance_points = quote_balance(doc) #+ _punct_balance(doc) doc.user_data['balance_points'] = balance_points return doc def quote_balance(doc): balance_points = [] quote_hash = {} for t in doc: if t.is_quote and quote_hash.get(t.orth) is None: quote_hash[t.orth] = t.i elif t.is_quote and quote_hash.get(t.orth) is not None: if span_is_only_whitespace(doc[quote_hash[t.orth]+1:t.i]): quote_hash[t.orth] = t.i else: balance_points.append( (t.orth_, quote_hash[t.orth], t.i) ) quote_hash[t.orth] = None return balance_points def span_is_only_whitespace(span): for t in span: if not t.is_space: return False return True def _punct_balance(doc): balance_points = [] symbol_hash = {} for t in doc: if t.is_left_punct and not t.is_quote: symbol_hash[t.orth] = t.i elif t.is_right_punct and not t.is_quote: symbol = sorted(symbol_hash, key=lambda entry: symbol_hash[entry], reverse=True)[0] balance_points.append( (t.orth_, symbol_hash[symbol], t.i) ) symbol_hash[symbol] = None return balance_points def symbol_stack(token): balance_points = sorted( token.doc.user_data['balance_points'], key=lambda bal: bal[1], reverse=True) ti = token.i return [bal[0] for bal in balance_points if bal[1] <= ti and bal[2] >= ti]
def stringify(token): if token.orth_ == 'I': return token.orth_ elif token.is_quote and token.i != 0 and token.nbor(-1).is_space: return ' ' + token.orth_ elif token.ent_type_ == '': return token.lower_ else: return token.orth_ def parse_stack(token): stack = [] if token.n_lefts + token.n_rights > 0: stack.append(token.dep_) child = token parent = child.head while parent != child: stack.append(parent.dep_) child = parent parent = child.head if len(stack) == 0: return [''] return stack def is_full_sentence(span): subject_present = False verb_present = False for token in span: if token.dep_ == 'nsubj': subject_present = True if token.pos_ == 'VERB': verb_present = True if subject_present and verb_present: return True return False def closing_punct(sent): final_word = sent[-1:] if len([q for q in sent if q == '"']) % 2 != 0: sent += '"' if not (final_word == '.' or final_word == '!' or final_word == '?' or (final_word == '"') or (final_word == "'")): return sent + '.' return sent def parse_complexity(span): return len(set([parse_stack(t)[0] for t in span])) def add_symbol_balance(doc): balance_points = quote_balance(doc) doc.user_data['balance_points'] = balance_points return doc def quote_balance(doc): balance_points = [] quote_hash = {} for t in doc: if t.is_quote and quote_hash.get(t.orth) is None: quote_hash[t.orth] = t.i elif t.is_quote and quote_hash.get(t.orth) is not None: if span_is_only_whitespace(doc[quote_hash[t.orth] + 1:t.i]): quote_hash[t.orth] = t.i else: balance_points.append((t.orth_, quote_hash[t.orth], t.i)) quote_hash[t.orth] = None return balance_points def span_is_only_whitespace(span): for t in span: if not t.is_space: return False return True def _punct_balance(doc): balance_points = [] symbol_hash = {} for t in doc: if t.is_left_punct and (not t.is_quote): symbol_hash[t.orth] = t.i elif t.is_right_punct and (not t.is_quote): symbol = sorted(symbol_hash, key=lambda entry: symbol_hash[entry], reverse=True)[0] balance_points.append((t.orth_, symbol_hash[symbol], t.i)) symbol_hash[symbol] = None return balance_points def symbol_stack(token): balance_points = sorted(token.doc.user_data['balance_points'], key=lambda bal: bal[1], reverse=True) ti = token.i return [bal[0] for bal in balance_points if bal[1] <= ti and bal[2] >= ti]
def configure(name): if name == 'compute_mfcc': return {"--allow-downsample":["false",str], "--allow-upsample":["false",str], "--blackman-coeff":[0.42,float], "--cepstral-lifter":[22,int], "--channel":[-1,int], "--debug-mel":["false",str], "--dither":[1,int], "--energy-floor":[0,int], "--frame-length":[25,int], "--frame-shift":[10,int], "--high-freq":[0,int], "--htk-compat":["false",str], "--low-freq":[20,int], "--max-feature-vectors":[-1,int], "--min-duration":[0,int], "--num-ceps":[13,int], "--num-mel-bins":[23,int], "--output-format":["kaldi",str], "--preemphasis-coefficient":[0.97,float], "--raw-energy":["true",str], "--remove-dc-offset":["true",str], "--round-to-power-of-two":["true",str], "--sample-frequency":[16000,int], "--snip-edges":["false",str], "--subtract-mean":["false",str], "--use-energy":["true",str], "--utt2spk":["",str], "--vtln-high":[-500,int], "--vtln-low":[100,int], "--vtln-map":["",str], "--vtln-warp":[1,int], "--window-type":["povey",str], "--write-utt2dur":["",str] } elif name == 'compute_fbank': return {"--allow-downsample":["false",str], "--allow-upsample":["false",str], "--blackman-coeff":[0.42,float], "--channel":[-1,int], "--debug-mel":["false",str], "--dither":[1,int], "--energy-floor":[0,int], "--frame-length":[25,int], "--frame-shift":[10,int], "--high-freq":[0,int], "--htk-compat":["false",str], "--low-freq":[20,int], "--max-feature-vectors":[-1,int], "--min-duration":[0,int], "--num-mel-bins":[23,int], "--output-format":["kaldi",str], "--preemphasis-coefficient":[0.97,float], "--raw-energy":["true",str], "--remove-dc-offset":["true",str], "--round-to-power-of-two":["true",str], "--sample-frequency":[16000,int], "--snip-edges":["false",str], "--subtract-mean":["false",str], "--use-energy":["true",str], "--use-log-fbank":["true",str], "--use-power":["true",str], "--utt2spk":["",str], "--vtln-high":[-500,int], "--vtln-low":[100,int], "--vtln-map":["",str], "--vtln-warp":[1,int], "--window-type":["povey",str], "--write-utt2dur":["",str] } elif name == 'compute_plp': return {"--allow-downsample":["false",str], "--allow-upsample":["false",str], "--blackman-coeff":[0.42,float], "--cepstral-lifter":[22,int], "--cepstral-scale":[1,int], "--channel":[-1,int], "--compress-factor":[0.33333,float], "--debug-mel":['false',float], "--dither":[1,int], "--energy-floor":[0,int], "--frame-length":[25,int], "--frame-shift":[10,int], "--high-freq":[0,int], "--htk-compat":["false",str], "--low-freq":[20,int], "--lpc-order":[12,int], "--max-feature-vectors":[-1,int], "--min-duration":[0,int], "--num-ceps":[13,int], "--num-mel-bins":[23,int], "--output-format":["kaldi",str], "--preemphasis-coefficient":[0.97,float], "--raw-energy":["true",str], "--remove-dc-offset":["true",str], "--round-to-power-of-two":["true",str], "--sample-frequency":[16000,int], "--snip-edges":["false",str], "--subtract-mean":["false",str], "--use-energy":["true",str], "--utt2spk":["",str], "--vtln-high":[-500,int], "--vtln-low":[100,int], "--vtln-map":["",str], "--vtln-warp":[1,int], "--window-type":["povey",str], "--write-utt2dur":["",str] } elif name == 'compute_spectrogram': return {"--allow-downsample":["false",str], "--allow-upsample":["false",str], "--blackman-coeff":[0.42,float], "--channel":[-1,int], "--dither":[1,int], "--energy-floor":[0,int], "--frame-length":[25,int], "--frame-shift":[10,int], "--max-feature-vectors":[-1,int], "--min-duration":[0,int], "--output-format":["kaldi",str], "--preemphasis-coefficient":[0.97,float], "--raw-energy":["true",str], "--remove-dc-offset":["true",str], "--round-to-power-of-two":["true",str], "--sample-frequency":[16000,int], "--snip-edges":["false",str], "--subtract-mean":["false",str], "--window-type":["povey",str], "--write-utt2dur":["",str] } elif name == 'decode_lattice': return {"--acoustic-scale":[0.1,float], "--allow-partial":["false",str], "--beam":[13,int], "--beam-delta":[0.5,float], "--delta":[0.000976562,float], "--determinize-lattice":["true",str], "--hash-ratio":[2,int], "--lattice-beam":[8,int], "--max-active":[7000,int], "--max-mem":[50000000,int], "--min-active":[200,int], "--minimize":["false",str], "--phone-determinize":["true",str], "--prune-interval":[25,int], "--word-determinize":["true",str], "--word-symbol-table":["",str] } else: return None
def configure(name): if name == 'compute_mfcc': return {'--allow-downsample': ['false', str], '--allow-upsample': ['false', str], '--blackman-coeff': [0.42, float], '--cepstral-lifter': [22, int], '--channel': [-1, int], '--debug-mel': ['false', str], '--dither': [1, int], '--energy-floor': [0, int], '--frame-length': [25, int], '--frame-shift': [10, int], '--high-freq': [0, int], '--htk-compat': ['false', str], '--low-freq': [20, int], '--max-feature-vectors': [-1, int], '--min-duration': [0, int], '--num-ceps': [13, int], '--num-mel-bins': [23, int], '--output-format': ['kaldi', str], '--preemphasis-coefficient': [0.97, float], '--raw-energy': ['true', str], '--remove-dc-offset': ['true', str], '--round-to-power-of-two': ['true', str], '--sample-frequency': [16000, int], '--snip-edges': ['false', str], '--subtract-mean': ['false', str], '--use-energy': ['true', str], '--utt2spk': ['', str], '--vtln-high': [-500, int], '--vtln-low': [100, int], '--vtln-map': ['', str], '--vtln-warp': [1, int], '--window-type': ['povey', str], '--write-utt2dur': ['', str]} elif name == 'compute_fbank': return {'--allow-downsample': ['false', str], '--allow-upsample': ['false', str], '--blackman-coeff': [0.42, float], '--channel': [-1, int], '--debug-mel': ['false', str], '--dither': [1, int], '--energy-floor': [0, int], '--frame-length': [25, int], '--frame-shift': [10, int], '--high-freq': [0, int], '--htk-compat': ['false', str], '--low-freq': [20, int], '--max-feature-vectors': [-1, int], '--min-duration': [0, int], '--num-mel-bins': [23, int], '--output-format': ['kaldi', str], '--preemphasis-coefficient': [0.97, float], '--raw-energy': ['true', str], '--remove-dc-offset': ['true', str], '--round-to-power-of-two': ['true', str], '--sample-frequency': [16000, int], '--snip-edges': ['false', str], '--subtract-mean': ['false', str], '--use-energy': ['true', str], '--use-log-fbank': ['true', str], '--use-power': ['true', str], '--utt2spk': ['', str], '--vtln-high': [-500, int], '--vtln-low': [100, int], '--vtln-map': ['', str], '--vtln-warp': [1, int], '--window-type': ['povey', str], '--write-utt2dur': ['', str]} elif name == 'compute_plp': return {'--allow-downsample': ['false', str], '--allow-upsample': ['false', str], '--blackman-coeff': [0.42, float], '--cepstral-lifter': [22, int], '--cepstral-scale': [1, int], '--channel': [-1, int], '--compress-factor': [0.33333, float], '--debug-mel': ['false', float], '--dither': [1, int], '--energy-floor': [0, int], '--frame-length': [25, int], '--frame-shift': [10, int], '--high-freq': [0, int], '--htk-compat': ['false', str], '--low-freq': [20, int], '--lpc-order': [12, int], '--max-feature-vectors': [-1, int], '--min-duration': [0, int], '--num-ceps': [13, int], '--num-mel-bins': [23, int], '--output-format': ['kaldi', str], '--preemphasis-coefficient': [0.97, float], '--raw-energy': ['true', str], '--remove-dc-offset': ['true', str], '--round-to-power-of-two': ['true', str], '--sample-frequency': [16000, int], '--snip-edges': ['false', str], '--subtract-mean': ['false', str], '--use-energy': ['true', str], '--utt2spk': ['', str], '--vtln-high': [-500, int], '--vtln-low': [100, int], '--vtln-map': ['', str], '--vtln-warp': [1, int], '--window-type': ['povey', str], '--write-utt2dur': ['', str]} elif name == 'compute_spectrogram': return {'--allow-downsample': ['false', str], '--allow-upsample': ['false', str], '--blackman-coeff': [0.42, float], '--channel': [-1, int], '--dither': [1, int], '--energy-floor': [0, int], '--frame-length': [25, int], '--frame-shift': [10, int], '--max-feature-vectors': [-1, int], '--min-duration': [0, int], '--output-format': ['kaldi', str], '--preemphasis-coefficient': [0.97, float], '--raw-energy': ['true', str], '--remove-dc-offset': ['true', str], '--round-to-power-of-two': ['true', str], '--sample-frequency': [16000, int], '--snip-edges': ['false', str], '--subtract-mean': ['false', str], '--window-type': ['povey', str], '--write-utt2dur': ['', str]} elif name == 'decode_lattice': return {'--acoustic-scale': [0.1, float], '--allow-partial': ['false', str], '--beam': [13, int], '--beam-delta': [0.5, float], '--delta': [0.000976562, float], '--determinize-lattice': ['true', str], '--hash-ratio': [2, int], '--lattice-beam': [8, int], '--max-active': [7000, int], '--max-mem': [50000000, int], '--min-active': [200, int], '--minimize': ['false', str], '--phone-determinize': ['true', str], '--prune-interval': [25, int], '--word-determinize': ['true', str], '--word-symbol-table': ['', str]} else: return None
class XForwardedHostMiddleware( object ): """ A WSGI middleware that changes the HTTP host header in the WSGI environ based on the X-Forwarded-Host header IF found """ def __init__( self, app, global_conf=None ): self.app = app def __call__( self, environ, start_response ): x_forwarded_host = environ.get( 'HTTP_X_FORWARDED_HOST', None ) if x_forwarded_host: environ[ 'ORGINAL_HTTP_HOST' ] = environ[ 'HTTP_HOST' ] environ[ 'HTTP_HOST' ] = x_forwarded_host x_forwarded_for = environ.get( 'HTTP_X_FORWARDED_FOR', None ) if x_forwarded_for: environ[ 'ORGINAL_REMOTE_ADDR' ] = environ[ 'REMOTE_ADDR' ] environ[ 'REMOTE_ADDR' ] = x_forwarded_for x_url_scheme = environ.get( 'HTTP_X_URL_SCHEME', None ) if x_url_scheme: environ[ 'original_wsgi.url_scheme' ] = environ[ 'wsgi.url_scheme' ] environ[ 'wsgi.url_scheme' ] = x_url_scheme return self.app( environ, start_response )
class Xforwardedhostmiddleware(object): """ A WSGI middleware that changes the HTTP host header in the WSGI environ based on the X-Forwarded-Host header IF found """ def __init__(self, app, global_conf=None): self.app = app def __call__(self, environ, start_response): x_forwarded_host = environ.get('HTTP_X_FORWARDED_HOST', None) if x_forwarded_host: environ['ORGINAL_HTTP_HOST'] = environ['HTTP_HOST'] environ['HTTP_HOST'] = x_forwarded_host x_forwarded_for = environ.get('HTTP_X_FORWARDED_FOR', None) if x_forwarded_for: environ['ORGINAL_REMOTE_ADDR'] = environ['REMOTE_ADDR'] environ['REMOTE_ADDR'] = x_forwarded_for x_url_scheme = environ.get('HTTP_X_URL_SCHEME', None) if x_url_scheme: environ['original_wsgi.url_scheme'] = environ['wsgi.url_scheme'] environ['wsgi.url_scheme'] = x_url_scheme return self.app(environ, start_response)
def sorter(item): return item['name'] presenters=[ {'name': 'Arthur', 'age': 9}, {'name': 'Nathaniel', 'age': 11} ] presenters.sort(key=sorter) print(presenters)
def sorter(item): return item['name'] presenters = [{'name': 'Arthur', 'age': 9}, {'name': 'Nathaniel', 'age': 11}] presenters.sort(key=sorter) print(presenters)
class FakeCUDAContext(object): ''' This stub implements functionality only for simulating a single GPU at the moment. ''' def __init__(self, device): self._device = device def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): pass def __str__(self): return "<Managed Device {self.id}>".format(self=self) @property def id(self): return self._device @property def compute_capability(self): return (5, 2) class FakeDeviceList(object): ''' This stub implements a device list containing a single GPU. It also keeps track of the GPU status, i.e. whether the context is closed or not, which may have been set by the user calling reset() ''' def __init__(self): self.lst = (FakeCUDAContext(0),) self.closed = False def __getitem__(self, devnum): self.closed = False return self.lst[devnum] def __str__(self): return ', '.join([str(d) for d in self.lst]) def __iter__(self): return iter(self.lst) def __len__(self): return len(self.lst) @property def current(self): if self.closed: return None return self.lst[0] gpus = FakeDeviceList() def reset(): gpus[0].closed = True def require_context(func): ''' In the simulator, a context is always "available", so this is a no-op. ''' return func
class Fakecudacontext(object): """ This stub implements functionality only for simulating a single GPU at the moment. """ def __init__(self, device): self._device = device def __enter__(self): pass def __exit__(self, exc_type, exc_val, exc_tb): pass def __str__(self): return '<Managed Device {self.id}>'.format(self=self) @property def id(self): return self._device @property def compute_capability(self): return (5, 2) class Fakedevicelist(object): """ This stub implements a device list containing a single GPU. It also keeps track of the GPU status, i.e. whether the context is closed or not, which may have been set by the user calling reset() """ def __init__(self): self.lst = (fake_cuda_context(0),) self.closed = False def __getitem__(self, devnum): self.closed = False return self.lst[devnum] def __str__(self): return ', '.join([str(d) for d in self.lst]) def __iter__(self): return iter(self.lst) def __len__(self): return len(self.lst) @property def current(self): if self.closed: return None return self.lst[0] gpus = fake_device_list() def reset(): gpus[0].closed = True def require_context(func): """ In the simulator, a context is always "available", so this is a no-op. """ return func
# do NOT import these models here. # from .model import Word as WordModel # from .model import Definition as DefinitionModel class Word(object): def __init__(self, model): self.model = model def set_definition(self, definitions: list): """ Replace the existing definition set by the one given in argument :param definition: :return: """ for d in definitions: if not isinstance(d, self.model.__class__): raise TypeError("A Definition object is expected.") self.model.definitions = definitions def add_definition(self, definition): if definition not in self.model.definitions: self.model.definitions.append(definition) def remove_definition(self, definition): if definition not in self.model.definitions: self.model.definitions.remove(definition) class Definition(object): def __init__(self, model): self.model = model
class Word(object): def __init__(self, model): self.model = model def set_definition(self, definitions: list): """ Replace the existing definition set by the one given in argument :param definition: :return: """ for d in definitions: if not isinstance(d, self.model.__class__): raise type_error('A Definition object is expected.') self.model.definitions = definitions def add_definition(self, definition): if definition not in self.model.definitions: self.model.definitions.append(definition) def remove_definition(self, definition): if definition not in self.model.definitions: self.model.definitions.remove(definition) class Definition(object): def __init__(self, model): self.model = model
""" https://leetcode.com/problems/valid-mountain-array/ Given an array A of integers, return true if and only if it is a valid mountain array. Recall that A is a mountain array if and only if: A.length >= 3 There exists some i with 0 < i < A.length - 1 such that: A[0] < A[1] < ... A[i-1] < A[i] A[i] > A[i+1] > ... > A[A.length - 1] Example 1: Input: [2,1] Output: false Example 2: Input: [3,5,5] Output: false Example 3: Input: [0,3,2,1] Output: true Note: 0 <= A.length <= 10000 0 <= A[i] <= 10000 """ # time complexity: O(n), space complexity: O(1) class Solution: def validMountainArray(self, A: List[int]) -> bool: if len(A) < 3 or A[0] >= A[1]: return False increase = True for i in range(1, len(A) - 1): if A[i] == A[i + 1]: return False elif A[i] < A[i + 1]: if not increase: return False else: if increase: increase = False return not increase
""" https://leetcode.com/problems/valid-mountain-array/ Given an array A of integers, return true if and only if it is a valid mountain array. Recall that A is a mountain array if and only if: A.length >= 3 There exists some i with 0 < i < A.length - 1 such that: A[0] < A[1] < ... A[i-1] < A[i] A[i] > A[i+1] > ... > A[A.length - 1] Example 1: Input: [2,1] Output: false Example 2: Input: [3,5,5] Output: false Example 3: Input: [0,3,2,1] Output: true Note: 0 <= A.length <= 10000 0 <= A[i] <= 10000 """ class Solution: def valid_mountain_array(self, A: List[int]) -> bool: if len(A) < 3 or A[0] >= A[1]: return False increase = True for i in range(1, len(A) - 1): if A[i] == A[i + 1]: return False elif A[i] < A[i + 1]: if not increase: return False elif increase: increase = False return not increase
# # PySNMP MIB module WWP-EXT-BRIDGE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/WWP-EXT-BRIDGE-MIB # Produced by pysmi-0.3.4 at Wed May 1 15:37:36 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") ConstraintsIntersection, SingleValueConstraint, ValueSizeConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "SingleValueConstraint", "ValueSizeConstraint", "ConstraintsUnion", "ValueRangeConstraint") ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "NotificationGroup") ModuleIdentity, Counter32, Counter64, Integer32, IpAddress, Bits, MibIdentifier, Gauge32, ObjectIdentity, iso, NotificationType, Unsigned32, TimeTicks, MibScalar, MibTable, MibTableRow, MibTableColumn = mibBuilder.importSymbols("SNMPv2-SMI", "ModuleIdentity", "Counter32", "Counter64", "Integer32", "IpAddress", "Bits", "MibIdentifier", "Gauge32", "ObjectIdentity", "iso", "NotificationType", "Unsigned32", "TimeTicks", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn") TruthValue, MacAddress, RowStatus, DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "TruthValue", "MacAddress", "RowStatus", "DisplayString", "TextualConvention") wwpModules, = mibBuilder.importSymbols("WWP-SMI", "wwpModules") wwpExtBridgeMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 6141, 2, 4)) wwpExtBridgeMIB.setRevisions(('2005-11-23 09:00', '2001-04-03 17:00',)) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: wwpExtBridgeMIB.setRevisionsDescriptions(('This MIB module is for the Extension of the BRIDGE MIB for WWP Products', 'Initial creation.',)) if mibBuilder.loadTexts: wwpExtBridgeMIB.setLastUpdated('200104031700Z') if mibBuilder.loadTexts: wwpExtBridgeMIB.setOrganization('World Wide Packets, Inc') if mibBuilder.loadTexts: wwpExtBridgeMIB.setContactInfo(' Mib Meister Postal: World Wide Packets P.O. Box 950 Veradale, WA 99037 USA Phone: +1 509 242 9000 Email: mib.meister@worldwidepackets.com') if mibBuilder.loadTexts: wwpExtBridgeMIB.setDescription('Updated with port rate limit state and rate limit value controls.') class PortList(TextualConvention, OctetString): description = "Each octet within this value specifies a set of eight ports, with the first octet specifying ports 1 through 8, the second octet specifying ports 9 through 16, etc. Within each octet, the most significant bit represents the lowest numbered port, and the least significant bit represents the highest numbered port. Thus, each port of the bridge is represented by a single bit within the value of this object. If that bit has a value of '1' then that port is included in the set of ports; the port is not included if its bit has a value of '0'." status = 'current' subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(0, 255) class VlanId(TextualConvention, Integer32): description = 'A 12-bit VLAN ID used in the VLAN Tag header.' status = 'current' subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 4094) wwpExtBridgeMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1)) wwpPort = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1)) wwpVlan = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2)) wwpExtBridgeMIBNotificationPrefix = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 4, 2)) wwpExtBridgeMIBNotifications = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 4, 2, 0)) wwpExtBridgeMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 4, 3)) wwpExtBridgeMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 4, 3, 1)) wwpExtBridgeMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 6141, 2, 4, 3, 2)) wwpPortTable = MibTable((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1), ) if mibBuilder.loadTexts: wwpPortTable.setStatus('current') if mibBuilder.loadTexts: wwpPortTable.setDescription('Table of Ports.') wwpPortEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1), ).setIndexNames((0, "WWP-EXT-BRIDGE-MIB", "wwpPortId")) if mibBuilder.loadTexts: wwpPortEntry.setStatus('current') if mibBuilder.loadTexts: wwpPortEntry.setDescription('Port Entry in the Table.') wwpPortId = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 65535))).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpPortId.setStatus('current') if mibBuilder.loadTexts: wwpPortId.setDescription("Port ID for the instance. Port ID's start at 1, and are consecutive for each additional port. This port Id should refer to the dot1dBasePort in the Dot1dBasePortEntry.") wwpPortType = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6))).clone(namedValues=NamedValues(("lx", 1), ("fastEth", 2), ("voip", 3), ("sx", 4), ("hundredFx", 5), ("unknown", 6)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpPortType.setStatus('current') if mibBuilder.loadTexts: wwpPortType.setDescription('The port type for the port.') wwpPortName = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 3), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpPortName.setStatus('current') if mibBuilder.loadTexts: wwpPortName.setDescription('Friendly name for the port.') wwpPortPhysAddr = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 4), MacAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpPortPhysAddr.setStatus('current') if mibBuilder.loadTexts: wwpPortPhysAddr.setDescription('The ethernet MAC address for the port. This information can also be achieved via dot1dTpFdbTable') wwpPortAutoNeg = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 5), TruthValue()).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpPortAutoNeg.setStatus('current') if mibBuilder.loadTexts: wwpPortAutoNeg.setDescription('The object sets the port to AUTO NEG MOde and vice versa. Specific platforms may have requirements of configuring speed before moving the port to out of AUTO-NEG mode.') wwpPortAdminStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpPortAdminStatus.setStatus('current') if mibBuilder.loadTexts: wwpPortAdminStatus.setDescription('The desired state of the port.') wwpPortOperStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 7), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("up", 1), ("down", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpPortOperStatus.setStatus('current') if mibBuilder.loadTexts: wwpPortOperStatus.setDescription('The current operational state of Port.') wwpPortAdminSpeed = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4))).clone(namedValues=NamedValues(("tenMb", 1), ("hundredMb", 2), ("gig", 3), ("auto", 4)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpPortAdminSpeed.setStatus('current') if mibBuilder.loadTexts: wwpPortAdminSpeed.setDescription("Desired speed of the port. Set the port speed to be either 10MB, 100MB, or gig. The Management Station can't set the adminSpeed to auto. The default value for this object depends upon the platform.") wwpPortOperSpeed = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpPortOperSpeed.setStatus('current') if mibBuilder.loadTexts: wwpPortOperSpeed.setDescription('The current operational speed of the port in MB.') wwpPortAdminDuplex = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 10), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("half", 1), ("full", 2), ("auto", 3)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpPortAdminDuplex.setStatus('current') if mibBuilder.loadTexts: wwpPortAdminDuplex.setDescription('The desired mode for the port. It can be set to either half or full duplex operation but not to auto.The default value for this object depends upon the platform.') wwpPortOperDuplex = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 11), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3))).clone(namedValues=NamedValues(("half", 1), ("full", 2), ("auto", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpPortOperDuplex.setStatus('current') if mibBuilder.loadTexts: wwpPortOperDuplex.setDescription('The current duplex mode of the port.') wwpPortAdminFlowCtrl = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 12), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpPortAdminFlowCtrl.setStatus('current') if mibBuilder.loadTexts: wwpPortAdminFlowCtrl.setDescription('Configures the ports flow control operation. Need to check 802.3x for additional modes for gig ports.') wwpPortOperFlowCtrl = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 13), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disabled", 0), ("enabled", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpPortOperFlowCtrl.setStatus('current') if mibBuilder.loadTexts: wwpPortOperFlowCtrl.setDescription('Shows ports flow control configuration.') wwpPortTagged = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("untagged", 0), ("tagged", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpPortTagged.setStatus('current') if mibBuilder.loadTexts: wwpPortTagged.setDescription("The port tagged Status can be set to tagged or untagged. If a port is part of more than one VLAN, then the port Status should be 'tagged'.") wwpPortUntaggedPriority = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 15), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=NamedValues(("p0", 0), ("p1", 1), ("p2", 2), ("p3", 3), ("p4", 4), ("p5", 5), ("p6", 6), ("p7", 7)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpPortUntaggedPriority.setStatus('current') if mibBuilder.loadTexts: wwpPortUntaggedPriority.setDescription('The 802.1p packet priority to be assigned to packets associated with this port that do not have an 802.1Q VLAN header.') wwpPortMaxFrameSize = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 16), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1522, 9126))).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpPortMaxFrameSize.setStatus('current') if mibBuilder.loadTexts: wwpPortMaxFrameSize.setDescription('Setting this object will set the max frame size allowed on a port. The max frame size can vary between 1522 bytes till 9216 bytes. Default value is 1522 bytes') wwpPortIngressFiltering = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 17), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("true", 1), ("false", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpPortIngressFiltering.setStatus('current') if mibBuilder.loadTexts: wwpPortIngressFiltering.setDescription('When this is true(1) the device will discard incoming frames for VLANs which do not include this Port in its Member set. When false(2), the port will accept all incoming frames.') wwpPortRateLimitState = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 18), TruthValue().clone('false')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpPortRateLimitState.setStatus('current') if mibBuilder.loadTexts: wwpPortRateLimitState.setDescription('When set to true, the rate limiting mechanism is enabled for this port. When set to false, the rate limiting mechanism is disabled for this port.') wwpPortRateLimitValue = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 19), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647)).clone(10000000)).setUnits('Bits per second').setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpPortRateLimitValue.setStatus('current') if mibBuilder.loadTexts: wwpPortRateLimitValue.setDescription('The value of this object represents the desired bit-rate limit for this port. When the rate limiting mechanism is enabled for this port, this value is enforced to the best extent possible by the device. For some devices the actual maximum bit-rate allowed may exceed the rate limit parameter under certain circumstances due to hardware and software limitations.') wwpLocalMgmtPortEnable = MibScalar((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 2), TruthValue().clone('true')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpLocalMgmtPortEnable.setStatus('deprecated') if mibBuilder.loadTexts: wwpLocalMgmtPortEnable.setDescription('Setting this object to false(2) will disable the local Management Port. The object has beed deprecated as we need to have the general functionality of disabling and enableing any in-band and out-band mgmt interface.') wwpVlanVersionNumber = MibScalar((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1))).clone(namedValues=NamedValues(("version1", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpVlanVersionNumber.setReference('IEEE 802.1Q/D11 Section 12.10.1.1') if mibBuilder.loadTexts: wwpVlanVersionNumber.setStatus('current') if mibBuilder.loadTexts: wwpVlanVersionNumber.setDescription('The version number of IEEE 802.1Q that this device supports.') wwpMaxVlanId = MibScalar((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 2), VlanId()).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpMaxVlanId.setReference('IEEE 802.1Q/D11 Section 9.3.2.3') if mibBuilder.loadTexts: wwpMaxVlanId.setStatus('current') if mibBuilder.loadTexts: wwpMaxVlanId.setDescription('The maximum IEEE 802.1Q VLAN ID that this device supports.') wwpMaxSupportedVlans = MibScalar((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 3), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpMaxSupportedVlans.setReference('IEEE 802.1Q/D11 Section 12.10.1.1') if mibBuilder.loadTexts: wwpMaxSupportedVlans.setStatus('current') if mibBuilder.loadTexts: wwpMaxSupportedVlans.setDescription('The maximum number of IEEE 802.1Q VLANs that this device supports.') wwpNumVlans = MibScalar((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 4), Unsigned32()).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpNumVlans.setReference('IEEE 802.1Q/D11 Section 12.7.1.1') if mibBuilder.loadTexts: wwpNumVlans.setStatus('current') if mibBuilder.loadTexts: wwpNumVlans.setDescription('The current number of IEEE 802.1Q VLANs that are configured in this device.') wwpVlanTable = MibTable((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 5), ) if mibBuilder.loadTexts: wwpVlanTable.setStatus('current') if mibBuilder.loadTexts: wwpVlanTable.setDescription('VLAN table') wwpVlanEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 5, 1), ).setIndexNames((0, "WWP-EXT-BRIDGE-MIB", "wwpVlanId")) if mibBuilder.loadTexts: wwpVlanEntry.setStatus('current') if mibBuilder.loadTexts: wwpVlanEntry.setDescription('table of vlans') wwpVlanId = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 5, 1, 1), VlanId()).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpVlanId.setStatus('current') if mibBuilder.loadTexts: wwpVlanId.setDescription('802.1Q VLAN ID (1-4094)') wwpVlanName = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 5, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readcreate") if mibBuilder.loadTexts: wwpVlanName.setStatus('current') if mibBuilder.loadTexts: wwpVlanName.setDescription('Name associated with this VLAN.') wwpVlanCurrentEgressPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 5, 1, 3), PortList().clone(hexValue="0000")).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpVlanCurrentEgressPorts.setReference('IEEE 802.1Q/D11 Section 12.10.2.1') if mibBuilder.loadTexts: wwpVlanCurrentEgressPorts.setStatus('current') if mibBuilder.loadTexts: wwpVlanCurrentEgressPorts.setDescription('The set of ports which are transmitting traffic for this VLAN as either tagged or untagged frames.') wwpVlanCurrentUntaggedPorts = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 5, 1, 4), PortList()).setMaxAccess("readonly") if mibBuilder.loadTexts: wwpVlanCurrentUntaggedPorts.setReference('IEEE 802.1Q/D11 Section 12.10.2.1') if mibBuilder.loadTexts: wwpVlanCurrentUntaggedPorts.setStatus('current') if mibBuilder.loadTexts: wwpVlanCurrentUntaggedPorts.setDescription('The set of ports which are transmitting traffic for this VLAN as untagged frames.') wwpVlanMgmtStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 5, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("notMgmtVlan", 0), ("remoteMgmtVlan", 1), ("localMgmtVlan", 2))).clone('notMgmtVlan')).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpVlanMgmtStatus.setStatus('current') if mibBuilder.loadTexts: wwpVlanMgmtStatus.setDescription('Indicates if this VLAN is a management VLAN. The system can have at most one remote mgt vlan, and one local mgt vlan. Any Valn can be set either to remoteMgmtVlan or localMgmtvlan.') wwpVlanRowStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 5, 1, 6), RowStatus()).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpVlanRowStatus.setStatus('current') if mibBuilder.loadTexts: wwpVlanRowStatus.setDescription("Used to manage the creation and deletion of the conceptual rows in this table. To create a row in this table, a manager must set this object to 'createAndGo'. To delete a row in this table, there should not be any port associated with this vlan.") wwpVlanXTable = MibTable((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 6), ) if mibBuilder.loadTexts: wwpVlanXTable.setStatus('current') if mibBuilder.loadTexts: wwpVlanXTable.setDescription('Extension of the VLAN table') wwpVlanXEntry = MibTableRow((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 6, 1), ) wwpVlanEntry.registerAugmentions(("WWP-EXT-BRIDGE-MIB", "wwpVlanXEntry")) wwpVlanXEntry.setIndexNames(*wwpVlanEntry.getIndexNames()) if mibBuilder.loadTexts: wwpVlanXEntry.setStatus('current') if mibBuilder.loadTexts: wwpVlanXEntry.setDescription('Entry in the extended vlan table.') wwpVlanTunnel = MibTableColumn((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 6, 1, 1), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("disable", 0), ("enable", 1)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: wwpVlanTunnel.setStatus('current') if mibBuilder.loadTexts: wwpVlanTunnel.setDescription('Enable/disable VLAN tunneling on this VLAN.') mibBuilder.exportSymbols("WWP-EXT-BRIDGE-MIB", wwpVlanId=wwpVlanId, wwpVlanEntry=wwpVlanEntry, wwpExtBridgeMIBObjects=wwpExtBridgeMIBObjects, wwpVlanName=wwpVlanName, wwpExtBridgeMIBCompliances=wwpExtBridgeMIBCompliances, wwpPortAdminDuplex=wwpPortAdminDuplex, wwpPortAdminFlowCtrl=wwpPortAdminFlowCtrl, wwpVlanCurrentUntaggedPorts=wwpVlanCurrentUntaggedPorts, wwpVlanXTable=wwpVlanXTable, wwpNumVlans=wwpNumVlans, wwpPortEntry=wwpPortEntry, VlanId=VlanId, PYSNMP_MODULE_ID=wwpExtBridgeMIB, wwpExtBridgeMIBConformance=wwpExtBridgeMIBConformance, wwpVlanCurrentEgressPorts=wwpVlanCurrentEgressPorts, wwpPortOperFlowCtrl=wwpPortOperFlowCtrl, wwpLocalMgmtPortEnable=wwpLocalMgmtPortEnable, wwpPortAutoNeg=wwpPortAutoNeg, wwpExtBridgeMIBNotificationPrefix=wwpExtBridgeMIBNotificationPrefix, wwpVlanTable=wwpVlanTable, wwpPortType=wwpPortType, wwpPortOperDuplex=wwpPortOperDuplex, wwpPortRateLimitState=wwpPortRateLimitState, wwpExtBridgeMIB=wwpExtBridgeMIB, wwpPortAdminStatus=wwpPortAdminStatus, wwpVlanRowStatus=wwpVlanRowStatus, wwpVlanMgmtStatus=wwpVlanMgmtStatus, wwpVlanVersionNumber=wwpVlanVersionNumber, wwpPortRateLimitValue=wwpPortRateLimitValue, wwpPortMaxFrameSize=wwpPortMaxFrameSize, wwpPortPhysAddr=wwpPortPhysAddr, wwpPortTagged=wwpPortTagged, wwpVlanTunnel=wwpVlanTunnel, wwpPortTable=wwpPortTable, wwpExtBridgeMIBGroups=wwpExtBridgeMIBGroups, wwpExtBridgeMIBNotifications=wwpExtBridgeMIBNotifications, wwpPortName=wwpPortName, wwpPortIngressFiltering=wwpPortIngressFiltering, wwpMaxVlanId=wwpMaxVlanId, wwpMaxSupportedVlans=wwpMaxSupportedVlans, PortList=PortList, wwpPortOperStatus=wwpPortOperStatus, wwpPortOperSpeed=wwpPortOperSpeed, wwpPort=wwpPort, wwpVlan=wwpVlan, wwpPortAdminSpeed=wwpPortAdminSpeed, wwpPortUntaggedPriority=wwpPortUntaggedPriority, wwpPortId=wwpPortId, wwpVlanXEntry=wwpVlanXEntry)
(object_identifier, integer, octet_string) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'Integer', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, single_value_constraint, value_size_constraint, constraints_union, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'SingleValueConstraint', 'ValueSizeConstraint', 'ConstraintsUnion', 'ValueRangeConstraint') (module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'NotificationGroup') (module_identity, counter32, counter64, integer32, ip_address, bits, mib_identifier, gauge32, object_identity, iso, notification_type, unsigned32, time_ticks, mib_scalar, mib_table, mib_table_row, mib_table_column) = mibBuilder.importSymbols('SNMPv2-SMI', 'ModuleIdentity', 'Counter32', 'Counter64', 'Integer32', 'IpAddress', 'Bits', 'MibIdentifier', 'Gauge32', 'ObjectIdentity', 'iso', 'NotificationType', 'Unsigned32', 'TimeTicks', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn') (truth_value, mac_address, row_status, display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'TruthValue', 'MacAddress', 'RowStatus', 'DisplayString', 'TextualConvention') (wwp_modules,) = mibBuilder.importSymbols('WWP-SMI', 'wwpModules') wwp_ext_bridge_mib = module_identity((1, 3, 6, 1, 4, 1, 6141, 2, 4)) wwpExtBridgeMIB.setRevisions(('2005-11-23 09:00', '2001-04-03 17:00')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): if mibBuilder.loadTexts: wwpExtBridgeMIB.setRevisionsDescriptions(('This MIB module is for the Extension of the BRIDGE MIB for WWP Products', 'Initial creation.')) if mibBuilder.loadTexts: wwpExtBridgeMIB.setLastUpdated('200104031700Z') if mibBuilder.loadTexts: wwpExtBridgeMIB.setOrganization('World Wide Packets, Inc') if mibBuilder.loadTexts: wwpExtBridgeMIB.setContactInfo(' Mib Meister Postal: World Wide Packets P.O. Box 950 Veradale, WA 99037 USA Phone: +1 509 242 9000 Email: mib.meister@worldwidepackets.com') if mibBuilder.loadTexts: wwpExtBridgeMIB.setDescription('Updated with port rate limit state and rate limit value controls.') class Portlist(TextualConvention, OctetString): description = "Each octet within this value specifies a set of eight ports, with the first octet specifying ports 1 through 8, the second octet specifying ports 9 through 16, etc. Within each octet, the most significant bit represents the lowest numbered port, and the least significant bit represents the highest numbered port. Thus, each port of the bridge is represented by a single bit within the value of this object. If that bit has a value of '1' then that port is included in the set of ports; the port is not included if its bit has a value of '0'." status = 'current' subtype_spec = OctetString.subtypeSpec + value_size_constraint(0, 255) class Vlanid(TextualConvention, Integer32): description = 'A 12-bit VLAN ID used in the VLAN Tag header.' status = 'current' subtype_spec = Integer32.subtypeSpec + value_range_constraint(1, 4094) wwp_ext_bridge_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1)) wwp_port = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1)) wwp_vlan = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2)) wwp_ext_bridge_mib_notification_prefix = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 4, 2)) wwp_ext_bridge_mib_notifications = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 4, 2, 0)) wwp_ext_bridge_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 4, 3)) wwp_ext_bridge_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 4, 3, 1)) wwp_ext_bridge_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 6141, 2, 4, 3, 2)) wwp_port_table = mib_table((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1)) if mibBuilder.loadTexts: wwpPortTable.setStatus('current') if mibBuilder.loadTexts: wwpPortTable.setDescription('Table of Ports.') wwp_port_entry = mib_table_row((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1)).setIndexNames((0, 'WWP-EXT-BRIDGE-MIB', 'wwpPortId')) if mibBuilder.loadTexts: wwpPortEntry.setStatus('current') if mibBuilder.loadTexts: wwpPortEntry.setDescription('Port Entry in the Table.') wwp_port_id = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 65535))).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpPortId.setStatus('current') if mibBuilder.loadTexts: wwpPortId.setDescription("Port ID for the instance. Port ID's start at 1, and are consecutive for each additional port. This port Id should refer to the dot1dBasePort in the Dot1dBasePortEntry.") wwp_port_type = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6))).clone(namedValues=named_values(('lx', 1), ('fastEth', 2), ('voip', 3), ('sx', 4), ('hundredFx', 5), ('unknown', 6)))).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpPortType.setStatus('current') if mibBuilder.loadTexts: wwpPortType.setDescription('The port type for the port.') wwp_port_name = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 3), display_string().subtype(subtypeSpec=value_size_constraint(0, 32))).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpPortName.setStatus('current') if mibBuilder.loadTexts: wwpPortName.setDescription('Friendly name for the port.') wwp_port_phys_addr = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 4), mac_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpPortPhysAddr.setStatus('current') if mibBuilder.loadTexts: wwpPortPhysAddr.setDescription('The ethernet MAC address for the port. This information can also be achieved via dot1dTpFdbTable') wwp_port_auto_neg = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 5), truth_value()).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpPortAutoNeg.setStatus('current') if mibBuilder.loadTexts: wwpPortAutoNeg.setDescription('The object sets the port to AUTO NEG MOde and vice versa. Specific platforms may have requirements of configuring speed before moving the port to out of AUTO-NEG mode.') wwp_port_admin_status = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('up', 1), ('down', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpPortAdminStatus.setStatus('current') if mibBuilder.loadTexts: wwpPortAdminStatus.setDescription('The desired state of the port.') wwp_port_oper_status = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 7), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('up', 1), ('down', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpPortOperStatus.setStatus('current') if mibBuilder.loadTexts: wwpPortOperStatus.setDescription('The current operational state of Port.') wwp_port_admin_speed = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4))).clone(namedValues=named_values(('tenMb', 1), ('hundredMb', 2), ('gig', 3), ('auto', 4)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpPortAdminSpeed.setStatus('current') if mibBuilder.loadTexts: wwpPortAdminSpeed.setDescription("Desired speed of the port. Set the port speed to be either 10MB, 100MB, or gig. The Management Station can't set the adminSpeed to auto. The default value for this object depends upon the platform.") wwp_port_oper_speed = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 9), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpPortOperSpeed.setStatus('current') if mibBuilder.loadTexts: wwpPortOperSpeed.setDescription('The current operational speed of the port in MB.') wwp_port_admin_duplex = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 10), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('half', 1), ('full', 2), ('auto', 3)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpPortAdminDuplex.setStatus('current') if mibBuilder.loadTexts: wwpPortAdminDuplex.setDescription('The desired mode for the port. It can be set to either half or full duplex operation but not to auto.The default value for this object depends upon the platform.') wwp_port_oper_duplex = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 11), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3))).clone(namedValues=named_values(('half', 1), ('full', 2), ('auto', 3)))).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpPortOperDuplex.setStatus('current') if mibBuilder.loadTexts: wwpPortOperDuplex.setDescription('The current duplex mode of the port.') wwp_port_admin_flow_ctrl = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 12), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disable', 0), ('enable', 1)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpPortAdminFlowCtrl.setStatus('current') if mibBuilder.loadTexts: wwpPortAdminFlowCtrl.setDescription('Configures the ports flow control operation. Need to check 802.3x for additional modes for gig ports.') wwp_port_oper_flow_ctrl = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 13), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disabled', 0), ('enabled', 1)))).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpPortOperFlowCtrl.setStatus('current') if mibBuilder.loadTexts: wwpPortOperFlowCtrl.setDescription('Shows ports flow control configuration.') wwp_port_tagged = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 14), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('untagged', 0), ('tagged', 1)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpPortTagged.setStatus('current') if mibBuilder.loadTexts: wwpPortTagged.setDescription("The port tagged Status can be set to tagged or untagged. If a port is part of more than one VLAN, then the port Status should be 'tagged'.") wwp_port_untagged_priority = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 15), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4, 5, 6, 7))).clone(namedValues=named_values(('p0', 0), ('p1', 1), ('p2', 2), ('p3', 3), ('p4', 4), ('p5', 5), ('p6', 6), ('p7', 7)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpPortUntaggedPriority.setStatus('current') if mibBuilder.loadTexts: wwpPortUntaggedPriority.setDescription('The 802.1p packet priority to be assigned to packets associated with this port that do not have an 802.1Q VLAN header.') wwp_port_max_frame_size = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 16), integer32().subtype(subtypeSpec=value_range_constraint(1522, 9126))).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpPortMaxFrameSize.setStatus('current') if mibBuilder.loadTexts: wwpPortMaxFrameSize.setDescription('Setting this object will set the max frame size allowed on a port. The max frame size can vary between 1522 bytes till 9216 bytes. Default value is 1522 bytes') wwp_port_ingress_filtering = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 17), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('true', 1), ('false', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpPortIngressFiltering.setStatus('current') if mibBuilder.loadTexts: wwpPortIngressFiltering.setDescription('When this is true(1) the device will discard incoming frames for VLANs which do not include this Port in its Member set. When false(2), the port will accept all incoming frames.') wwp_port_rate_limit_state = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 18), truth_value().clone('false')).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpPortRateLimitState.setStatus('current') if mibBuilder.loadTexts: wwpPortRateLimitState.setDescription('When set to true, the rate limiting mechanism is enabled for this port. When set to false, the rate limiting mechanism is disabled for this port.') wwp_port_rate_limit_value = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 1, 1, 19), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647)).clone(10000000)).setUnits('Bits per second').setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpPortRateLimitValue.setStatus('current') if mibBuilder.loadTexts: wwpPortRateLimitValue.setDescription('The value of this object represents the desired bit-rate limit for this port. When the rate limiting mechanism is enabled for this port, this value is enforced to the best extent possible by the device. For some devices the actual maximum bit-rate allowed may exceed the rate limit parameter under certain circumstances due to hardware and software limitations.') wwp_local_mgmt_port_enable = mib_scalar((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 1, 2), truth_value().clone('true')).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpLocalMgmtPortEnable.setStatus('deprecated') if mibBuilder.loadTexts: wwpLocalMgmtPortEnable.setDescription('Setting this object to false(2) will disable the local Management Port. The object has beed deprecated as we need to have the general functionality of disabling and enableing any in-band and out-band mgmt interface.') wwp_vlan_version_number = mib_scalar((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1))).clone(namedValues=named_values(('version1', 1)))).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpVlanVersionNumber.setReference('IEEE 802.1Q/D11 Section 12.10.1.1') if mibBuilder.loadTexts: wwpVlanVersionNumber.setStatus('current') if mibBuilder.loadTexts: wwpVlanVersionNumber.setDescription('The version number of IEEE 802.1Q that this device supports.') wwp_max_vlan_id = mib_scalar((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 2), vlan_id()).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpMaxVlanId.setReference('IEEE 802.1Q/D11 Section 9.3.2.3') if mibBuilder.loadTexts: wwpMaxVlanId.setStatus('current') if mibBuilder.loadTexts: wwpMaxVlanId.setDescription('The maximum IEEE 802.1Q VLAN ID that this device supports.') wwp_max_supported_vlans = mib_scalar((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 3), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpMaxSupportedVlans.setReference('IEEE 802.1Q/D11 Section 12.10.1.1') if mibBuilder.loadTexts: wwpMaxSupportedVlans.setStatus('current') if mibBuilder.loadTexts: wwpMaxSupportedVlans.setDescription('The maximum number of IEEE 802.1Q VLANs that this device supports.') wwp_num_vlans = mib_scalar((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 4), unsigned32()).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpNumVlans.setReference('IEEE 802.1Q/D11 Section 12.7.1.1') if mibBuilder.loadTexts: wwpNumVlans.setStatus('current') if mibBuilder.loadTexts: wwpNumVlans.setDescription('The current number of IEEE 802.1Q VLANs that are configured in this device.') wwp_vlan_table = mib_table((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 5)) if mibBuilder.loadTexts: wwpVlanTable.setStatus('current') if mibBuilder.loadTexts: wwpVlanTable.setDescription('VLAN table') wwp_vlan_entry = mib_table_row((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 5, 1)).setIndexNames((0, 'WWP-EXT-BRIDGE-MIB', 'wwpVlanId')) if mibBuilder.loadTexts: wwpVlanEntry.setStatus('current') if mibBuilder.loadTexts: wwpVlanEntry.setDescription('table of vlans') wwp_vlan_id = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 5, 1, 1), vlan_id()).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpVlanId.setStatus('current') if mibBuilder.loadTexts: wwpVlanId.setDescription('802.1Q VLAN ID (1-4094)') wwp_vlan_name = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 5, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(0, 32))).setMaxAccess('readcreate') if mibBuilder.loadTexts: wwpVlanName.setStatus('current') if mibBuilder.loadTexts: wwpVlanName.setDescription('Name associated with this VLAN.') wwp_vlan_current_egress_ports = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 5, 1, 3), port_list().clone(hexValue='0000')).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpVlanCurrentEgressPorts.setReference('IEEE 802.1Q/D11 Section 12.10.2.1') if mibBuilder.loadTexts: wwpVlanCurrentEgressPorts.setStatus('current') if mibBuilder.loadTexts: wwpVlanCurrentEgressPorts.setDescription('The set of ports which are transmitting traffic for this VLAN as either tagged or untagged frames.') wwp_vlan_current_untagged_ports = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 5, 1, 4), port_list()).setMaxAccess('readonly') if mibBuilder.loadTexts: wwpVlanCurrentUntaggedPorts.setReference('IEEE 802.1Q/D11 Section 12.10.2.1') if mibBuilder.loadTexts: wwpVlanCurrentUntaggedPorts.setStatus('current') if mibBuilder.loadTexts: wwpVlanCurrentUntaggedPorts.setDescription('The set of ports which are transmitting traffic for this VLAN as untagged frames.') wwp_vlan_mgmt_status = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 5, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2))).clone(namedValues=named_values(('notMgmtVlan', 0), ('remoteMgmtVlan', 1), ('localMgmtVlan', 2))).clone('notMgmtVlan')).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpVlanMgmtStatus.setStatus('current') if mibBuilder.loadTexts: wwpVlanMgmtStatus.setDescription('Indicates if this VLAN is a management VLAN. The system can have at most one remote mgt vlan, and one local mgt vlan. Any Valn can be set either to remoteMgmtVlan or localMgmtvlan.') wwp_vlan_row_status = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 5, 1, 6), row_status()).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpVlanRowStatus.setStatus('current') if mibBuilder.loadTexts: wwpVlanRowStatus.setDescription("Used to manage the creation and deletion of the conceptual rows in this table. To create a row in this table, a manager must set this object to 'createAndGo'. To delete a row in this table, there should not be any port associated with this vlan.") wwp_vlan_x_table = mib_table((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 6)) if mibBuilder.loadTexts: wwpVlanXTable.setStatus('current') if mibBuilder.loadTexts: wwpVlanXTable.setDescription('Extension of the VLAN table') wwp_vlan_x_entry = mib_table_row((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 6, 1)) wwpVlanEntry.registerAugmentions(('WWP-EXT-BRIDGE-MIB', 'wwpVlanXEntry')) wwpVlanXEntry.setIndexNames(*wwpVlanEntry.getIndexNames()) if mibBuilder.loadTexts: wwpVlanXEntry.setStatus('current') if mibBuilder.loadTexts: wwpVlanXEntry.setDescription('Entry in the extended vlan table.') wwp_vlan_tunnel = mib_table_column((1, 3, 6, 1, 4, 1, 6141, 2, 4, 1, 2, 6, 1, 1), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('disable', 0), ('enable', 1)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: wwpVlanTunnel.setStatus('current') if mibBuilder.loadTexts: wwpVlanTunnel.setDescription('Enable/disable VLAN tunneling on this VLAN.') mibBuilder.exportSymbols('WWP-EXT-BRIDGE-MIB', wwpVlanId=wwpVlanId, wwpVlanEntry=wwpVlanEntry, wwpExtBridgeMIBObjects=wwpExtBridgeMIBObjects, wwpVlanName=wwpVlanName, wwpExtBridgeMIBCompliances=wwpExtBridgeMIBCompliances, wwpPortAdminDuplex=wwpPortAdminDuplex, wwpPortAdminFlowCtrl=wwpPortAdminFlowCtrl, wwpVlanCurrentUntaggedPorts=wwpVlanCurrentUntaggedPorts, wwpVlanXTable=wwpVlanXTable, wwpNumVlans=wwpNumVlans, wwpPortEntry=wwpPortEntry, VlanId=VlanId, PYSNMP_MODULE_ID=wwpExtBridgeMIB, wwpExtBridgeMIBConformance=wwpExtBridgeMIBConformance, wwpVlanCurrentEgressPorts=wwpVlanCurrentEgressPorts, wwpPortOperFlowCtrl=wwpPortOperFlowCtrl, wwpLocalMgmtPortEnable=wwpLocalMgmtPortEnable, wwpPortAutoNeg=wwpPortAutoNeg, wwpExtBridgeMIBNotificationPrefix=wwpExtBridgeMIBNotificationPrefix, wwpVlanTable=wwpVlanTable, wwpPortType=wwpPortType, wwpPortOperDuplex=wwpPortOperDuplex, wwpPortRateLimitState=wwpPortRateLimitState, wwpExtBridgeMIB=wwpExtBridgeMIB, wwpPortAdminStatus=wwpPortAdminStatus, wwpVlanRowStatus=wwpVlanRowStatus, wwpVlanMgmtStatus=wwpVlanMgmtStatus, wwpVlanVersionNumber=wwpVlanVersionNumber, wwpPortRateLimitValue=wwpPortRateLimitValue, wwpPortMaxFrameSize=wwpPortMaxFrameSize, wwpPortPhysAddr=wwpPortPhysAddr, wwpPortTagged=wwpPortTagged, wwpVlanTunnel=wwpVlanTunnel, wwpPortTable=wwpPortTable, wwpExtBridgeMIBGroups=wwpExtBridgeMIBGroups, wwpExtBridgeMIBNotifications=wwpExtBridgeMIBNotifications, wwpPortName=wwpPortName, wwpPortIngressFiltering=wwpPortIngressFiltering, wwpMaxVlanId=wwpMaxVlanId, wwpMaxSupportedVlans=wwpMaxSupportedVlans, PortList=PortList, wwpPortOperStatus=wwpPortOperStatus, wwpPortOperSpeed=wwpPortOperSpeed, wwpPort=wwpPort, wwpVlan=wwpVlan, wwpPortAdminSpeed=wwpPortAdminSpeed, wwpPortUntaggedPriority=wwpPortUntaggedPriority, wwpPortId=wwpPortId, wwpVlanXEntry=wwpVlanXEntry)
"""Custom exceptions for the punter package.""" class PunterException(Exception): def __init__(self, *args, **kwargs): super(PunterException, self).__init__(*args, **kwargs) class InvalidAPIKeyException(PunterException): pass class InvalidQueryStringException(PunterException): pass
"""Custom exceptions for the punter package.""" class Punterexception(Exception): def __init__(self, *args, **kwargs): super(PunterException, self).__init__(*args, **kwargs) class Invalidapikeyexception(PunterException): pass class Invalidquerystringexception(PunterException): pass
n, q = map(int, input().split()) d = {} init = input().split() for i in range(1, n+1): d[i] = init[i-1] for j in range(q): line = input().split() req = line[0] if req == '1': d[int(line[1])] = line[2] else: print(abs(int(d[int(line[1])]) - int(d[int(line[2])])))
(n, q) = map(int, input().split()) d = {} init = input().split() for i in range(1, n + 1): d[i] = init[i - 1] for j in range(q): line = input().split() req = line[0] if req == '1': d[int(line[1])] = line[2] else: print(abs(int(d[int(line[1])]) - int(d[int(line[2])])))
"""Work in Progress Template based on Shoelace""" # import pathlib # import jinja2 # import panel as pn # ROOT = pathlib.Path(__file__).parent # JS = (ROOT / "index.js").read_text() # CSS = (ROOT / "index.css").read_text() # TEMPLATES_FOLDER = str(ROOT / "templates") # bokehLoader = jinja2.PackageLoader("bokeh.core", "_templates") # templateLoader = jinja2.FileSystemLoader(searchpath=TEMPLATES_FOLDER) # loader = jinja2.ChoiceLoader([templateLoader]) # templateEnv = jinja2.Environment(loader=loader) # TEMPLATE_FILE = "index.html" # template = templateEnv.pn.template.FastListTemplate(TEMPLATE_FILE) # # outputText = template.render() # this is where to put args to the template renderer # tmpl = pn.Template(template) # tmpl.add_variable("app_title", "Awesome Panel") # tmpl.add_variable("app_css", CSS) # tmpl.add_variable("app_js", JS) # tmpl.servable()
"""Work in Progress Template based on Shoelace"""
# Link to problem : https://leetcode.com/problems/remove-element/ class Solution: def removeElement(self, nums ,val): count = 0 for i in range(len(nums)): if(nums[i] != val): nums[count] = nums[i] count += 1 return count
class Solution: def remove_element(self, nums, val): count = 0 for i in range(len(nums)): if nums[i] != val: nums[count] = nums[i] count += 1 return count
""" @file @brief Shortcut to *parsers*. """
""" @file @brief Shortcut to *parsers*. """
while True: n = int(input()) if not n: break s = 0 for i in range(n): s += [int(x) for x in input().split()][1] // 2 print(s//2)
while True: n = int(input()) if not n: break s = 0 for i in range(n): s += [int(x) for x in input().split()][1] // 2 print(s // 2)
new_minimum_detection = input("What is the minimum confidence?: ") with open('object_detection_webcam.py', 'r') as file: lines = file.readlines() for line in lines: if line[0:18] == ' min_detection_': line = ' min_detection_confidence = '+new_minimum_detection+' ###EDITED BY SETTINGS PROGRAM###\n' print(line) #for line in lines: #print(line, end='')
new_minimum_detection = input('What is the minimum confidence?: ') with open('object_detection_webcam.py', 'r') as file: lines = file.readlines() for line in lines: if line[0:18] == ' min_detection_': line = ' min_detection_confidence = ' + new_minimum_detection + ' ###EDITED BY SETTINGS PROGRAM###\n' print(line)
# class Student(object): # def __init__(self, name, score): # self.name = name # self.score = score # def print_score(self): # print('%s: %s' % (self.name, self.score)) class Student(object): def __init__(self, name, score): self.__name = name self.__score = score def print_score(self): print('%s: %s' % (self.__name, self.__score)) fyp = Student('fyp', 59) print("fyp===>", fyp) print("fyp===>", fyp.name) print("fyp===>", fyp.score)
class Student(object): def __init__(self, name, score): self.__name = name self.__score = score def print_score(self): print('%s: %s' % (self.__name, self.__score)) fyp = student('fyp', 59) print('fyp===>', fyp) print('fyp===>', fyp.name) print('fyp===>', fyp.score)
"""Demonstrate module statements being executed on first import.""" print("Initialise", __name__) def fib(n: int) -> None: """Write Fibonacci series up to n.""" a, b = 0, 1 while a < n: print(a, end=" ") a, b = b, a + b print()
"""Demonstrate module statements being executed on first import.""" print('Initialise', __name__) def fib(n: int) -> None: """Write Fibonacci series up to n.""" (a, b) = (0, 1) while a < n: print(a, end=' ') (a, b) = (b, a + b) print()
# # 359. Logger Rate Limiter # # Q: https://leetcode.com/problems/logger-rate-limiter/ # A: https://leetcode.com/problems/logger-rate-limiter/discuss/473779/Javascript-Python3-C%2B%2B-hash-table # class Logger: def __init__(self): self.m = {} def shouldPrintMessage(self, t: int, s: str) -> bool: m = self.m if not s in m or 10 <= t - m[s]: m[s] = t return True return False
class Logger: def __init__(self): self.m = {} def should_print_message(self, t: int, s: str) -> bool: m = self.m if not s in m or 10 <= t - m[s]: m[s] = t return True return False
""" dp[i][k] := the minimal number of characters that needed to change for s[:i] with k disjoint substrings """ class Solution(object): def palindromePartition(self, s, K): def count(r, l): c = 0 while r>l: if s[r]!=s[l]: c += 1 r -= 1 l += 1 return c N = len(s) dp = [[float('inf') for _ in xrange(K+1)] for _ in xrange(N+1)] dp[0][0] = 0 for i in xrange(1, N+1): for k in xrange(1, min(K, i)+1): for j in xrange(k, i+1): dp[i][k] = min(dp[i][k], dp[j-1][k-1] + count(i-1, j-1)) return dp[N][K] """ The above `count()` are able to use dp technique to optimize. dp[i][k] := the minimal number of characters that needed to change for s[:i] with k disjoint substrings count[i][j] := the operation needed for s[i:j+1] become palindrome. """ class Solution(object): def palindromePartition(self, s, K): N = len(s) count = [[0 for _ in xrange(N)] for _ in xrange(N)] for i in xrange(N): count[i][i] = 0 for l in xrange(2, N+1): for i in xrange(N): j = i+l-1 if j>=N: continue count[j][i] = count[j-1][i+1] + (0 if s[i]==s[j] else 1) dp = [[float('inf') for _ in xrange(K+1)] for _ in xrange(N+1)] dp[0][0] = 0 for i in xrange(1, N+1): for k in xrange(1, min(K, i)+1): for j in xrange(k, i+1): dp[i][k] = min(dp[i][k], dp[j-1][k-1] + count[i-1][j-1]) return dp[N][K]
""" dp[i][k] := the minimal number of characters that needed to change for s[:i] with k disjoint substrings """ class Solution(object): def palindrome_partition(self, s, K): def count(r, l): c = 0 while r > l: if s[r] != s[l]: c += 1 r -= 1 l += 1 return c n = len(s) dp = [[float('inf') for _ in xrange(K + 1)] for _ in xrange(N + 1)] dp[0][0] = 0 for i in xrange(1, N + 1): for k in xrange(1, min(K, i) + 1): for j in xrange(k, i + 1): dp[i][k] = min(dp[i][k], dp[j - 1][k - 1] + count(i - 1, j - 1)) return dp[N][K] '\nThe above `count()` are able to use dp technique to optimize.\ndp[i][k] := the minimal number of characters that needed to change for s[:i] with k disjoint substrings\ncount[i][j] := the operation needed for s[i:j+1] become palindrome.\n' class Solution(object): def palindrome_partition(self, s, K): n = len(s) count = [[0 for _ in xrange(N)] for _ in xrange(N)] for i in xrange(N): count[i][i] = 0 for l in xrange(2, N + 1): for i in xrange(N): j = i + l - 1 if j >= N: continue count[j][i] = count[j - 1][i + 1] + (0 if s[i] == s[j] else 1) dp = [[float('inf') for _ in xrange(K + 1)] for _ in xrange(N + 1)] dp[0][0] = 0 for i in xrange(1, N + 1): for k in xrange(1, min(K, i) + 1): for j in xrange(k, i + 1): dp[i][k] = min(dp[i][k], dp[j - 1][k - 1] + count[i - 1][j - 1]) return dp[N][K]
for t in range(int(input())): a=int(input()) s=input() L=[] for i in range(0,a*8,8): b=s[i:i+8] k=0 for i in range(8): if b[i] == 'I': k += 2**(7-i) L.append(k) print("Case #"+str(t+1),end=": ") for i in L: print(chr(i),end="") print()
for t in range(int(input())): a = int(input()) s = input() l = [] for i in range(0, a * 8, 8): b = s[i:i + 8] k = 0 for i in range(8): if b[i] == 'I': k += 2 ** (7 - i) L.append(k) print('Case #' + str(t + 1), end=': ') for i in L: print(chr(i), end='') print()
# A program to display a number of seconds in other units data = 75475984 changedData = data years = 0 days = 0 hours = 0 minutes = 0 seconds = 0 now = 0 if data == 0: now = 1 for i in range(100): if changedData >= 31556952: years += 1 changedData -= 31556952 for i in range(365): if changedData >= 86400: days += 1 changedData -= 86400 for i in range(24): if changedData >= 3600: hours += 1 changedData -= 3600 for i in range(60): if changedData >= 60: minutes += 1 changedData -= 60 for i in range(60): if changedData >= 1: seconds += 1 changedData -= 1 if years or days or hours or minutes or seconds >= 1: print("Years: " + str(years) + "\nDays: " + str(days) + "\nHours: " + str(hours) + "\nMinutes: " + str(minutes) + "\nSeconds: " + str(seconds)) elif now == 1: print("Now!") else: print("Something Went Wrong")
data = 75475984 changed_data = data years = 0 days = 0 hours = 0 minutes = 0 seconds = 0 now = 0 if data == 0: now = 1 for i in range(100): if changedData >= 31556952: years += 1 changed_data -= 31556952 for i in range(365): if changedData >= 86400: days += 1 changed_data -= 86400 for i in range(24): if changedData >= 3600: hours += 1 changed_data -= 3600 for i in range(60): if changedData >= 60: minutes += 1 changed_data -= 60 for i in range(60): if changedData >= 1: seconds += 1 changed_data -= 1 if years or days or hours or minutes or (seconds >= 1): print('Years: ' + str(years) + '\nDays: ' + str(days) + '\nHours: ' + str(hours) + '\nMinutes: ' + str(minutes) + '\nSeconds: ' + str(seconds)) elif now == 1: print('Now!') else: print('Something Went Wrong')
nombre=input("nombre del archivo? ") f=open(nombre,"r") palabras=[] for linea in f: palabras.extend(linea.split()) print(palabras)
nombre = input('nombre del archivo? ') f = open(nombre, 'r') palabras = [] for linea in f: palabras.extend(linea.split()) print(palabras)
# %% [278. First Bad Version](https://leetcode.com/problems/first-bad-version/) class Solution: def firstBadVersion(self, n): lo, up = 0, n while up - lo > 1: mid = (lo + up) // 2 if isBadVersion(mid): up = mid else: lo = mid return up
class Solution: def first_bad_version(self, n): (lo, up) = (0, n) while up - lo > 1: mid = (lo + up) // 2 if is_bad_version(mid): up = mid else: lo = mid return up
# dataset settings data_root = 'data/' img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) crop_size = (256, 512) train_pipeline = [ dict(type='LoadImageFromFile_Semi'), dict(type='LoadAnnotations_Semi'), dict(type='RandomCrop_Semi', crop_size=crop_size, cat_max_ratio=0.75), dict(type='RandomFlip_Semi', prob=0.5), dict(type='PhotoMetricDistortion_Semi'), dict(type='Normalize_Semi', **img_norm_cfg), dict(type='DefaultFormatBundle_Semi'), dict( type='Collect', keys=['img_v0_0', 'img_v0_1', 'img_v0_1_s', 'img_v1_0', 'img_v1_1', 'img_v1_1_s', 'gt'], meta_keys=(), ), ] test_pipeline = [ dict(type='LoadImageFromFile'), dict( type='MultiScaleFlipAug', img_scale=(1024, 512), # img_ratios=[0.5, 0.75, 1.0, 1.25, 1.5, 1.75], flip=False, transforms=[ dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img']), ], ), ] data = dict( samples_per_gpu=2, workers_per_gpu=2, train=dict( type='CityscapesSemiDataset', data_root=data_root, img_dir='cityscapes/leftImg8bit_sequence_down_2x/train', ann_dir='cityscapes/gtFine_down_2x/train', split='splits/train_unsup_1-30.txt', split_unlabeled='splits/train_unsup_all.txt', pipeline=train_pipeline, ), val=dict( type='CityscapesDataset', data_root=data_root, img_dir='cityscapes/leftImg8bit_sequence_down_2x/val', ann_dir='cityscapes/gtFine_down_2x/val', split='splits/val.txt', pipeline=test_pipeline, ), )
data_root = 'data/' img_norm_cfg = dict(mean=[123.675, 116.28, 103.53], std=[58.395, 57.12, 57.375], to_rgb=True) crop_size = (256, 512) train_pipeline = [dict(type='LoadImageFromFile_Semi'), dict(type='LoadAnnotations_Semi'), dict(type='RandomCrop_Semi', crop_size=crop_size, cat_max_ratio=0.75), dict(type='RandomFlip_Semi', prob=0.5), dict(type='PhotoMetricDistortion_Semi'), dict(type='Normalize_Semi', **img_norm_cfg), dict(type='DefaultFormatBundle_Semi'), dict(type='Collect', keys=['img_v0_0', 'img_v0_1', 'img_v0_1_s', 'img_v1_0', 'img_v1_1', 'img_v1_1_s', 'gt'], meta_keys=())] test_pipeline = [dict(type='LoadImageFromFile'), dict(type='MultiScaleFlipAug', img_scale=(1024, 512), flip=False, transforms=[dict(type='RandomFlip'), dict(type='Normalize', **img_norm_cfg), dict(type='ImageToTensor', keys=['img']), dict(type='Collect', keys=['img'])])] data = dict(samples_per_gpu=2, workers_per_gpu=2, train=dict(type='CityscapesSemiDataset', data_root=data_root, img_dir='cityscapes/leftImg8bit_sequence_down_2x/train', ann_dir='cityscapes/gtFine_down_2x/train', split='splits/train_unsup_1-30.txt', split_unlabeled='splits/train_unsup_all.txt', pipeline=train_pipeline), val=dict(type='CityscapesDataset', data_root=data_root, img_dir='cityscapes/leftImg8bit_sequence_down_2x/val', ann_dir='cityscapes/gtFine_down_2x/val', split='splits/val.txt', pipeline=test_pipeline))
""" You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters. Kata.getMiddle("test") should return "es" Kata.getMiddle("testing") should return "t" Kata.getMiddle("middle") should return "dd" Kata.getMiddle("A") should return "A" """ def get_middle(string: str) -> str: """Get middle value of a string. Examples: >>> assert get_middle('middle') == 'dd' """ if len(string) > 2: index: int = int(len(string) / 2) if len(string) % 2: return string[index] return f'{string[index-1]}{string[index]}' return string def get_middle_opt(string: str) -> str: """Get middle value of a string (efficient). Examples: >>> assert get_middle_opt('middle') == 'dd' """ return ( string[int(len(string) // 2) - 1 : int(len(string) // 2) + 1] if not len(string) % 2 else string[int(len(string) // 2)] ) if __name__ == '__main__': print(get_middle('middle')) print(get_middle_opt('middle'))
""" You are going to be given a word. Your job is to return the middle character of the word. If the word's length is odd, return the middle character. If the word's length is even, return the middle 2 characters. Kata.getMiddle("test") should return "es" Kata.getMiddle("testing") should return "t" Kata.getMiddle("middle") should return "dd" Kata.getMiddle("A") should return "A" """ def get_middle(string: str) -> str: """Get middle value of a string. Examples: >>> assert get_middle('middle') == 'dd' """ if len(string) > 2: index: int = int(len(string) / 2) if len(string) % 2: return string[index] return f'{string[index - 1]}{string[index]}' return string def get_middle_opt(string: str) -> str: """Get middle value of a string (efficient). Examples: >>> assert get_middle_opt('middle') == 'dd' """ return string[int(len(string) // 2) - 1:int(len(string) // 2) + 1] if not len(string) % 2 else string[int(len(string) // 2)] if __name__ == '__main__': print(get_middle('middle')) print(get_middle_opt('middle'))
P, T = map(int, input().split()) solved = 0 for _ in range(P): flag = True for _ in range(T): test1 = input().strip() test = test1[0].lower() + test1[1:] if test == test1.lower(): continue else: flag = False if flag: solved += 1 print(solved)
(p, t) = map(int, input().split()) solved = 0 for _ in range(P): flag = True for _ in range(T): test1 = input().strip() test = test1[0].lower() + test1[1:] if test == test1.lower(): continue else: flag = False if flag: solved += 1 print(solved)
# accounts.tests # Tests for the account app # # Author: Benjamin Bengfort <benjamin@bengfort.com> # Created: Wed May 02 15:41:44 2018 -0400 # # ID: __init__.py [0395481] benjamin@bengfort.com $ """ Tests for the account app """
""" Tests for the account app """
def nb_year(p0, percent, aug, p): year = 0 while p0 < p: p0 = int(p0 + p0*(percent/100) + aug) year += 1 print(p0) return year print(nb_year(1000, 2, 50, 1200))
def nb_year(p0, percent, aug, p): year = 0 while p0 < p: p0 = int(p0 + p0 * (percent / 100) + aug) year += 1 print(p0) return year print(nb_year(1000, 2, 50, 1200))
# custom exceptions for ElasticSearch class SearchException(Exception): pass class IndexNotFoundError(SearchException): pass class MalformedQueryError(SearchException): pass class SearchUnavailableError(SearchException): pass
class Searchexception(Exception): pass class Indexnotfounderror(SearchException): pass class Malformedqueryerror(SearchException): pass class Searchunavailableerror(SearchException): pass
# -*- coding: utf-8 -*- """ Created on Sat Dec 14 08:35:11 2019 @author: NOTEBOOK """ def main(): print ('First Rectangle Details') length1 = float(input('Enter length: ')) width1 = float(input('Enter width: ')) area_1 = length1 * width1 print('The area of the Rectangle is',format(area_1,'.2f')) # Area 2 print ('second Rectangle Details') length2 = float(input('Enter length: ')) width2 = float(input('Enter width: ')) area_2 = length2 * width2 print('The area of the Rectangle is',format(area_2,'.2f')) if area_1 > area_2: print('The First rectangle has a larger area') elif area_1 < area_2: print('The second rectangle has a larger area') else: print('The rectangles are of the same size') main()
""" Created on Sat Dec 14 08:35:11 2019 @author: NOTEBOOK """ def main(): print('First Rectangle Details') length1 = float(input('Enter length: ')) width1 = float(input('Enter width: ')) area_1 = length1 * width1 print('The area of the Rectangle is', format(area_1, '.2f')) print('second Rectangle Details') length2 = float(input('Enter length: ')) width2 = float(input('Enter width: ')) area_2 = length2 * width2 print('The area of the Rectangle is', format(area_2, '.2f')) if area_1 > area_2: print('The First rectangle has a larger area') elif area_1 < area_2: print('The second rectangle has a larger area') else: print('The rectangles are of the same size') main()
print("Digite um numero...") numero = int(input()); numero numeroSucessor = print(numero + 1); numeroAntecessor = print(numero - 1); print("o seu valor eh {}, seu sucessor eh {} e o seu antecessor eh {}".format(numero, numeroSucessor, numeroAntecessor));
print('Digite um numero...') numero = int(input()) numero numero_sucessor = print(numero + 1) numero_antecessor = print(numero - 1) print('o seu valor eh {}, seu sucessor eh {} e o seu antecessor eh {}'.format(numero, numeroSucessor, numeroAntecessor))
host_='127.0.0.1' port_=8086 user_='user name' pass_ ='user password' protocol='line' air_api_key="air api key" weather_api_key="weather_api_key"
host_ = '127.0.0.1' port_ = 8086 user_ = 'user name' pass_ = 'user password' protocol = 'line' air_api_key = 'air api key' weather_api_key = 'weather_api_key'
MASTER_KEY = "masterKey" BASE_URL = "http://127.0.0.1:7700" INDEX_UID = "indexUID" INDEX_UID2 = "indexUID2" INDEX_UID3 = "indexUID3" INDEX_UID4 = "indexUID4" INDEX_FIXTURE = [ {"uid": INDEX_UID}, {"uid": INDEX_UID2, "options": {"primaryKey": "book_id"}}, {"uid": INDEX_UID3, "options": {"uid": "wrong", "primaryKey": "book_id"}}, ]
master_key = 'masterKey' base_url = 'http://127.0.0.1:7700' index_uid = 'indexUID' index_uid2 = 'indexUID2' index_uid3 = 'indexUID3' index_uid4 = 'indexUID4' index_fixture = [{'uid': INDEX_UID}, {'uid': INDEX_UID2, 'options': {'primaryKey': 'book_id'}}, {'uid': INDEX_UID3, 'options': {'uid': 'wrong', 'primaryKey': 'book_id'}}]
#!/usr/bin/env python3 # -*- coding: utf-8 -*- class Inyourshoes(object): def __init__(self, nlp, object): self.object = object self.matcher = object.matcher.Matcher(nlp.vocab) self.matcher.add("Inyourshoes", None, #what i would do [{'LOWER': 'what'}, {'LOWER': 'i'}, {'LOWER': 'would'}, {'LOWER': 'do'}], # if i were you [{'LOWER': 'if'}, {'LOWER': 'i'}, {'LOWER': 'were'}, {'LOWER': 'you'}], # i would not [{'LOWER': 'i'}, {'LOWER': 'would'}, {'LOWER': 'not'}] ) def __call__(self, doc): matches = self.matcher(doc) for match_id, start, end in matches: sents = self.object.tokens.Span(doc, start, end).sent sent_start, sent_end = sents.start, sents.end opinion = self.object.tokens.Span(doc, sent_start, sent_end, label = "INYOURSHOES") doc._.opinion.append(opinion,) return doc
class Inyourshoes(object): def __init__(self, nlp, object): self.object = object self.matcher = object.matcher.Matcher(nlp.vocab) self.matcher.add('Inyourshoes', None, [{'LOWER': 'what'}, {'LOWER': 'i'}, {'LOWER': 'would'}, {'LOWER': 'do'}], [{'LOWER': 'if'}, {'LOWER': 'i'}, {'LOWER': 'were'}, {'LOWER': 'you'}], [{'LOWER': 'i'}, {'LOWER': 'would'}, {'LOWER': 'not'}]) def __call__(self, doc): matches = self.matcher(doc) for (match_id, start, end) in matches: sents = self.object.tokens.Span(doc, start, end).sent (sent_start, sent_end) = (sents.start, sents.end) opinion = self.object.tokens.Span(doc, sent_start, sent_end, label='INYOURSHOES') doc._.opinion.append(opinion) return doc
class Solution: def lengthOfLongestSubstring(self, s: str) -> int: max_len = start = 0 m = {} for end, char in enumerate(s): if m.get(char, -1) >= start: # if in the current range start = m[char] + 1 max_len = max(max_len, end - start + 1) m[char] = end return max_len if __name__ == "__main__": solver = Solution() print(solver.lengthOfLongestSubstring("abcabcbb")) print(solver.lengthOfLongestSubstring("bbbbbb")) print(solver.lengthOfLongestSubstring("pwwkew"))
class Solution: def length_of_longest_substring(self, s: str) -> int: max_len = start = 0 m = {} for (end, char) in enumerate(s): if m.get(char, -1) >= start: start = m[char] + 1 max_len = max(max_len, end - start + 1) m[char] = end return max_len if __name__ == '__main__': solver = solution() print(solver.lengthOfLongestSubstring('abcabcbb')) print(solver.lengthOfLongestSubstring('bbbbbb')) print(solver.lengthOfLongestSubstring('pwwkew'))
if __name__ == "__main__": null = "null" placeholder = null undefined = "undefined"
if __name__ == '__main__': null = 'null' placeholder = null undefined = 'undefined'
# optimized_primality_test : O(sqrt(n)) - if x divide n then n/x = y which divides n as well, so we need to check only # numbers from 1 to sqrt(n). sqrt(n) is border because sqrt(n) * sqrt(n) gives n, which then implies that values after # sqrt(n) need to be multiplied by values lesser then sqrt(n) which we already checked def primality_test(num): i = 2 while i*i <= num: if num % i == 0: return False i += 1 return True print(primality_test(6793))
def primality_test(num): i = 2 while i * i <= num: if num % i == 0: return False i += 1 return True print(primality_test(6793))
Elements_Symbols_Reverse = { "H":"Hydrogen", "He":"Helium", "Li":"Lithium", "Be":"Beryllium", "B":"Boron", "C":"Carbon", "N":"Nitrogen", "O":"Oxygen", "F":"Fluorine", "Ne":"Neon", "Na":"Sodium", "Mg":"Magnesium", "Al":"Aluminium", "Si":"Silicon", "P":"Phosphorus", "S":"Sulphur", "Cl":"Chlorine", "Ar":"Argon", "K":"Potassium", "Ca":"Calcium", "Sc":"Scandium", "Ti":"Titanium", "V":"Vanadium", "Cr":"Chromium", "Mn":"Manganese", "Fe":"Iron", "Co":"Cobalt", "Ni":"Nickel", "Cu":"Copper", "Zn":"Zinc", "Ga":"Gallium", "Ge":"Germanium", "As":"Arsenic", "Se":"Selenium", "Br":"Bromine", "Kr":"Krypton", "Rb":"Rubidium", "Sr":"Strontium", "Y":"Yttrium", "Zr":"Zirconium", "Nb":"Niobium", "Mo":"Molybdenum", "Tc":"Technetium", "Ru":"Ruthenium", "Rh":"Rhodium", "Pd":"Palladium", "Ag":"Silver", "Cd":"Cadmium", "In":"Indium", "Sn":"Tin", "Sb":"Antimony", "Te":"Tellurium", "I":"Iodine", "Xe":"Xenon", "Cs":"Caesium", "Ba":"Barium", "La":"Lanthanum", "Ce":"Cerium", "Pr":"Praseodymium", "Nd":"Neodymium", "Pm":"Promethium", "Sm":"Samarium", "Eu":"Europium", "Gd":"Gadolinium", "Tb":"Terbium", "Dy":"Dysprosium", "Ho":"Holmium", "Er":"Erbium", "Tm":"Thulium", "Yb":"Ytterbium", "Lu":"Lutetium", "Hf":"Halfnium", "Ta":"Tantalum", "W":"Tungsten", "Re":"Rhenium", "Os":"Osmium", "Ir":"Iridium", "Pt":"Platinum", "Au":"Gold", "Hg":"Mercury", "Tl":"Thallium", "Pb":"Lead", "Bi":"Bismuth", "Po":"Polonium", "At":"Astatine", "Rn":"Radon", "Fr":"Francium", "Ra":"Radium", "Ac":"Actinium", "Th":"Thorium", "Pa":"Protactinium", "U":"Uranium", "Np":"Neptunium", "Pu":"Plutonium", "Am":"Americium", "Cm":"Curium", "Bk":"Berkelium", "Cf":"Californium", "Es":"Einsteinium", "Fm":"Fermium", "Md":"Mendelevium", "No":"Nobelium", "Lr":"Lawrencium", "Rf":"Rutherfordium", "Db":"Dubnium", "Sg":"Seaborgium", "Bh":"Bohrium", "Hs":"Hassium", "Mt":"Meitnerium", "Ds":"Darmstadtium", "Rg":"Roentgenium", "Cn":"Copernicium", "Nh":"Nihonium", "Fl":"Flerovium", "Mc":"Moscovium", "Lv":"Livermorium", "Ts":"Tennessine", "Og":"Oganesson" }
elements__symbols__reverse = {'H': 'Hydrogen', 'He': 'Helium', 'Li': 'Lithium', 'Be': 'Beryllium', 'B': 'Boron', 'C': 'Carbon', 'N': 'Nitrogen', 'O': 'Oxygen', 'F': 'Fluorine', 'Ne': 'Neon', 'Na': 'Sodium', 'Mg': 'Magnesium', 'Al': 'Aluminium', 'Si': 'Silicon', 'P': 'Phosphorus', 'S': 'Sulphur', 'Cl': 'Chlorine', 'Ar': 'Argon', 'K': 'Potassium', 'Ca': 'Calcium', 'Sc': 'Scandium', 'Ti': 'Titanium', 'V': 'Vanadium', 'Cr': 'Chromium', 'Mn': 'Manganese', 'Fe': 'Iron', 'Co': 'Cobalt', 'Ni': 'Nickel', 'Cu': 'Copper', 'Zn': 'Zinc', 'Ga': 'Gallium', 'Ge': 'Germanium', 'As': 'Arsenic', 'Se': 'Selenium', 'Br': 'Bromine', 'Kr': 'Krypton', 'Rb': 'Rubidium', 'Sr': 'Strontium', 'Y': 'Yttrium', 'Zr': 'Zirconium', 'Nb': 'Niobium', 'Mo': 'Molybdenum', 'Tc': 'Technetium', 'Ru': 'Ruthenium', 'Rh': 'Rhodium', 'Pd': 'Palladium', 'Ag': 'Silver', 'Cd': 'Cadmium', 'In': 'Indium', 'Sn': 'Tin', 'Sb': 'Antimony', 'Te': 'Tellurium', 'I': 'Iodine', 'Xe': 'Xenon', 'Cs': 'Caesium', 'Ba': 'Barium', 'La': 'Lanthanum', 'Ce': 'Cerium', 'Pr': 'Praseodymium', 'Nd': 'Neodymium', 'Pm': 'Promethium', 'Sm': 'Samarium', 'Eu': 'Europium', 'Gd': 'Gadolinium', 'Tb': 'Terbium', 'Dy': 'Dysprosium', 'Ho': 'Holmium', 'Er': 'Erbium', 'Tm': 'Thulium', 'Yb': 'Ytterbium', 'Lu': 'Lutetium', 'Hf': 'Halfnium', 'Ta': 'Tantalum', 'W': 'Tungsten', 'Re': 'Rhenium', 'Os': 'Osmium', 'Ir': 'Iridium', 'Pt': 'Platinum', 'Au': 'Gold', 'Hg': 'Mercury', 'Tl': 'Thallium', 'Pb': 'Lead', 'Bi': 'Bismuth', 'Po': 'Polonium', 'At': 'Astatine', 'Rn': 'Radon', 'Fr': 'Francium', 'Ra': 'Radium', 'Ac': 'Actinium', 'Th': 'Thorium', 'Pa': 'Protactinium', 'U': 'Uranium', 'Np': 'Neptunium', 'Pu': 'Plutonium', 'Am': 'Americium', 'Cm': 'Curium', 'Bk': 'Berkelium', 'Cf': 'Californium', 'Es': 'Einsteinium', 'Fm': 'Fermium', 'Md': 'Mendelevium', 'No': 'Nobelium', 'Lr': 'Lawrencium', 'Rf': 'Rutherfordium', 'Db': 'Dubnium', 'Sg': 'Seaborgium', 'Bh': 'Bohrium', 'Hs': 'Hassium', 'Mt': 'Meitnerium', 'Ds': 'Darmstadtium', 'Rg': 'Roentgenium', 'Cn': 'Copernicium', 'Nh': 'Nihonium', 'Fl': 'Flerovium', 'Mc': 'Moscovium', 'Lv': 'Livermorium', 'Ts': 'Tennessine', 'Og': 'Oganesson'}
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you 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. ''' Created on Jan 8, 2020 @author: ballance ''' class TestData(object): def __init__(self, teststatus, toolcategory : str, date : str, simtime : float = 0.0, timeunit : str = "ns", runcwd : str = ".", cputime : float = 0.0, seed : str = "0", cmd : str = "", args : str = "", compulsory : int = 0, user : str = "user", cost : float = 0.0 ): self.teststatus = teststatus self.simtime = simtime self.timeunit = timeunit self.runcwd = runcwd self.cputime = cputime self.seed = seed self.cmd = cmd self.args = args self.compulsory = compulsory self.date = date self.user = user self.cost = cost self.toolcategory = toolcategory
""" Created on Jan 8, 2020 @author: ballance """ class Testdata(object): def __init__(self, teststatus, toolcategory: str, date: str, simtime: float=0.0, timeunit: str='ns', runcwd: str='.', cputime: float=0.0, seed: str='0', cmd: str='', args: str='', compulsory: int=0, user: str='user', cost: float=0.0): self.teststatus = teststatus self.simtime = simtime self.timeunit = timeunit self.runcwd = runcwd self.cputime = cputime self.seed = seed self.cmd = cmd self.args = args self.compulsory = compulsory self.date = date self.user = user self.cost = cost self.toolcategory = toolcategory
def even_numbers(numbers): even = [] for num in numbers: if num % 2 == 0: even.append(num) return even def odd_numbers(numbers): odd = [] for num in numbers: if num % 2 != 0: odd.append(num) return odd def sum_numbers(numbers): sum = 0 for num in numbers: sum = sum + num return sum # getSumOfOddNumbers 30 def sum_even_numbers(numbers): even = [] for num in numbers: if num % 2 == 0: even.append(num) return sum(even) def sum_odd_numbers(numbers): odd = [] for num in numbers: if num % 2 != 0: odd.append(num) return sum(odd) def map_logic_numbers(numbers): list_new = [] for num in numbers: if num % 2 == 0: list_new.append(num + 1) else: list_new.append(num + 2) return list_new list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(even_numbers(list_numbers)) print(odd_numbers(list_numbers)) print(sum_numbers(list_numbers)) print(sum_odd_numbers(list_numbers)) print(sum_even_numbers(list_numbers)) print(map_logic_numbers(list_numbers))
def even_numbers(numbers): even = [] for num in numbers: if num % 2 == 0: even.append(num) return even def odd_numbers(numbers): odd = [] for num in numbers: if num % 2 != 0: odd.append(num) return odd def sum_numbers(numbers): sum = 0 for num in numbers: sum = sum + num return sum def sum_even_numbers(numbers): even = [] for num in numbers: if num % 2 == 0: even.append(num) return sum(even) def sum_odd_numbers(numbers): odd = [] for num in numbers: if num % 2 != 0: odd.append(num) return sum(odd) def map_logic_numbers(numbers): list_new = [] for num in numbers: if num % 2 == 0: list_new.append(num + 1) else: list_new.append(num + 2) return list_new list_numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(even_numbers(list_numbers)) print(odd_numbers(list_numbers)) print(sum_numbers(list_numbers)) print(sum_odd_numbers(list_numbers)) print(sum_even_numbers(list_numbers)) print(map_logic_numbers(list_numbers))
''' disjoint set forest implementation, uses union by rank and path compression worst case T.C for find_set is O(logn) in first find_set operation T.C for union and create_set is O(1) ''' class Node: # the identity of node(member of set) is given by data, parent_link, rank def __init__(self, data=None, rank=None, parent_link=None): self.data = data self.rank = rank self.parent_link = parent_link class DisjointSet: # dictionary is important here because here I need to map data to node def __init__(self, node_map): self.node_map = node_map # create a new set i.e create a node, make it point to itself and set rank def create_set(self, data): node = Node(data, 0) # setting the data and rank node.parent_link = node # since its the only node in the set self.node_map[data] = node # creating the data to node mapping # returns the data contained in the representative_node def find_set(self, data): # getting the node containing data node = self.node_map[data] representative_node = self.find_representative(node) return representative_node.data # returns the representative_node of the node passed as agrument in fun # this method is also responsible for path compression, here I am using # recusive approach to perform the path compression def find_representative(self, node): # getting the parent of the given node parent = node.parent_link # check if the parent is the root (i.e. representative_node) or not if parent == node: # if root, then parent will be same as node return parent # set the parent_link of each node in the path to the root node.parent_link = self.find_representative(node.parent_link) return node.parent_link # performs the union using using by rank method def union(self, data1, data2): # get the node corrosponding to data1 and data2 node1 = self.node_map[data1] node2 = self.node_map[data2] # check if both data1 and data2 belongs to same set or not # for this I need to know the representative_node of each data1 & data2 rep1 = self.find_representative(node1) rep2 = self.find_representative(node2) if rep1.data == rep2.data: return False # False indicates, there is not need to perform union # the tree with higher rank should become the final representative_node if rep1.rank >= rep2.rank: # if rank of both set is same then final rank will increase by 1 # else the rank would be same as rep1's rank rep1.rank = 1 + rep1.rank if rep1.rank == rep2.rank else rep1.rank # set the parent_link of set2 to representative_node of set1 rep2.parent_link = rep1 else: # setting the parent_link of set1 to representative_node of set2 rep1.parent_link = rep2 return True # represents that union happened successfully
""" disjoint set forest implementation, uses union by rank and path compression worst case T.C for find_set is O(logn) in first find_set operation T.C for union and create_set is O(1) """ class Node: def __init__(self, data=None, rank=None, parent_link=None): self.data = data self.rank = rank self.parent_link = parent_link class Disjointset: def __init__(self, node_map): self.node_map = node_map def create_set(self, data): node = node(data, 0) node.parent_link = node self.node_map[data] = node def find_set(self, data): node = self.node_map[data] representative_node = self.find_representative(node) return representative_node.data def find_representative(self, node): parent = node.parent_link if parent == node: return parent node.parent_link = self.find_representative(node.parent_link) return node.parent_link def union(self, data1, data2): node1 = self.node_map[data1] node2 = self.node_map[data2] rep1 = self.find_representative(node1) rep2 = self.find_representative(node2) if rep1.data == rep2.data: return False if rep1.rank >= rep2.rank: rep1.rank = 1 + rep1.rank if rep1.rank == rep2.rank else rep1.rank rep2.parent_link = rep1 else: rep1.parent_link = rep2 return True
'''# from app.game import determine_winner # FYI normally we'd have this application code (determine_winner()) in another file, # ... but for this exercise we'll keep it here def determine_winner(user_choice, computer_choice): return "rock" # todo: write logic here to make the tests pass! if user_choice == computer_choice: return None elif user_choice == "rock" and computer_choice == "scissors" winner = "rock" def test_determine_winner(): assert determine_winner("rock", "rock") == None assert determine_winner("rock", "paper") == "paper" assert determine_winner("rock", "scissors") == "rock" assert determine_winner("paper", "rock") == "paper" assert determine_winner("paper", "paper") == None assert determine_winner("paper", "scissors") == "scissors" assert determine_winner("scissors", "rock") == "rock" assert determine_winner("scissors", "paper") == "scissors" assert determine_winner("scissors", "scissors") == None '''
"""# from app.game import determine_winner # FYI normally we'd have this application code (determine_winner()) in another file, # ... but for this exercise we'll keep it here def determine_winner(user_choice, computer_choice): return "rock" # todo: write logic here to make the tests pass! if user_choice == computer_choice: return None elif user_choice == "rock" and computer_choice == "scissors" winner = "rock" def test_determine_winner(): assert determine_winner("rock", "rock") == None assert determine_winner("rock", "paper") == "paper" assert determine_winner("rock", "scissors") == "rock" assert determine_winner("paper", "rock") == "paper" assert determine_winner("paper", "paper") == None assert determine_winner("paper", "scissors") == "scissors" assert determine_winner("scissors", "rock") == "rock" assert determine_winner("scissors", "paper") == "scissors" assert determine_winner("scissors", "scissors") == None """
N = int(input()) a = list(map(int, input().split())) for i, _ in sorted(enumerate(a), key=lambda x: x[1], reverse=True): print(i + 1)
n = int(input()) a = list(map(int, input().split())) for (i, _) in sorted(enumerate(a), key=lambda x: x[1], reverse=True): print(i + 1)
class Environment: def __init__(self, width=1000, height=1000): self.width = width self.height = height self.agent = None self.doors = [] def add_door(self, door): self.doors.append(door) def get_env_size(self): size = (self.height, self.width) return size
class Environment: def __init__(self, width=1000, height=1000): self.width = width self.height = height self.agent = None self.doors = [] def add_door(self, door): self.doors.append(door) def get_env_size(self): size = (self.height, self.width) return size
# custom exceptions class PybamWarn(Exception): pass class PybamError(Exception): pass
class Pybamwarn(Exception): pass class Pybamerror(Exception): pass
################################################################################ # Copyright (c) 2015-2018 Skymind, Inc. # # This program and the accompanying materials are made available under the # terms of the Apache License, Version 2.0 which is available at # https://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 ################################################################################ # automatically generated by the FlatBuffers compiler, do not modify # namespace: graph class OpType(object): TRANSFORM = 0 ACCUMULATION = 1 INDEX_ACCUMULATION = 2 SCALAR = 3 BROADCAST = 4 PAIRWISE = 5 ACCUMULATION3 = 6 SUMMARYSTATS = 7 SHAPE = 8 AGGREGATION = 9 RANDOM = 10 CUSTOM = 11 GRAPH = 12 VARIABLE = 30 BOOLEAN = 40 LOGIC = 119
class Optype(object): transform = 0 accumulation = 1 index_accumulation = 2 scalar = 3 broadcast = 4 pairwise = 5 accumulation3 = 6 summarystats = 7 shape = 8 aggregation = 9 random = 10 custom = 11 graph = 12 variable = 30 boolean = 40 logic = 119
'''Given a binary string s, return true if the longest contiguous segment of 1s is strictly longer than the longest contiguous segment of 0s in s. Return false otherwise. For example, in s = "110100010" the longest contiguous segment of 1s has length 2, and the longest contiguous segment of 0s has length 3. Note that if there are no 0s, then the longest contiguous segment of 0s is considered to have length 0. The same applies if there are no 1s.''' class Solution: def checkZeroOnes(self, l0: str) -> bool: self.l0 = l0 temp = 1 num_1 = 0 num_0 = 0 for i in range(1,len(l0)): curr_1 = 0 curr_0 = 0 if(int(l0[i]) - int(l0[i-1]) == 0): temp+=1 elif(int(l0[i]) - int(l0[i-1] )== -1): curr_1 = temp if(curr_1 > num_1 ): num_1 = curr_1 temp = 1 else: curr_0 = temp if(curr_0 > num_0 ): num_0 = curr_0 temp = 1 if(l0[-1] == '0'): if(num_0 < temp): num_0 = temp else: if(num_1 < temp): num_1 = temp if(num_1 > num_0): return True else:return False
"""Given a binary string s, return true if the longest contiguous segment of 1s is strictly longer than the longest contiguous segment of 0s in s. Return false otherwise. For example, in s = "110100010" the longest contiguous segment of 1s has length 2, and the longest contiguous segment of 0s has length 3. Note that if there are no 0s, then the longest contiguous segment of 0s is considered to have length 0. The same applies if there are no 1s.""" class Solution: def check_zero_ones(self, l0: str) -> bool: self.l0 = l0 temp = 1 num_1 = 0 num_0 = 0 for i in range(1, len(l0)): curr_1 = 0 curr_0 = 0 if int(l0[i]) - int(l0[i - 1]) == 0: temp += 1 elif int(l0[i]) - int(l0[i - 1]) == -1: curr_1 = temp if curr_1 > num_1: num_1 = curr_1 temp = 1 else: curr_0 = temp if curr_0 > num_0: num_0 = curr_0 temp = 1 if l0[-1] == '0': if num_0 < temp: num_0 = temp elif num_1 < temp: num_1 = temp if num_1 > num_0: return True else: return False
class UndergroundSystem(object): def __init__(self): # record the customer's starting trip # card ID: [station, t] self.customer_trip = {} # record the average travel time from start station to end station # (start, end): [t, times] self.trips = {} def checkIn(self, id, stationName, t): self.customer_trip[id] = [stationName, t] def checkOut(self, id, stationName, t): # get the check in information of the customer start_station, start_t = self.customer_trip[id] del self.customer_trip[id] # the trip information # stationName => end_station # t => end_t trip = (start_station, stationName) travel_time = t - start_t # store / update the trip information if trip not in self.trips: self.trips[trip] = [travel_time, 1] else: # another way to write that is store the total traveling time and the number of travels # so that you do not need to calculate the avg time everytime avg_t, times = self.trips[trip] self.trips[trip] = [ (avg_t * times + travel_time) / (times + 1.0), times + 1] def getAverageTime(self, startStation, endStation): return self.trips[(startStation, endStation)][0] # Your UndergroundSystem object will be instantiated and called as such: # obj = UndergroundSystem() # obj.checkIn(id,stationName,t) # obj.checkOut(id,stationName,t) # param_3 = obj.getAverageTime(startStation,endStation)
class Undergroundsystem(object): def __init__(self): self.customer_trip = {} self.trips = {} def check_in(self, id, stationName, t): self.customer_trip[id] = [stationName, t] def check_out(self, id, stationName, t): (start_station, start_t) = self.customer_trip[id] del self.customer_trip[id] trip = (start_station, stationName) travel_time = t - start_t if trip not in self.trips: self.trips[trip] = [travel_time, 1] else: (avg_t, times) = self.trips[trip] self.trips[trip] = [(avg_t * times + travel_time) / (times + 1.0), times + 1] def get_average_time(self, startStation, endStation): return self.trips[startStation, endStation][0]
# Black list for auto vote cast Blacklist_team = ["Royal Never Give Up", "NAVI"] Blacklist_game = ["CSGO"] Blacklist_event = [] # Program debug debugLevel = 0 # Switch of auto vote cast function autoVote = True # Cycle of tasks (seconds) cycleTime = 1800
blacklist_team = ['Royal Never Give Up', 'NAVI'] blacklist_game = ['CSGO'] blacklist_event = [] debug_level = 0 auto_vote = True cycle_time = 1800
print("Calorie Calulator") FAT = float(input("Enter grams of fat: ")) CARBOHYDRATES = float(input("Enter grams of Carbohydrates: ")) PROTEIN= float(input("Enter grams of Protein: ")) Fatg = 9 * FAT print("Number of calories from Fat is: " + str(Fatg)) Protieng = 4 * PROTEIN print("Number of calories from Protein is: " + str(Protieng)) Carbohydratesg = 4 * CARBOHYDRATES print("Number of calories from Carbohydrates is: " + str(Carbohydratesg)) totalCalorie = Fatg + Protieng + Carbohydratesg print("Total number of Calories is: " + str(totalCalorie))
print('Calorie Calulator') fat = float(input('Enter grams of fat: ')) carbohydrates = float(input('Enter grams of Carbohydrates: ')) protein = float(input('Enter grams of Protein: ')) fatg = 9 * FAT print('Number of calories from Fat is: ' + str(Fatg)) protieng = 4 * PROTEIN print('Number of calories from Protein is: ' + str(Protieng)) carbohydratesg = 4 * CARBOHYDRATES print('Number of calories from Carbohydrates is: ' + str(Carbohydratesg)) total_calorie = Fatg + Protieng + Carbohydratesg print('Total number of Calories is: ' + str(totalCalorie))
# sudoku solver with backtracking algorithm... board = [[4,0,0,0,1,0,3,0,0], [0,6,0,4,0,7,0,0,0], [0,5,0,0,3,2,1,4,0], [9,0,4,0,0,1,0,8,5], [0,0,6,0,0,0,9,0,0], [3,1,0,7,0,0,6,0,4], [0,4,9,5,7,0,0,3,0], [0,0,0,1,0,4,0,7,0], [0,0,1,0,9,0,0,0,2]] def findEmpty(): for i in range(0,9): for j in range(0,9): if board[i][j]==0: return (i,j) return None def printBoard(): print("\n"*3) for i in range(1,10): for j in range(1,10): print(board[i-1][j-1],end = '') if j%3==0: print(" | ",end = '') print("\n",end='') if i%3==0 and i!=9: print("_"*17) print("\n"*3) def valid(bo, num, pos): # Check row for i in range(len(bo[0])): if bo[pos[0]][i] == num and pos[1] != i: return False # Check column for i in range(len(bo)): if bo[i][pos[1]] == num and pos[0] != i: return False # Check box box_x = pos[1] // 3 box_y = pos[0] // 3 for i in range(box_y*3, box_y*3 + 3): for j in range(box_x * 3, box_x*3 + 3): if bo[i][j] == num and (i,j) != pos: return False return True def solveSudoku(): pos = findEmpty() if pos==None: printBoard() return True (row,col) = pos for no in range(1,10): #print ("working at position",pos) if valid(board,no,pos): board[row][col] = no if solveSudoku()==True: return True board[row][col] = 0 return False printBoard() boo = solveSudoku() if boo: print("puzzle solved") else: print("Sorry, this puzzle can't be solved")
board = [[4, 0, 0, 0, 1, 0, 3, 0, 0], [0, 6, 0, 4, 0, 7, 0, 0, 0], [0, 5, 0, 0, 3, 2, 1, 4, 0], [9, 0, 4, 0, 0, 1, 0, 8, 5], [0, 0, 6, 0, 0, 0, 9, 0, 0], [3, 1, 0, 7, 0, 0, 6, 0, 4], [0, 4, 9, 5, 7, 0, 0, 3, 0], [0, 0, 0, 1, 0, 4, 0, 7, 0], [0, 0, 1, 0, 9, 0, 0, 0, 2]] def find_empty(): for i in range(0, 9): for j in range(0, 9): if board[i][j] == 0: return (i, j) return None def print_board(): print('\n' * 3) for i in range(1, 10): for j in range(1, 10): print(board[i - 1][j - 1], end='') if j % 3 == 0: print(' | ', end='') print('\n', end='') if i % 3 == 0 and i != 9: print('_' * 17) print('\n' * 3) def valid(bo, num, pos): for i in range(len(bo[0])): if bo[pos[0]][i] == num and pos[1] != i: return False for i in range(len(bo)): if bo[i][pos[1]] == num and pos[0] != i: return False box_x = pos[1] // 3 box_y = pos[0] // 3 for i in range(box_y * 3, box_y * 3 + 3): for j in range(box_x * 3, box_x * 3 + 3): if bo[i][j] == num and (i, j) != pos: return False return True def solve_sudoku(): pos = find_empty() if pos == None: print_board() return True (row, col) = pos for no in range(1, 10): if valid(board, no, pos): board[row][col] = no if solve_sudoku() == True: return True board[row][col] = 0 return False print_board() boo = solve_sudoku() if boo: print('puzzle solved') else: print("Sorry, this puzzle can't be solved")
# https://www.hackerrank.com/challenges/ctci-is-binary-search-tree """ Node is defined as class node: def __init__(self, data): self.data = data self.left = None self.right = None """ def check_binary_search_tree_(root): # To check if its a binary search tree, do an inorder search # and compare it with the same list but sorted. def inOrder(node): arr = [] if node is None: return [] arr.extend(inOrder(node.left)) arr.append(node.data) arr.extend(inOrder(node.right)) return arr arr = inOrder(root) # So, check that the traversal array is sorted, and check that # all elements are unique by using a set (a tree with repeated # elements can not be a BST). return arr == sorted(arr) and len(set(arr)) == len(arr)
""" Node is defined as class node: def __init__(self, data): self.data = data self.left = None self.right = None """ def check_binary_search_tree_(root): def in_order(node): arr = [] if node is None: return [] arr.extend(in_order(node.left)) arr.append(node.data) arr.extend(in_order(node.right)) return arr arr = in_order(root) return arr == sorted(arr) and len(set(arr)) == len(arr)
class Solution(object): def searchInsert(self,nums, target): """ :type nums: List[int] :type target: int :rtype: int """ length=len(nums) l=0 r=length-1 while l<=r: if l==r: return l if nums[l]>=target else l+1 mid=(l+r)/2 if nums[mid]>=target: r=mid else: l=mid+1
class Solution(object): def search_insert(self, nums, target): """ :type nums: List[int] :type target: int :rtype: int """ length = len(nums) l = 0 r = length - 1 while l <= r: if l == r: return l if nums[l] >= target else l + 1 mid = (l + r) / 2 if nums[mid] >= target: r = mid else: l = mid + 1
#!/usr/bin/env python3 # -*- coding: UTF-8 -*- # ----------------------------------------------------------------------------- # # P A G E B O T E X A M P L E S # # Copyright (c) 2017 Thom Janssen <https://github.com/thomgb> # www.pagebot.io # Licensed under MIT conditions # # Supporting DrawBot, www.drawbot.com # Supporting Flat, xxyxyz.org/flat # ----------------------------------------------------------------------------- # # BinaryData.py # # Shows how to read and write binary data. More here: # # https://www.devdungeon.com/content/working-binary-data-python # Creates empty bytes. empty_bytes = bytes(4) print(type(empty_bytes)) print(empty_bytes) # Casts bytes to bytearray. mutable_bytes = bytearray(empty_bytes) print(mutable_bytes) mutable_bytes = bytearray(b'\x00\x0F') # Bytearray allows modification: mutable_bytes[0] = 255 mutable_bytes.append(255) print(mutable_bytes) # Cast bytearray back to bytes immutable_bytes = bytes(mutable_bytes) print(immutable_bytes) s = b'bla' print(s.decode('utf8'))
empty_bytes = bytes(4) print(type(empty_bytes)) print(empty_bytes) mutable_bytes = bytearray(empty_bytes) print(mutable_bytes) mutable_bytes = bytearray(b'\x00\x0f') mutable_bytes[0] = 255 mutable_bytes.append(255) print(mutable_bytes) immutable_bytes = bytes(mutable_bytes) print(immutable_bytes) s = b'bla' print(s.decode('utf8'))
# import math # import numpy as np def lagrange(f, xs, x): ys = [f(i) for i in xs] n = len(xs) y = 0 for k in range(0, n): t = 1 for j in range(0, n): if j != k: s = (x - xs[j]) / (xs[k] - xs[j]) t = t * s y = y + t * ys[k] return y def difference_quotient(f, xs): res = 0 n = len(xs) for k in range(n): t = 1 for j in range(n): if j != k: t *= (xs[k] - xs[j]) res += f(xs[k]) / t return res def newtown(f, xs, x): n = len(xs) y = f(xs[0]) for k in range(1, n): t = difference_quotient(f, xs[:k + 1]) for j in range(k): t *= (x - xs[j]) y += t return y def piecewise_linear(f, xs, x): interval = [0, 1] if x < xs[0]: interval = [xs[0], xs[1]] elif x > xs[-1]: interval = [xs[-2], xs[-1]] else: for i in range(len(xs) - 1): if x >= xs[i] and x <= xs[i + 1]: interval = [xs[i], xs[i + 1]] break return lagrange(f, interval, x) # print(lagrange(lambda x: 1 / (1 + x * x), np.linspace(-5, 5, 11), 0.5)) # print(lagrange(lambda x: 1 / (1 + x * x), np.linspace(-5, 5, 11), 4.5)) # print(piecewise_linear(lambda x: 1 / (1 + x * x), np.linspace(-5, 5, 11), 0.5)) # print(piecewise_linear(lambda x: 1 / (1 + x * x), np.linspace(-5, 5, 11), 4.5)) # print( # difference_quotient(lambda x: x * x * x - 4 * x, (np.arange(5))[1:]), # difference_quotient(lambda x: x * x * x - 4 * x, [1, 2]), # difference_quotient(lambda x: x * x * x - 4 * x, [1, 2, 3]) # ) # print(newtown(lambda x: x * x * x - 4 * x, (np.arange(5))[1:], 5)) # print(newtown(lambda x: math.sqrt(x), [1, 4, 9], 5))
def lagrange(f, xs, x): ys = [f(i) for i in xs] n = len(xs) y = 0 for k in range(0, n): t = 1 for j in range(0, n): if j != k: s = (x - xs[j]) / (xs[k] - xs[j]) t = t * s y = y + t * ys[k] return y def difference_quotient(f, xs): res = 0 n = len(xs) for k in range(n): t = 1 for j in range(n): if j != k: t *= xs[k] - xs[j] res += f(xs[k]) / t return res def newtown(f, xs, x): n = len(xs) y = f(xs[0]) for k in range(1, n): t = difference_quotient(f, xs[:k + 1]) for j in range(k): t *= x - xs[j] y += t return y def piecewise_linear(f, xs, x): interval = [0, 1] if x < xs[0]: interval = [xs[0], xs[1]] elif x > xs[-1]: interval = [xs[-2], xs[-1]] else: for i in range(len(xs) - 1): if x >= xs[i] and x <= xs[i + 1]: interval = [xs[i], xs[i + 1]] break return lagrange(f, interval, x)
def find_neighbors(index, width, height, costmap, orthogonal_step_cost): """ Identifies neighbor nodes inspecting the 8 adjacent neighbors Checks if neighbor is inside the map boundaries and if is not an obstacle according to a threshold Returns a list with valid neighbour nodes as [index, step_cost] pairs """ neighbors = [] # length of diagonal = length of one side by the square root of 2 (1.41421) diagonal_step_cost = orthogonal_step_cost * 1.41421 # threshold value used to reject neighbor nodes as they are considered as obstacles [1-254] lethal_cost = 150 upper = index - width if upper > 0: if costmap[upper] < lethal_cost: step_cost = orthogonal_step_cost + costmap[upper]/255 neighbors.append([upper, step_cost]) left = index - 1 if left % width > 0: if costmap[left] < lethal_cost: step_cost = orthogonal_step_cost + costmap[left]/255 neighbors.append([left, step_cost]) upper_left = index - width - 1 if upper_left > 0 and upper_left % width > 0: if costmap[upper_left] < lethal_cost: step_cost = diagonal_step_cost + costmap[upper_left]/255 neighbors.append([index - width - 1, step_cost]) upper_right = index - width + 1 if upper_right > 0 and (upper_right) % width != (width - 1): if costmap[upper_right] < lethal_cost: step_cost = diagonal_step_cost + costmap[upper_right]/255 neighbors.append([upper_right, step_cost]) right = index + 1 if right % width != (width + 1): if costmap[right] < lethal_cost: step_cost = orthogonal_step_cost + costmap[right]/255 neighbors.append([right, step_cost]) lower_left = index + width - 1 if lower_left < height * width and lower_left % width != 0: if costmap[lower_left] < lethal_cost: step_cost = diagonal_step_cost + costmap[lower_left]/255 neighbors.append([lower_left, step_cost]) lower = index + width if lower <= height * width: if costmap[lower] < lethal_cost: step_cost = orthogonal_step_cost + costmap[lower]/255 neighbors.append([lower, step_cost]) lower_right = index + width + 1 if (lower_right) <= height * width and lower_right % width != (width - 1): if costmap[lower_right] < lethal_cost: step_cost = diagonal_step_cost + costmap[lower_right]/255 neighbors.append([lower_right, step_cost]) return neighbors def find_weighted_neighbors(index, width, height, costmap, orthogonal_step_cost): """ Identifies neighbor nodes inspecting the 8 adjacent neighbors Checks if neighbor is inside the map boundaries and if is not an obstacle according to a threshold Returns a list with valid neighbour nodes as [index, step_cost] pairs """ neighbors = [] # length of diagonal = length of one side by the square root of 2 (1.41421) diagonal_step_cost = orthogonal_step_cost * 1.41421 # threshold value used to reject neighbor nodes as they are considered as obstacles [1-254] lethal_cost = 150 step_cost = 0 upper = index - width if upper > 0: if costmap[upper] < lethal_cost: step_cost = orthogonal_step_cost + costmap[upper]/255 else: step_cost = float('inf') neighbors.append([upper, step_cost]) left = index - 1 if left % width > 0: if costmap[left] < lethal_cost: step_cost = orthogonal_step_cost + costmap[left]/255 else: step_cost = float('inf') neighbors.append([left, step_cost]) upper_left = index - width - 1 if upper_left > 0 and upper_left % width > 0: if costmap[upper_left] < lethal_cost: step_cost = diagonal_step_cost + costmap[upper_left]/255 else: step_cost = float('inf') neighbors.append([index - width - 1, step_cost]) upper_right = index - width + 1 if upper_right > 0 and (upper_right) % width != (width - 1): if costmap[upper_right] < lethal_cost: step_cost = diagonal_step_cost + costmap[upper_right]/255 else: step_cost = float('inf') neighbors.append([upper_right, step_cost]) right = index + 1 if right % width != (width + 1): if costmap[right] < lethal_cost: step_cost = orthogonal_step_cost + costmap[right]/255 else: step_cost = float('inf') neighbors.append([right, step_cost]) lower_left = index + width - 1 if lower_left < height * width and lower_left % width != 0: if costmap[lower_left] < lethal_cost: step_cost = diagonal_step_cost + costmap[lower_left]/255 else: step_cost = float('inf') neighbors.append([lower_left, step_cost]) lower = index + width if lower <= height * width: if costmap[lower] < lethal_cost: step_cost = orthogonal_step_cost + costmap[lower]/255 else: step_cost = float('inf') neighbors.append([lower, step_cost]) lower_right = index + width + 1 if (lower_right) <= height * width and lower_right % width != (width - 1): if costmap[lower_right] < lethal_cost: step_cost = diagonal_step_cost + costmap[lower_right]/255 else: step_cost = float('inf') neighbors.append([lower_right, step_cost]) return neighbors
def find_neighbors(index, width, height, costmap, orthogonal_step_cost): """ Identifies neighbor nodes inspecting the 8 adjacent neighbors Checks if neighbor is inside the map boundaries and if is not an obstacle according to a threshold Returns a list with valid neighbour nodes as [index, step_cost] pairs """ neighbors = [] diagonal_step_cost = orthogonal_step_cost * 1.41421 lethal_cost = 150 upper = index - width if upper > 0: if costmap[upper] < lethal_cost: step_cost = orthogonal_step_cost + costmap[upper] / 255 neighbors.append([upper, step_cost]) left = index - 1 if left % width > 0: if costmap[left] < lethal_cost: step_cost = orthogonal_step_cost + costmap[left] / 255 neighbors.append([left, step_cost]) upper_left = index - width - 1 if upper_left > 0 and upper_left % width > 0: if costmap[upper_left] < lethal_cost: step_cost = diagonal_step_cost + costmap[upper_left] / 255 neighbors.append([index - width - 1, step_cost]) upper_right = index - width + 1 if upper_right > 0 and upper_right % width != width - 1: if costmap[upper_right] < lethal_cost: step_cost = diagonal_step_cost + costmap[upper_right] / 255 neighbors.append([upper_right, step_cost]) right = index + 1 if right % width != width + 1: if costmap[right] < lethal_cost: step_cost = orthogonal_step_cost + costmap[right] / 255 neighbors.append([right, step_cost]) lower_left = index + width - 1 if lower_left < height * width and lower_left % width != 0: if costmap[lower_left] < lethal_cost: step_cost = diagonal_step_cost + costmap[lower_left] / 255 neighbors.append([lower_left, step_cost]) lower = index + width if lower <= height * width: if costmap[lower] < lethal_cost: step_cost = orthogonal_step_cost + costmap[lower] / 255 neighbors.append([lower, step_cost]) lower_right = index + width + 1 if lower_right <= height * width and lower_right % width != width - 1: if costmap[lower_right] < lethal_cost: step_cost = diagonal_step_cost + costmap[lower_right] / 255 neighbors.append([lower_right, step_cost]) return neighbors def find_weighted_neighbors(index, width, height, costmap, orthogonal_step_cost): """ Identifies neighbor nodes inspecting the 8 adjacent neighbors Checks if neighbor is inside the map boundaries and if is not an obstacle according to a threshold Returns a list with valid neighbour nodes as [index, step_cost] pairs """ neighbors = [] diagonal_step_cost = orthogonal_step_cost * 1.41421 lethal_cost = 150 step_cost = 0 upper = index - width if upper > 0: if costmap[upper] < lethal_cost: step_cost = orthogonal_step_cost + costmap[upper] / 255 else: step_cost = float('inf') neighbors.append([upper, step_cost]) left = index - 1 if left % width > 0: if costmap[left] < lethal_cost: step_cost = orthogonal_step_cost + costmap[left] / 255 else: step_cost = float('inf') neighbors.append([left, step_cost]) upper_left = index - width - 1 if upper_left > 0 and upper_left % width > 0: if costmap[upper_left] < lethal_cost: step_cost = diagonal_step_cost + costmap[upper_left] / 255 else: step_cost = float('inf') neighbors.append([index - width - 1, step_cost]) upper_right = index - width + 1 if upper_right > 0 and upper_right % width != width - 1: if costmap[upper_right] < lethal_cost: step_cost = diagonal_step_cost + costmap[upper_right] / 255 else: step_cost = float('inf') neighbors.append([upper_right, step_cost]) right = index + 1 if right % width != width + 1: if costmap[right] < lethal_cost: step_cost = orthogonal_step_cost + costmap[right] / 255 else: step_cost = float('inf') neighbors.append([right, step_cost]) lower_left = index + width - 1 if lower_left < height * width and lower_left % width != 0: if costmap[lower_left] < lethal_cost: step_cost = diagonal_step_cost + costmap[lower_left] / 255 else: step_cost = float('inf') neighbors.append([lower_left, step_cost]) lower = index + width if lower <= height * width: if costmap[lower] < lethal_cost: step_cost = orthogonal_step_cost + costmap[lower] / 255 else: step_cost = float('inf') neighbors.append([lower, step_cost]) lower_right = index + width + 1 if lower_right <= height * width and lower_right % width != width - 1: if costmap[lower_right] < lethal_cost: step_cost = diagonal_step_cost + costmap[lower_right] / 255 else: step_cost = float('inf') neighbors.append([lower_right, step_cost]) return neighbors
#! /usr/bin/env python3 ''' Problem 52 - Project Euler http://projecteuler.net/index.php?section=problems&id=052 ''' def samedigits(x,y): return set(str(x)) == set(str(y)) if __name__ == '__main__': maxn = 6 x = 1 while True: for n in range(2, maxn+1): if not samedigits(x, x * n): break else: print([x * i for i in range(1, maxn+1)]) break x += 1
""" Problem 52 - Project Euler http://projecteuler.net/index.php?section=problems&id=052 """ def samedigits(x, y): return set(str(x)) == set(str(y)) if __name__ == '__main__': maxn = 6 x = 1 while True: for n in range(2, maxn + 1): if not samedigits(x, x * n): break else: print([x * i for i in range(1, maxn + 1)]) break x += 1
##Write code to assign the number of characters in the string rv to a variable num_chars. rv = """Once upon a midnight dreary, while I pondered, weak and weary, Over many a quaint and curious volume of forgotten lore, While I nodded, nearly napping, suddenly there came a tapping, As of some one gently rapping, rapping at my chamber door. 'Tis some visitor, I muttered, tapping at my chamber door; Only this and nothing more.""" num_chars = len(rv)
rv = "Once upon a midnight dreary, while I pondered, weak and weary,\n Over many a quaint and curious volume of forgotten lore,\n While I nodded, nearly napping, suddenly there came a tapping,\n As of some one gently rapping, rapping at my chamber door.\n 'Tis some visitor, I muttered, tapping at my chamber door;\n Only this and nothing more." num_chars = len(rv)
""" Leetcode 209. Minimum Size Subarray Sum Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead. Example 1: Input: target = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: The subarray [4,3] has the minimal length under the problem constraint. Example 2: Input: target = 4, nums = [1,4,4] Output: 1 Example 3: Input: target = 11, nums = [1,1,1,1,1,1,1,1] Output: 0 Constraints: 1 <= target <= 109 1 <= nums.length <= 105 1 <= nums[i] <= 105 """ class Solution: def minSubArrayLen(self, s: int, nums: List[int]) -> int: windowSum, windowStart = 0, 0 minimumLength = float('inf') for windowEnd in range(len(nums)): windowSum += nums[windowEnd] while windowSum >= s: length = windowEnd - windowStart + 1 minimumLength = min(length, minimumLength) windowSum -= nums[windowStart] windowStart += 1 if minimumLength == float('inf'): return 0 return minimumLength
""" Leetcode 209. Minimum Size Subarray Sum Given an array of positive integers nums and a positive integer target, return the minimal length of a contiguous subarray [numsl, numsl+1, ..., numsr-1, numsr] of which the sum is greater than or equal to target. If there is no such subarray, return 0 instead. Example 1: Input: target = 7, nums = [2,3,1,2,4,3] Output: 2 Explanation: The subarray [4,3] has the minimal length under the problem constraint. Example 2: Input: target = 4, nums = [1,4,4] Output: 1 Example 3: Input: target = 11, nums = [1,1,1,1,1,1,1,1] Output: 0 Constraints: 1 <= target <= 109 1 <= nums.length <= 105 1 <= nums[i] <= 105 """ class Solution: def min_sub_array_len(self, s: int, nums: List[int]) -> int: (window_sum, window_start) = (0, 0) minimum_length = float('inf') for window_end in range(len(nums)): window_sum += nums[windowEnd] while windowSum >= s: length = windowEnd - windowStart + 1 minimum_length = min(length, minimumLength) window_sum -= nums[windowStart] window_start += 1 if minimumLength == float('inf'): return 0 return minimumLength
# Licensed to the Apache Software Foundation (ASF) under one # or more contributor license agreements. See the NOTICE file # distributed with this work for additional information # regarding copyright ownership. The ASF licenses this file # to you under the Apache License, Version 2.0 (the # "License"); you may not use this file except in compliance # with the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, # software distributed under the License is distributed on an # "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY # KIND, either express or implied. See the License for the # specific language governing permissions and limitations # under the License. # ############################################################################### # Module: utils # Purpose: Contains useful utility functions that don't belong to a category # # Notes: # ############################################################################### def dump(obj): s = "" for attr in dir(obj): if not attr.startswith("__"): s += "obj.%s = %s\n" % (attr, getattr(obj, attr)) return s def merge_dicts(x, y): """Given two dicts, merge them into a new dict as a shallow copy.""" if not y: return x z = x.copy() z.update(y) return z def merge_attributes(obj, attr): """Given an object objA and an object objB, merge the dictionary of attributes from objB into objA. For example: obj is an instance of class A which has only one attribute, a: objA.a = 'foo' attr is a dictionary with a single key 'b': attr = { 'b': 'bar' } obj = merge_attributes(obj, attr) Now obj has two attributes: a and b obj.a = 'foo' obj.b = 'bar' Note that if attr contains keys on attributes already existing in obj, the values for these attributes on obj will be overwritten. For example: objA.a = 'foo' attr = { 'a': 'bar' } obj = merge_attributes(obj, attr) Now obj still has one attribute: a obj.a = 'bar' :param object obj: The object to merge attributes into, from attr :param dict attr: The dictionary to merge attributes from, into obj """ obj.__dict__ = merge_dicts(obj.__dict__, attr)
def dump(obj): s = '' for attr in dir(obj): if not attr.startswith('__'): s += 'obj.%s = %s\n' % (attr, getattr(obj, attr)) return s def merge_dicts(x, y): """Given two dicts, merge them into a new dict as a shallow copy.""" if not y: return x z = x.copy() z.update(y) return z def merge_attributes(obj, attr): """Given an object objA and an object objB, merge the dictionary of attributes from objB into objA. For example: obj is an instance of class A which has only one attribute, a: objA.a = 'foo' attr is a dictionary with a single key 'b': attr = { 'b': 'bar' } obj = merge_attributes(obj, attr) Now obj has two attributes: a and b obj.a = 'foo' obj.b = 'bar' Note that if attr contains keys on attributes already existing in obj, the values for these attributes on obj will be overwritten. For example: objA.a = 'foo' attr = { 'a': 'bar' } obj = merge_attributes(obj, attr) Now obj still has one attribute: a obj.a = 'bar' :param object obj: The object to merge attributes into, from attr :param dict attr: The dictionary to merge attributes from, into obj """ obj.__dict__ = merge_dicts(obj.__dict__, attr)
''' Given an array of integers what is the length of the longest subArray containing no more than two distinct values such that the distinct values differ by no more than 1 For Example: arr = [0, 1, 2, 1, 2, 3] -> length = 4; [1,2,1,2] arr = [1, 2, 3, 4, 5] -> length = 2; [1,2] arr = [1, 1, 1, 3, 3, 2, 2] -> length = 4; [3,3,2,2] arr = [1, 1, 2, 2, 1, 2, 3, 3, 2, 2, 3, 3] -> length = 7; [2, 3, 3, 2, 2, 3, 3] ''' # def get_max_len(arr): # # code here # # dict containing the last occurance of that element # elem = {arr[0]:0} # max_len = 0 # first = 0 # for i in range(1,arr): # if arr[i] in elem: # # Storing the latest occurence # elem[arr[i]] = i # else: # for ele in elem: # if abs(arr[i] - ele)==1: # if len(elem) == 1: # max_len = max(max_len, i+1) # elem[arr[i]] = i # elif len(elem) == 2: # max_len = max(max_len, i-first) # # Deleted the previous element and arr[i] is added to elem # elem = {ele:elem[ele], arr[i]:i} # break # else: # if len(elem)==1: # elem = {arr[i]:i} # if len(elem) == 2: # # Contains the value and its first and last occurence in the list # class Node: # def __init__(self, data): # self.data = data # self.last = None # self.next = None # class Queue: # def __init__(self): # self.head = None # def insert(self, val): # if self.head == None: # self.head = Node(val, first) # else: # new_node = Node(val, first) # self.head.next = new_node arr = list(map(int, input().strip().split())) print(get_max_len(arr))
""" Given an array of integers what is the length of the longest subArray containing no more than two distinct values such that the distinct values differ by no more than 1 For Example: arr = [0, 1, 2, 1, 2, 3] -> length = 4; [1,2,1,2] arr = [1, 2, 3, 4, 5] -> length = 2; [1,2] arr = [1, 1, 1, 3, 3, 2, 2] -> length = 4; [3,3,2,2] arr = [1, 1, 2, 2, 1, 2, 3, 3, 2, 2, 3, 3] -> length = 7; [2, 3, 3, 2, 2, 3, 3] """ arr = list(map(int, input().strip().split())) print(get_max_len(arr))
#!/usr/bin/env python3 # # --- Day 21: Dirac Dice / Part Two --- # # Now that you're warmed up, it's time to play the real game. # # A second compartment opens, this time labeled Dirac dice. Out of it falls # a single three-sided die. # # As you experiment with the die, you feel a little strange. An informational # brochure in the compartment explains that this is a quantum die: when you # roll it, the universe splits into multiple copies, one copy for each possible # outcome of the die. In this case, rolling the die always splits the universe # into three copies: one where the outcome of the roll was 1, one where it was # 2, and one where it was 3. # # The game is played the same as before, although to prevent things from # getting too far out of hand, the game now ends when either player's score # reaches at least 21. # # Using the same starting positions as in the example above, # player 1 wins in 444356092776315 universes, while player 2 merely wins # in 341960390180808 universes. # # Using your given starting positions, determine every possible outcome. # Find the player that wins in more universes; in how many universes # does that player win? # # # --- Solution --- # # This is mostly a start from scratch... First we count the possible outcomes # from a 3 rolls and how many these outcomes happen. Then we prepare a function # that will simulate every possible way the game will go. At given positions, # scores and turn, for each possible rolls outcome, we calculate new results # and two things may happen: either we finish the game with the new scores, # or we should simulate recurrently the game with a new set of conditions. # As a result, we simply count the numbers of times there was a win for each # of all possible rolls. After about 30 seconds it gives us the right answer. # INPUT_FILE = 'input.txt' GOAL = 21 PLAYER_1 = 0 PLAYER_2 = 1 CACHE = {} def game(possibilities, positions, scores, turn=0): uuid = ((tuple(positions), tuple(scores), turn)) if uuid in CACHE: return CACHE[uuid] player = PLAYER_1 if turn % 2 == 0 else PLAYER_2 turn = (turn + 1) % 2 wins = [0, 0] for roll, times in possibilities.items(): new_positions = positions.copy() new_scores = scores.copy() new_position = (positions[player] + roll) % 10 new_positions[player] = new_position new_scores[player] += (new_position + 1) if new_scores[PLAYER_1] < GOAL and new_scores[PLAYER_2] < GOAL: win1, win2 = game(possibilities, new_positions, new_scores, turn) wins[0] += win1 * times wins[1] += win2 * times else: if new_scores[PLAYER_1] >= GOAL: wins[PLAYER_1] += times else: wins[PLAYER_2] += times CACHE[uuid] = wins return wins def main(): positions = [int(line.strip().split()[-1]) - 1 for line in open(INPUT_FILE, 'r')] scores = [0, 0] possibilities = {} # 3x roll result -> how many times it can happen for dice1 in [1, 2, 3]: for dice2 in [1, 2, 3]: for dice3 in [1, 2, 3]: result = dice1 + dice2 + dice3 if result not in possibilities: possibilities[result] = 1 else: possibilities[result] += 1 wins = game(possibilities, positions, scores, turn=0) print(max(wins)) if __name__ == '__main__': main()
input_file = 'input.txt' goal = 21 player_1 = 0 player_2 = 1 cache = {} def game(possibilities, positions, scores, turn=0): uuid = (tuple(positions), tuple(scores), turn) if uuid in CACHE: return CACHE[uuid] player = PLAYER_1 if turn % 2 == 0 else PLAYER_2 turn = (turn + 1) % 2 wins = [0, 0] for (roll, times) in possibilities.items(): new_positions = positions.copy() new_scores = scores.copy() new_position = (positions[player] + roll) % 10 new_positions[player] = new_position new_scores[player] += new_position + 1 if new_scores[PLAYER_1] < GOAL and new_scores[PLAYER_2] < GOAL: (win1, win2) = game(possibilities, new_positions, new_scores, turn) wins[0] += win1 * times wins[1] += win2 * times elif new_scores[PLAYER_1] >= GOAL: wins[PLAYER_1] += times else: wins[PLAYER_2] += times CACHE[uuid] = wins return wins def main(): positions = [int(line.strip().split()[-1]) - 1 for line in open(INPUT_FILE, 'r')] scores = [0, 0] possibilities = {} for dice1 in [1, 2, 3]: for dice2 in [1, 2, 3]: for dice3 in [1, 2, 3]: result = dice1 + dice2 + dice3 if result not in possibilities: possibilities[result] = 1 else: possibilities[result] += 1 wins = game(possibilities, positions, scores, turn=0) print(max(wins)) if __name__ == '__main__': main()
# write recursively # ie # 10 > 7+3 or 5+5 # 7+3 is done # 5+5 -> 3 + 2 + 5 # 3+ 2 + 5 -> 3 + 2 + 3 + 2 is done # if the number youre breaking is even you get 2 initially, if its odd you get 1 more sum def solve(): raise NotImplementedError if __name__ == '__main__': print(solve())
def solve(): raise NotImplementedError if __name__ == '__main__': print(solve())
# -*- mode:python; coding:utf-8 -*- # Copyright (c) 2020 IBM Corp. All rights reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """Trestle core errors module.""" class TrestleError(RuntimeError): """ General framework (non-application) related errors. Attributes: msg (str): Human readable string describing the exception. """ def __init__(self, msg: str): """Intialization for TresleError. Args: msg (str): The error message """ RuntimeError.__init__(self) self.msg = msg def __str__(self) -> str: """Return Trestle error message if asked for a string.""" return self.msg class TrestleNotFoundError(TrestleError): """ General framwork related not found error. Attributes: msg (str): Human readable string describing the exception. """ def __init__(self, msg: str): """ Intialization for TresleNotFoundError. Args: msg: The error message """ super().__init__(msg) class TrestleValidationError(TrestleError): """ General framwork related validation error. Attributes: msg (str): Human readable string describing the exception. """ def __init__(self, msg: str): """ Intialization for TresleValidationError. Args: msg (str): The error message """ super().__init__(msg)
"""Trestle core errors module.""" class Trestleerror(RuntimeError): """ General framework (non-application) related errors. Attributes: msg (str): Human readable string describing the exception. """ def __init__(self, msg: str): """Intialization for TresleError. Args: msg (str): The error message """ RuntimeError.__init__(self) self.msg = msg def __str__(self) -> str: """Return Trestle error message if asked for a string.""" return self.msg class Trestlenotfounderror(TrestleError): """ General framwork related not found error. Attributes: msg (str): Human readable string describing the exception. """ def __init__(self, msg: str): """ Intialization for TresleNotFoundError. Args: msg: The error message """ super().__init__(msg) class Trestlevalidationerror(TrestleError): """ General framwork related validation error. Attributes: msg (str): Human readable string describing the exception. """ def __init__(self, msg: str): """ Intialization for TresleValidationError. Args: msg (str): The error message """ super().__init__(msg)
guest = input() host = input() pile = input() print("YES" if sorted(pile) == sorted(guest + host) else "NO")
guest = input() host = input() pile = input() print('YES' if sorted(pile) == sorted(guest + host) else 'NO')
#!/usr/bin/env python # -*- coding: utf-8 -*- """ Bellkor.Utils """
""" Bellkor.Utils """
# -*- coding: utf-8 -*- def write_out(message): with open('/tmp/out', 'w') as f: f.write("We have triggered.") f.write(message)
def write_out(message): with open('/tmp/out', 'w') as f: f.write('We have triggered.') f.write(message)
class Arithmatic: #This function does adding to integer def Add(self, x, y): return x + y #This fnction does su def Subtraction(self, x, y): return x - y
class Arithmatic: def add(self, x, y): return x + y def subtraction(self, x, y): return x - y
def category(cat): def set_cat(cmd): cmd.category = cat.title() return cmd return set_cat
def category(cat): def set_cat(cmd): cmd.category = cat.title() return cmd return set_cat
''' File to calculate the Budget associated with new motorcycle ''' class Budget(object): def __init__(self): self.price = 13000 self.years = 5 self.interet = 7 def pvtx(self): """Calcul of the provincial tax on sale price""" return self.price * 0.0975 def fdtx(self): """Calcul of the Federal taxe on sale price""" return self.price * 0.05 def comtx(self): """Calcul taxe for a Commercial transaction""" return self.fdtx() + self.pvtx() def totalpv(self): """Calcul Total price for a Private transaction""" return self.price + self.pvtx() def totalcom(self): """Calcul Total price for a Commercial Transaction""" return self.price + self.comtx() def payment(self): """Calculate payment for for a commercial transaction""" month = float(self.years) * 12 interest_rate = float(self.interet) / 100 / 12 # Formula to calculate monthly payments return self.totalcom() * (interest_rate * (1 + interest_rate) ** month) / ((1 + interest_rate) ** month - 1) def promp_int(self, msg): """ General def to ask for user for information DO NOT CALL DIRECLY """ while True: try: x = int(input(msg)) break except: print("That's not a valid number") return x def set_price(self): """Call to change the price of the item""" msg = 'What is the price of the item?' self.price = self.promp_int(msg) def set_interest(self): """Call to change the interest rate""" msg = 'What is the interest for the loan?' self.interet = self.promp_int(msg) def set_years(self): """Call to change the ammoritssmeent""" msg = 'How long is the amortissement (years)?' self.years = self.promp_int(msg)
""" File to calculate the Budget associated with new motorcycle """ class Budget(object): def __init__(self): self.price = 13000 self.years = 5 self.interet = 7 def pvtx(self): """Calcul of the provincial tax on sale price""" return self.price * 0.0975 def fdtx(self): """Calcul of the Federal taxe on sale price""" return self.price * 0.05 def comtx(self): """Calcul taxe for a Commercial transaction""" return self.fdtx() + self.pvtx() def totalpv(self): """Calcul Total price for a Private transaction""" return self.price + self.pvtx() def totalcom(self): """Calcul Total price for a Commercial Transaction""" return self.price + self.comtx() def payment(self): """Calculate payment for for a commercial transaction""" month = float(self.years) * 12 interest_rate = float(self.interet) / 100 / 12 return self.totalcom() * (interest_rate * (1 + interest_rate) ** month) / ((1 + interest_rate) ** month - 1) def promp_int(self, msg): """ General def to ask for user for information DO NOT CALL DIRECLY """ while True: try: x = int(input(msg)) break except: print("That's not a valid number") return x def set_price(self): """Call to change the price of the item""" msg = 'What is the price of the item?' self.price = self.promp_int(msg) def set_interest(self): """Call to change the interest rate""" msg = 'What is the interest for the loan?' self.interet = self.promp_int(msg) def set_years(self): """Call to change the ammoritssmeent""" msg = 'How long is the amortissement (years)?' self.years = self.promp_int(msg)
# Copyright (C) 2018 Garth N. Wells # # SPDX-License-Identifier: MIT """This module contains utility functions.""" def sorted_by_key(x, i, reverse=False): """For a list of lists/tuples, return list sorted by the ith component of the list/tuple, Examples: Sort on first entry of tuple: >>> sorted_by_key([(1, 2), (5, 1)], 0) [(1, 2), (5, 1)] Sort on second entry of tuple: >>> sorted_by_key([(1, 2), (5, 1)], 1) [(5, 1), (1, 2)] Args: x (list): A list of lists/tuples to be sorted i (int): Sort according to which element of the inner lists/tuples reverse (bool, optional): Default False Returns: list: Sorted list of lists/tuples """ return sorted(x, key=lambda x: x[i], reverse=reverse)
"""This module contains utility functions.""" def sorted_by_key(x, i, reverse=False): """For a list of lists/tuples, return list sorted by the ith component of the list/tuple, Examples: Sort on first entry of tuple: >>> sorted_by_key([(1, 2), (5, 1)], 0) [(1, 2), (5, 1)] Sort on second entry of tuple: >>> sorted_by_key([(1, 2), (5, 1)], 1) [(5, 1), (1, 2)] Args: x (list): A list of lists/tuples to be sorted i (int): Sort according to which element of the inner lists/tuples reverse (bool, optional): Default False Returns: list: Sorted list of lists/tuples """ return sorted(x, key=lambda x: x[i], reverse=reverse)
class Solution: def isAdditiveNumber(self, num: str) -> bool: def isValid(str1, str2, num): if not num: return True res = str(int(str1) + int(str2)) # print(str1, str2, res, num) str1, str2 = str2, res l = len(res) return num.startswith(res) and isValid(str1, str2, num[l:]) n = len(num) for i in range(1, n // 2 + 1): if num[0] == '0' and i > 1: return False sub1 = num[:i] for j in range(1, n): if max(i, j) > n - i - j: break if num[i] == '0' and j > 1: break sub2 = num[i:i + j] if isValid(sub1, sub2, num[i + j:]): return True return False
class Solution: def is_additive_number(self, num: str) -> bool: def is_valid(str1, str2, num): if not num: return True res = str(int(str1) + int(str2)) (str1, str2) = (str2, res) l = len(res) return num.startswith(res) and is_valid(str1, str2, num[l:]) n = len(num) for i in range(1, n // 2 + 1): if num[0] == '0' and i > 1: return False sub1 = num[:i] for j in range(1, n): if max(i, j) > n - i - j: break if num[i] == '0' and j > 1: break sub2 = num[i:i + j] if is_valid(sub1, sub2, num[i + j:]): return True return False
if __name__ == '__main__': if (1!=1) : print("IF") else : print("InnerElse") else: print("OuterElse")
if __name__ == '__main__': if 1 != 1: print('IF') else: print('InnerElse') else: print('OuterElse')
num = int(input()) lista = [[0] * num for i in range(num)] for i in range(num): for j in range(num): if i < j: lista[i][j] = 0 elif i > j: lista[i][j] = 2 else: lista[i][j] = 1 for r in lista: print(' '.join([str(elem) for elem in r]))
num = int(input()) lista = [[0] * num for i in range(num)] for i in range(num): for j in range(num): if i < j: lista[i][j] = 0 elif i > j: lista[i][j] = 2 else: lista[i][j] = 1 for r in lista: print(' '.join([str(elem) for elem in r]))
def aumentar(preco=0, taxa=0, formato=False): res = preco + (preco * taxa/100) return res if formato is False else moeda(res) def diminuir(preco=0, taxa=0, formato=False): res = preco - (preco * taxa/100) return res if formato is False else moeda(res) def dobro(preco=0, formato=False): res = preco * 2 return res if not formato else moeda(res) def metade(preco=0, formato=False): res = preco / 2 return res if not formato else moeda(res) def moeda(p=0, m='R$'): return f'{m}{p:>.2f}' .replace('.', ',')
def aumentar(preco=0, taxa=0, formato=False): res = preco + preco * taxa / 100 return res if formato is False else moeda(res) def diminuir(preco=0, taxa=0, formato=False): res = preco - preco * taxa / 100 return res if formato is False else moeda(res) def dobro(preco=0, formato=False): res = preco * 2 return res if not formato else moeda(res) def metade(preco=0, formato=False): res = preco / 2 return res if not formato else moeda(res) def moeda(p=0, m='R$'): return f'{m}{p:>.2f}'.replace('.', ',')
# Copyright 2014 Metaswitch Networks # # 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. class StubNetworkSubscriber(object): """ Stub version of the Network Subscriber class. The methods prefixed test_ are for unit test script use. """ def __init__(self, network_store): self.network_store = network_store def test_update_group(self, group_uuid, members, rules): """ Pass a group update message to the Network Store. - group_uuid: The UUID of the group to create / update - members: A dictionary {endpoint_uuid: [endpoint IPs], ...} - rules: A rules object (see Calico API Proposal) """ self.network_store.update_group(group_uuid, members, rules)
class Stubnetworksubscriber(object): """ Stub version of the Network Subscriber class. The methods prefixed test_ are for unit test script use. """ def __init__(self, network_store): self.network_store = network_store def test_update_group(self, group_uuid, members, rules): """ Pass a group update message to the Network Store. - group_uuid: The UUID of the group to create / update - members: A dictionary {endpoint_uuid: [endpoint IPs], ...} - rules: A rules object (see Calico API Proposal) """ self.network_store.update_group(group_uuid, members, rules)
def test(): # Here we can either check objects created in the solution code, or the # string value of the solution, available as __solution__. A helper for # printing formatted messages is available as __msg__. See the testTemplate # in the meta.json for details. # If an assertion fails, the message will be displayed assert first_author_name == dataset_description["Authors"][0]["Name"],\ 'That is not the authors name from the original dictionary' assert "first_author_name = output" in __solution__,\ 'Did you just typed the name in?' __msg__.good("Well done!")
def test(): assert first_author_name == dataset_description['Authors'][0]['Name'], 'That is not the authors name from the original dictionary' assert 'first_author_name = output' in __solution__, 'Did you just typed the name in?' __msg__.good('Well done!')
class PartyAnimal: x = 0 def party(self): self.x = self.x + 1 print(f'So far {self.x}') an = PartyAnimal() an.party() an.party() an.party() print(dir(an))
class Partyanimal: x = 0 def party(self): self.x = self.x + 1 print(f'So far {self.x}') an = party_animal() an.party() an.party() an.party() print(dir(an))
with open("./build-scripts/opcodes.txt", "r") as f: opcodes = f.readlines() opcodes_h = open("./src/core/bc_data/opcodes.txt", "w") opcodes_h.write("enum au_opcode {\n") callbacks_h = open("./src/core/bc_data/callbacks.txt", "w") callbacks_h.write("static void *cb[] = {\n") dbg_h = open("./src/core/bc_data/dbg.txt", "w") dbg_h.write("const char *au_opcode_dbg[AU_MAX_OPCODE] = {\n") num_opcodes = 0 for opcode in opcodes: if opcode == "\n" or opcode.startswith("#"): continue opcode = opcode.strip() opcodes_h.write(f"AU_OP_{opcode} = {num_opcodes},\n") callbacks_h.write(f"&&CASE(AU_OP_{opcode}),\n") dbg_h.write(f"\"{opcode}\",\n") num_opcodes += 1 opcodes_h.write("};\n") callbacks_h.write("};\n") dbg_h.write("};\n")
with open('./build-scripts/opcodes.txt', 'r') as f: opcodes = f.readlines() opcodes_h = open('./src/core/bc_data/opcodes.txt', 'w') opcodes_h.write('enum au_opcode {\n') callbacks_h = open('./src/core/bc_data/callbacks.txt', 'w') callbacks_h.write('static void *cb[] = {\n') dbg_h = open('./src/core/bc_data/dbg.txt', 'w') dbg_h.write('const char *au_opcode_dbg[AU_MAX_OPCODE] = {\n') num_opcodes = 0 for opcode in opcodes: if opcode == '\n' or opcode.startswith('#'): continue opcode = opcode.strip() opcodes_h.write(f'AU_OP_{opcode} = {num_opcodes},\n') callbacks_h.write(f'&&CASE(AU_OP_{opcode}),\n') dbg_h.write(f'"{opcode}",\n') num_opcodes += 1 opcodes_h.write('};\n') callbacks_h.write('};\n') dbg_h.write('};\n')
""" Iterable - __iter__() or __getitem__() Iterator - __next__() Iteration - """ def gen(n): for i in range(n): yield i #g = gen(89765456432165464988789465456421321564578979874654654613216547897894654) # dont print number upto n number print location # print(g) g = gen(4) print(g.__next__()) print(g.__next__()) print(g.__next__()) print(g.__next__())
""" Iterable - __iter__() or __getitem__() Iterator - __next__() Iteration - """ def gen(n): for i in range(n): yield i g = gen(4) print(g.__next__()) print(g.__next__()) print(g.__next__()) print(g.__next__())
# lets make a Player class class Player: def __init__(self, name, starting_room): self.name = name self.current_room = starting_room
class Player: def __init__(self, name, starting_room): self.name = name self.current_room = starting_room
#!/usr/local/bin/python3 # Frequency queries def freqQuery(queries): result = [] numbers = {} occurrences = {} for operation, value in queries: if operation == 1: quantity = numbers.get(value, 0) if quantity > 0: occurrences[quantity] = occurrences[quantity] - 1 numbers[value] = numbers.get(value, 0) + 1 occurrences[numbers[value]] = occurrences.get(numbers[value], 0) + 1 elif operation == 2: quantity = numbers.get(value, 0) if quantity > 0: numbers[value] = quantity - 1 occurrences[quantity] = occurrences[quantity] - 1 occurrences[quantity - 1] = occurrences.get(quantity - 1, 0) + 1 else: result.append(1) if occurrences.get(value) else result.append(0) return result
def freq_query(queries): result = [] numbers = {} occurrences = {} for (operation, value) in queries: if operation == 1: quantity = numbers.get(value, 0) if quantity > 0: occurrences[quantity] = occurrences[quantity] - 1 numbers[value] = numbers.get(value, 0) + 1 occurrences[numbers[value]] = occurrences.get(numbers[value], 0) + 1 elif operation == 2: quantity = numbers.get(value, 0) if quantity > 0: numbers[value] = quantity - 1 occurrences[quantity] = occurrences[quantity] - 1 occurrences[quantity - 1] = occurrences.get(quantity - 1, 0) + 1 else: result.append(1) if occurrences.get(value) else result.append(0) return result
#GuestList: names = ['tony','steve','thor'] message = ", You are invited!" print(names[0]+message) print(names[1]+message) print(names[2]+message)
names = ['tony', 'steve', 'thor'] message = ', You are invited!' print(names[0] + message) print(names[1] + message) print(names[2] + message)
general = { 'provide-edep-targets' : True, } edeps = { 'zmdep-b' : { 'rootdir': '../zmdep-b', 'export-includes' : '../zmdep-b', 'buildtypes-map' : { 'debug' : 'mydebug', 'release' : 'myrelease', }, }, } subdirs = [ 'libs/core', 'libs/engine' ] tasks = { 'main' : { 'features' : 'cxxprogram', 'source' : 'main/main.cpp', 'includes' : 'libs', 'use' : 'engine zmdep-b:service', 'rpath' : '.', 'configure' : [ dict(do = 'check-headers', names = 'iostream'), ], }, } buildtypes = { 'debug' : { 'cflags.select' : { 'default': '-fPIC -O0 -g', # gcc/clang 'msvc' : '/Od', }, }, 'release' : { 'cflags.select' : { 'default': '-fPIC -O2', # gcc/clang 'msvc' : '/O2', }, }, 'default' : 'debug', }
general = {'provide-edep-targets': True} edeps = {'zmdep-b': {'rootdir': '../zmdep-b', 'export-includes': '../zmdep-b', 'buildtypes-map': {'debug': 'mydebug', 'release': 'myrelease'}}} subdirs = ['libs/core', 'libs/engine'] tasks = {'main': {'features': 'cxxprogram', 'source': 'main/main.cpp', 'includes': 'libs', 'use': 'engine zmdep-b:service', 'rpath': '.', 'configure': [dict(do='check-headers', names='iostream')]}} buildtypes = {'debug': {'cflags.select': {'default': '-fPIC -O0 -g', 'msvc': '/Od'}}, 'release': {'cflags.select': {'default': '-fPIC -O2', 'msvc': '/O2'}}, 'default': 'debug'}
#exercicio 63 termos = int(input('Quantos termos vc quer na sequencia de fibonacci? ')) c = 1 sequencia = 1 sequencia2 = 0 while c != termos: fi = (sequencia+sequencia2) - ((sequencia+sequencia2)-sequencia2) print ('{}'.format(fi), end='- ') sequencia += sequencia2 sequencia2 = sequencia - sequencia2 c += 1
termos = int(input('Quantos termos vc quer na sequencia de fibonacci? ')) c = 1 sequencia = 1 sequencia2 = 0 while c != termos: fi = sequencia + sequencia2 - (sequencia + sequencia2 - sequencia2) print('{}'.format(fi), end='- ') sequencia += sequencia2 sequencia2 = sequencia - sequencia2 c += 1
##Create a target array in the given order def generate_target_array(nums, index): length_of_num = len(nums) target_array = [] for i in range(0, length_of_num): if index[i] >= length_of_num: target_array.append(nums[i]) else: target_array.insert(index[i], nums[i]) return target_array if __name__ == "__main__": nums = [0, 1, 2, 3, 4] index = [0, 1, 2, 2, 1] print(*generate_target_array(nums, index))
def generate_target_array(nums, index): length_of_num = len(nums) target_array = [] for i in range(0, length_of_num): if index[i] >= length_of_num: target_array.append(nums[i]) else: target_array.insert(index[i], nums[i]) return target_array if __name__ == '__main__': nums = [0, 1, 2, 3, 4] index = [0, 1, 2, 2, 1] print(*generate_target_array(nums, index))
class ExtractedItem: def __init__(self, _id=None, field_name=None, data=None): self.data = data if data else None self._id = _id self.field_name = field_name def get_dict(self): """ returns the data in json format :return: """ if self.field_name: return { self.field_name: self.data } else: return self.data def __repr__(self): return "<ExtractedItem field_name=\"{field_name}\" data=\"{data}\" >".format( field_name=self.field_name, data=self.data )
class Extracteditem: def __init__(self, _id=None, field_name=None, data=None): self.data = data if data else None self._id = _id self.field_name = field_name def get_dict(self): """ returns the data in json format :return: """ if self.field_name: return {self.field_name: self.data} else: return self.data def __repr__(self): return '<ExtractedItem field_name="{field_name}" data="{data}" >'.format(field_name=self.field_name, data=self.data)
""" Module: 'uasyncio.core' on pyboard 1.13.0-95 """ # MCU: (sysname='pyboard', nodename='pyboard', release='1.13.0', version='v1.13-95-g0fff2e03f on 2020-10-03', machine='PYBv1.1 with STM32F405RG') # Stubber: 1.3.4 class CancelledError: '' class IOQueue: '' def _dequeue(): pass def _enqueue(): pass def queue_read(): pass def queue_write(): pass def remove(): pass def wait_io_event(): pass class Loop: '' _exc_handler = None def call_exception_handler(): pass def close(): pass def create_task(): pass def default_exception_handler(): pass def get_exception_handler(): pass def run_forever(): pass def run_until_complete(): pass def set_exception_handler(): pass def stop(): pass class SingletonGenerator: '' class Task: ''
""" Module: 'uasyncio.core' on pyboard 1.13.0-95 """ class Cancellederror: """""" class Ioqueue: """""" def _dequeue(): pass def _enqueue(): pass def queue_read(): pass def queue_write(): pass def remove(): pass def wait_io_event(): pass class Loop: """""" _exc_handler = None def call_exception_handler(): pass def close(): pass def create_task(): pass def default_exception_handler(): pass def get_exception_handler(): pass def run_forever(): pass def run_until_complete(): pass def set_exception_handler(): pass def stop(): pass class Singletongenerator: """""" class Task: """"""