content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
t = int(input()) for _ in range(t): a, b = [int(x) for x in input().split()] print(a * b)
t = int(input()) for _ in range(t): (a, b) = [int(x) for x in input().split()] print(a * b)
"""Rules to work with protoc plugins in a language agnostic manner. """ load("@bazel_skylib//lib:paths.bzl", "paths") load("@rules_proto//proto:defs.bzl", "ProtoInfo") load("//protoc:providers.bzl", "ProtocPluginInfo") _DEFAULT_PROTOC = "@com_google_protobuf//:protoc" def run_protoc( ctx, protos, protoc, plugin, options, outputs, plugin_out = ".", data = []): """Run protoc with a plugin. Args: ctx: The Bazel context used to create actions. protos (list of ProtoInfo): The proto libraries to generate code for. protoc (executable): The protoc executable. plugin (executable): The plugin executable. options (list of str): List of options passed to the plugin. outputs (list of File): List of files that are going to be generated by the plugin. plugin_out (str): The output root to generate the files to. This will be passed as --<plugin-name>_out=<plugin_out> to the protoc executable. data (depset of File): Additional files added to the action as inputs. """ # Merge proto root paths of all protos. Each proto root path will be passed # with the --proto_path (-I) option to protoc. proto_roots = depset(transitive = [p.transitive_proto_path for p in protos]) args = ctx.actions.args() for root in proto_roots.to_list(): args.add("--proto_path=" + root) # actually name does not matter name = plugin.basename.replace(".exe", "") args.add("--plugin=protoc-gen-" + name + "=" + plugin.path) # Add the output prefix. Protoc will put all files that the plugin returns # other this folder. E.g. a retuned file `a/b/c.pb.go` will then be placed # and thus be generated under `<plugin_out>/a/b/c.pb.go`. # The user provided plugin_out is relative to the workspace directory. Join # with the Bazel bin directory to generate the output where it is expected # by Bazel (bazel-out/{arch}/bin/<plugin_out>). plugin_out = paths.join(ctx.bin_dir.path, plugin_out) args.add("--" + name + "_out=" + plugin_out) # Add option arguments. for opt in options: args.add("--" + name + "_opt=" + opt) # Direct sources that are requested on command line. For these corresponding # files will be generated. for proto in protos: args.add_all(proto.direct_sources) # Collect inputs. direct_sources = [] # list of File for proto in protos: direct_sources.extend(proto.direct_sources) transitive_sources = [p.transitive_sources for p in protos] # list of depsets inputs = depset(direct_sources, transitive = transitive_sources + [data]) # data is a depset ctx.actions.run_shell( inputs = inputs, outputs = outputs, command = "mkdir -p {} && {} $@".format(plugin_out, protoc.path), arguments = [args], mnemonic = "ProtocPlugins", tools = [protoc, plugin], progress_message = "Generating plugin output in {}".format(plugin_out), ) def _protoc_output_impl(ctx): protos = [p[ProtoInfo] for p in ctx.attr.protos] # Default the plugin_out parameter to <rule_dir>/<target_name> if not specified. plugin_out = ctx.attr.plugin_out if plugin_out == "": plugin_out = paths.join(ctx.label.package, ctx.label.name) # Call the plugin provided output function to obtain the filenames that the plugin # is going to generated. See the documentation of ProtocPluginInfo for more information # how that works. plugin_info = ctx.attr.plugin[ProtocPluginInfo] filenames = plugin_info.outputs(protos, ctx.attr.outputs, **plugin_info.outputs_kwargs) outputs = [] for file in filenames: out_full_name = paths.join(plugin_out, file) if not out_full_name.startswith(ctx.label.package): fail("""Trying to generate an output file named \"{}\" that is not under the current package \"{}/\". Bazel requires files to be generated in/below the package of their corresponging rule.""".format(out_name, ctx.label.package)) # Make the output path relative to ctx.label.package. When declaring files # with ctx.actions.declare_file the file is always assumed to be relative # to the current package. out_name = paths.relativize(out_full_name, ctx.label.package) out = ctx.actions.declare_file(out_name) outputs.append(out) expanded_options = [] for opt in ctx.attr.options: # TODO: $(locations ...) produces a space-separated list of output paths, # this must somewhat be handeled since it is passed directly to the # command line via "key=value value value". expanded_options.append(ctx.expand_location(opt, ctx.attr.data)) run_protoc( ctx = ctx, protos = protos, protoc = ctx.executable.protoc, plugin = plugin_info.executable, outputs = outputs, options = expanded_options + plugin_info.default_options, plugin_out = plugin_out, data = depset(ctx.files.data, transitive = [plugin_info.runfiles.files]), ) return DefaultInfo(files = depset(outputs)) protoc_output = rule( implementation = _protoc_output_impl, doc = """Runs a protoc plugin.""", attrs = { "protos": attr.label_list( doc = "The proto libraries to generate code for.", providers = [ProtoInfo], allow_empty = False, ), "plugin": attr.label( doc = "The plugin to run.", providers = [ProtocPluginInfo], mandatory = True, ), "outputs": attr.string_list( doc = """Optional output attributes passed to the plugins. For plugin that define the their outputs using predeclared outputs, this is the list of predeclared outputs. See ProtocPluginInfo.output for more information.""", ), "options": attr.string_list( doc = """Options passed to the plugin. For example: `["x=3", "y=5"]` will be passed as ``` --<plugin-name>_opt=x=3 --<plugin-name>_opt=y=5 ``` to the command line line when running protoc with the plugin (`<plugin-name>`). The `options` are subject to ctx.expanded_locations: For example, use ``` "config=$(location :my_data_file)" ``` to obtain the runfile location of `:my_data_file` and passed it as `config` option to the plugin. `:my_data_file` must be passed in the `data` attribute for the expansion to work. Do not use the `locations` (note the `s`) directive. """, ), "data": attr.label_list( doc = "Files added to the actions execution environment such that the plugin can access them.", allow_files = True, ), "plugin_out": attr.string( default = "", doc = """The output root to generate the files to. This will be passed as --<plugin-name>_out=<plugin_out> to the protoc executable. Defaults to `<bazel_package>/<target_name>/`. When using a different value, this will affect where to plugin generates its outputs files to. Each file that the plugin returns will be placed under `<plugin_out>/<generated_filename>`. Bazel requires that all files must be generated under the current Bazel package, so when setting `plugin_out` set it in a way that the resulting outputs are generated accordingly.""", ), "protoc": attr.label( executable = True, doc = "The protoc executable.", cfg = "exec", allow_files = True, default = Label(_DEFAULT_PROTOC), ), }, )
"""Rules to work with protoc plugins in a language agnostic manner. """ load('@bazel_skylib//lib:paths.bzl', 'paths') load('@rules_proto//proto:defs.bzl', 'ProtoInfo') load('//protoc:providers.bzl', 'ProtocPluginInfo') _default_protoc = '@com_google_protobuf//:protoc' def run_protoc(ctx, protos, protoc, plugin, options, outputs, plugin_out='.', data=[]): """Run protoc with a plugin. Args: ctx: The Bazel context used to create actions. protos (list of ProtoInfo): The proto libraries to generate code for. protoc (executable): The protoc executable. plugin (executable): The plugin executable. options (list of str): List of options passed to the plugin. outputs (list of File): List of files that are going to be generated by the plugin. plugin_out (str): The output root to generate the files to. This will be passed as --<plugin-name>_out=<plugin_out> to the protoc executable. data (depset of File): Additional files added to the action as inputs. """ proto_roots = depset(transitive=[p.transitive_proto_path for p in protos]) args = ctx.actions.args() for root in proto_roots.to_list(): args.add('--proto_path=' + root) name = plugin.basename.replace('.exe', '') args.add('--plugin=protoc-gen-' + name + '=' + plugin.path) plugin_out = paths.join(ctx.bin_dir.path, plugin_out) args.add('--' + name + '_out=' + plugin_out) for opt in options: args.add('--' + name + '_opt=' + opt) for proto in protos: args.add_all(proto.direct_sources) direct_sources = [] for proto in protos: direct_sources.extend(proto.direct_sources) transitive_sources = [p.transitive_sources for p in protos] inputs = depset(direct_sources, transitive=transitive_sources + [data]) ctx.actions.run_shell(inputs=inputs, outputs=outputs, command='mkdir -p {} && {} $@'.format(plugin_out, protoc.path), arguments=[args], mnemonic='ProtocPlugins', tools=[protoc, plugin], progress_message='Generating plugin output in {}'.format(plugin_out)) def _protoc_output_impl(ctx): protos = [p[ProtoInfo] for p in ctx.attr.protos] plugin_out = ctx.attr.plugin_out if plugin_out == '': plugin_out = paths.join(ctx.label.package, ctx.label.name) plugin_info = ctx.attr.plugin[ProtocPluginInfo] filenames = plugin_info.outputs(protos, ctx.attr.outputs, **plugin_info.outputs_kwargs) outputs = [] for file in filenames: out_full_name = paths.join(plugin_out, file) if not out_full_name.startswith(ctx.label.package): fail('Trying to generate an output file named "{}" that is not under the current package "{}/".\nBazel requires files to be generated in/below the package of their corresponging rule.'.format(out_name, ctx.label.package)) out_name = paths.relativize(out_full_name, ctx.label.package) out = ctx.actions.declare_file(out_name) outputs.append(out) expanded_options = [] for opt in ctx.attr.options: expanded_options.append(ctx.expand_location(opt, ctx.attr.data)) run_protoc(ctx=ctx, protos=protos, protoc=ctx.executable.protoc, plugin=plugin_info.executable, outputs=outputs, options=expanded_options + plugin_info.default_options, plugin_out=plugin_out, data=depset(ctx.files.data, transitive=[plugin_info.runfiles.files])) return default_info(files=depset(outputs)) protoc_output = rule(implementation=_protoc_output_impl, doc='Runs a protoc plugin.', attrs={'protos': attr.label_list(doc='The proto libraries to generate code for.', providers=[ProtoInfo], allow_empty=False), 'plugin': attr.label(doc='The plugin to run.', providers=[ProtocPluginInfo], mandatory=True), 'outputs': attr.string_list(doc='Optional output attributes passed to the plugins.\n\nFor plugin that define the their outputs using predeclared outputs,\nthis is the list of predeclared outputs.\n\nSee ProtocPluginInfo.output for more information.'), 'options': attr.string_list(doc='Options passed to the plugin.\nFor example: `["x=3", "y=5"]` will be passed as \n\n```\n--<plugin-name>_opt=x=3 --<plugin-name>_opt=y=5\n``` \n\nto the command line line when running protoc with the plugin (`<plugin-name>`).\nThe `options` are subject to ctx.expanded_locations: For example, use \n\n```\n"config=$(location :my_data_file)"\n```\n\nto obtain the runfile location of `:my_data_file` and passed it as `config` option to the plugin.\n`:my_data_file` must be passed in the `data` attribute for the expansion to work.\nDo not use the `locations` (note the `s`) directive.\n'), 'data': attr.label_list(doc='Files added to the actions execution environment such that the plugin can access them.', allow_files=True), 'plugin_out': attr.string(default='', doc='The output root to generate the files to. This will be passed as --<plugin-name>_out=<plugin_out> to the protoc executable.\n\nDefaults to `<bazel_package>/<target_name>/`.\nWhen using a different value, this will affect where to plugin generates its outputs files to.\nEach file that the plugin returns will be placed under `<plugin_out>/<generated_filename>`.\nBazel requires that all files must be generated under the current Bazel package,\nso when setting `plugin_out` set it in a way that the resulting outputs are generated accordingly.'), 'protoc': attr.label(executable=True, doc='The protoc executable.', cfg='exec', allow_files=True, default=label(_DEFAULT_PROTOC))})
class Solution: def combinationSum2(self, candidates: List[int], target: int) -> List[List[int]]: res = [] candidates.sort() def backtrack(pos,cur,target): if target == 0 : res.append(cur.copy()) if target <= 0 : return prev = -1 for i in range(pos,len(candidates)): if candidates[i] == prev : continue cur.append(candidates[i]) backtrack(i+1,cur,target - candidates[i] ) cur.pop() prev = candidates[i] backtrack(0,[],target) return res
class Solution: def combination_sum2(self, candidates: List[int], target: int) -> List[List[int]]: res = [] candidates.sort() def backtrack(pos, cur, target): if target == 0: res.append(cur.copy()) if target <= 0: return prev = -1 for i in range(pos, len(candidates)): if candidates[i] == prev: continue cur.append(candidates[i]) backtrack(i + 1, cur, target - candidates[i]) cur.pop() prev = candidates[i] backtrack(0, [], target) return res
class NumString: def __init__(self, value): self.value = str(value) def __str__(self): return self.value def __int__(self): return int(self.value) def __float__(self): return float(self.value) #EXAMPLE: NumString(5) + 5 = 10 def __add__(self, other): if '.' in self.value: return float(self) + other return int(self) + other #If you reflect your addition, this method will reflect it again so the __add__ method can be used #EXAMPLE: 2 + NumString(5) becomes NumString(5) + 2 def __radd__(self, other): return self + other #will store a calculated self.value and therefore change the instance of NumString #EXAMPLE: NumString(25) += 5 will change Numstring(25) into Numstring(30) def __iadd__(self, other): self.value = self + other return self.value
class Numstring: def __init__(self, value): self.value = str(value) def __str__(self): return self.value def __int__(self): return int(self.value) def __float__(self): return float(self.value) def __add__(self, other): if '.' in self.value: return float(self) + other return int(self) + other def __radd__(self, other): return self + other def __iadd__(self, other): self.value = self + other return self.value
# import time def slowprint(string): for letter in string: print(letter, end='') # time.sleep(.05)
def slowprint(string): for letter in string: print(letter, end='')
def prob1(): sum = 0 i = 1 for i in range(1000): if (((i % 3) == 0) or ((i % 5) == 0)): sum = sum +i print(sum) print(i) if __name__ == "__main__": print("Project Euler Problem 1") prob1()
def prob1(): sum = 0 i = 1 for i in range(1000): if i % 3 == 0 or i % 5 == 0: sum = sum + i print(sum) print(i) if __name__ == '__main__': print('Project Euler Problem 1') prob1()
# String Formation ''' Given an array of strings, each of the same length and a target string construct the target string using characters from the strings in the given array such that the indices of the characters in the order in which they are used to form a strictly increasing sequence. Here the index of character is the position at which it appears in the string. Note that it is acceptable to use multiple characters from the same string. Determine the number of ways to construct the target string. One construction is different from another if either the sequences of indices they use are different, or the sequences are same but there exists a character at some index such that it is chosen from a different string in these constructions. Since the answer can be very large, return the value modulo (10^9 + 7). ''' # mod = 1000000007 mod = 10 ** 9 + 7 dp = [[-1 for i in range(1000)] for j in range(1000)] def calculate(pos, prev, s, index): if pos == len(s): return 1 if dp[pos][prev] != -1: return dp[pos][prev] c = ord(s[pos]) - ord('a'); answer = 0 for i in range(len(index[c])): if index[c][i] > prev: answer = (answer % mod + calculate(pos + 1, index[c][i], s, index) % mod) % mod dp[pos][prev] = answer # Store and return the solution for this subproblem return dp[pos][prev] def countWays(a, s): n = len(a) index = [[] for i in range(26)] for i in range(n): for j in range(len(a[i])): index[ord(a[i][j]) - ord('a')].append(j + 1) return calculate(0, 0, s, index) # Driver Code if __name__ == '__main__': A = [] A.append("adc") A.append("aec") A.append("erg") S = "ac" # A = ["valya", "lyglb", "vldoh"] # S = "val" # A = ["xzu", "dfw", "eor", "mat", "jyc"] # S = "cf" # A = ["afsdc", "aeeeedc", "ddegerg"] # S = "ae" print(countWays(A, S))
""" Given an array of strings, each of the same length and a target string construct the target string using characters from the strings in the given array such that the indices of the characters in the order in which they are used to form a strictly increasing sequence. Here the index of character is the position at which it appears in the string. Note that it is acceptable to use multiple characters from the same string. Determine the number of ways to construct the target string. One construction is different from another if either the sequences of indices they use are different, or the sequences are same but there exists a character at some index such that it is chosen from a different string in these constructions. Since the answer can be very large, return the value modulo (10^9 + 7). """ mod = 10 ** 9 + 7 dp = [[-1 for i in range(1000)] for j in range(1000)] def calculate(pos, prev, s, index): if pos == len(s): return 1 if dp[pos][prev] != -1: return dp[pos][prev] c = ord(s[pos]) - ord('a') answer = 0 for i in range(len(index[c])): if index[c][i] > prev: answer = (answer % mod + calculate(pos + 1, index[c][i], s, index) % mod) % mod dp[pos][prev] = answer return dp[pos][prev] def count_ways(a, s): n = len(a) index = [[] for i in range(26)] for i in range(n): for j in range(len(a[i])): index[ord(a[i][j]) - ord('a')].append(j + 1) return calculate(0, 0, s, index) if __name__ == '__main__': a = [] A.append('adc') A.append('aec') A.append('erg') s = 'ac' print(count_ways(A, S))
# colors.py # # GameGenerator is free to use, modify, and redistribute for any purpose # that is both educational and non-commercial, as long as this paragraph # remains unmodified and in its entirety in a prominent place in all # significant portions of the final code. No warranty, express or # implied, is made regarding the merchantability, fitness for a # particular purpose, or any other aspect of the software contained in # this module. """This file contains some basic colors for you to use in your game if you so choose. Or you can use colors from the huge list included with Pygame, or type your own. Up to you. """ BLACK = (0, 0, 0) WHITE = (255, 255, 255) GRAY = (127, 127, 127) DARK_GRAY = (31, 31, 31) MEDIUM_DARK_GRAY = (63, 63, 63) MEDIUM_LIGHT_GRAY = (180, 180, 180) LIGHT_GRAY = (236, 236, 236) RED = (255, 0, 0) MAROON = (102, 0, 0) PINK = (255, 204, 204) GREEN = (0, 255, 0) DARK_GREEN = (51, 102, 0) LIGHT_GREEN = (204, 255, 153) BLUE = (0, 0, 255) DARK_BLUE = (0, 51, 102) LIGHT_BLUE = (153, 204, 255) CYAN = (0, 255, 255) TEAL = (0, 153, 153) MAGENTA = (255, 0, 255) FUCSIA = (255, 0, 127) YELLOW = (255, 255, 0) ORANGE = (255, 128, 0) BROWN = (153, 76, 0) PURPLE = (102, 0, 204)
"""This file contains some basic colors for you to use in your game if you so choose. Or you can use colors from the huge list included with Pygame, or type your own. Up to you. """ black = (0, 0, 0) white = (255, 255, 255) gray = (127, 127, 127) dark_gray = (31, 31, 31) medium_dark_gray = (63, 63, 63) medium_light_gray = (180, 180, 180) light_gray = (236, 236, 236) red = (255, 0, 0) maroon = (102, 0, 0) pink = (255, 204, 204) green = (0, 255, 0) dark_green = (51, 102, 0) light_green = (204, 255, 153) blue = (0, 0, 255) dark_blue = (0, 51, 102) light_blue = (153, 204, 255) cyan = (0, 255, 255) teal = (0, 153, 153) magenta = (255, 0, 255) fucsia = (255, 0, 127) yellow = (255, 255, 0) orange = (255, 128, 0) brown = (153, 76, 0) purple = (102, 0, 204)
#!/usr/bin/env python grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] #grid[0][0] grid[1][0] grid[2][0] #grid[0][1] grid[1][1] grid[2][1] for i in range(len(grid[0])): for j in range(len(grid)): print(grid[j][i], end='') print('')
grid = [['.', '.', '.', '.', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['O', 'O', 'O', 'O', 'O', '.'], ['.', 'O', 'O', 'O', 'O', 'O'], ['O', 'O', 'O', 'O', 'O', '.'], ['O', 'O', 'O', 'O', '.', '.'], ['.', 'O', 'O', '.', '.', '.'], ['.', '.', '.', '.', '.', '.']] for i in range(len(grid[0])): for j in range(len(grid)): print(grid[j][i], end='') print('')
# Python code to reverse a string # using loop def reverse(s): str = "" for i in s: str = i + str return str s = "Geeksforgeeks" print ("The original string is : ",end="") print (s) print ("The reversed string(using loops) is : ",end="") print (reverse(s))
def reverse(s): str = '' for i in s: str = i + str return str s = 'Geeksforgeeks' print('The original string is : ', end='') print(s) print('The reversed string(using loops) is : ', end='') print(reverse(s))
def has_line(game_result): for l in game_result: if l == tuple("XXX"): return "X" elif l == tuple("OOO"): return "O" return None def has_col(game_result): return has_line(zip(*[list(e) for e in game_result])) def has_diag(game_result): def check_diag(c, reverse=False) : for i in range(len(game_result)): if (not reverse and game_result[i][i] != c) or \ (reverse and game_result[i][len(game_result) - 1 - i] != c): return False return True return "X" if check_diag("X") or check_diag("X", reverse=True) else "O" if check_diag("O") or check_diag("O", reverse=True) else None def checkio(game_result): line = has_line([tuple(e) for e in game_result]) col = has_col(game_result) diag = has_diag(game_result) return line if line is not None else col if col is not None else diag if diag is not None else "D" if __name__ == '__main__': #These "asserts" using only for self-checking and not necessary for #auto-testing assert checkio(["X.O", "XX.", "XOO"]) == "X", "Xs wins" assert checkio(["OO.", "XOX", "XOX"]) == "O", "Os wins" assert checkio(["OOX", "XXO", "OXX"]) == "D", "Draw" assert checkio(["O.X", "XX.", "XOO"]) == "X", "Xs wins again"
def has_line(game_result): for l in game_result: if l == tuple('XXX'): return 'X' elif l == tuple('OOO'): return 'O' return None def has_col(game_result): return has_line(zip(*[list(e) for e in game_result])) def has_diag(game_result): def check_diag(c, reverse=False): for i in range(len(game_result)): if not reverse and game_result[i][i] != c or (reverse and game_result[i][len(game_result) - 1 - i] != c): return False return True return 'X' if check_diag('X') or check_diag('X', reverse=True) else 'O' if check_diag('O') or check_diag('O', reverse=True) else None def checkio(game_result): line = has_line([tuple(e) for e in game_result]) col = has_col(game_result) diag = has_diag(game_result) return line if line is not None else col if col is not None else diag if diag is not None else 'D' if __name__ == '__main__': assert checkio(['X.O', 'XX.', 'XOO']) == 'X', 'Xs wins' assert checkio(['OO.', 'XOX', 'XOX']) == 'O', 'Os wins' assert checkio(['OOX', 'XXO', 'OXX']) == 'D', 'Draw' assert checkio(['O.X', 'XX.', 'XOO']) == 'X', 'Xs wins again'
#!/usr/bin/env python3 def validate_no_repeated(passphrase): words = passphrase.strip().split() return len(set(words)) == len(words) def validate_no_anagrams(passphrase): words = [''.join(sorted(word)) for word in passphrase.strip().split()] return len(set(words)) == len(words) assert validate_no_repeated("aa bb cc dd ee") assert validate_no_repeated("aa bb cc dd aaa") assert not validate_no_repeated("aa bb cc dd aa") assert validate_no_anagrams("aa bb cc dd ee") assert validate_no_anagrams("aa bb cc dd aaa") assert validate_no_anagrams("abcde fghij") assert validate_no_anagrams("a ab abc abd abf abj") assert validate_no_anagrams("iiii oiii ooii oooi oooo") assert not validate_no_anagrams("aa bb cc dd aa") assert not validate_no_anagrams("abcde xyz ecdab") assert not validate_no_anagrams("oiii ioii iioi iiio") if __name__ == '__main__': with open('input') as f: lines = f.readlines() print(sum(validate_no_repeated(passphrase) for passphrase in lines)) print(sum(validate_no_anagrams(passphrase) for passphrase in lines))
def validate_no_repeated(passphrase): words = passphrase.strip().split() return len(set(words)) == len(words) def validate_no_anagrams(passphrase): words = [''.join(sorted(word)) for word in passphrase.strip().split()] return len(set(words)) == len(words) assert validate_no_repeated('aa bb cc dd ee') assert validate_no_repeated('aa bb cc dd aaa') assert not validate_no_repeated('aa bb cc dd aa') assert validate_no_anagrams('aa bb cc dd ee') assert validate_no_anagrams('aa bb cc dd aaa') assert validate_no_anagrams('abcde fghij') assert validate_no_anagrams('a ab abc abd abf abj') assert validate_no_anagrams('iiii oiii ooii oooi oooo') assert not validate_no_anagrams('aa bb cc dd aa') assert not validate_no_anagrams('abcde xyz ecdab') assert not validate_no_anagrams('oiii ioii iioi iiio') if __name__ == '__main__': with open('input') as f: lines = f.readlines() print(sum((validate_no_repeated(passphrase) for passphrase in lines))) print(sum((validate_no_anagrams(passphrase) for passphrase in lines)))
def clean_number_list(numbers_to_add): """ Input: a List of numbers to be added together Function will clean the list and then return the new list. Cleaning involves conversion of string to numbers Function will return False if an invalid value has been found """ # Verify that the input is a list if not isinstance(numbers_to_add, list): return False # Build a new list with cleaned values numbers_to_add_list = [] for item in numbers_to_add: if isinstance(item, str): if item.isdigit(): numbers_to_add_list.append(int(item)) else: try: float_value = float(item) numbers_to_add_list.append(float_value) except Exception as e: # print(type(e)) # TODO # Print to log file return False if isinstance(item, (int, float)): numbers_to_add_list.append(item) return (numbers_to_add_list)
def clean_number_list(numbers_to_add): """ Input: a List of numbers to be added together Function will clean the list and then return the new list. Cleaning involves conversion of string to numbers Function will return False if an invalid value has been found """ if not isinstance(numbers_to_add, list): return False numbers_to_add_list = [] for item in numbers_to_add: if isinstance(item, str): if item.isdigit(): numbers_to_add_list.append(int(item)) else: try: float_value = float(item) numbers_to_add_list.append(float_value) except Exception as e: return False if isinstance(item, (int, float)): numbers_to_add_list.append(item) return numbers_to_add_list
linha = '-' * 30 totMais18 = 0 totHomens = 0 totMulherMenos20 = 0 while True: print(linha) print('{:^30}'.format('CADASTRE UMA PESSOA')) print(linha) idadeTXT = ' ' while not idadeTXT.isnumeric(): idadeTXT = str(input('Idade: ')) idade = int(idadeTXT) sexo = ' ' while sexo not in 'MF': sexo = str(input('Sexo: [M/F] ')).strip().upper()[0] if idade > 18: totMais18 += 1 if sexo == 'M': totHomens += 1 if (sexo == 'F' and idade < 20): totMulherMenos20 += 1 continuar = ' ' while continuar not in 'SN': continuar = str(input('Deseja continuar? [S/N?] ')).strip().upper()[0] if continuar == 'N': break print(linha) print('Total de pessoas com mais de 18:', totMais18) print('Ao todo, temos {} homens cadastrados'.format(totHomens)) print(f'E temos {totMulherMenos20} mulheres com menos de 20 anos')
linha = '-' * 30 tot_mais18 = 0 tot_homens = 0 tot_mulher_menos20 = 0 while True: print(linha) print('{:^30}'.format('CADASTRE UMA PESSOA')) print(linha) idade_txt = ' ' while not idadeTXT.isnumeric(): idade_txt = str(input('Idade: ')) idade = int(idadeTXT) sexo = ' ' while sexo not in 'MF': sexo = str(input('Sexo: [M/F] ')).strip().upper()[0] if idade > 18: tot_mais18 += 1 if sexo == 'M': tot_homens += 1 if sexo == 'F' and idade < 20: tot_mulher_menos20 += 1 continuar = ' ' while continuar not in 'SN': continuar = str(input('Deseja continuar? [S/N?] ')).strip().upper()[0] if continuar == 'N': break print(linha) print('Total de pessoas com mais de 18:', totMais18) print('Ao todo, temos {} homens cadastrados'.format(totHomens)) print(f'E temos {totMulherMenos20} mulheres com menos de 20 anos')
""" A pangram is a sentence where every letter of the English alphabet appears at least once. Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise. Example 1: Input: sentence = "thequickbrownfoxjumpsoverthelazydog" Output: true Explanation: sentence contains at least one of every letter of the English alphabet. Example 2: Input: sentence = "leetcode" Output: false Constraints: 1 <= sentence.length <= 1000 sentence consists of lowercase English letters. # algorithm: iterate through string if char has been seen do nothing else add char to result string if string.length == 26 return true : false """ def pan_gram(string): result = '' for char in string: if char not in result: result += char if len(result) == 26: return True else: return False def another(string): return len(set(string)) == 26
""" A pangram is a sentence where every letter of the English alphabet appears at least once. Given a string sentence containing only lowercase English letters, return true if sentence is a pangram, or false otherwise. Example 1: Input: sentence = "thequickbrownfoxjumpsoverthelazydog" Output: true Explanation: sentence contains at least one of every letter of the English alphabet. Example 2: Input: sentence = "leetcode" Output: false Constraints: 1 <= sentence.length <= 1000 sentence consists of lowercase English letters. # algorithm: iterate through string if char has been seen do nothing else add char to result string if string.length == 26 return true : false """ def pan_gram(string): result = '' for char in string: if char not in result: result += char if len(result) == 26: return True else: return False def another(string): return len(set(string)) == 26
GRAPH = { "A": ["B","D","E"], "B": ["A","C","D"], "C": ["B","G"], "D": ["A","B","E","F"], "E": ["A","D"], "F": ["D"], "G": ["C"] } def bfs(graph, current_vertex): queue = [] # an empty queue visited = [] # an empty list of visited nodes queue.append(current_vertex) # enqueue while len(queue) > 0: # while queue not empty current_vertex = queue.pop(0) # dequeue visited.append(current_vertex) for neighbour in graph[current_vertex]: if neighbour not in visited and \ neighbour not in queue: queue.append(neighbour) return visited # main program traversal = bfs(GRAPH, 'A') print('Nodes visited in this order:', traversal)
graph = {'A': ['B', 'D', 'E'], 'B': ['A', 'C', 'D'], 'C': ['B', 'G'], 'D': ['A', 'B', 'E', 'F'], 'E': ['A', 'D'], 'F': ['D'], 'G': ['C']} def bfs(graph, current_vertex): queue = [] visited = [] queue.append(current_vertex) while len(queue) > 0: current_vertex = queue.pop(0) visited.append(current_vertex) for neighbour in graph[current_vertex]: if neighbour not in visited and neighbour not in queue: queue.append(neighbour) return visited traversal = bfs(GRAPH, 'A') print('Nodes visited in this order:', traversal)
# use an increment and assign operator count = 0 while count != 5: count += 1 print(count) # increment count by 3 count = 0 while count <= 20: count += 3 print(count) # decrements count by 3 count = 20 while count >= 0: count -= 3 print(count)
count = 0 while count != 5: count += 1 print(count) count = 0 while count <= 20: count += 3 print(count) count = 20 while count >= 0: count -= 3 print(count)
class Solution: def solve(self, s): lCount = 0 rCount = 0 choiceCount = 0 for i in s: if i == 'L': lCount += 1 elif i == 'R': rCount += 1 else: choiceCount += 1 if lCount > rCount: return (lCount + choiceCount) - rCount else: return (rCount + choiceCount) - lCount
class Solution: def solve(self, s): l_count = 0 r_count = 0 choice_count = 0 for i in s: if i == 'L': l_count += 1 elif i == 'R': r_count += 1 else: choice_count += 1 if lCount > rCount: return lCount + choiceCount - rCount else: return rCount + choiceCount - lCount
class Vertice: def __init__(self, n): self.nombre = n class Grafo: vertices = {} bordes = [] indices_bordes = {} def agregar_vertice(self, vertex): if isinstance(vertex, Vertice) and vertex.nombre not in self.vertices: self.vertices[vertex.nombre] = vertex for fila in self.bordes: fila.append(0) self.bordes.append([0] * (len(self.bordes) + 1)) self.indices_bordes[vertex.nombre] = len(self.indices_bordes) return True else: return False def agregar_borde(self, u, v, weight=1): if u in self.vertices and v in self.vertices: self.bordes[self.indices_bordes[u]][self.indices_bordes[v]] = weight self.bordes[self.indices_bordes[v]][self.indices_bordes[u]] = weight return True else: return False def imprimir_grafo(self): for v, x in sorted(self.indices_bordes.items()): print(v + ' ', end='') for j in range(len(self.bordes)): print(self.bordes[x][j], end='') print(' ') g = Grafo() a = Vertice('1') g.agregar_vertice(a) g.agregar_vertice(Vertice('2')) for i in range(ord('1'), ord('8')): g.agregar_vertice(Vertice(chr(i))) bordes = ['12', '24', '26', '43', '32', '45', '52', '65', '67', '75', '74'] for borde in bordes: g.agregar_borde(borde[:1], borde[1:]) g.imprimir_grafo()
class Vertice: def __init__(self, n): self.nombre = n class Grafo: vertices = {} bordes = [] indices_bordes = {} def agregar_vertice(self, vertex): if isinstance(vertex, Vertice) and vertex.nombre not in self.vertices: self.vertices[vertex.nombre] = vertex for fila in self.bordes: fila.append(0) self.bordes.append([0] * (len(self.bordes) + 1)) self.indices_bordes[vertex.nombre] = len(self.indices_bordes) return True else: return False def agregar_borde(self, u, v, weight=1): if u in self.vertices and v in self.vertices: self.bordes[self.indices_bordes[u]][self.indices_bordes[v]] = weight self.bordes[self.indices_bordes[v]][self.indices_bordes[u]] = weight return True else: return False def imprimir_grafo(self): for (v, x) in sorted(self.indices_bordes.items()): print(v + ' ', end='') for j in range(len(self.bordes)): print(self.bordes[x][j], end='') print(' ') g = grafo() a = vertice('1') g.agregar_vertice(a) g.agregar_vertice(vertice('2')) for i in range(ord('1'), ord('8')): g.agregar_vertice(vertice(chr(i))) bordes = ['12', '24', '26', '43', '32', '45', '52', '65', '67', '75', '74'] for borde in bordes: g.agregar_borde(borde[:1], borde[1:]) g.imprimir_grafo()
#Single line concat "Hello " "World" #Multi line concat with line continuation "Goodbye " \ "World" #Single line concat in list [ "a" "b" ] #Single line, looks like tuple, but is just parenthesized ("c" "d" ) #Multi line in list [ 'e' 'f' ] #Simple String "string" #String with escapes "\n\n\n\n" #String with unicode escapes '\u0123\u1234' #Concat with empty String 'word' '' #String with escapes and concatenation : '\n\n\n\n' '0' #Multiline string ''' line 0 line 1 ''' #Multiline impicitly concatenated string ''' line 2 line 3 ''' ''' line 4 line 5 ''' #Implicitly concatenated
"""Hello World""" 'Goodbye World' ['ab'] 'cd' ['ef'] 'string' '\n\n\n\n' 'ģሴ' 'word' '\n\n\n\n0' '\nline 0\nline 1\n' '\nline 2\nline 3\n\nline 4\nline 5\n'
class WalletError(Exception): """Base Exception raised for all wallet errors.""" pass class InsufficientFunds(WalletError): """Error raised when address has insufficient funds to make a transaction. Attributes: address: input address for which the error occurred balance: current balance for the address message: explanation of the error """ def __init__(self, address, balance=0): super().__init__() self.address = address self.balance = balance self.message = f"Insufficient funds for address {address} (balance = {balance})" @classmethod def forAmount(cls, address, balance, out_amount, fee): ex = cls(address, balance) total = out_amount + fee ex.message = f"Balance {balance} is less than {total} (including {fee} fee)" return ex def __str__(self): return self.message class EmptyUnspentTransactionOutputSet(InsufficientFunds): """Error raised when address has an empty UTXO set. Attributes: address: input address for which the error occurred balance: current balance for the address message: explanation of the error """ def __init__(self, address): super().__init__(address) self.message = f"No unspent transactions were found for address {address})" class NoConfirmedTransactionsFound(InsufficientFunds): """Error raised when address has no confirmed unspent transactions to use. Attributes: address: input address for which the error occurred balance: current balance for the address message: explanation of the error """ def __init__(self, address, min_confirmations): super().__init__(address) self.message = f"No confirmed unspent transactions were found for address {address} (asking for min: {min_confirmations})"
class Walleterror(Exception): """Base Exception raised for all wallet errors.""" pass class Insufficientfunds(WalletError): """Error raised when address has insufficient funds to make a transaction. Attributes: address: input address for which the error occurred balance: current balance for the address message: explanation of the error """ def __init__(self, address, balance=0): super().__init__() self.address = address self.balance = balance self.message = f'Insufficient funds for address {address} (balance = {balance})' @classmethod def for_amount(cls, address, balance, out_amount, fee): ex = cls(address, balance) total = out_amount + fee ex.message = f'Balance {balance} is less than {total} (including {fee} fee)' return ex def __str__(self): return self.message class Emptyunspenttransactionoutputset(InsufficientFunds): """Error raised when address has an empty UTXO set. Attributes: address: input address for which the error occurred balance: current balance for the address message: explanation of the error """ def __init__(self, address): super().__init__(address) self.message = f'No unspent transactions were found for address {address})' class Noconfirmedtransactionsfound(InsufficientFunds): """Error raised when address has no confirmed unspent transactions to use. Attributes: address: input address for which the error occurred balance: current balance for the address message: explanation of the error """ def __init__(self, address, min_confirmations): super().__init__(address) self.message = f'No confirmed unspent transactions were found for address {address} (asking for min: {min_confirmations})'
num1 = 111 num2 = 222 num3 = 333333 num3 = 333 num4 = 444 num6 = 666 num5 = 555 num7 = 777
num1 = 111 num2 = 222 num3 = 333333 num3 = 333 num4 = 444 num6 = 666 num5 = 555 num7 = 777
# True & False limit = 5000 limit == 4000 # returns False limit == 5000 # returns True 5 == 4 # returns False 5 == 5 # returns True # if & else & elif gain = 50000 limit = 50000 if gain > limit: print("gain is greater than the limit") elif gain == limit: print("gain equally limit") else: print("limit is greater than the gain")
limit = 5000 limit == 4000 limit == 5000 5 == 4 5 == 5 gain = 50000 limit = 50000 if gain > limit: print('gain is greater than the limit') elif gain == limit: print('gain equally limit') else: print('limit is greater than the gain')
#!/usr/bin/env python ''' THIS IS DOUBLY LINKED LIST IMPLEMENTATION ''' class Node: def __init__(self, prev=None, next=None, data=None): self.prev = prev self.next = next self.data = data def __str__(self): return str(self.data) class DoublyLinkedList: def __init__(self): self.head = None self.count = int(0) def display(self): temp = self.head print("\nDLL Content: "), while (temp): print(str(temp.data)), temp = temp.next print(" #") def show_count(self): print(self.count) def get_count(self): return self.count def push(self, new_data): new_node = Node(data=new_data) new_node.prev = None new_node.next = self.head if self.head is not None: self.head.prev = new_node self.head = new_node self.count = self.count + 1 def insertBefore(self, cursor, new_data): if cursor is None: print("Error: Node doesn't exist") return new_node = Node(data=new_data) new_node.prev = cursor.prev new_node.next = cursor if cursor.prev is not None: cursor.prev.next = new_node cursor.prev = new_node self.count = self.count + 1 def insertAfter(self, cursor, new_data): if cursor is None: print("Error: Node doesn't exist") return new_node = Node(data=new_data) new_node.prev = cursor new_node.next = cursor.next cursor.next = new_node if new_node.next is not None: new_node.next.prev = new_node self.count = self.count + 1 def append(self, new_data): new_node = Node(data=new_data) new_node.next = None if self.head is None: new_node.prev = None self.head = new_node self.count = self.count + 1 return last = self.head while (last.next is not None): last = last.next new_node.prev = last last.next = new_node self.count = self.count + 1 def menu(): print("Doubly Linked List\n") print("1. Show List") print("2. Insert at Start") print("3. Insert Before") print("4. Insert After") print("5. Insert at End") print("9. # of Element") print("0. Exit") print(">> "), def main(): dll = DoublyLinkedList() while(True): menu() choice = int(raw_input()) if choice == int('1'): dll.display() elif choice == int('2'): print("Enter data to insert: "), data = raw_input() dll.push(data) elif choice == int('3'): print("Enter data to insert: "), data = raw_input() print("Enter position of cursor (before): "), pos = int(raw_input()) if pos == int('1'): dll.push(data) continue cursor = dll.head for i in range(1, pos): cursor = cursor.next print(cursor) dll.insertBefore(cursor, data) # print("3") elif choice == int('4'): print("Enter data to insert: "), data = raw_input() print("Enter position of cursor (after): "), pos = int(raw_input()) cursor = dll.head for i in range(pos - 1): cursor = cursor.next print(cursor) dll.insertAfter(cursor, data) # print("4") elif choice == int('5'): print("Enter data to insert: "), data = raw_input() dll.append(data) # print("5") elif choice == int('9'): print("No of element: "), dll.show_count() elif choice == int('0'): break else: print("Invalid Selection") print('\n\nEND\n\n') if __name__ == '__main__': main()
""" THIS IS DOUBLY LINKED LIST IMPLEMENTATION """ class Node: def __init__(self, prev=None, next=None, data=None): self.prev = prev self.next = next self.data = data def __str__(self): return str(self.data) class Doublylinkedlist: def __init__(self): self.head = None self.count = int(0) def display(self): temp = self.head (print('\nDLL Content: '),) while temp: (print(str(temp.data)),) temp = temp.next print(' #') def show_count(self): print(self.count) def get_count(self): return self.count def push(self, new_data): new_node = node(data=new_data) new_node.prev = None new_node.next = self.head if self.head is not None: self.head.prev = new_node self.head = new_node self.count = self.count + 1 def insert_before(self, cursor, new_data): if cursor is None: print("Error: Node doesn't exist") return new_node = node(data=new_data) new_node.prev = cursor.prev new_node.next = cursor if cursor.prev is not None: cursor.prev.next = new_node cursor.prev = new_node self.count = self.count + 1 def insert_after(self, cursor, new_data): if cursor is None: print("Error: Node doesn't exist") return new_node = node(data=new_data) new_node.prev = cursor new_node.next = cursor.next cursor.next = new_node if new_node.next is not None: new_node.next.prev = new_node self.count = self.count + 1 def append(self, new_data): new_node = node(data=new_data) new_node.next = None if self.head is None: new_node.prev = None self.head = new_node self.count = self.count + 1 return last = self.head while last.next is not None: last = last.next new_node.prev = last last.next = new_node self.count = self.count + 1 def menu(): print('Doubly Linked List\n') print('1. Show List') print('2. Insert at Start') print('3. Insert Before') print('4. Insert After') print('5. Insert at End') print('9. # of Element') print('0. Exit') (print('>> '),) def main(): dll = doubly_linked_list() while True: menu() choice = int(raw_input()) if choice == int('1'): dll.display() elif choice == int('2'): (print('Enter data to insert: '),) data = raw_input() dll.push(data) elif choice == int('3'): (print('Enter data to insert: '),) data = raw_input() (print('Enter position of cursor (before): '),) pos = int(raw_input()) if pos == int('1'): dll.push(data) continue cursor = dll.head for i in range(1, pos): cursor = cursor.next print(cursor) dll.insertBefore(cursor, data) elif choice == int('4'): (print('Enter data to insert: '),) data = raw_input() (print('Enter position of cursor (after): '),) pos = int(raw_input()) cursor = dll.head for i in range(pos - 1): cursor = cursor.next print(cursor) dll.insertAfter(cursor, data) elif choice == int('5'): (print('Enter data to insert: '),) data = raw_input() dll.append(data) elif choice == int('9'): (print('No of element: '),) dll.show_count() elif choice == int('0'): break else: print('Invalid Selection') print('\n\nEND\n\n') if __name__ == '__main__': main()
""" Created on Wed Aug 25 12:52:52 2021 AI and deep learnin with Python Data types and operators Quiz Data types and Operators """ # The current volume of a water reservoir is ( in cubic meters) reservoir_volume = 4.445e8 # The amount of rainfall from a storm (in cubic meters) rainfall = 5e6 # Decrease the rainfall variable by 10% to account for runoff rainfall *= 0.9 # add the rainfall variable to the reservoir_volume variable reservoir_volume += rainfall print(reservoir_volume)
""" Created on Wed Aug 25 12:52:52 2021 AI and deep learnin with Python Data types and operators Quiz Data types and Operators """ reservoir_volume = 444500000.0 rainfall = 5000000.0 rainfall *= 0.9 reservoir_volume += rainfall print(reservoir_volume)
'''input 2 9 3 6 12 5 20 11 12 9 17 12 74 ''' # -*- coding: utf-8 -*- # AtCoder Beginner Contest # Problem B if __name__ == '__main__': ball_count = int(input()) robotB_position = int(input()) positions = list(map(int, input().split())) total_length = 0 for i in range(ball_count): if positions[i] < abs(robotB_position - positions[i]): total_length += 2 * positions[i] else: total_length += 2 * abs(robotB_position - positions[i]) print(total_length)
"""input 2 9 3 6 12 5 20 11 12 9 17 12 74 """ if __name__ == '__main__': ball_count = int(input()) robot_b_position = int(input()) positions = list(map(int, input().split())) total_length = 0 for i in range(ball_count): if positions[i] < abs(robotB_position - positions[i]): total_length += 2 * positions[i] else: total_length += 2 * abs(robotB_position - positions[i]) print(total_length)
S = input() K = int(input()) for i, s in enumerate(S): if s == "1": if i + 1 == K: print(1) exit() else: print(s) exit()
s = input() k = int(input()) for (i, s) in enumerate(S): if s == '1': if i + 1 == K: print(1) exit() else: print(s) exit()
# PASSED _ = input() lst = sorted(list(map(int, input().split()))) output = [] if len(lst) % 2: output.append(lst.pop(0)) while lst: output.append(lst[-1]) output.append(lst[0]) lst = lst[1:-1] print(*reversed(output))
_ = input() lst = sorted(list(map(int, input().split()))) output = [] if len(lst) % 2: output.append(lst.pop(0)) while lst: output.append(lst[-1]) output.append(lst[0]) lst = lst[1:-1] print(*reversed(output))
''' Read numbers and put in a list one list will have the EVEN numbers the other will have the ODD ones SHow the result ''' odd_list = [] even_list = [] num = int(input('Type a number: ')) if num%2 == 0: even_list.append(num) elif num%2 != 0: odd_list.append(num) while True: opt = str(input('Do you want to keep adding numbers? [Y/N]: ')).lower() if 'y' in opt: num = int(input('Type a number: ')) if num%2 == 0: even_list.append(num) elif num%2 != 0: odd_list.append(num) elif 'n' in opt: print(f'The list is: {sorted(even_list + odd_list)}') print(f'The EVEN list: {sorted(even_list)}') print(f'The ODD list: {sorted(odd_list)}') break else: print('Sorry, the options are Y - yes or N - no.')
""" Read numbers and put in a list one list will have the EVEN numbers the other will have the ODD ones SHow the result """ odd_list = [] even_list = [] num = int(input('Type a number: ')) if num % 2 == 0: even_list.append(num) elif num % 2 != 0: odd_list.append(num) while True: opt = str(input('Do you want to keep adding numbers? [Y/N]: ')).lower() if 'y' in opt: num = int(input('Type a number: ')) if num % 2 == 0: even_list.append(num) elif num % 2 != 0: odd_list.append(num) elif 'n' in opt: print(f'The list is: {sorted(even_list + odd_list)}') print(f'The EVEN list: {sorted(even_list)}') print(f'The ODD list: {sorted(odd_list)}') break else: print('Sorry, the options are Y - yes or N - no.')
__version__ = "1.0.8" def get_version(): return __version__
__version__ = '1.0.8' def get_version(): return __version__
#14 def sumDigits(num): sum = 0 for digit in str(num): sum += int(digit) return sum num = int(input('Enter a 4-digit number:')) print('Sum of the digits:', sumDigits(num))
def sum_digits(num): sum = 0 for digit in str(num): sum += int(digit) return sum num = int(input('Enter a 4-digit number:')) print('Sum of the digits:', sum_digits(num))
# Definition for a binary tree node. # class TreeNode(object): # def __init__(self, x): # self.val = x # self.left = None # self.right = None class Solution(object): def findTarget(self, root, k): """ :type root: TreeNode :type k: int :rtype: bool """ hashset = set() return self.inorder(root, k, hashset) def inorder(self, root, k, hashset): if root: left = self.inorder(root.left, k, hashset) if left or k - root.val in hashset: return True hashset.add(root.val) right = self.inorder(root.right, k, hashset) return right return False
class Solution(object): def find_target(self, root, k): """ :type root: TreeNode :type k: int :rtype: bool """ hashset = set() return self.inorder(root, k, hashset) def inorder(self, root, k, hashset): if root: left = self.inorder(root.left, k, hashset) if left or k - root.val in hashset: return True hashset.add(root.val) right = self.inorder(root.right, k, hashset) return right return False
class BinaryChunkHeader: LUA_SIGNATURE = bytes(b'\x1bLua') LUAC_VERSION = 0x53 LUAC_FORMAT = 0x0 LUAC_DATA = bytes(b'\x19\x93\r\n\x1a\n') CINT_SIZE = 4 CSIZET_SIZE = 8 INST_SIZE = 4 LUA_INT_SIZE = 8 LUA_NUMBER_SIZE = 8 LUAC_INT = 0x5678 LUAC_NUM = 370.5 def __init__(self, br): self.signature = br.read_bytes(4) self.version = br.read_uint8() self.format = br.read_uint8() self.luac_data = br.read_bytes(6) self.cint_size = br.read_uint8() self.csizet_size = br.read_uint8() self.inst_size = br.read_uint8() self.lua_int_size = br.read_uint8() self.lua_number_size = br.read_uint8() self.luac_int = br.read_uint64() self.luac_num = br.read_double() def check(self): assert(self.signature == BinaryChunkHeader.LUA_SIGNATURE) assert(self.version == BinaryChunkHeader.LUAC_VERSION) assert(self.format == BinaryChunkHeader.LUAC_FORMAT) assert(self.luac_data == BinaryChunkHeader.LUAC_DATA) assert(self.cint_size == BinaryChunkHeader.CINT_SIZE) assert(self.csizet_size == BinaryChunkHeader.CSIZET_SIZE) assert(self.inst_size == BinaryChunkHeader.INST_SIZE) assert(self.lua_int_size == BinaryChunkHeader.LUA_INT_SIZE) assert(self.lua_number_size == BinaryChunkHeader.LUA_NUMBER_SIZE) assert(self.luac_int == BinaryChunkHeader.LUAC_INT) assert(self.luac_num == BinaryChunkHeader.LUAC_NUM) def dump(self): print('signature: ', self.signature) print('version: ', self.version) print('format: ', self.format) print('luac_data: ', self.luac_data) print('cint_size: ', self.cint_size) print('csizet_size: ', self.csizet_size) print('inst_size: ', self.inst_size) print('lua_int_size: ', self.lua_int_size) print('lua_number_size: ', self.lua_number_size) print('luac_int: ', hex(self.luac_int)) print('luac_num: ', self.luac_num) print()
class Binarychunkheader: lua_signature = bytes(b'\x1bLua') luac_version = 83 luac_format = 0 luac_data = bytes(b'\x19\x93\r\n\x1a\n') cint_size = 4 csizet_size = 8 inst_size = 4 lua_int_size = 8 lua_number_size = 8 luac_int = 22136 luac_num = 370.5 def __init__(self, br): self.signature = br.read_bytes(4) self.version = br.read_uint8() self.format = br.read_uint8() self.luac_data = br.read_bytes(6) self.cint_size = br.read_uint8() self.csizet_size = br.read_uint8() self.inst_size = br.read_uint8() self.lua_int_size = br.read_uint8() self.lua_number_size = br.read_uint8() self.luac_int = br.read_uint64() self.luac_num = br.read_double() def check(self): assert self.signature == BinaryChunkHeader.LUA_SIGNATURE assert self.version == BinaryChunkHeader.LUAC_VERSION assert self.format == BinaryChunkHeader.LUAC_FORMAT assert self.luac_data == BinaryChunkHeader.LUAC_DATA assert self.cint_size == BinaryChunkHeader.CINT_SIZE assert self.csizet_size == BinaryChunkHeader.CSIZET_SIZE assert self.inst_size == BinaryChunkHeader.INST_SIZE assert self.lua_int_size == BinaryChunkHeader.LUA_INT_SIZE assert self.lua_number_size == BinaryChunkHeader.LUA_NUMBER_SIZE assert self.luac_int == BinaryChunkHeader.LUAC_INT assert self.luac_num == BinaryChunkHeader.LUAC_NUM def dump(self): print('signature: ', self.signature) print('version: ', self.version) print('format: ', self.format) print('luac_data: ', self.luac_data) print('cint_size: ', self.cint_size) print('csizet_size: ', self.csizet_size) print('inst_size: ', self.inst_size) print('lua_int_size: ', self.lua_int_size) print('lua_number_size: ', self.lua_number_size) print('luac_int: ', hex(self.luac_int)) print('luac_num: ', self.luac_num) print()
# FUNCTIONS # Positional-Only Arguments def pos_only(arg1, arg2, /): print(f'{arg1}, {arg2}') pos_only('One', 2) # Cannot pass keyword arguments to a function of positional-only arguments # pos_only(arg1='One', arg2=2) # Keyword-Only Arguments def kw_only(*, arg1, arg2): print(f'{arg1}, {arg2}') kw_only(arg1='First', arg2='Second') kw_only(arg2=2, arg1=1) # Cannot pass arguments without their name being specified specifically # kw_only(1, arg1=2) # No Restriction On Positional-Only Or Keyword-Only Arguments def no_res(arg1, arg2): print(f'{arg1}, {arg2}') # Positional arguments will always need to be placed in front of keyword arguments no_res('Firstly', arg2='Secondly') # Combine Both Positional-Only, Positional-Or-Keyword and Keyword-Only Arguments def fn(pos1, pos2, /, pos_or_kw1, pos_or_kw2, *, kw1, kw2): print(f'{pos1}, {pos2}, {pos_or_kw1}, {pos_or_kw2}, {kw1}, {kw2}') fn(1, 'Two', 3, pos_or_kw2='Four', kw1=5, kw2='Six') # Arbitrary Argument Lists def hyper_link(protocol, domain, *routes, separator='/'): return f'{protocol}://{domain}/' + separator.join(routes) print(hyper_link('https', 'python.org', 'downloads', 'release', 'python-385', separator='/')) # Unpacking List/Tuple Argument Lists with * and Dictionary Arguments with ** def server(host, port, separator=':'): return f'{host}{separator}{port}' print(server(*['localhost', 8080])) # call with arguments unpacked from a list def url(routes, params): r = '/'.join(routes) p = '&'.join([f'{name}={value}' for name, value in params.items()]) return f'{r}?{p}' route_config = { 'routes': ['download', 'latest'], 'params': { 'ver': 3, 'os': 'windows' } } print(url(**route_config)) # call with arguments unpacked from a dictionary # Lambda Expressions week_days = ['Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat', 'Sun'] day_codes = [3, 5, 2, 6, 1, 7] def convert_days(converter_fn, day_codes): return [converter_fn(day_code) for day_code in day_codes] converted_days = convert_days( lambda day_code: week_days[day_code % 7], day_codes) print(converted_days)
def pos_only(arg1, arg2, /): print(f'{arg1}, {arg2}') pos_only('One', 2) def kw_only(*, arg1, arg2): print(f'{arg1}, {arg2}') kw_only(arg1='First', arg2='Second') kw_only(arg2=2, arg1=1) def no_res(arg1, arg2): print(f'{arg1}, {arg2}') no_res('Firstly', arg2='Secondly') def fn(pos1, pos2, /, pos_or_kw1, pos_or_kw2, *, kw1, kw2): print(f'{pos1}, {pos2}, {pos_or_kw1}, {pos_or_kw2}, {kw1}, {kw2}') fn(1, 'Two', 3, pos_or_kw2='Four', kw1=5, kw2='Six') def hyper_link(protocol, domain, *routes, separator='/'): return f'{protocol}://{domain}/' + separator.join(routes) print(hyper_link('https', 'python.org', 'downloads', 'release', 'python-385', separator='/')) def server(host, port, separator=':'): return f'{host}{separator}{port}' print(server(*['localhost', 8080])) def url(routes, params): r = '/'.join(routes) p = '&'.join([f'{name}={value}' for (name, value) in params.items()]) return f'{r}?{p}' route_config = {'routes': ['download', 'latest'], 'params': {'ver': 3, 'os': 'windows'}} print(url(**route_config)) week_days = ['Mon', 'Tue', 'Wed', 'Thr', 'Fri', 'Sat', 'Sun'] day_codes = [3, 5, 2, 6, 1, 7] def convert_days(converter_fn, day_codes): return [converter_fn(day_code) for day_code in day_codes] converted_days = convert_days(lambda day_code: week_days[day_code % 7], day_codes) print(converted_days)
""" bigrange - big ranges. Really. Only one cool iterator in Python that supports big integers. """ def bigrange(a,b,step=1): """ A replacement for the xrange iterator; the builtin class doesn't handle arbitrarely large numbers. Input: a First numeric output b Lower (or upper) bound, never yield step Defaults to 1 """ i=a while cmp(i,b)==cmp(0,step): yield i i+=step
""" bigrange - big ranges. Really. Only one cool iterator in Python that supports big integers. """ def bigrange(a, b, step=1): """ A replacement for the xrange iterator; the builtin class doesn't handle arbitrarely large numbers. Input: a First numeric output b Lower (or upper) bound, never yield step Defaults to 1 """ i = a while cmp(i, b) == cmp(0, step): yield i i += step
class Solution(object): def reorderLogFiles(self, logs): letter_log = {} letter_logs = [] res = [] for idx, log in enumerate(logs): if log.split(' ')[-1].isdigit(): res.append(log) else: letters = tuple(log.split(' ')[1:]) letter_log[letters] = idx letter_logs.append(letters) letter_logs.sort(reverse=True) for letters in letter_logs: res.insert(0, logs[letter_log[letters]]) return res if __name__ == '__main__': print(Solution().reorderLogFiles(["a1 9 2 3 1", "g1 act car", "zo4 4 7", "ab1 off key dog", "a8 act zoo"]))
class Solution(object): def reorder_log_files(self, logs): letter_log = {} letter_logs = [] res = [] for (idx, log) in enumerate(logs): if log.split(' ')[-1].isdigit(): res.append(log) else: letters = tuple(log.split(' ')[1:]) letter_log[letters] = idx letter_logs.append(letters) letter_logs.sort(reverse=True) for letters in letter_logs: res.insert(0, logs[letter_log[letters]]) return res if __name__ == '__main__': print(solution().reorderLogFiles(['a1 9 2 3 1', 'g1 act car', 'zo4 4 7', 'ab1 off key dog', 'a8 act zoo']))
class FiniteStateMachine: def __init__(self, states, starting): self.states = states self.current = starting self.entry_words = {} # Dictionary of states, {state.name : word}, words where words are the words used to enter the state self.stay_words = {} # Dictionary of states, {states.name: [words]}, words is list with words which lead to staying in state def process(self, sentence): for word in sentence.split(): word = word.lower() next_state = self.current.get_next_state(word) if next_state is not None: # Change state self.entry_words[next_state.name] = word self.current = next_state else: # Stay in same state if self.current.name in self.stay_words: # State already in dict => more than 1 word for staying in this state self.stay_words[self.current.name].append(word) else: # state not in dict word_list = [word] self.stay_words[self.current.name] = word_list return self.current # return final state
class Finitestatemachine: def __init__(self, states, starting): self.states = states self.current = starting self.entry_words = {} self.stay_words = {} def process(self, sentence): for word in sentence.split(): word = word.lower() next_state = self.current.get_next_state(word) if next_state is not None: self.entry_words[next_state.name] = word self.current = next_state elif self.current.name in self.stay_words: self.stay_words[self.current.name].append(word) else: word_list = [word] self.stay_words[self.current.name] = word_list return self.current
class _ReadOnlyWidgetProxy(object): def __init__(self, widget): self.widget = widget def __getattr__(self, name): return getattr(self.widget, name) def __call__(self, field, **kwargs): kwargs.setdefault('readonly', True) return self.widget(field, **kwargs) def readonly_field(field): def _do_nothing(*args, **kwargs): pass field.widget = _ReadOnlyWidgetProxy(field.widget) field.process = _do_nothing field.populate_obj = _do_nothing return field
class _Readonlywidgetproxy(object): def __init__(self, widget): self.widget = widget def __getattr__(self, name): return getattr(self.widget, name) def __call__(self, field, **kwargs): kwargs.setdefault('readonly', True) return self.widget(field, **kwargs) def readonly_field(field): def _do_nothing(*args, **kwargs): pass field.widget = __read_only_widget_proxy(field.widget) field.process = _do_nothing field.populate_obj = _do_nothing return field
def reverse(s): return " ".join((s.split())[::-1]) s = input("Enter a sentence: ") print(reverse(s))
def reverse(s): return ' '.join(s.split()[::-1]) s = input('Enter a sentence: ') print(reverse(s))
fenceMap = hero.findNearest(hero.findFriends()).getMap() def convertCoor(row, col): return {"x": 34 + col * 4, "y": 26 + row * 4} for i in range(len(fenceMap)): for j in range(len(fenceMap[i])): if fenceMap[i][j] == 1: pos = convertCoor(i, j) hero.buildXY("fence", pos["x"], pos["y"]) hero.moveXY(30, 18)
fence_map = hero.findNearest(hero.findFriends()).getMap() def convert_coor(row, col): return {'x': 34 + col * 4, 'y': 26 + row * 4} for i in range(len(fenceMap)): for j in range(len(fenceMap[i])): if fenceMap[i][j] == 1: pos = convert_coor(i, j) hero.buildXY('fence', pos['x'], pos['y']) hero.moveXY(30, 18)
class Student: pass Jiggu = Student() Himanshu = Student() Jiggu.name = "Jiggu" Jiggu.std = 12 Jiggu.section = 1 Himanshu.std = 11 Himanshu.subjects = ["Hindi","English"] print(Jiggu.section, Himanshu.subjects)
class Student: pass jiggu = student() himanshu = student() Jiggu.name = 'Jiggu' Jiggu.std = 12 Jiggu.section = 1 Himanshu.std = 11 Himanshu.subjects = ['Hindi', 'English'] print(Jiggu.section, Himanshu.subjects)
# # PySNMP MIB module NETSCREEN-VPN-PHASEONE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/NETSCREEN-VPN-PHASEONE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 20:10:52 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, ObjectIdentifier, OctetString = mibBuilder.importSymbols("ASN1", "Integer", "ObjectIdentifier", "OctetString") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ConstraintsUnion, ValueSizeConstraint, ValueRangeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ConstraintsUnion", "ValueSizeConstraint", "ValueRangeConstraint", "SingleValueConstraint") netscreenVpn, netscreenVpnMibModule = mibBuilder.importSymbols("NETSCREEN-SMI", "netscreenVpn", "netscreenVpnMibModule") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") Counter64, ObjectIdentity, MibIdentifier, Gauge32, Bits, iso, Integer32, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, ModuleIdentity, TimeTicks, Counter32, IpAddress, NotificationType = mibBuilder.importSymbols("SNMPv2-SMI", "Counter64", "ObjectIdentity", "MibIdentifier", "Gauge32", "Bits", "iso", "Integer32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "ModuleIdentity", "TimeTicks", "Counter32", "IpAddress", "NotificationType") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") netscreenVpnPhaseoneMibModule = ModuleIdentity((1, 3, 6, 1, 4, 1, 3224, 4, 0, 5)) netscreenVpnPhaseoneMibModule.setRevisions(('2004-05-03 00:00', '2004-03-03 00:00', '2003-11-13 00:00', '2001-09-28 00:00', '2001-05-14 00:00',)) if mibBuilder.loadTexts: netscreenVpnPhaseoneMibModule.setLastUpdated('200405032022Z') if mibBuilder.loadTexts: netscreenVpnPhaseoneMibModule.setOrganization('Juniper Networks, Inc.') nsVpnPhaseOneCfg = MibIdentifier((1, 3, 6, 1, 4, 1, 3224, 4, 5)) nsVpnPhOneTable = MibTable((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1), ) if mibBuilder.loadTexts: nsVpnPhOneTable.setStatus('current') nsVpnPhOneEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1), ).setIndexNames((0, "NETSCREEN-VPN-PHASEONE-MIB", "nsVpnPhOneIndex")) if mibBuilder.loadTexts: nsVpnPhOneEntry.setStatus('current') nsVpnPhOneIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 2147483647))).setMaxAccess("readonly") if mibBuilder.loadTexts: nsVpnPhOneIndex.setStatus('current') nsVpnPhOneName = MibTableColumn((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 2), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(0, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: nsVpnPhOneName.setStatus('current') nsVpnPhOneAuthMethod = MibTableColumn((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("preshare", 0), ("rsa-sig", 1), ("dsa-sig", 2), ("rsa-enc", 3), ("rsa-rev", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: nsVpnPhOneAuthMethod.setStatus('current') nsVpnPhOneDhGroup = MibTableColumn((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 4), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: nsVpnPhOneDhGroup.setStatus('current') nsVpnPhOneEncryp = MibTableColumn((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("null", 0), ("des", 1), ("des3", 2), ("aes", 3), ("aes-192", 4), ("aes-256", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: nsVpnPhOneEncryp.setStatus('current') nsVpnPhOneHash = MibTableColumn((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("null", 0), ("md5", 1), ("sha", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: nsVpnPhOneHash.setStatus('current') nsVpnPhOneLifetime = MibTableColumn((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: nsVpnPhOneLifetime.setStatus('current') nsVpnPhOneLifetimeMeasure = MibTableColumn((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("second", 0), ("minute", 1), ("hours", 2), ("days", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: nsVpnPhOneLifetimeMeasure.setStatus('current') nsVpnPhOneVsys = MibTableColumn((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: nsVpnPhOneVsys.setStatus('current') mibBuilder.exportSymbols("NETSCREEN-VPN-PHASEONE-MIB", nsVpnPhaseOneCfg=nsVpnPhaseOneCfg, nsVpnPhOneVsys=nsVpnPhOneVsys, nsVpnPhOneIndex=nsVpnPhOneIndex, nsVpnPhOneEntry=nsVpnPhOneEntry, PYSNMP_MODULE_ID=netscreenVpnPhaseoneMibModule, netscreenVpnPhaseoneMibModule=netscreenVpnPhaseoneMibModule, nsVpnPhOneLifetime=nsVpnPhOneLifetime, nsVpnPhOneName=nsVpnPhOneName, nsVpnPhOneAuthMethod=nsVpnPhOneAuthMethod, nsVpnPhOneLifetimeMeasure=nsVpnPhOneLifetimeMeasure, nsVpnPhOneHash=nsVpnPhOneHash, nsVpnPhOneDhGroup=nsVpnPhOneDhGroup, nsVpnPhOneTable=nsVpnPhOneTable, nsVpnPhOneEncryp=nsVpnPhOneEncryp)
(integer, object_identifier, octet_string) = mibBuilder.importSymbols('ASN1', 'Integer', 'ObjectIdentifier', 'OctetString') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, constraints_union, value_size_constraint, value_range_constraint, single_value_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ConstraintsUnion', 'ValueSizeConstraint', 'ValueRangeConstraint', 'SingleValueConstraint') (netscreen_vpn, netscreen_vpn_mib_module) = mibBuilder.importSymbols('NETSCREEN-SMI', 'netscreenVpn', 'netscreenVpnMibModule') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (counter64, object_identity, mib_identifier, gauge32, bits, iso, integer32, mib_scalar, mib_table, mib_table_row, mib_table_column, unsigned32, module_identity, time_ticks, counter32, ip_address, notification_type) = mibBuilder.importSymbols('SNMPv2-SMI', 'Counter64', 'ObjectIdentity', 'MibIdentifier', 'Gauge32', 'Bits', 'iso', 'Integer32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Unsigned32', 'ModuleIdentity', 'TimeTicks', 'Counter32', 'IpAddress', 'NotificationType') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') netscreen_vpn_phaseone_mib_module = module_identity((1, 3, 6, 1, 4, 1, 3224, 4, 0, 5)) netscreenVpnPhaseoneMibModule.setRevisions(('2004-05-03 00:00', '2004-03-03 00:00', '2003-11-13 00:00', '2001-09-28 00:00', '2001-05-14 00:00')) if mibBuilder.loadTexts: netscreenVpnPhaseoneMibModule.setLastUpdated('200405032022Z') if mibBuilder.loadTexts: netscreenVpnPhaseoneMibModule.setOrganization('Juniper Networks, Inc.') ns_vpn_phase_one_cfg = mib_identifier((1, 3, 6, 1, 4, 1, 3224, 4, 5)) ns_vpn_ph_one_table = mib_table((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1)) if mibBuilder.loadTexts: nsVpnPhOneTable.setStatus('current') ns_vpn_ph_one_entry = mib_table_row((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1)).setIndexNames((0, 'NETSCREEN-VPN-PHASEONE-MIB', 'nsVpnPhOneIndex')) if mibBuilder.loadTexts: nsVpnPhOneEntry.setStatus('current') ns_vpn_ph_one_index = mib_table_column((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(0, 2147483647))).setMaxAccess('readonly') if mibBuilder.loadTexts: nsVpnPhOneIndex.setStatus('current') ns_vpn_ph_one_name = mib_table_column((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 2), display_string().subtype(subtypeSpec=value_size_constraint(0, 32))).setMaxAccess('readonly') if mibBuilder.loadTexts: nsVpnPhOneName.setStatus('current') ns_vpn_ph_one_auth_method = mib_table_column((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4))).clone(namedValues=named_values(('preshare', 0), ('rsa-sig', 1), ('dsa-sig', 2), ('rsa-enc', 3), ('rsa-rev', 4)))).setMaxAccess('readonly') if mibBuilder.loadTexts: nsVpnPhOneAuthMethod.setStatus('current') ns_vpn_ph_one_dh_group = mib_table_column((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 4), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: nsVpnPhOneDhGroup.setStatus('current') ns_vpn_ph_one_encryp = mib_table_column((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4, 5))).clone(namedValues=named_values(('null', 0), ('des', 1), ('des3', 2), ('aes', 3), ('aes-192', 4), ('aes-256', 5)))).setMaxAccess('readonly') if mibBuilder.loadTexts: nsVpnPhOneEncryp.setStatus('current') ns_vpn_ph_one_hash = mib_table_column((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2))).clone(namedValues=named_values(('null', 0), ('md5', 1), ('sha', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: nsVpnPhOneHash.setStatus('current') ns_vpn_ph_one_lifetime = mib_table_column((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 7), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: nsVpnPhOneLifetime.setStatus('current') ns_vpn_ph_one_lifetime_measure = mib_table_column((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3))).clone(namedValues=named_values(('second', 0), ('minute', 1), ('hours', 2), ('days', 3)))).setMaxAccess('readonly') if mibBuilder.loadTexts: nsVpnPhOneLifetimeMeasure.setStatus('current') ns_vpn_ph_one_vsys = mib_table_column((1, 3, 6, 1, 4, 1, 3224, 4, 5, 1, 1, 9), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: nsVpnPhOneVsys.setStatus('current') mibBuilder.exportSymbols('NETSCREEN-VPN-PHASEONE-MIB', nsVpnPhaseOneCfg=nsVpnPhaseOneCfg, nsVpnPhOneVsys=nsVpnPhOneVsys, nsVpnPhOneIndex=nsVpnPhOneIndex, nsVpnPhOneEntry=nsVpnPhOneEntry, PYSNMP_MODULE_ID=netscreenVpnPhaseoneMibModule, netscreenVpnPhaseoneMibModule=netscreenVpnPhaseoneMibModule, nsVpnPhOneLifetime=nsVpnPhOneLifetime, nsVpnPhOneName=nsVpnPhOneName, nsVpnPhOneAuthMethod=nsVpnPhOneAuthMethod, nsVpnPhOneLifetimeMeasure=nsVpnPhOneLifetimeMeasure, nsVpnPhOneHash=nsVpnPhOneHash, nsVpnPhOneDhGroup=nsVpnPhOneDhGroup, nsVpnPhOneTable=nsVpnPhOneTable, nsVpnPhOneEncryp=nsVpnPhOneEncryp)
#!/usr/bin/env python # coding: utf-8 # In[ ]: class Solution: def xorOperation(self, n: int, start: int) -> int: #Defining the nums array nums=[int(start+2*i) for i in range (n)] #Initializing the xor xor=nums[0] for i in range(1,len(nums)): xor^=nums[i] #Taking bitwise xor of each element return xor
class Solution: def xor_operation(self, n: int, start: int) -> int: nums = [int(start + 2 * i) for i in range(n)] xor = nums[0] for i in range(1, len(nums)): xor ^= nums[i] return xor
''' Body mass index is a measure to assess body fat. It is widely use because it is easy to calculate and can apply to everyone. The Body Mass Index (BMI) can calculate using the following equation. Body Mass Index (BMI) = weight / height2 (Height in meters) If BMI is 40 or greater, the program should print Fattest. If BMI is 35.0 or above but less than 40 , the program should print Fat level II. If BMI is 28.5 or above, but less than 35, the program should print Fat level I. If BMI is 23.5 or above but less than 28.5, the program should print Overweight. If BMI is 18.5 or above but less than 23.5, the program should print Normally. If BMI is less than 18.5, the program should print Underweight. Input The first line is height (cm) The second line is weight (kg) Output The first line shows BMI (2 decimal places). The second line shows the interpretation of BMI level. ''' h = float(input()) / 100 w = float(input()) bmi = w / (h * h) print(f'{bmi:.2f}') if bmi >= 40: print('Fattest') elif 40 > bmi >= 35: print('Fat level II') elif 35 > bmi >= 28.5: print('Fat level I') elif 28.5 > bmi >= 23.5: print('Overweight') elif 23.5 > bmi >= 18.5: print('Normally') else: print('Underweight')
""" Body mass index is a measure to assess body fat. It is widely use because it is easy to calculate and can apply to everyone. The Body Mass Index (BMI) can calculate using the following equation. Body Mass Index (BMI) = weight / height2 (Height in meters) If BMI is 40 or greater, the program should print Fattest. If BMI is 35.0 or above but less than 40 , the program should print Fat level II. If BMI is 28.5 or above, but less than 35, the program should print Fat level I. If BMI is 23.5 or above but less than 28.5, the program should print Overweight. If BMI is 18.5 or above but less than 23.5, the program should print Normally. If BMI is less than 18.5, the program should print Underweight. Input The first line is height (cm) The second line is weight (kg) Output The first line shows BMI (2 decimal places). The second line shows the interpretation of BMI level. """ h = float(input()) / 100 w = float(input()) bmi = w / (h * h) print(f'{bmi:.2f}') if bmi >= 40: print('Fattest') elif 40 > bmi >= 35: print('Fat level II') elif 35 > bmi >= 28.5: print('Fat level I') elif 28.5 > bmi >= 23.5: print('Overweight') elif 23.5 > bmi >= 18.5: print('Normally') else: print('Underweight')
""" Problem: 3.2 Stack Min: How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in 0(1) time. Hints:#27, #59, #78 -- Algorithm The default implementation of a Stack already has Push and Pop as operations in O(1) time. Thus, the goal here is to implement the Min operation. How can we do this? We have to somehow keep a list of the minimum values so that we can reach them really fast. A Hashmap would not work because it won't be ordered with the same order the elements were added to the stack. A MinHeap would help, but the operations to remove the elements would be O(logn) time. Another option is to use another stack to keep the minimum elements. Let's look at an example: Input: [5,2,3,6,1] OriginalStack [5,2,3,6,1] - the last element is on top MinStack [5,2,1] Every time we push a new element, if it is less than or equal to the top of the MinStack, we added there too. When MinStack is empty, we just add the element. Also, when we pop an element, we check if the element is in the top of the MinStack, if it is, we pop it there. Now, when we want to check the minimum element, we just look at the top of the MinStack. -- How to test it? Let's assume our input is a list of operations in a stack: - Push - Pop - Min Our return will be the minimum values we asked for. So we will check if they are correct. """ class StackWithMin: def __init__(self) -> None: self.__stack = [] self.__min_stack = [] def push(self, val): self.__stack.append(val) if not self.__min_stack: self.__min_stack.append(val) elif val <= self.__min_stack[-1]: self.__min_stack.append(val) def pop(self): if not self.__stack: raise Exception("Stack is empty") if self.__stack[-1] == self.__min_stack[-1]: self.__min_stack.pop() return self.__stack.pop() def min(self): if not self.__stack: raise Exception("Stack is empty") return self.__min_stack[-1] def query_stack(commands): stack = StackWithMin() result = [] for command in commands: query = command.split() if query[0] == "push": stack.push(int(query[1])) elif query[0] == "pop": stack.pop() elif query[0] == "min": min_value = stack.min() result.append(min_value) return result def test(commands, expected_answer): answer = query_stack(commands) if answer != expected_answer: raise Exception( f"Answer {answer} is wrong. Expected answer is {expected_answer}" ) if __name__ == "__main__": test(["push 5", "push 1", "push 2", "min", "pop", "min", "pop", "min"], [1, 1, 5]) test(["push 5", "min", "push 6", "min", "push 2", "min"], [5, 5, 2]) test(["push 5", "push 1", "push 3", "push 1", "min", "pop", "min"], [1, 1]) test(["push -5", "min", "push 6", "push -6", "min"], [-5, -6]) print("All tests passed!")
""" Problem: 3.2 Stack Min: How would you design a stack which, in addition to push and pop, has a function min which returns the minimum element? Push, pop and min should all operate in 0(1) time. Hints:#27, #59, #78 -- Algorithm The default implementation of a Stack already has Push and Pop as operations in O(1) time. Thus, the goal here is to implement the Min operation. How can we do this? We have to somehow keep a list of the minimum values so that we can reach them really fast. A Hashmap would not work because it won't be ordered with the same order the elements were added to the stack. A MinHeap would help, but the operations to remove the elements would be O(logn) time. Another option is to use another stack to keep the minimum elements. Let's look at an example: Input: [5,2,3,6,1] OriginalStack [5,2,3,6,1] - the last element is on top MinStack [5,2,1] Every time we push a new element, if it is less than or equal to the top of the MinStack, we added there too. When MinStack is empty, we just add the element. Also, when we pop an element, we check if the element is in the top of the MinStack, if it is, we pop it there. Now, when we want to check the minimum element, we just look at the top of the MinStack. -- How to test it? Let's assume our input is a list of operations in a stack: - Push - Pop - Min Our return will be the minimum values we asked for. So we will check if they are correct. """ class Stackwithmin: def __init__(self) -> None: self.__stack = [] self.__min_stack = [] def push(self, val): self.__stack.append(val) if not self.__min_stack: self.__min_stack.append(val) elif val <= self.__min_stack[-1]: self.__min_stack.append(val) def pop(self): if not self.__stack: raise exception('Stack is empty') if self.__stack[-1] == self.__min_stack[-1]: self.__min_stack.pop() return self.__stack.pop() def min(self): if not self.__stack: raise exception('Stack is empty') return self.__min_stack[-1] def query_stack(commands): stack = stack_with_min() result = [] for command in commands: query = command.split() if query[0] == 'push': stack.push(int(query[1])) elif query[0] == 'pop': stack.pop() elif query[0] == 'min': min_value = stack.min() result.append(min_value) return result def test(commands, expected_answer): answer = query_stack(commands) if answer != expected_answer: raise exception(f'Answer {answer} is wrong. Expected answer is {expected_answer}') if __name__ == '__main__': test(['push 5', 'push 1', 'push 2', 'min', 'pop', 'min', 'pop', 'min'], [1, 1, 5]) test(['push 5', 'min', 'push 6', 'min', 'push 2', 'min'], [5, 5, 2]) test(['push 5', 'push 1', 'push 3', 'push 1', 'min', 'pop', 'min'], [1, 1]) test(['push -5', 'min', 'push 6', 'push -6', 'min'], [-5, -6]) print('All tests passed!')
#!/usr/bin/env python3 # Write a program that computes the GC% of a DNA sequence # Format the output for 2 decimal places # Use all three formatting methods dna = 'ACAGAGCCAGCAGATATACAGCAGATACTAT' # feel free to change s_count = 0 for nt in dna: if nt == "G" or nt == "C": s_count += 1 s_frac = s_count / len(dna) # Method 1: % print('%.2f' %(s_frac)) # Method 2:{}.format print('{:.2f}'.format(s_frac)) #Method 3:f{} print(f'{s_frac:.2f}') """ 0.42 0.42 0.42 """
dna = 'ACAGAGCCAGCAGATATACAGCAGATACTAT' s_count = 0 for nt in dna: if nt == 'G' or nt == 'C': s_count += 1 s_frac = s_count / len(dna) print('%.2f' % s_frac) print('{:.2f}'.format(s_frac)) print(f'{s_frac:.2f}') '\n0.42\n0.42\n0.42\n'
#[playbook(say_hi)] def say_hi(ctx): with open('/scratch/output.txt', 'w') as f: print("{message}".format(**ctx), file=f)
def say_hi(ctx): with open('/scratch/output.txt', 'w') as f: print('{message}'.format(**ctx), file=f)
class Solution(object): def wordPattern(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ s=pattern t=str.split() return map(s.index, s) == map(t.index, t)
class Solution(object): def word_pattern(self, pattern, str): """ :type pattern: str :type str: str :rtype: bool """ s = pattern t = str.split() return map(s.index, s) == map(t.index, t)
{ "targets": [ { "target_name": "sypexgeo", "sources": [ "src/xyz/vyvid/sypexgeo/bindings/nodejs/sypexgeo_node.cc", "src/xyz/vyvid/sypexgeo/bindings/nodejs/sypexgeo_node.h", "src/xyz/vyvid/sypexgeo/util/string_builder.h", "src/xyz/vyvid/sypexgeo/uint24_t.h", "src/xyz/vyvid/sypexgeo/db.cc", "src/xyz/vyvid/sypexgeo/db.h", "src/xyz/vyvid/sypexgeo/errors.h", "src/xyz/vyvid/sypexgeo/header.h", "src/xyz/vyvid/sypexgeo/location.cc", "src/xyz/vyvid/sypexgeo/location.h", "src/xyz/vyvid/sypexgeo/raw_city_access.h", "src/xyz/vyvid/sypexgeo/raw_country_access.h", "src/xyz/vyvid/sypexgeo/raw_region_access.h" ], "include_dirs": [ "<!(node -e \"require('nan')\")", "./src" ], "cflags": [ "-std=gnu++11", "-fno-rtti", "-Wall", "-fexceptions" ], "cflags_cc": [ "-std=gnu++11", "-fno-rtti", "-Wall", "-fexceptions" ], "conditions": [ [ "OS=='mac'", { "xcode_settings": { "GCC_ENABLE_CPP_EXCEPTIONS": "YES", "GCC_ENABLE_CPP_RTTI": "NO", "CLANG_CXX_LANGUAGE_STANDARD": "gnu++11", "CLANG_CXX_LIBRARY": "libc++", "MACOSX_DEPLOYMENT_TARGET": "10.7" } } ] ] } ] }
{'targets': [{'target_name': 'sypexgeo', 'sources': ['src/xyz/vyvid/sypexgeo/bindings/nodejs/sypexgeo_node.cc', 'src/xyz/vyvid/sypexgeo/bindings/nodejs/sypexgeo_node.h', 'src/xyz/vyvid/sypexgeo/util/string_builder.h', 'src/xyz/vyvid/sypexgeo/uint24_t.h', 'src/xyz/vyvid/sypexgeo/db.cc', 'src/xyz/vyvid/sypexgeo/db.h', 'src/xyz/vyvid/sypexgeo/errors.h', 'src/xyz/vyvid/sypexgeo/header.h', 'src/xyz/vyvid/sypexgeo/location.cc', 'src/xyz/vyvid/sypexgeo/location.h', 'src/xyz/vyvid/sypexgeo/raw_city_access.h', 'src/xyz/vyvid/sypexgeo/raw_country_access.h', 'src/xyz/vyvid/sypexgeo/raw_region_access.h'], 'include_dirs': ['<!(node -e "require(\'nan\')")', './src'], 'cflags': ['-std=gnu++11', '-fno-rtti', '-Wall', '-fexceptions'], 'cflags_cc': ['-std=gnu++11', '-fno-rtti', '-Wall', '-fexceptions'], 'conditions': [["OS=='mac'", {'xcode_settings': {'GCC_ENABLE_CPP_EXCEPTIONS': 'YES', 'GCC_ENABLE_CPP_RTTI': 'NO', 'CLANG_CXX_LANGUAGE_STANDARD': 'gnu++11', 'CLANG_CXX_LIBRARY': 'libc++', 'MACOSX_DEPLOYMENT_TARGET': '10.7'}}]]}]}
# # PySNMP MIB module Unisphere-Data-AUTOCONFIGURE-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/Unisphere-Data-AUTOCONFIGURE-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 21:23:11 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ConstraintsIntersection, ValueSizeConstraint, SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsIntersection", "ValueSizeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint") InterfaceIndex, = mibBuilder.importSymbols("IF-MIB", "InterfaceIndex") ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup") Unsigned32, Integer32, IpAddress, MibScalar, MibTable, MibTableRow, MibTableColumn, iso, Counter64, Counter32, NotificationType, TimeTicks, Gauge32, ModuleIdentity, ObjectIdentity, Bits, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "Unsigned32", "Integer32", "IpAddress", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "iso", "Counter64", "Counter32", "NotificationType", "TimeTicks", "Gauge32", "ModuleIdentity", "ObjectIdentity", "Bits", "MibIdentifier") DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention") usDataMibs, = mibBuilder.importSymbols("Unisphere-Data-MIBs", "usDataMibs") UsdEnable, = mibBuilder.importSymbols("Unisphere-Data-TC", "UsdEnable") usdAutoConfMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48)) usdAutoConfMIB.setRevisions(('2002-11-18 00:00', '2000-11-16 00:00',)) if mibBuilder.loadTexts: usdAutoConfMIB.setLastUpdated('200211190000Z') if mibBuilder.loadTexts: usdAutoConfMIB.setOrganization('Unisphere Networks Inc.') class UsdAutoConfEncaps(TextualConvention, Integer32): status = 'current' subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(0, 1, 17, 19)) namedValues = NamedValues(("ip", 0), ("ppp", 1), ("pppoe", 17), ("bridgedEthernet", 19)) usdAutoConfObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1)) usdAutoConf = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1, 1)) usdAutoConfTable = MibTable((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1, 1, 1), ) if mibBuilder.loadTexts: usdAutoConfTable.setStatus('current') usdAutoConfEntry = MibTableRow((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1, 1, 1, 1), ).setIndexNames((0, "Unisphere-Data-AUTOCONFIGURE-MIB", "usdAutoConfIfIndex"), (0, "Unisphere-Data-AUTOCONFIGURE-MIB", "usdAutoConfEncaps")) if mibBuilder.loadTexts: usdAutoConfEntry.setStatus('current') usdAutoConfIfIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1, 1, 1, 1, 1), InterfaceIndex()) if mibBuilder.loadTexts: usdAutoConfIfIndex.setStatus('current') usdAutoConfEncaps = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1, 1, 1, 1, 2), UsdAutoConfEncaps()) if mibBuilder.loadTexts: usdAutoConfEncaps.setStatus('current') usdAutoConfEnable = MibTableColumn((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1, 1, 1, 1, 3), UsdEnable()).setMaxAccess("readwrite") if mibBuilder.loadTexts: usdAutoConfEnable.setStatus('current') usdAutoConfMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 4)) usdAutoConfMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 4, 1)) usdAutoConfMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 4, 2)) usdAutoConfCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 4, 1, 1)).setObjects(("Unisphere-Data-AUTOCONFIGURE-MIB", "usdAutoConfGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdAutoConfCompliance = usdAutoConfCompliance.setStatus('current') usdAutoConfGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 4, 2, 1)).setObjects(("Unisphere-Data-AUTOCONFIGURE-MIB", "usdAutoConfEnable")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usdAutoConfGroup = usdAutoConfGroup.setStatus('current') mibBuilder.exportSymbols("Unisphere-Data-AUTOCONFIGURE-MIB", usdAutoConfIfIndex=usdAutoConfIfIndex, usdAutoConfGroup=usdAutoConfGroup, usdAutoConfMIBConformance=usdAutoConfMIBConformance, usdAutoConfMIB=usdAutoConfMIB, usdAutoConfCompliance=usdAutoConfCompliance, UsdAutoConfEncaps=UsdAutoConfEncaps, usdAutoConfEncaps=usdAutoConfEncaps, usdAutoConfTable=usdAutoConfTable, usdAutoConfEntry=usdAutoConfEntry, usdAutoConfMIBCompliances=usdAutoConfMIBCompliances, usdAutoConf=usdAutoConf, usdAutoConfObjects=usdAutoConfObjects, usdAutoConfEnable=usdAutoConfEnable, usdAutoConfMIBGroups=usdAutoConfMIBGroups, PYSNMP_MODULE_ID=usdAutoConfMIB)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (constraints_intersection, value_size_constraint, single_value_constraint, constraints_union, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ConstraintsIntersection', 'ValueSizeConstraint', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueRangeConstraint') (interface_index,) = mibBuilder.importSymbols('IF-MIB', 'InterfaceIndex') (object_group, module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ObjectGroup', 'ModuleCompliance', 'NotificationGroup') (unsigned32, integer32, ip_address, mib_scalar, mib_table, mib_table_row, mib_table_column, iso, counter64, counter32, notification_type, time_ticks, gauge32, module_identity, object_identity, bits, mib_identifier) = mibBuilder.importSymbols('SNMPv2-SMI', 'Unsigned32', 'Integer32', 'IpAddress', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'iso', 'Counter64', 'Counter32', 'NotificationType', 'TimeTicks', 'Gauge32', 'ModuleIdentity', 'ObjectIdentity', 'Bits', 'MibIdentifier') (display_string, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'DisplayString', 'TextualConvention') (us_data_mibs,) = mibBuilder.importSymbols('Unisphere-Data-MIBs', 'usDataMibs') (usd_enable,) = mibBuilder.importSymbols('Unisphere-Data-TC', 'UsdEnable') usd_auto_conf_mib = module_identity((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48)) usdAutoConfMIB.setRevisions(('2002-11-18 00:00', '2000-11-16 00:00')) if mibBuilder.loadTexts: usdAutoConfMIB.setLastUpdated('200211190000Z') if mibBuilder.loadTexts: usdAutoConfMIB.setOrganization('Unisphere Networks Inc.') class Usdautoconfencaps(TextualConvention, Integer32): status = 'current' subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(0, 1, 17, 19)) named_values = named_values(('ip', 0), ('ppp', 1), ('pppoe', 17), ('bridgedEthernet', 19)) usd_auto_conf_objects = mib_identifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1)) usd_auto_conf = mib_identifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1, 1)) usd_auto_conf_table = mib_table((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1, 1, 1)) if mibBuilder.loadTexts: usdAutoConfTable.setStatus('current') usd_auto_conf_entry = mib_table_row((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1, 1, 1, 1)).setIndexNames((0, 'Unisphere-Data-AUTOCONFIGURE-MIB', 'usdAutoConfIfIndex'), (0, 'Unisphere-Data-AUTOCONFIGURE-MIB', 'usdAutoConfEncaps')) if mibBuilder.loadTexts: usdAutoConfEntry.setStatus('current') usd_auto_conf_if_index = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1, 1, 1, 1, 1), interface_index()) if mibBuilder.loadTexts: usdAutoConfIfIndex.setStatus('current') usd_auto_conf_encaps = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1, 1, 1, 1, 2), usd_auto_conf_encaps()) if mibBuilder.loadTexts: usdAutoConfEncaps.setStatus('current') usd_auto_conf_enable = mib_table_column((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 1, 1, 1, 1, 3), usd_enable()).setMaxAccess('readwrite') if mibBuilder.loadTexts: usdAutoConfEnable.setStatus('current') usd_auto_conf_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 4)) usd_auto_conf_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 4, 1)) usd_auto_conf_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 4, 2)) usd_auto_conf_compliance = module_compliance((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 4, 1, 1)).setObjects(('Unisphere-Data-AUTOCONFIGURE-MIB', 'usdAutoConfGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usd_auto_conf_compliance = usdAutoConfCompliance.setStatus('current') usd_auto_conf_group = object_group((1, 3, 6, 1, 4, 1, 4874, 2, 2, 48, 4, 2, 1)).setObjects(('Unisphere-Data-AUTOCONFIGURE-MIB', 'usdAutoConfEnable')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): usd_auto_conf_group = usdAutoConfGroup.setStatus('current') mibBuilder.exportSymbols('Unisphere-Data-AUTOCONFIGURE-MIB', usdAutoConfIfIndex=usdAutoConfIfIndex, usdAutoConfGroup=usdAutoConfGroup, usdAutoConfMIBConformance=usdAutoConfMIBConformance, usdAutoConfMIB=usdAutoConfMIB, usdAutoConfCompliance=usdAutoConfCompliance, UsdAutoConfEncaps=UsdAutoConfEncaps, usdAutoConfEncaps=usdAutoConfEncaps, usdAutoConfTable=usdAutoConfTable, usdAutoConfEntry=usdAutoConfEntry, usdAutoConfMIBCompliances=usdAutoConfMIBCompliances, usdAutoConf=usdAutoConf, usdAutoConfObjects=usdAutoConfObjects, usdAutoConfEnable=usdAutoConfEnable, usdAutoConfMIBGroups=usdAutoConfMIBGroups, PYSNMP_MODULE_ID=usdAutoConfMIB)
# http://flask-sqlalchemy.pocoo.org/2.1/config/ SQLALCHEMY_DATABASE_URI = 'sqlite:////commandment/commandment.db' # FSADeprecationWarning: SQLALCHEMY_TRACK_MODIFICATIONS adds significant overhead and will be disabled by default in the future. SQLALCHEMY_TRACK_MODIFICATIONS = False PORT = 5443 # PLEASE! Do not take this key and use it for another product/project. It's # only for Commandment's use. If you'd like to get your own (free!) key # contact the mdmcert.download administrators and get your own key for your # own project/product. We're trying to keep statistics on which products are # requesting certs (per Apple T&C). Don't force Apple's hand and # ruin it for everyone! MDMCERT_API_KEY = 'b742461ff981756ca3f924f02db5a12e1f6639a9109db047ead1814aafc058dd' PLISTIFY_MIMETYPE = 'application/xml'
sqlalchemy_database_uri = 'sqlite:////commandment/commandment.db' sqlalchemy_track_modifications = False port = 5443 mdmcert_api_key = 'b742461ff981756ca3f924f02db5a12e1f6639a9109db047ead1814aafc058dd' plistify_mimetype = 'application/xml'
def combine_words(word, **kwargs): if 'prefix' in kwargs: return kwargs['prefix'] + word elif 'suffix' in kwargs: return word + kwargs['suffix'] return word print(combine_words('child', prefix='man')) print(combine_words('child', suffix='ish')) print(combine_words('child'))
def combine_words(word, **kwargs): if 'prefix' in kwargs: return kwargs['prefix'] + word elif 'suffix' in kwargs: return word + kwargs['suffix'] return word print(combine_words('child', prefix='man')) print(combine_words('child', suffix='ish')) print(combine_words('child'))
# -*- coding: utf-8 -*- """ Created on Sun Jul 5 09:03:49 2020 @author: Okuda """
""" Created on Sun Jul 5 09:03:49 2020 @author: Okuda """
#Tuple #ordered #indexed #Immutable #Faster than list t = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday") print(t) print(type(t)) #t.append(20) AttributeError: 'tuple' object has no attribute 'append' print(t[2]) print(t[-1]) print(t[1:3]) print(len(t)) print(t.count("Monday")) print(t.index("Friday")) #Problem: """ Given a tuple A , find if all elements of tuple are different or not. Example 1: Input: A = (1, 2, 3, 4, 5, 4) Output: Not Distinct Example 2: Input: A = (1, 2, 3, 4, 5) Output: Distinct """ A = (1, 2, 3, 4) s = set(A) if len(A) != len(s): output = "Not Distinct" elif len(A) == len(s): output = "Distinct" print(output) print("#######################################################") #Problem: """ Given a tuple A with distinct elements and an integer X, find the index position of X. Assume to have X in the tuple always. Example 1: Input: A = (1, 2, 3, 4, 5) X = 3 Output: 2 Example 2: Input: A = (3, 2, 1, 5, 4) X = 5 Output: 3 """ A = (1, 2, 3, 4, 5) X = 3 for i in range(len(A)): if A[i] == X: print(i)
t = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday') print(t) print(type(t)) print(t[2]) print(t[-1]) print(t[1:3]) print(len(t)) print(t.count('Monday')) print(t.index('Friday')) '\nGiven a tuple A , find if all elements of tuple are different or not.\n\nExample 1:\n\nInput:\nA = (1, 2, 3, 4, 5, 4)\nOutput: \nNot Distinct\nExample 2:\n\nInput:\nA = (1, 2, 3, 4, 5)\nOutput: \nDistinct\n\n' a = (1, 2, 3, 4) s = set(A) if len(A) != len(s): output = 'Not Distinct' elif len(A) == len(s): output = 'Distinct' print(output) print('#######################################################') '\nGiven a tuple A with distinct elements and an integer X, find the index position of X. Assume to have X in the tuple always.\n\nExample 1:\n\nInput:\nA = (1, 2, 3, 4, 5)\nX = 3\nOutput: \n2\nExample 2:\n\nInput:\nA = (3, 2, 1, 5, 4)\nX = 5\nOutput: \n3\n\n' a = (1, 2, 3, 4, 5) x = 3 for i in range(len(A)): if A[i] == X: print(i)
# -*- coding: utf-8 -*- PI = 3.14159 def main(): r = float(input()) area = PI * r * r print('A=%.4f' % area) if __name__ == '__main__': main()
pi = 3.14159 def main(): r = float(input()) area = PI * r * r print('A=%.4f' % area) if __name__ == '__main__': main()
def get_action(self, states, epsilon): if np.random.random() < epsilon: return np.random.choice(self.num_actions) else: return np.argmax(self.predict(np.atleast_2d(states))[0])
def get_action(self, states, epsilon): if np.random.random() < epsilon: return np.random.choice(self.num_actions) else: return np.argmax(self.predict(np.atleast_2d(states))[0])
class TogaLayout(extends=android.view.ViewGroup): @super({context: android.content.Context}) def __init__(self, context, interface): self.interface = interface def shouldDelayChildPressedState(self) -> bool: return False def onMeasure(self, width: int, height: int) -> void: # print("ON MEASURE %sx%s" % (width, height)) self.measureChildren(width, height) self.interface.rehint() self.setMeasuredDimension(width, height) def onLayout(self, changed: bool, left: int, top: int, right: int, bottom: int) -> void: # print("ON LAYOUT %s %sx%s -> %sx%s" % (changed, left, top, right, bottom)) device_scale = self.interface.app._impl.device_scale self.interface._update_layout( width=(right - left) / device_scale, height=(bottom - top) / device_scale, ) self.interface.style.apply() count = self.getChildCount() # print("LAYOUT: There are %d children" % count) for i in range(0, count): child = self.getChildAt(i) # print(" child: %s" % child, child.getMeasuredHeight(), child.getMeasuredWidth(), child.getWidth(), child.getHeight()) # print(" layout: ", child.interface.layout) child.layout( child.interface.layout.absolute.left * device_scale, child.interface.layout.absolute.top * device_scale, (child.interface.layout.absolute.left + child.interface.layout.width) * device_scale, (child.interface.layout.absolute.top + child.interface.layout.height) * device_scale, ) # def onSizeChanged(self, left: int, top: int, right: int, bottom: int) -> void: # print("ON SIZE CHANGE %sx%s -> %sx%s" % (left, top, right, bottom)) # count = self.getChildCount() # print("CHANGE: There are %d children" % count) # for i in range(0, count): # child = self.getChildAt(i) # print(" child: %s" % child)
class Togalayout(extends=android.view.ViewGroup): @super({context: android.content.Context}) def __init__(self, context, interface): self.interface = interface def should_delay_child_pressed_state(self) -> bool: return False def on_measure(self, width: int, height: int) -> void: self.measureChildren(width, height) self.interface.rehint() self.setMeasuredDimension(width, height) def on_layout(self, changed: bool, left: int, top: int, right: int, bottom: int) -> void: device_scale = self.interface.app._impl.device_scale self.interface._update_layout(width=(right - left) / device_scale, height=(bottom - top) / device_scale) self.interface.style.apply() count = self.getChildCount() for i in range(0, count): child = self.getChildAt(i) child.layout(child.interface.layout.absolute.left * device_scale, child.interface.layout.absolute.top * device_scale, (child.interface.layout.absolute.left + child.interface.layout.width) * device_scale, (child.interface.layout.absolute.top + child.interface.layout.height) * device_scale)
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Interpreter version: python 2.7 # # Imports ===================================================================== # Functions & classes ========================================================= def _by_attr(xdom, attr): """ From `xdom` pick element with attributes defined by `attr`. Args: xdom (obj): DOM parsed by :mod:`xmltodict`. attr (dict): Dictionary defining all the arguments. Returns: obj: List in case that multiple records were returned, or OrderedDict \ instance in case that there was only one. Blank array in case of \ no matching tag. """ out = [] for tag in xdom: for attr_name, val in attr.iteritems(): if attr_name not in tag: break if val is not None and tag[attr_name] != val: break out.append(tag) return out[0] if len(out) == 1 else out class Modes(object): """ Container holding informations about modes which may be used by registrar to register documents. Attributes: by_resolver (bool): True if the mode can be used. by_registrar (bool): True if the mode can be used. by_reservation (bool): True if the mode can be used. """ def __init__(self, by_resolver=False, by_registrar=False, by_reservation=False): self.by_resolver = by_resolver self.by_registrar = by_registrar self.by_reservation = by_reservation def __eq__(self, other): return all([ self.by_resolver == other.by_resolver, self.by_registrar == other.by_registrar, self.by_reservation == other.by_reservation, ]) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return "Modes(%r%r%r)" % ( self.by_resolver, self.by_registrar, self.by_reservation ) @staticmethod def from_xmldict(modes_tag): """ Parse Modes information from XML. Args: modes_tags (obj): OrderedDict ``<modes>`` tag returned from :mod:`xmltodict`. Returns: obj: :class:`.Modes` instance. """ by_resolver = _by_attr(modes_tag, attr={"@name": "BY_RESOLVER"}) by_registrar = _by_attr(modes_tag, attr={"@name": "BY_REGISTRAR"}) by_reservation = _by_attr(modes_tag, attr={"@name": "BY_RESERVATION"}) return Modes( by_resolver=by_resolver["@enabled"].lower() == "true", by_registrar=by_registrar["@enabled"].lower() == "true", by_reservation=by_reservation["@enabled"].lower() == "true", )
def _by_attr(xdom, attr): """ From `xdom` pick element with attributes defined by `attr`. Args: xdom (obj): DOM parsed by :mod:`xmltodict`. attr (dict): Dictionary defining all the arguments. Returns: obj: List in case that multiple records were returned, or OrderedDict instance in case that there was only one. Blank array in case of no matching tag. """ out = [] for tag in xdom: for (attr_name, val) in attr.iteritems(): if attr_name not in tag: break if val is not None and tag[attr_name] != val: break out.append(tag) return out[0] if len(out) == 1 else out class Modes(object): """ Container holding informations about modes which may be used by registrar to register documents. Attributes: by_resolver (bool): True if the mode can be used. by_registrar (bool): True if the mode can be used. by_reservation (bool): True if the mode can be used. """ def __init__(self, by_resolver=False, by_registrar=False, by_reservation=False): self.by_resolver = by_resolver self.by_registrar = by_registrar self.by_reservation = by_reservation def __eq__(self, other): return all([self.by_resolver == other.by_resolver, self.by_registrar == other.by_registrar, self.by_reservation == other.by_reservation]) def __ne__(self, other): return not self.__eq__(other) def __repr__(self): return 'Modes(%r%r%r)' % (self.by_resolver, self.by_registrar, self.by_reservation) @staticmethod def from_xmldict(modes_tag): """ Parse Modes information from XML. Args: modes_tags (obj): OrderedDict ``<modes>`` tag returned from :mod:`xmltodict`. Returns: obj: :class:`.Modes` instance. """ by_resolver = _by_attr(modes_tag, attr={'@name': 'BY_RESOLVER'}) by_registrar = _by_attr(modes_tag, attr={'@name': 'BY_REGISTRAR'}) by_reservation = _by_attr(modes_tag, attr={'@name': 'BY_RESERVATION'}) return modes(by_resolver=by_resolver['@enabled'].lower() == 'true', by_registrar=by_registrar['@enabled'].lower() == 'true', by_reservation=by_reservation['@enabled'].lower() == 'true')
L = list(map(int,list(input()))) i = 0 k = 1 while i < len(L): L2 = list(map(int,list(str(k)))) j = 0 while i<len(L) and j <len(L2): if L[i] == L2[j]: i+=1 j+=1 k+=1 print(k-1)
l = list(map(int, list(input()))) i = 0 k = 1 while i < len(L): l2 = list(map(int, list(str(k)))) j = 0 while i < len(L) and j < len(L2): if L[i] == L2[j]: i += 1 j += 1 k += 1 print(k - 1)
# # PySNMP MIB module CENTILLION-ROOT-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CENTILLION-ROOT-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 17:15:30 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueSizeConstraint, ConstraintsUnion, SingleValueConstraint, ConstraintsIntersection, ValueRangeConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueSizeConstraint", "ConstraintsUnion", "SingleValueConstraint", "ConstraintsIntersection", "ValueRangeConstraint") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") MibIdentifier, iso, Counter32, Gauge32, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32, Bits, TimeTicks, Counter64, Integer32, ModuleIdentity, NotificationType, enterprises, IpAddress, ObjectIdentity = mibBuilder.importSymbols("SNMPv2-SMI", "MibIdentifier", "iso", "Counter32", "Gauge32", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32", "Bits", "TimeTicks", "Counter64", "Integer32", "ModuleIdentity", "NotificationType", "enterprises", "IpAddress", "ObjectIdentity") Counter32, = mibBuilder.importSymbols("SNMPv2-SMI-v1", "Counter32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") class StatusIndicator(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("valid", 1), ("invalid", 2)) class SsBackplaneType(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("other", 1), ("atmBus", 2)) class SsChassisType(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7)) namedValues = NamedValues(("other", 1), ("six-slot", 2), ("twelve-slot", 3), ("workgroup", 4), ("three-slotC50N", 5), ("three-slotC50T", 6), ("six-slotBH5005", 7)) class SsModuleType(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)) namedValues = NamedValues(("empty", 1), ("other", 2), ("mTR4PC", 3), ("mTRMCP4PC", 4), ("mATM", 5), ("mTRFiber", 6), ("mTRMCPFiber", 7), ("mEther16PC10BT", 8), ("mEtherMCP8PC10BT", 9), ("mATM2PSMFiber", 10), ("mATM2PCopper", 11), ("mATM4PMMFiber", 12), ("mATM4PSMFiber", 13), ("mATM4PCopper", 14), ("mATMMCP2PSMFiber", 15), ("mATMMCP2PMMFiber", 16), ("mATMMCP2PCopper", 17), ("mATMMCP4PSMFiber", 18), ("mATMMCP4PMMFiber", 19), ("mATMMCP4PCopper", 20), ("mATM2PC", 21), ("mATM4PC", 22), ("mATMMCP2PC", 23), ("mATMMCP4PC", 24), ("mEther16P10BT100BTCopper", 25), ("mEther14P10BT100BF", 26), ("mEther8P10BF", 27), ("mEther10P10BT100BT", 28), ("mEther16P10BT100BTMixed", 29), ("mEther10P10BT100BTMIX", 30), ("mEther12PBFL", 32), ("mEther16P4x4", 33), ("mTRMCP8PC", 34), ("mTR8PC", 35), ("mEther24PC", 36), ("mEther24P10BT100BT", 37), ("mEther24P100BFx", 38), ("mTR8PFiber", 39), ("mATM4PMDA", 40), ("mATMMCP4PMDA", 41), ("mEther4P100BT", 42), ("mTR24PC", 43), ("mTR16PC", 44), ("mATMMCP1PSMFiber", 45), ("mATMMCP1PMMFiber", 46), ("mATM1PMMFiber", 47), ("mATM1PVNR", 48), ("mEther24P10BT100BTx", 49), ("mEther24P100BFX", 50)) class SsMediaType(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5)) namedValues = NamedValues(("mediaUnkown", 1), ("mediaTokenRing", 2), ("mediaFDDI", 3), ("mediaEthernet", 4), ("mediaATM", 5)) class MacAddress(OctetString): subtypeSpec = OctetString.subtypeSpec + ValueSizeConstraint(6, 6) fixedLength = 6 class Boolean(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("true", 1), ("false", 2)) class BitField(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("clear", 1), ("set", 2)) class PortId(Integer32): subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 65535) class CardId(Integer32): subtypeSpec = Integer32.subtypeSpec + ValueRangeConstraint(1, 16) class FailIndicator(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("on", 1), ("off", 2)) class EnableIndicator(Integer32): subtypeSpec = Integer32.subtypeSpec + ConstraintsUnion(SingleValueConstraint(1, 2)) namedValues = NamedValues(("disabled", 1), ("enabled", 2)) centillion = MibIdentifier((1, 3, 6, 1, 4, 1, 930)) cnProducts = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 1)) proprietary = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2)) extensions = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 3)) cnTemporary = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 4)) cnSystem = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 1)) cnATM = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 2)) sysChassis = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 1)) sysConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 2)) sysMonitor = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 3)) sysTrap = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 4)) sysEvtLogMgmt = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 5)) atmConfig = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 2, 1)) atmMonitor = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 2, 2)) atmLane = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 2, 3)) atmSonet = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 2, 4)) sysMcpRedundTrap = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 4, 1)) cnPvcTraps = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 4, 2)) cnCentillion100 = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 1, 1)) cnIBM8251 = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 1, 2)) cnBayStack301 = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 1, 3)) cn5000BH_MCP = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 1, 4)).setLabel("cn5000BH-MCP") cnCentillion50N = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 1, 5)) cnCentillion50T = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 1, 6)) cn5005BH_MCP = MibIdentifier((1, 3, 6, 1, 4, 1, 930, 1, 7)).setLabel("cn5005BH-MCP") chassisType = MibScalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 1), SsChassisType()).setMaxAccess("readonly") if mibBuilder.loadTexts: chassisType.setStatus('mandatory') chassisBkplType = MibScalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 2), SsBackplaneType()).setMaxAccess("readonly") if mibBuilder.loadTexts: chassisBkplType.setStatus('mandatory') chassisPs1FailStatus = MibScalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 3), FailIndicator()).setMaxAccess("readonly") if mibBuilder.loadTexts: chassisPs1FailStatus.setStatus('mandatory') chassisPs2FailStatus = MibScalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 4), FailIndicator()).setMaxAccess("readonly") if mibBuilder.loadTexts: chassisPs2FailStatus.setStatus('mandatory') chassisFanFailStatus = MibScalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 5), FailIndicator()).setMaxAccess("readonly") if mibBuilder.loadTexts: chassisFanFailStatus.setStatus('mandatory') chassisSerialNumber = MibScalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 6), OctetString().subtype(subtypeSpec=ValueSizeConstraint(3, 3)).setFixedLength(3)).setMaxAccess("readonly") if mibBuilder.loadTexts: chassisSerialNumber.setStatus('mandatory') chassisPartNumber = MibScalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 7), OctetString().subtype(subtypeSpec=ValueSizeConstraint(6, 6)).setFixedLength(6)).setMaxAccess("readonly") if mibBuilder.loadTexts: chassisPartNumber.setStatus('mandatory') slotConfigTable = MibTable((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9), ) if mibBuilder.loadTexts: slotConfigTable.setStatus('mandatory') slotConfigEntry = MibTableRow((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1), ).setIndexNames((0, "CENTILLION-ROOT-MIB", "slotNumber")) if mibBuilder.loadTexts: slotConfigEntry.setStatus('mandatory') slotNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 1), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotNumber.setStatus('mandatory') slotModuleType = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 2), SsModuleType()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotModuleType.setStatus('deprecated') slotModuleHwVer = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 3), OctetString().subtype(subtypeSpec=ValueSizeConstraint(6, 6)).setFixedLength(6)).setMaxAccess("readonly") if mibBuilder.loadTexts: slotModuleHwVer.setStatus('mandatory') slotModuleSerialNumber = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 4), OctetString().subtype(subtypeSpec=ValueSizeConstraint(3, 3)).setFixedLength(3)).setMaxAccess("readonly") if mibBuilder.loadTexts: slotModuleSerialNumber.setStatus('mandatory') slotModuleSwVer = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 5), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotModuleSwVer.setStatus('mandatory') slotModuleStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("ok", 1), ("fail", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: slotModuleStatus.setStatus('mandatory') slotModuleLeds = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 7), OctetString()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotModuleLeds.setStatus('mandatory') slotModuleReset = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 8), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2))).clone(namedValues=NamedValues(("noReset", 1), ("reset", 2)))).setMaxAccess("readwrite") if mibBuilder.loadTexts: slotModuleReset.setStatus('mandatory') slotConfigDelete = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 9), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: slotConfigDelete.setStatus('mandatory') slotConfigMediaType = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 10), SsMediaType()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotConfigMediaType.setStatus('mandatory') slotModuleMaxRAM = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 11), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotModuleMaxRAM.setStatus('mandatory') slotModuleInstalledRAM = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 12), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotModuleInstalledRAM.setStatus('mandatory') slotModuleFlashSize = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 13), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotModuleFlashSize.setStatus('mandatory') slotModuleProductImageId = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 14), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(1, 2, 3, 4, 5))).clone(namedValues=NamedValues(("notApplicable", 1), ("noAtmLanEmulation", 2), ("minAtmLanEmulation", 3), ("fullAtmLanEmulation", 4), ("pnnifullAtmLanEmulation", 5)))).setMaxAccess("readonly") if mibBuilder.loadTexts: slotModuleProductImageId.setStatus('mandatory') slotModuleBaseMacAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 15), MacAddress()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotModuleBaseMacAddress.setStatus('mandatory') slotLastResetEPC = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 16), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotLastResetEPC.setStatus('mandatory') slotLastResetVirtualAddress = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 17), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotLastResetVirtualAddress.setStatus('mandatory') slotLastResetCause = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 18), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotLastResetCause.setStatus('mandatory') slotLastResetTimeStamp = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 19), Counter32()).setMaxAccess("readonly") if mibBuilder.loadTexts: slotLastResetTimeStamp.setStatus('mandatory') slotConfigAdd = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 20), Boolean()).setMaxAccess("readwrite") if mibBuilder.loadTexts: slotConfigAdd.setStatus('mandatory') slotConfigExtClockSource = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 21), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: slotConfigExtClockSource.setStatus('mandatory') slotConfigTrafficShapingRate = MibTableColumn((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 22), Integer32()).setMaxAccess("readwrite") if mibBuilder.loadTexts: slotConfigTrafficShapingRate.setStatus('mandatory') mibBuilder.exportSymbols("CENTILLION-ROOT-MIB", EnableIndicator=EnableIndicator, slotNumber=slotNumber, SsChassisType=SsChassisType, SsModuleType=SsModuleType, slotLastResetEPC=slotLastResetEPC, cnPvcTraps=cnPvcTraps, slotLastResetVirtualAddress=slotLastResetVirtualAddress, sysMcpRedundTrap=sysMcpRedundTrap, sysEvtLogMgmt=sysEvtLogMgmt, CardId=CardId, chassisPs1FailStatus=chassisPs1FailStatus, cnATM=cnATM, SsMediaType=SsMediaType, slotConfigTable=slotConfigTable, slotModuleHwVer=slotModuleHwVer, slotConfigMediaType=slotConfigMediaType, cnBayStack301=cnBayStack301, SsBackplaneType=SsBackplaneType, sysConfig=sysConfig, chassisPartNumber=chassisPartNumber, slotModuleLeds=slotModuleLeds, slotConfigExtClockSource=slotConfigExtClockSource, FailIndicator=FailIndicator, proprietary=proprietary, slotModuleReset=slotModuleReset, sysChassis=sysChassis, cnIBM8251=cnIBM8251, chassisBkplType=chassisBkplType, extensions=extensions, cnCentillion50N=cnCentillion50N, slotModuleType=slotModuleType, slotModuleProductImageId=slotModuleProductImageId, atmLane=atmLane, StatusIndicator=StatusIndicator, cnSystem=cnSystem, slotConfigEntry=slotConfigEntry, BitField=BitField, cnTemporary=cnTemporary, centillion=centillion, slotModuleStatus=slotModuleStatus, cnCentillion50T=cnCentillion50T, chassisSerialNumber=chassisSerialNumber, slotModuleSerialNumber=slotModuleSerialNumber, slotModuleFlashSize=slotModuleFlashSize, slotModuleBaseMacAddress=slotModuleBaseMacAddress, slotConfigAdd=slotConfigAdd, slotConfigDelete=slotConfigDelete, Boolean=Boolean, slotLastResetTimeStamp=slotLastResetTimeStamp, chassisFanFailStatus=chassisFanFailStatus, cn5000BH_MCP=cn5000BH_MCP, slotModuleInstalledRAM=slotModuleInstalledRAM, cnProducts=cnProducts, cn5005BH_MCP=cn5005BH_MCP, PortId=PortId, slotModuleSwVer=slotModuleSwVer, slotLastResetCause=slotLastResetCause, atmConfig=atmConfig, slotModuleMaxRAM=slotModuleMaxRAM, slotConfigTrafficShapingRate=slotConfigTrafficShapingRate, cnCentillion100=cnCentillion100, sysMonitor=sysMonitor, atmMonitor=atmMonitor, chassisPs2FailStatus=chassisPs2FailStatus, sysTrap=sysTrap, atmSonet=atmSonet, chassisType=chassisType, MacAddress=MacAddress)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_size_constraint, constraints_union, single_value_constraint, constraints_intersection, value_range_constraint) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueSizeConstraint', 'ConstraintsUnion', 'SingleValueConstraint', 'ConstraintsIntersection', 'ValueRangeConstraint') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (mib_identifier, iso, counter32, gauge32, mib_scalar, mib_table, mib_table_row, mib_table_column, unsigned32, bits, time_ticks, counter64, integer32, module_identity, notification_type, enterprises, ip_address, object_identity) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibIdentifier', 'iso', 'Counter32', 'Gauge32', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Unsigned32', 'Bits', 'TimeTicks', 'Counter64', 'Integer32', 'ModuleIdentity', 'NotificationType', 'enterprises', 'IpAddress', 'ObjectIdentity') (counter32,) = mibBuilder.importSymbols('SNMPv2-SMI-v1', 'Counter32') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') class Statusindicator(Integer32): subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2)) named_values = named_values(('valid', 1), ('invalid', 2)) class Ssbackplanetype(Integer32): subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2)) named_values = named_values(('other', 1), ('atmBus', 2)) class Sschassistype(Integer32): subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7)) named_values = named_values(('other', 1), ('six-slot', 2), ('twelve-slot', 3), ('workgroup', 4), ('three-slotC50N', 5), ('three-slotC50T', 6), ('six-slotBH5005', 7)) class Ssmoduletype(Integer32): subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50)) named_values = named_values(('empty', 1), ('other', 2), ('mTR4PC', 3), ('mTRMCP4PC', 4), ('mATM', 5), ('mTRFiber', 6), ('mTRMCPFiber', 7), ('mEther16PC10BT', 8), ('mEtherMCP8PC10BT', 9), ('mATM2PSMFiber', 10), ('mATM2PCopper', 11), ('mATM4PMMFiber', 12), ('mATM4PSMFiber', 13), ('mATM4PCopper', 14), ('mATMMCP2PSMFiber', 15), ('mATMMCP2PMMFiber', 16), ('mATMMCP2PCopper', 17), ('mATMMCP4PSMFiber', 18), ('mATMMCP4PMMFiber', 19), ('mATMMCP4PCopper', 20), ('mATM2PC', 21), ('mATM4PC', 22), ('mATMMCP2PC', 23), ('mATMMCP4PC', 24), ('mEther16P10BT100BTCopper', 25), ('mEther14P10BT100BF', 26), ('mEther8P10BF', 27), ('mEther10P10BT100BT', 28), ('mEther16P10BT100BTMixed', 29), ('mEther10P10BT100BTMIX', 30), ('mEther12PBFL', 32), ('mEther16P4x4', 33), ('mTRMCP8PC', 34), ('mTR8PC', 35), ('mEther24PC', 36), ('mEther24P10BT100BT', 37), ('mEther24P100BFx', 38), ('mTR8PFiber', 39), ('mATM4PMDA', 40), ('mATMMCP4PMDA', 41), ('mEther4P100BT', 42), ('mTR24PC', 43), ('mTR16PC', 44), ('mATMMCP1PSMFiber', 45), ('mATMMCP1PMMFiber', 46), ('mATM1PMMFiber', 47), ('mATM1PVNR', 48), ('mEther24P10BT100BTx', 49), ('mEther24P100BFX', 50)) class Ssmediatype(Integer32): subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2, 3, 4, 5)) named_values = named_values(('mediaUnkown', 1), ('mediaTokenRing', 2), ('mediaFDDI', 3), ('mediaEthernet', 4), ('mediaATM', 5)) class Macaddress(OctetString): subtype_spec = OctetString.subtypeSpec + value_size_constraint(6, 6) fixed_length = 6 class Boolean(Integer32): subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2)) named_values = named_values(('true', 1), ('false', 2)) class Bitfield(Integer32): subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2)) named_values = named_values(('clear', 1), ('set', 2)) class Portid(Integer32): subtype_spec = Integer32.subtypeSpec + value_range_constraint(1, 65535) class Cardid(Integer32): subtype_spec = Integer32.subtypeSpec + value_range_constraint(1, 16) class Failindicator(Integer32): subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2)) named_values = named_values(('on', 1), ('off', 2)) class Enableindicator(Integer32): subtype_spec = Integer32.subtypeSpec + constraints_union(single_value_constraint(1, 2)) named_values = named_values(('disabled', 1), ('enabled', 2)) centillion = mib_identifier((1, 3, 6, 1, 4, 1, 930)) cn_products = mib_identifier((1, 3, 6, 1, 4, 1, 930, 1)) proprietary = mib_identifier((1, 3, 6, 1, 4, 1, 930, 2)) extensions = mib_identifier((1, 3, 6, 1, 4, 1, 930, 3)) cn_temporary = mib_identifier((1, 3, 6, 1, 4, 1, 930, 4)) cn_system = mib_identifier((1, 3, 6, 1, 4, 1, 930, 2, 1)) cn_atm = mib_identifier((1, 3, 6, 1, 4, 1, 930, 2, 2)) sys_chassis = mib_identifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 1)) sys_config = mib_identifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 2)) sys_monitor = mib_identifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 3)) sys_trap = mib_identifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 4)) sys_evt_log_mgmt = mib_identifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 5)) atm_config = mib_identifier((1, 3, 6, 1, 4, 1, 930, 2, 2, 1)) atm_monitor = mib_identifier((1, 3, 6, 1, 4, 1, 930, 2, 2, 2)) atm_lane = mib_identifier((1, 3, 6, 1, 4, 1, 930, 2, 2, 3)) atm_sonet = mib_identifier((1, 3, 6, 1, 4, 1, 930, 2, 2, 4)) sys_mcp_redund_trap = mib_identifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 4, 1)) cn_pvc_traps = mib_identifier((1, 3, 6, 1, 4, 1, 930, 2, 1, 4, 2)) cn_centillion100 = mib_identifier((1, 3, 6, 1, 4, 1, 930, 1, 1)) cn_ibm8251 = mib_identifier((1, 3, 6, 1, 4, 1, 930, 1, 2)) cn_bay_stack301 = mib_identifier((1, 3, 6, 1, 4, 1, 930, 1, 3)) cn5000_bh_mcp = mib_identifier((1, 3, 6, 1, 4, 1, 930, 1, 4)).setLabel('cn5000BH-MCP') cn_centillion50_n = mib_identifier((1, 3, 6, 1, 4, 1, 930, 1, 5)) cn_centillion50_t = mib_identifier((1, 3, 6, 1, 4, 1, 930, 1, 6)) cn5005_bh_mcp = mib_identifier((1, 3, 6, 1, 4, 1, 930, 1, 7)).setLabel('cn5005BH-MCP') chassis_type = mib_scalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 1), ss_chassis_type()).setMaxAccess('readonly') if mibBuilder.loadTexts: chassisType.setStatus('mandatory') chassis_bkpl_type = mib_scalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 2), ss_backplane_type()).setMaxAccess('readonly') if mibBuilder.loadTexts: chassisBkplType.setStatus('mandatory') chassis_ps1_fail_status = mib_scalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 3), fail_indicator()).setMaxAccess('readonly') if mibBuilder.loadTexts: chassisPs1FailStatus.setStatus('mandatory') chassis_ps2_fail_status = mib_scalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 4), fail_indicator()).setMaxAccess('readonly') if mibBuilder.loadTexts: chassisPs2FailStatus.setStatus('mandatory') chassis_fan_fail_status = mib_scalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 5), fail_indicator()).setMaxAccess('readonly') if mibBuilder.loadTexts: chassisFanFailStatus.setStatus('mandatory') chassis_serial_number = mib_scalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 6), octet_string().subtype(subtypeSpec=value_size_constraint(3, 3)).setFixedLength(3)).setMaxAccess('readonly') if mibBuilder.loadTexts: chassisSerialNumber.setStatus('mandatory') chassis_part_number = mib_scalar((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 7), octet_string().subtype(subtypeSpec=value_size_constraint(6, 6)).setFixedLength(6)).setMaxAccess('readonly') if mibBuilder.loadTexts: chassisPartNumber.setStatus('mandatory') slot_config_table = mib_table((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9)) if mibBuilder.loadTexts: slotConfigTable.setStatus('mandatory') slot_config_entry = mib_table_row((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1)).setIndexNames((0, 'CENTILLION-ROOT-MIB', 'slotNumber')) if mibBuilder.loadTexts: slotConfigEntry.setStatus('mandatory') slot_number = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 1), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: slotNumber.setStatus('mandatory') slot_module_type = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 2), ss_module_type()).setMaxAccess('readonly') if mibBuilder.loadTexts: slotModuleType.setStatus('deprecated') slot_module_hw_ver = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 3), octet_string().subtype(subtypeSpec=value_size_constraint(6, 6)).setFixedLength(6)).setMaxAccess('readonly') if mibBuilder.loadTexts: slotModuleHwVer.setStatus('mandatory') slot_module_serial_number = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 4), octet_string().subtype(subtypeSpec=value_size_constraint(3, 3)).setFixedLength(3)).setMaxAccess('readonly') if mibBuilder.loadTexts: slotModuleSerialNumber.setStatus('mandatory') slot_module_sw_ver = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 5), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: slotModuleSwVer.setStatus('mandatory') slot_module_status = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('ok', 1), ('fail', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: slotModuleStatus.setStatus('mandatory') slot_module_leds = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 7), octet_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: slotModuleLeds.setStatus('mandatory') slot_module_reset = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 8), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2))).clone(namedValues=named_values(('noReset', 1), ('reset', 2)))).setMaxAccess('readwrite') if mibBuilder.loadTexts: slotModuleReset.setStatus('mandatory') slot_config_delete = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 9), boolean()).setMaxAccess('readwrite') if mibBuilder.loadTexts: slotConfigDelete.setStatus('mandatory') slot_config_media_type = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 10), ss_media_type()).setMaxAccess('readonly') if mibBuilder.loadTexts: slotConfigMediaType.setStatus('mandatory') slot_module_max_ram = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 11), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: slotModuleMaxRAM.setStatus('mandatory') slot_module_installed_ram = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 12), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: slotModuleInstalledRAM.setStatus('mandatory') slot_module_flash_size = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 13), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: slotModuleFlashSize.setStatus('mandatory') slot_module_product_image_id = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 14), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(1, 2, 3, 4, 5))).clone(namedValues=named_values(('notApplicable', 1), ('noAtmLanEmulation', 2), ('minAtmLanEmulation', 3), ('fullAtmLanEmulation', 4), ('pnnifullAtmLanEmulation', 5)))).setMaxAccess('readonly') if mibBuilder.loadTexts: slotModuleProductImageId.setStatus('mandatory') slot_module_base_mac_address = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 15), mac_address()).setMaxAccess('readonly') if mibBuilder.loadTexts: slotModuleBaseMacAddress.setStatus('mandatory') slot_last_reset_epc = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 16), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: slotLastResetEPC.setStatus('mandatory') slot_last_reset_virtual_address = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 17), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: slotLastResetVirtualAddress.setStatus('mandatory') slot_last_reset_cause = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 18), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: slotLastResetCause.setStatus('mandatory') slot_last_reset_time_stamp = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 19), counter32()).setMaxAccess('readonly') if mibBuilder.loadTexts: slotLastResetTimeStamp.setStatus('mandatory') slot_config_add = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 20), boolean()).setMaxAccess('readwrite') if mibBuilder.loadTexts: slotConfigAdd.setStatus('mandatory') slot_config_ext_clock_source = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 21), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: slotConfigExtClockSource.setStatus('mandatory') slot_config_traffic_shaping_rate = mib_table_column((1, 3, 6, 1, 4, 1, 930, 2, 1, 1, 9, 1, 22), integer32()).setMaxAccess('readwrite') if mibBuilder.loadTexts: slotConfigTrafficShapingRate.setStatus('mandatory') mibBuilder.exportSymbols('CENTILLION-ROOT-MIB', EnableIndicator=EnableIndicator, slotNumber=slotNumber, SsChassisType=SsChassisType, SsModuleType=SsModuleType, slotLastResetEPC=slotLastResetEPC, cnPvcTraps=cnPvcTraps, slotLastResetVirtualAddress=slotLastResetVirtualAddress, sysMcpRedundTrap=sysMcpRedundTrap, sysEvtLogMgmt=sysEvtLogMgmt, CardId=CardId, chassisPs1FailStatus=chassisPs1FailStatus, cnATM=cnATM, SsMediaType=SsMediaType, slotConfigTable=slotConfigTable, slotModuleHwVer=slotModuleHwVer, slotConfigMediaType=slotConfigMediaType, cnBayStack301=cnBayStack301, SsBackplaneType=SsBackplaneType, sysConfig=sysConfig, chassisPartNumber=chassisPartNumber, slotModuleLeds=slotModuleLeds, slotConfigExtClockSource=slotConfigExtClockSource, FailIndicator=FailIndicator, proprietary=proprietary, slotModuleReset=slotModuleReset, sysChassis=sysChassis, cnIBM8251=cnIBM8251, chassisBkplType=chassisBkplType, extensions=extensions, cnCentillion50N=cnCentillion50N, slotModuleType=slotModuleType, slotModuleProductImageId=slotModuleProductImageId, atmLane=atmLane, StatusIndicator=StatusIndicator, cnSystem=cnSystem, slotConfigEntry=slotConfigEntry, BitField=BitField, cnTemporary=cnTemporary, centillion=centillion, slotModuleStatus=slotModuleStatus, cnCentillion50T=cnCentillion50T, chassisSerialNumber=chassisSerialNumber, slotModuleSerialNumber=slotModuleSerialNumber, slotModuleFlashSize=slotModuleFlashSize, slotModuleBaseMacAddress=slotModuleBaseMacAddress, slotConfigAdd=slotConfigAdd, slotConfigDelete=slotConfigDelete, Boolean=Boolean, slotLastResetTimeStamp=slotLastResetTimeStamp, chassisFanFailStatus=chassisFanFailStatus, cn5000BH_MCP=cn5000BH_MCP, slotModuleInstalledRAM=slotModuleInstalledRAM, cnProducts=cnProducts, cn5005BH_MCP=cn5005BH_MCP, PortId=PortId, slotModuleSwVer=slotModuleSwVer, slotLastResetCause=slotLastResetCause, atmConfig=atmConfig, slotModuleMaxRAM=slotModuleMaxRAM, slotConfigTrafficShapingRate=slotConfigTrafficShapingRate, cnCentillion100=cnCentillion100, sysMonitor=sysMonitor, atmMonitor=atmMonitor, chassisPs2FailStatus=chassisPs2FailStatus, sysTrap=sysTrap, atmSonet=atmSonet, chassisType=chassisType, MacAddress=MacAddress)
l = 2 if(l == 1): print(l) elif(l == 2): print(l+5) else: print(l+1)
l = 2 if l == 1: print(l) elif l == 2: print(l + 5) else: print(l + 1)
n1, n2, n3 = map(int, input().split()) total = n1 * n2 * n3 print(total)
(n1, n2, n3) = map(int, input().split()) total = n1 * n2 * n3 print(total)
class Atom: def __init__(self, name, children): self.name = name self.children = children if None in children: raise Exception("none in lisp atom") def __str__(self): child_string = " ".join( [str(e) if type(e) != str else f'"{e}"' for e in self.children] ) return f"({self.name} {child_string})" class Literal: def __init__(self, value): self.value = value def __str__(self): return self.value def __repr__(self): return self.value def __eq__(self, other): return self.value == other
class Atom: def __init__(self, name, children): self.name = name self.children = children if None in children: raise exception('none in lisp atom') def __str__(self): child_string = ' '.join([str(e) if type(e) != str else f'"{e}"' for e in self.children]) return f'({self.name} {child_string})' class Literal: def __init__(self, value): self.value = value def __str__(self): return self.value def __repr__(self): return self.value def __eq__(self, other): return self.value == other
#This algoritm was copied at 16/Nov/2018 from https://en.wikibooks.org/wiki/Algorithm_Implementation/Strings/Levenshtein_distance#Python and applied to activity sequences delimter = "@" def length(s): return s.count(delimter) + 1 def enumerateSequence(s): list = s.split(delimter) return enumerate(list,0) def levenshtein(s1, s2): if length(s1) < length(s2): return levenshtein(s2, s1) # len(s1) >= len(s2) if length(s2) == 0: return length(s1) previous_row = range(length(s2) + 1) for i, c1 in enumerateSequence(s1): current_row = [i + 1] for j, c2 in enumerateSequence(s2): insertions = previous_row[j + 1] + 1 # j+1 instead of j since previous_row and current_row are one character longer deletions = current_row[j] + 1 # than s2 substitutions = previous_row[j] + (c1 != c2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1]
delimter = '@' def length(s): return s.count(delimter) + 1 def enumerate_sequence(s): list = s.split(delimter) return enumerate(list, 0) def levenshtein(s1, s2): if length(s1) < length(s2): return levenshtein(s2, s1) if length(s2) == 0: return length(s1) previous_row = range(length(s2) + 1) for (i, c1) in enumerate_sequence(s1): current_row = [i + 1] for (j, c2) in enumerate_sequence(s2): insertions = previous_row[j + 1] + 1 deletions = current_row[j] + 1 substitutions = previous_row[j] + (c1 != c2) current_row.append(min(insertions, deletions, substitutions)) previous_row = current_row return previous_row[-1]
# -*- Mode: Python; coding: utf-8; indent-tabs-mpythoode: nil; tab-width: 4 -*- # CODEWARS # https://www.codewars.com/kata/5583090cbe83f4fd8c000051 # # "Convert number to reversed array of digits" def digitize(n): if n == 0: return [0] if n < 0: n *= -1 arr = [] while n > 0: arr += [n % 10] n /= 10 return arr def testEqual(test, str1, str2): print(test, str1 == str2) def main(): testEqual(1, digitize(35231),[1,3,2,5,3]) testEqual(2, digitize(348597),[7,9,5,8,4,3]) testEqual(3, digitize(0),[0]) testEqual(4, digitize(1),[1]) testEqual(5, digitize(10),[0,1]) testEqual(6, digitize(100),[0,0,1]) testEqual(7, digitize(-1000),[0,0,0,1]) if __name__ == '__main__': main()
def digitize(n): if n == 0: return [0] if n < 0: n *= -1 arr = [] while n > 0: arr += [n % 10] n /= 10 return arr def test_equal(test, str1, str2): print(test, str1 == str2) def main(): test_equal(1, digitize(35231), [1, 3, 2, 5, 3]) test_equal(2, digitize(348597), [7, 9, 5, 8, 4, 3]) test_equal(3, digitize(0), [0]) test_equal(4, digitize(1), [1]) test_equal(5, digitize(10), [0, 1]) test_equal(6, digitize(100), [0, 0, 1]) test_equal(7, digitize(-1000), [0, 0, 0, 1]) if __name__ == '__main__': main()
class Solution: def lengthOfLastWord(self, s: str) -> int: end = len(s) -1 c = 0 while s[end] == " ": end -= 1 while s[end] != " " and end >= 0: c += 1 end -= 1 return c
class Solution: def length_of_last_word(self, s: str) -> int: end = len(s) - 1 c = 0 while s[end] == ' ': end -= 1 while s[end] != ' ' and end >= 0: c += 1 end -= 1 return c
class Phoneme: def __init__(self, ptype: str): self.ptype = ptype class Cons(Phoneme): def __init__(self, voice: int, ctype: str): super().__init__("Cons") self.voice = voice self.ctype = ctype class PulmCons(Cons): def __init__(self, voice: int, pcmanner: int, pcplace: int): super().__init__(voice, "PulmCons") self.pcmanner = pcmanner self.pcplace = pcplace class NonPulmCons(Cons): def __init__(self, voice: int, npctype: str): super().__init__(voice, "NonPulmCons") self.npctype = npctype class Ejective(NonPulmCons): def __init__(self, voice: int, ejmanner: int, ejplace: int): super().__init__(voice, "Ejective") self.ejmanner = ejmanner self.ejplace = ejplace class Click(NonPulmCons): def __init__(self, voice: int, clmanner: int, clplace: int): super().__init__(voice, "Click") self.clmanner = clmanner self.clplace = clplace class Implosive(NonPulmCons): def __init__(self, voice: int, implace: int): super().__init__(voice, "Implosive") self.implace = implace class Multi(Cons): def __init__(self, voice: int, catype: str): super().__init__(voice, "Multi") self.catype = catype self.sequence = [] def append(self, cons: Cons): self.sequence.append(cons)
class Phoneme: def __init__(self, ptype: str): self.ptype = ptype class Cons(Phoneme): def __init__(self, voice: int, ctype: str): super().__init__('Cons') self.voice = voice self.ctype = ctype class Pulmcons(Cons): def __init__(self, voice: int, pcmanner: int, pcplace: int): super().__init__(voice, 'PulmCons') self.pcmanner = pcmanner self.pcplace = pcplace class Nonpulmcons(Cons): def __init__(self, voice: int, npctype: str): super().__init__(voice, 'NonPulmCons') self.npctype = npctype class Ejective(NonPulmCons): def __init__(self, voice: int, ejmanner: int, ejplace: int): super().__init__(voice, 'Ejective') self.ejmanner = ejmanner self.ejplace = ejplace class Click(NonPulmCons): def __init__(self, voice: int, clmanner: int, clplace: int): super().__init__(voice, 'Click') self.clmanner = clmanner self.clplace = clplace class Implosive(NonPulmCons): def __init__(self, voice: int, implace: int): super().__init__(voice, 'Implosive') self.implace = implace class Multi(Cons): def __init__(self, voice: int, catype: str): super().__init__(voice, 'Multi') self.catype = catype self.sequence = [] def append(self, cons: Cons): self.sequence.append(cons)
log_table = [] alpha_table = [] def multiplie(x, y, P): if x == 0 or y == 0: return 0 P_deg = len(bin(P)) - 3 i, j = log_table[x], log_table[y] return alpha_table[(i + j) % ((1 << P_deg)-1)]
log_table = [] alpha_table = [] def multiplie(x, y, P): if x == 0 or y == 0: return 0 p_deg = len(bin(P)) - 3 (i, j) = (log_table[x], log_table[y]) return alpha_table[(i + j) % ((1 << P_deg) - 1)]
""" auto generated test file """ # Create your tests here.
""" auto generated test file """
# https://leetcode.com/problems/delete-columns-to-make-sorted/ # You are given an array of n strings strs, all of the same length. # The strings can be arranged such that there is one on each line, making a grid. # For example, strs = ["abc", "bce", "cae"] can be arranged as: # You want to delete the columns that are not sorted lexicographically. In the # above example (0-indexed), columns 0 ('a', 'b', 'c') and 2 ('c', 'e', 'e') are # sorted while column 1 ('b', 'c', 'a') is not, so you would delete column 1. # Return the number of columns that you will delete. ################################################################################ class Solution: def minDeletionSize(self, strs: List[str]) -> int: ans = 0 for col in zip(*strs): for i in range(len(col) - 1): if col[i] > col[i+1]: ans += 1 break return ans
class Solution: def min_deletion_size(self, strs: List[str]) -> int: ans = 0 for col in zip(*strs): for i in range(len(col) - 1): if col[i] > col[i + 1]: ans += 1 break return ans
def full_query(okta_id, video_string, fan_string, limit=5000): query = f''' WITH -- FIRST CTE all_comments ( comment_id, parent_youtube_comment_id, youtube_fan_id, by_creator, content, archived, timestamp, up_vote, down_vote, video_title, video_id, video_thumbnail, classification ) AS ( SELECT comments.id as comment_id, comments.parent_youtube_comment_id as parent_youtube_comment_id, comments.youtube_fan_id as youtube_fan_id, comments.by_creator as by_creator, comments.content as content, comments.archived as archived, comments.timestamp as timestamp, comments.up_vote as up_vote, comments.down_vote as down_vote, video.video_title as video_title, video.video_id as video_id, video.thumbnail_url as video_thumbnail, comments.classification as classification FROM ( SELECT id as video_id, video_title, thumbnail_url FROM ( SELECT id as creator_id FROM creators WHERE okta_platform_account_id = '{okta_id}' ) creator JOIN youtube_videos ON youtube_videos.creator_id = creator.creator_id ) video JOIN youtube_comments comments ON video.video_id = comments.youtube_video_id ), -- SECOND CTE top_comments ( comment_id, parent_youtube_comment_id, youtube_fan_id, by_creator, content, archived, timestamp, up_vote, down_vote, video_title, video_id, video_thumbnail, classification ) AS ( SELECT * FROM all_comments WHERE parent_youtube_comment_id is NULL{video_string}{fan_string} AND by_creator is false ORDER BY timestamp desc LIMIT {limit} ), -- THIRD CTE top_fan_comments ( comment_id, parent_youtube_comment_id, youtube_fan_id, timestamp ) AS ( SELECT all_comments.comment_id as comment_id, all_comments.parent_youtube_comment_id as parent_youtube_comment_id, all_comments.youtube_fan_id as youtube_fan_id, all_comments.timestamp as timestamp FROM ( SELECT DISTINCT youtube_fan_id as id FROM top_comments ) top_fans JOIN all_comments ON top_fans.id = all_comments.youtube_fan_id ), -- FOURTH CTE top_comments_with_replies ( comment_id, parent_youtube_comment_id, youtube_fan_id, by_creator, content, archived, timestamp, up_vote, down_vote, video_title, video_id, video_thumbnail, classification ) AS ( SELECT * FROM top_comments UNION SELECT replies.comment_id as comment_id, parent_youtube_comment_id, youtube_fan_id, by_creator, content, archived, timestamp, up_vote, down_vote, video_title, video_id, video_thumbnail, classification FROM ( SELECT comment_id FROM top_comments ) roots JOIN all_comments replies ON roots.comment_id = replies.parent_youtube_comment_id ) -- MAIN QUERY SELECT top_comments_with_replies.comment_id, top_comments_with_replies.parent_youtube_comment_id, top_comments_with_replies.youtube_fan_id, top_comments_with_replies.content, top_comments_with_replies.archived, top_comments_with_replies.timestamp, top_comments_with_replies.up_vote, top_comments_with_replies.down_vote, top_comments_with_replies.video_title, top_comments_with_replies.video_id, top_comments_with_replies.video_thumbnail, fan_aggregations.total_comments, fan_aggregations.total_replies, fan_aggregations.responses, fan_aggregations.sec_comment, youtube_fans.account_title, youtube_fans.thumbnail_url, top_comments_with_replies.classification, youtube_fans.note FROM top_comments_with_replies LEFT JOIN ( -- AGGREGATION SELECT top_fan_comments.youtube_fan_id as youtube_fan_id, COUNT(top_fan_comments.comment_id) as total_comments, COUNT(top_fan_comments.parent_youtube_comment_id) as total_replies, COUNT(responses.creator_response) as responses, MAX(second_comment.sec_timestamp) as sec_comment FROM top_fan_comments JOIN -- Second Comment timestamp ( SELECT comment_id, youtube_fan_id, nth_value(timestamp,2) OVER (PARTITION BY youtube_fan_id ORDER BY timestamp DESC) AS sec_timestamp FROM top_fan_comments ) second_comment ON top_fan_comments.comment_id = second_comment.comment_id LEFT JOIN -- Creator Responses ( SELECT distinct parent_youtube_comment_id as creator_response FROM all_comments WHERE by_creator = TRUE ) responses ON top_fan_comments.comment_id = responses.creator_response GROUP BY top_fan_comments.youtube_fan_id ) fan_aggregations ON top_comments_with_replies.youtube_fan_id = fan_aggregations.youtube_fan_id LEFT JOIN ( SELECT id, account_title, thumbnail_url, note FROM youtube_fans ) youtube_fans ON top_comments_with_replies.youtube_fan_id = youtube_fans.id ''' return query
def full_query(okta_id, video_string, fan_string, limit=5000): query = f"\n WITH \n -- FIRST CTE\n all_comments (\n comment_id, \n parent_youtube_comment_id,\n youtube_fan_id,\n by_creator,\n content,\n archived,\n timestamp,\n up_vote,\n down_vote,\n video_title,\n video_id,\n video_thumbnail,\n classification\n )\n AS (\n SELECT \n comments.id as comment_id,\n comments.parent_youtube_comment_id as parent_youtube_comment_id,\n comments.youtube_fan_id as youtube_fan_id,\n comments.by_creator as by_creator,\n comments.content as content,\n comments.archived as archived,\n comments.timestamp as timestamp,\n comments.up_vote as up_vote,\n comments.down_vote as down_vote,\n video.video_title as video_title,\n video.video_id as video_id,\n video.thumbnail_url as video_thumbnail,\n comments.classification as classification\n\n FROM\n ( \n SELECT \n id as video_id,\n video_title,\n thumbnail_url\n FROM\n (\n SELECT\n id as creator_id\n FROM\n creators\n WHERE\n okta_platform_account_id = '{okta_id}'\n )\n creator\n JOIN\n youtube_videos\n ON youtube_videos.creator_id = creator.creator_id\n )\n video\n JOIN \n youtube_comments comments\n ON video.video_id = comments.youtube_video_id\n ),\n\n -- SECOND CTE \n top_comments (\n comment_id, \n parent_youtube_comment_id,\n youtube_fan_id,\n by_creator,\n content,\n archived,\n timestamp,\n up_vote,\n down_vote,\n video_title,\n video_id,\n video_thumbnail,\n classification\n )\n AS \n ( \n SELECT\n *\n FROM \n all_comments\n WHERE \n parent_youtube_comment_id is NULL{video_string}{fan_string}\n AND\n by_creator is false\n ORDER BY timestamp desc\n LIMIT {limit}\n\n ),\n\n -- THIRD CTE\n top_fan_comments (\n comment_id, \n parent_youtube_comment_id,\n youtube_fan_id,\n timestamp\n )\n AS (\n SELECT\n all_comments.comment_id as comment_id, \n all_comments.parent_youtube_comment_id as parent_youtube_comment_id,\n all_comments.youtube_fan_id as youtube_fan_id,\n all_comments.timestamp as timestamp\n FROM \n (\n SELECT\n DISTINCT youtube_fan_id as id\n FROM top_comments\n )\n top_fans\n JOIN all_comments\n ON top_fans.id = all_comments.youtube_fan_id\n ),\n\n -- FOURTH CTE\n top_comments_with_replies (\n comment_id, \n parent_youtube_comment_id,\n youtube_fan_id,\n by_creator,\n content,\n archived,\n timestamp,\n up_vote,\n down_vote,\n video_title,\n video_id,\n video_thumbnail,\n classification\n )\n AS (\n SELECT\n *\n FROM\n top_comments \n UNION\n SELECT\n replies.comment_id as comment_id,\n parent_youtube_comment_id,\n youtube_fan_id,\n by_creator,\n content,\n archived,\n timestamp,\n up_vote,\n down_vote,\n video_title,\n video_id,\n video_thumbnail,\n classification\n FROM\n (\n SELECT\n comment_id\n FROM\n top_comments\n ) roots\n JOIN\n all_comments replies\n ON roots.comment_id = replies.parent_youtube_comment_id\n )\n\n -- MAIN QUERY\n SELECT\n top_comments_with_replies.comment_id,\n top_comments_with_replies.parent_youtube_comment_id,\n top_comments_with_replies.youtube_fan_id,\n top_comments_with_replies.content,\n top_comments_with_replies.archived,\n top_comments_with_replies.timestamp,\n top_comments_with_replies.up_vote,\n top_comments_with_replies.down_vote,\n top_comments_with_replies.video_title,\n top_comments_with_replies.video_id,\n top_comments_with_replies.video_thumbnail,\n fan_aggregations.total_comments,\n fan_aggregations.total_replies,\n fan_aggregations.responses,\n fan_aggregations.sec_comment,\n youtube_fans.account_title,\n youtube_fans.thumbnail_url,\n top_comments_with_replies.classification,\n youtube_fans.note\n FROM\n top_comments_with_replies\n LEFT JOIN\n ( -- AGGREGATION\n SELECT \n top_fan_comments.youtube_fan_id as youtube_fan_id, \n COUNT(top_fan_comments.comment_id) as total_comments, \n COUNT(top_fan_comments.parent_youtube_comment_id) as total_replies, \n COUNT(responses.creator_response) as responses, \n MAX(second_comment.sec_timestamp) as sec_comment\n FROM \n top_fan_comments\n JOIN -- Second Comment timestamp\n (\n SELECT \n comment_id,\n youtube_fan_id, \n nth_value(timestamp,2) OVER (PARTITION BY youtube_fan_id\n ORDER BY timestamp DESC) AS sec_timestamp\n FROM top_fan_comments\n )\n second_comment\n ON top_fan_comments.comment_id = second_comment.comment_id\n LEFT JOIN -- Creator Responses\n (\n SELECT\n distinct parent_youtube_comment_id as creator_response\n FROM all_comments\n WHERE by_creator = TRUE\n )\n responses\n ON top_fan_comments.comment_id = responses.creator_response\n GROUP BY top_fan_comments.youtube_fan_id\n )\n fan_aggregations\n ON top_comments_with_replies.youtube_fan_id = fan_aggregations.youtube_fan_id\n\n LEFT JOIN\n (\n SELECT\n id,\n account_title,\n thumbnail_url,\n note\n FROM\n youtube_fans\n )\n youtube_fans\n ON top_comments_with_replies.youtube_fan_id = youtube_fans.id\n " return query
n = int(input()) for j in range(1,n+1): led = 0 x = input() for i in range(0,len(x)): if x[i] == '1': led = led + 2 if x[i] == '2': led = led + 5 if x[i] == '3': led = led + 5 if x[i] == '4': led = led + 4 if x[i] == '5': led = led + 5 if x[i] == '6': led = led + 6 if x[i] == '7': led = led + 3 if x[i] == '8': led = led + 7 if x[i] == '9': led = led + 6 if x[i] == '0': led = led + 6 print('{} leds'.format(led))
n = int(input()) for j in range(1, n + 1): led = 0 x = input() for i in range(0, len(x)): if x[i] == '1': led = led + 2 if x[i] == '2': led = led + 5 if x[i] == '3': led = led + 5 if x[i] == '4': led = led + 4 if x[i] == '5': led = led + 5 if x[i] == '6': led = led + 6 if x[i] == '7': led = led + 3 if x[i] == '8': led = led + 7 if x[i] == '9': led = led + 6 if x[i] == '0': led = led + 6 print('{} leds'.format(led))
#Write a Python program to sum of three given integers. However, if two values are equal sum will be zero def sumif(a,b,c): if a != b != c and c !=a: return a+b+c else: return 0 print(sumif(42,5,9)) print(sumif(8,8,12)) print(sumif(9,54,9)) print(sumif(87,4,9))
def sumif(a, b, c): if a != b != c and c != a: return a + b + c else: return 0 print(sumif(42, 5, 9)) print(sumif(8, 8, 12)) print(sumif(9, 54, 9)) print(sumif(87, 4, 9))
# -*- coding: utf-8 -*- # Copyright: (c) 2016, Charles Paul <cpaul@ansible.com> # GNU General Public License v3.0+ (see COPYING or https://www.gnu.org/licenses/gpl-3.0.txt) class ModuleDocFragment(object): # Parameters for VCA modules DOCUMENTATION = r''' options: username: description: - The vca username or email address, if not set the environment variable C(VCA_USER) is checked for the username. type: str aliases: [ user ] password: description: - The vca password, if not set the environment variable C(VCA_PASS) is checked for the password. type: str aliases: [ pass, passwd] org: description: - The org to login to for creating vapp. - This option is required when the C(service_type) is I(vdc). type: str instance_id: description: - The instance ID in a vchs environment to be used for creating the vapp. type: str host: description: - The authentication host to be used when service type is vcd. type: str api_version: description: - The API version to be used with the vca. type: str default: "5.7" service_type: description: - The type of service we are authenticating against. type: str choices: [ vca, vcd, vchs ] default: vca state: description: - Whether the object should be added or removed. type: str choices: [ absent, present ] default: present validate_certs: description: - If the certificates of the authentication is to be verified. type: bool default: yes aliases: [ verify_certs ] vdc_name: description: - The name of the vdc where the gateway is located. type: str gateway_name: description: - The name of the gateway of the vdc where the rule should be added. type: str default: gateway '''
class Moduledocfragment(object): documentation = '\noptions:\n username:\n description:\n - The vca username or email address, if not set the environment variable C(VCA_USER) is checked for the username.\n type: str\n aliases: [ user ]\n password:\n description:\n - The vca password, if not set the environment variable C(VCA_PASS) is checked for the password.\n type: str\n aliases: [ pass, passwd]\n org:\n description:\n - The org to login to for creating vapp.\n - This option is required when the C(service_type) is I(vdc).\n type: str\n instance_id:\n description:\n - The instance ID in a vchs environment to be used for creating the vapp.\n type: str\n host:\n description:\n - The authentication host to be used when service type is vcd.\n type: str\n api_version:\n description:\n - The API version to be used with the vca.\n type: str\n default: "5.7"\n service_type:\n description:\n - The type of service we are authenticating against.\n type: str\n choices: [ vca, vcd, vchs ]\n default: vca\n state:\n description:\n - Whether the object should be added or removed.\n type: str\n choices: [ absent, present ]\n default: present\n validate_certs:\n description:\n - If the certificates of the authentication is to be verified.\n type: bool\n default: yes\n aliases: [ verify_certs ]\n vdc_name:\n description:\n - The name of the vdc where the gateway is located.\n type: str\n gateway_name:\n description:\n - The name of the gateway of the vdc where the rule should be added.\n type: str\n default: gateway\n'
''' Array Sum You are given an array of integers of size . You need to print the sum of the elements in the array, keeping in mind that some of those integers may be quite large. Input Format The first line of the input consists of an integer . The next line contains space-separated integers contained in the array. Output Format Print a single value equal to the sum of the elements in the array. Constraints 1<=N<=10 0<=a[i]<=10^10 SAMPLE INPUT 5 1000000001 1000000002 1000000003 1000000004 1000000005 SAMPLE OUTPUT 5000000015 ''' n=int(input()) x=map(int,input().split()) print(sum(x)) #List comprehension n=int(input()) print(sum([int(x) for x in input().split()]))
""" Array Sum You are given an array of integers of size . You need to print the sum of the elements in the array, keeping in mind that some of those integers may be quite large. Input Format The first line of the input consists of an integer . The next line contains space-separated integers contained in the array. Output Format Print a single value equal to the sum of the elements in the array. Constraints 1<=N<=10 0<=a[i]<=10^10 SAMPLE INPUT 5 1000000001 1000000002 1000000003 1000000004 1000000005 SAMPLE OUTPUT 5000000015 """ n = int(input()) x = map(int, input().split()) print(sum(x)) n = int(input()) print(sum([int(x) for x in input().split()]))
DEFAULT_FPGA='VC709' def addClock(file, FPGA=DEFAULT_FPGA): file.write("#Clock Source\r\n") if(FPGA=='VC709'): file.write("set_property IOSTANDARD DIFF_SSTL15 [get_ports clk_p]\r\n") file.write("set_property PACKAGE_PIN H19 [get_ports clk_p]\r\n") file.write("set_property PACKAGE_PIN G18 [get_ports clk_n]\r\n") file.write("set_property IOSTANDARD DIFF_SSTL15 [get_ports clk_n]\r\n") elif(FPGA=='A735'): file.write("set_property -dict {PACKAGE_PIN E3 IOSTANDARD LVCMOS33} [get_ports CLK]\r\n") file.write("create_clock -period 10.000 -name sys_clk_pin -waveform {0.000 5.000} -add [get_ports CLK]\r\n") elif(FPGA=='A7100'): file.write("set_property -dict {PACKAGE_PIN E3 IOSTANDARD LVCMOS33} [get_ports CLK]\r\n") file.write("create_clock -period 10.000 -name sys_clk_pin -waveform {0.000 5.000} -add [get_ports CLK]\r\n") file.write("\r\n") def addLED(file, FPGA=DEFAULT_FPGA): file.write("#LEDs\r\n") if(FPGA=='VC709'): file.write("set_property -dict { PACKAGE_PIN AM39 IOSTANDARD LVCMOS18 } [get_ports { LED[0] }];\r\n") file.write("set_property -dict { PACKAGE_PIN AN39 IOSTANDARD LVCMOS18 } [get_ports { LED[1] }];\r\n") file.write("set_property -dict { PACKAGE_PIN AR37 IOSTANDARD LVCMOS18 } [get_ports { LED[2] }];\r\n") file.write("set_property -dict { PACKAGE_PIN AT37 IOSTANDARD LVCMOS18 } [get_ports { LED[3] }];\r\n") file.write("set_property -dict { PACKAGE_PIN AR35 IOSTANDARD LVCMOS18 } [get_ports { LED[4] }];\r\n") file.write("set_property -dict { PACKAGE_PIN AP41 IOSTANDARD LVCMOS18 } [get_ports { LED[5] }];\r\n") file.write("set_property -dict { PACKAGE_PIN AP42 IOSTANDARD LVCMOS18 } [get_ports { LED[6] }];\r\n") file.write("set_property -dict { PACKAGE_PIN AU39 IOSTANDARD LVCMOS18 } [get_ports { LED[7] }];\r\n") elif(FPGA=='A735'): file.write("set_property -dict { PACKAGE_PIN H5 IOSTANDARD LVCMOS33 } [get_ports { LED[0] }];\r\n") file.write("set_property -dict { PACKAGE_PIN J5 IOSTANDARD LVCMOS33 } [get_ports { LED[1] }];\r\n") file.write("set_property -dict { PACKAGE_PIN T9 IOSTANDARD LVCMOS33 } [get_ports { LED[2] }];\r\n") file.write("set_property -dict { PACKAGE_PIN T10 IOSTANDARD LVCMOS33 } [get_ports { LED[3] }];\r\n") elif(FPGA=='A7100'): file.write("set_property -dict { PACKAGE_PIN H5 IOSTANDARD LVCMOS33 } [get_ports { LED[0] }];\r\n") file.write("set_property -dict { PACKAGE_PIN J5 IOSTANDARD LVCMOS33 } [get_ports { LED[1] }];\r\n") file.write("set_property -dict { PACKAGE_PIN T9 IOSTANDARD LVCMOS33 } [get_ports { LED[2] }];\r\n") file.write("set_property -dict { PACKAGE_PIN T10 IOSTANDARD LVCMOS33 } [get_ports { LED[3] }];\r\n") file.write("\r\n") def addSwitches(file, FPGA=DEFAULT_FPGA): file.write("#Switches\r\n") if(FPGA=='VC709'): file.write("set_property -dict { PACKAGE_PIN AV30 IOSTANDARD LVCMOS18 } [get_ports { SW[0] }];\r\n") file.write("set_property -dict { PACKAGE_PIN AY33 IOSTANDARD LVCMOS18 } [get_ports { SW[1] }];\r\n") file.write("set_property -dict { PACKAGE_PIN BA31 IOSTANDARD LVCMOS18 } [get_ports { SW[2] }];\r\n") file.write("set_property -dict { PACKAGE_PIN BA32 IOSTANDARD LVCMOS18 } [get_ports { SW[3] }];\r\n") file.write("set_property -dict { PACKAGE_PIN AW30 IOSTANDARD LVCMOS18 } [get_ports { SW[4] }];\r\n") file.write("set_property -dict { PACKAGE_PIN AY30 IOSTANDARD LVCMOS33 } [get_ports { SW[5] }];\r\n") file.write("set_property -dict { PACKAGE_PIN BA30 IOSTANDARD LVCMOS18 } [get_ports { SW[6] }];\r\n") file.write("set_property -dict { PACKAGE_PIN BB31 IOSTANDARD LVCMOS18 } [get_ports { SW[7] }];\r\n") elif(FPGA=='A735'): file.write("set_property -dict { PACKAGE_PIN A8 IOSTANDARD LVCMOS33 } [get_ports { SW[0] }];\r\n") file.write("set_property -dict { PACKAGE_PIN C11 IOSTANDARD LVCMOS33 } [get_ports { SW[1] }];\r\n") file.write("set_property -dict { PACKAGE_PIN C10 IOSTANDARD LVCMOS33 } [get_ports { SW[2] }];\r\n") file.write("set_property -dict { PACKAGE_PIN A10 IOSTANDARD LVCMOS33 } [get_ports { SW[3] }];\r\n") elif(FPGA=='A7100'): file.write("set_property -dict { PACKAGE_PIN A8 IOSTANDARD LVCMOS33 } [get_ports { SW[0] }];\r\n") file.write("set_property -dict { PACKAGE_PIN C11 IOSTANDARD LVCMOS33 } [get_ports { SW[1] }];\r\n") file.write("set_property -dict { PACKAGE_PIN C10 IOSTANDARD LVCMOS33 } [get_ports { SW[2] }];\r\n") file.write("set_property -dict { PACKAGE_PIN A10 IOSTANDARD LVCMOS33 } [get_ports { SW[3] }];\r\n") file.write("\r\n") def addUART(file, FPGA=DEFAULT_FPGA): file.write("#Uart\r\n") if(FPGA=='VC709'): file.write("set_property -dict { PACKAGE_PIN AU36 IOSTANDARD LVCMOS18 } [get_ports { TX }];\r\n") elif(FPGA=='A735'): file.write("set_property -dict { PACKAGE_PIN D10 IOSTANDARD LVCMOS33 } [get_ports { TX }];\r\n") file.write("#set_property -dict {PACKAGE_PIN A9 IOSTANDARD LVCMOS33 } [get_ports RX];\r\n") elif(FPGA=='A7100'): file.write("set_property -dict { PACKAGE_PIN D10 IOSTANDARD LVCMOS33 } [get_ports { TX }];\r\n") file.write("#set_property -dict {PACKAGE_PIN A9 IOSTANDARD LVCMOS33 } [get_ports RX];\r\n") file.write("\r\n") def addButtons(file, FPGA=DEFAULT_FPGA): file.write("#Buttons\r\n") if(FPGA=='VC709'): file.write("set_property -dict { PACKAGE_PIN AV39 IOSTANDARD LVCMOS18 } [get_ports { BUTTON[0] }];\r\n") file.write("set_property -dict { PACKAGE_PIN AW40 IOSTANDARD LVCMOS18 } [get_ports { BUTTON[1] }];\r\n") file.write("set_property -dict { PACKAGE_PIN AP40 IOSTANDARD LVCMOS18 } [get_ports { BUTTON[2] }];\r\n") file.write("set_property -dict { PACKAGE_PIN AU38 IOSTANDARD LVCMOS18 } [get_ports { BUTTON[3] }];\r\n") file.write("set_property -dict { PACKAGE_PIN AR40 IOSTANDARD LVCMOS18 } [get_ports { BUTTON[4] }];\r\n") elif(FPGA=='A735'): file.write("set_property -dict { PACKAGE_PIN D9 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[0] }];\r\n") file.write("set_property -dict { PACKAGE_PIN C9 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[1] }];\r\n") file.write("set_property -dict { PACKAGE_PIN B9 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[2] }];\r\n") file.write("set_property -dict { PACKAGE_PIN B8 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[3] }];\r\n") elif(FPGA=='A7100'): file.write("set_property -dict { PACKAGE_PIN D9 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[0] }];\r\n") file.write("set_property -dict { PACKAGE_PIN C9 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[1] }];\r\n") file.write("set_property -dict { PACKAGE_PIN B9 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[2] }];\r\n") file.write("set_property -dict { PACKAGE_PIN B8 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[3] }];\r\n") file.write("\r\n") def addClockBlock(file, FPGA=DEFAULT_FPGA): file.write("create_pblock pblock_clk_div\r\n") file.write("add_cells_to_pblock [get_pblocks pblock_clk_div] [get_cells -quiet [list clk_div]]\r\n") if(FPGA=='VC709'): file.write("resize_pblock [get_pblocks pblock_clk_div] -add {SLICE_X196Y475:SLICE_X221Y499}\r\n") file.write("resize_pblock [get_pblocks pblock_clk_div] -add {RAMB18_X13Y190:RAMB18_X14Y199}\r\n") file.write("resize_pblock [get_pblocks pblock_clk_div] -add {RAMB36_X13Y95:RAMB36_X14Y99}\r\n") elif(FPGA=='A735'): file.write("resize_pblock [get_pblocks pblock_clk_div] -add {SLICE_X36Y134:SLICE_X57Y149}\r\n") file.write("resize_pblock [get_pblocks pblock_clk_div] -add {RAMB18_X1Y54:RAMB18_X1Y59}\r\n") file.write("resize_pblock [get_pblocks pblock_clk_div] -add {RAMB36_X1Y27:RAMB36_X1Y29}\r\n") file.write("set_property BEL MMCME2_ADV [get_cells clk_div/MMCME2_ADV_inst]\r\n") file.write("set_property LOC MMCME2_ADV_X1Y1 [get_cells clk_div/MMCME2_ADV_inst]\r\n") elif(FPGA=='A7100'): file.write("resize_pblock [get_pblocks pblock_clk_div] -add {SLICE_X66Y134:SLICE_X79Y149}\r\n") file.write("resize_pblock [get_pblocks pblock_clk_div] -add {RAMB18_X2Y54:RAMB18_X2Y59}\r\n") file.write("resize_pblock [get_pblocks pblock_clk_div] -add {RAMB36_X2Y27:RAMB36_X2Y29}\r\n") file.write("set_property BEL MMCME2_ADV [get_cells clk_div/MMCME2_ADV_inst]\r\n") file.write("set_property LOC MMCME2_ADV_X1Y1 [get_cells clk_div/MMCME2_ADV_inst]\r\n") file.write("set_property SNAPPING_MODE ON [get_pblocks pblock_clk_div]\r\n") file.write("\r\n") def addUARTCtrlBlock(file, FPGA=DEFAULT_FPGA): file.write("create_pblock pblock_uart_ctrl\r\n") file.write("add_cells_to_pblock [get_pblocks pblock_uart_ctrl] [get_cells -quiet [list uart_ctrl]]\r\n") if(FPGA=='VC709'): file.write("resize_pblock [get_pblocks pblock_uart_ctrl] -add {SLICE_X170Y475:SLICE_X195Y499}\r\n") file.write("resize_pblock [get_pblocks pblock_uart_ctrl] -add {RAMB18_X11Y190:RAMB18_X12Y199}\r\n") file.write("resize_pblock [get_pblocks pblock_uart_ctrl] -add {RAMB36_X11Y95:RAMB36_X12Y99}\r\n") elif(FPGA=='A735'): file.write("resize_pblock [get_pblocks pblock_uart_ctrl] -add {SLICE_X36Y118:SLICE_X57Y133}\r\n") file.write("resize_pblock [get_pblocks pblock_uart_ctrl] -add {RAMB18_X1Y50:RAMB18_X1Y51}\r\n") file.write("resize_pblock [get_pblocks pblock_uart_ctrl] -add {RAMB36_X1Y25:RAMB36_X1Y25}\r\n") elif(FPGA=='A7100'): file.write("resize_pblock [get_pblocks pblock_uart_ctrl] -add {SLICE_X52Y134:SLICE_X65Y149}\r\n") file.write("resize_pblock [get_pblocks pblock_uart_ctrl] -add {RAMB18_X1Y54:RAMB18_X1Y59}\r\n") file.write("resize_pblock [get_pblocks pblock_uart_ctrl] -add {RAMB36_X1Y27:RAMB36_X1Y29}\r\n") file.write("set_property SNAPPING_MODE ON [get_pblocks pblock_uart_ctrl]\r\n") file.write("\r\n") def addRRAMCtrlBlock(file, FPGA=DEFAULT_FPGA): file.write("create_pblock pblock_rram_ctrl\r\n") file.write("add_cells_to_pblock [get_pblocks pblock_rram_ctrl] [get_cells -quiet [list rram_ctrl instdb]]\r\n") if(FPGA=='VC709'): file.write("resize_pblock [get_pblocks pblock_rram_ctrl] -add {SLICE_X170Y0:SLICE_X221Y474}\r\n") file.write("resize_pblock [get_pblocks pblock_rram_ctrl] -add {RAMB18_X11Y0:RAMB18_X14Y189}\r\n") file.write("resize_pblock [get_pblocks pblock_rram_ctrl] -add {RAMB36_X11Y0:RAMB36_X14Y94}\r\n") elif(FPGA=='A735'): file.write("resize_pblock [get_pblocks pblock_rram_ctrl] -add {SLICE_X36Y0:SLICE_X65Y99}\r\n") file.write("resize_pblock [get_pblocks pblock_rram_ctrl] -add {RAMB18_X1Y0:RAMB18_X2Y39}\r\n") file.write("resize_pblock [get_pblocks pblock_rram_ctrl] -add {RAMB36_X1Y0:RAMB36_X2Y19}\r\n") elif(FPGA=='A7100'): file.write("resize_pblock [get_pblocks pblock_rram_ctrl] -add {SLICE_X52Y0:SLICE_X79Y133}\r\n") file.write("resize_pblock [get_pblocks pblock_rram_ctrl] -add {RAMB18_X1Y0:RAMB18_X2Y51}\r\n") file.write("resize_pblock [get_pblocks pblock_rram_ctrl] -add {RAMB36_X1Y0:RAMB36_X2Y25}\r\n") file.write("set_property SNAPPING_MODE ON [get_pblocks pblock_rram_ctrl]\r\n") file.write("\r\n")
default_fpga = 'VC709' def add_clock(file, FPGA=DEFAULT_FPGA): file.write('#Clock Source\r\n') if FPGA == 'VC709': file.write('set_property IOSTANDARD DIFF_SSTL15 [get_ports clk_p]\r\n') file.write('set_property PACKAGE_PIN H19 [get_ports clk_p]\r\n') file.write('set_property PACKAGE_PIN G18 [get_ports clk_n]\r\n') file.write('set_property IOSTANDARD DIFF_SSTL15 [get_ports clk_n]\r\n') elif FPGA == 'A735': file.write('set_property -dict {PACKAGE_PIN E3 IOSTANDARD LVCMOS33} [get_ports CLK]\r\n') file.write('create_clock -period 10.000 -name sys_clk_pin -waveform {0.000 5.000} -add [get_ports CLK]\r\n') elif FPGA == 'A7100': file.write('set_property -dict {PACKAGE_PIN E3 IOSTANDARD LVCMOS33} [get_ports CLK]\r\n') file.write('create_clock -period 10.000 -name sys_clk_pin -waveform {0.000 5.000} -add [get_ports CLK]\r\n') file.write('\r\n') def add_led(file, FPGA=DEFAULT_FPGA): file.write('#LEDs\r\n') if FPGA == 'VC709': file.write('set_property -dict { PACKAGE_PIN AM39 IOSTANDARD LVCMOS18 } [get_ports { LED[0] }];\r\n') file.write('set_property -dict { PACKAGE_PIN AN39 IOSTANDARD LVCMOS18 } [get_ports { LED[1] }];\r\n') file.write('set_property -dict { PACKAGE_PIN AR37 IOSTANDARD LVCMOS18 } [get_ports { LED[2] }];\r\n') file.write('set_property -dict { PACKAGE_PIN AT37 IOSTANDARD LVCMOS18 } [get_ports { LED[3] }];\r\n') file.write('set_property -dict { PACKAGE_PIN AR35 IOSTANDARD LVCMOS18 } [get_ports { LED[4] }];\r\n') file.write('set_property -dict { PACKAGE_PIN AP41 IOSTANDARD LVCMOS18 } [get_ports { LED[5] }];\r\n') file.write('set_property -dict { PACKAGE_PIN AP42 IOSTANDARD LVCMOS18 } [get_ports { LED[6] }];\r\n') file.write('set_property -dict { PACKAGE_PIN AU39 IOSTANDARD LVCMOS18 } [get_ports { LED[7] }];\r\n') elif FPGA == 'A735': file.write('set_property -dict { PACKAGE_PIN H5 IOSTANDARD LVCMOS33 } [get_ports { LED[0] }];\r\n') file.write('set_property -dict { PACKAGE_PIN J5 IOSTANDARD LVCMOS33 } [get_ports { LED[1] }];\r\n') file.write('set_property -dict { PACKAGE_PIN T9 IOSTANDARD LVCMOS33 } [get_ports { LED[2] }];\r\n') file.write('set_property -dict { PACKAGE_PIN T10 IOSTANDARD LVCMOS33 } [get_ports { LED[3] }];\r\n') elif FPGA == 'A7100': file.write('set_property -dict { PACKAGE_PIN H5 IOSTANDARD LVCMOS33 } [get_ports { LED[0] }];\r\n') file.write('set_property -dict { PACKAGE_PIN J5 IOSTANDARD LVCMOS33 } [get_ports { LED[1] }];\r\n') file.write('set_property -dict { PACKAGE_PIN T9 IOSTANDARD LVCMOS33 } [get_ports { LED[2] }];\r\n') file.write('set_property -dict { PACKAGE_PIN T10 IOSTANDARD LVCMOS33 } [get_ports { LED[3] }];\r\n') file.write('\r\n') def add_switches(file, FPGA=DEFAULT_FPGA): file.write('#Switches\r\n') if FPGA == 'VC709': file.write('set_property -dict { PACKAGE_PIN AV30 IOSTANDARD LVCMOS18 } [get_ports { SW[0] }];\r\n') file.write('set_property -dict { PACKAGE_PIN AY33 IOSTANDARD LVCMOS18 } [get_ports { SW[1] }];\r\n') file.write('set_property -dict { PACKAGE_PIN BA31 IOSTANDARD LVCMOS18 } [get_ports { SW[2] }];\r\n') file.write('set_property -dict { PACKAGE_PIN BA32 IOSTANDARD LVCMOS18 } [get_ports { SW[3] }];\r\n') file.write('set_property -dict { PACKAGE_PIN AW30 IOSTANDARD LVCMOS18 } [get_ports { SW[4] }];\r\n') file.write('set_property -dict { PACKAGE_PIN AY30 IOSTANDARD LVCMOS33 } [get_ports { SW[5] }];\r\n') file.write('set_property -dict { PACKAGE_PIN BA30 IOSTANDARD LVCMOS18 } [get_ports { SW[6] }];\r\n') file.write('set_property -dict { PACKAGE_PIN BB31 IOSTANDARD LVCMOS18 } [get_ports { SW[7] }];\r\n') elif FPGA == 'A735': file.write('set_property -dict { PACKAGE_PIN A8 IOSTANDARD LVCMOS33 } [get_ports { SW[0] }];\r\n') file.write('set_property -dict { PACKAGE_PIN C11 IOSTANDARD LVCMOS33 } [get_ports { SW[1] }];\r\n') file.write('set_property -dict { PACKAGE_PIN C10 IOSTANDARD LVCMOS33 } [get_ports { SW[2] }];\r\n') file.write('set_property -dict { PACKAGE_PIN A10 IOSTANDARD LVCMOS33 } [get_ports { SW[3] }];\r\n') elif FPGA == 'A7100': file.write('set_property -dict { PACKAGE_PIN A8 IOSTANDARD LVCMOS33 } [get_ports { SW[0] }];\r\n') file.write('set_property -dict { PACKAGE_PIN C11 IOSTANDARD LVCMOS33 } [get_ports { SW[1] }];\r\n') file.write('set_property -dict { PACKAGE_PIN C10 IOSTANDARD LVCMOS33 } [get_ports { SW[2] }];\r\n') file.write('set_property -dict { PACKAGE_PIN A10 IOSTANDARD LVCMOS33 } [get_ports { SW[3] }];\r\n') file.write('\r\n') def add_uart(file, FPGA=DEFAULT_FPGA): file.write('#Uart\r\n') if FPGA == 'VC709': file.write('set_property -dict { PACKAGE_PIN AU36 IOSTANDARD LVCMOS18 } [get_ports { TX }];\r\n') elif FPGA == 'A735': file.write('set_property -dict { PACKAGE_PIN D10 IOSTANDARD LVCMOS33 } [get_ports { TX }];\r\n') file.write('#set_property -dict {PACKAGE_PIN A9 IOSTANDARD LVCMOS33 } [get_ports RX];\r\n') elif FPGA == 'A7100': file.write('set_property -dict { PACKAGE_PIN D10 IOSTANDARD LVCMOS33 } [get_ports { TX }];\r\n') file.write('#set_property -dict {PACKAGE_PIN A9 IOSTANDARD LVCMOS33 } [get_ports RX];\r\n') file.write('\r\n') def add_buttons(file, FPGA=DEFAULT_FPGA): file.write('#Buttons\r\n') if FPGA == 'VC709': file.write('set_property -dict { PACKAGE_PIN AV39 IOSTANDARD LVCMOS18 } [get_ports { BUTTON[0] }];\r\n') file.write('set_property -dict { PACKAGE_PIN AW40 IOSTANDARD LVCMOS18 } [get_ports { BUTTON[1] }];\r\n') file.write('set_property -dict { PACKAGE_PIN AP40 IOSTANDARD LVCMOS18 } [get_ports { BUTTON[2] }];\r\n') file.write('set_property -dict { PACKAGE_PIN AU38 IOSTANDARD LVCMOS18 } [get_ports { BUTTON[3] }];\r\n') file.write('set_property -dict { PACKAGE_PIN AR40 IOSTANDARD LVCMOS18 } [get_ports { BUTTON[4] }];\r\n') elif FPGA == 'A735': file.write('set_property -dict { PACKAGE_PIN D9 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[0] }];\r\n') file.write('set_property -dict { PACKAGE_PIN C9 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[1] }];\r\n') file.write('set_property -dict { PACKAGE_PIN B9 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[2] }];\r\n') file.write('set_property -dict { PACKAGE_PIN B8 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[3] }];\r\n') elif FPGA == 'A7100': file.write('set_property -dict { PACKAGE_PIN D9 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[0] }];\r\n') file.write('set_property -dict { PACKAGE_PIN C9 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[1] }];\r\n') file.write('set_property -dict { PACKAGE_PIN B9 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[2] }];\r\n') file.write('set_property -dict { PACKAGE_PIN B8 IOSTANDARD LVCMOS33 } [get_ports { BUTTON[3] }];\r\n') file.write('\r\n') def add_clock_block(file, FPGA=DEFAULT_FPGA): file.write('create_pblock pblock_clk_div\r\n') file.write('add_cells_to_pblock [get_pblocks pblock_clk_div] [get_cells -quiet [list clk_div]]\r\n') if FPGA == 'VC709': file.write('resize_pblock [get_pblocks pblock_clk_div] -add {SLICE_X196Y475:SLICE_X221Y499}\r\n') file.write('resize_pblock [get_pblocks pblock_clk_div] -add {RAMB18_X13Y190:RAMB18_X14Y199}\r\n') file.write('resize_pblock [get_pblocks pblock_clk_div] -add {RAMB36_X13Y95:RAMB36_X14Y99}\r\n') elif FPGA == 'A735': file.write('resize_pblock [get_pblocks pblock_clk_div] -add {SLICE_X36Y134:SLICE_X57Y149}\r\n') file.write('resize_pblock [get_pblocks pblock_clk_div] -add {RAMB18_X1Y54:RAMB18_X1Y59}\r\n') file.write('resize_pblock [get_pblocks pblock_clk_div] -add {RAMB36_X1Y27:RAMB36_X1Y29}\r\n') file.write('set_property BEL MMCME2_ADV [get_cells clk_div/MMCME2_ADV_inst]\r\n') file.write('set_property LOC MMCME2_ADV_X1Y1 [get_cells clk_div/MMCME2_ADV_inst]\r\n') elif FPGA == 'A7100': file.write('resize_pblock [get_pblocks pblock_clk_div] -add {SLICE_X66Y134:SLICE_X79Y149}\r\n') file.write('resize_pblock [get_pblocks pblock_clk_div] -add {RAMB18_X2Y54:RAMB18_X2Y59}\r\n') file.write('resize_pblock [get_pblocks pblock_clk_div] -add {RAMB36_X2Y27:RAMB36_X2Y29}\r\n') file.write('set_property BEL MMCME2_ADV [get_cells clk_div/MMCME2_ADV_inst]\r\n') file.write('set_property LOC MMCME2_ADV_X1Y1 [get_cells clk_div/MMCME2_ADV_inst]\r\n') file.write('set_property SNAPPING_MODE ON [get_pblocks pblock_clk_div]\r\n') file.write('\r\n') def add_uart_ctrl_block(file, FPGA=DEFAULT_FPGA): file.write('create_pblock pblock_uart_ctrl\r\n') file.write('add_cells_to_pblock [get_pblocks pblock_uart_ctrl] [get_cells -quiet [list uart_ctrl]]\r\n') if FPGA == 'VC709': file.write('resize_pblock [get_pblocks pblock_uart_ctrl] -add {SLICE_X170Y475:SLICE_X195Y499}\r\n') file.write('resize_pblock [get_pblocks pblock_uart_ctrl] -add {RAMB18_X11Y190:RAMB18_X12Y199}\r\n') file.write('resize_pblock [get_pblocks pblock_uart_ctrl] -add {RAMB36_X11Y95:RAMB36_X12Y99}\r\n') elif FPGA == 'A735': file.write('resize_pblock [get_pblocks pblock_uart_ctrl] -add {SLICE_X36Y118:SLICE_X57Y133}\r\n') file.write('resize_pblock [get_pblocks pblock_uart_ctrl] -add {RAMB18_X1Y50:RAMB18_X1Y51}\r\n') file.write('resize_pblock [get_pblocks pblock_uart_ctrl] -add {RAMB36_X1Y25:RAMB36_X1Y25}\r\n') elif FPGA == 'A7100': file.write('resize_pblock [get_pblocks pblock_uart_ctrl] -add {SLICE_X52Y134:SLICE_X65Y149}\r\n') file.write('resize_pblock [get_pblocks pblock_uart_ctrl] -add {RAMB18_X1Y54:RAMB18_X1Y59}\r\n') file.write('resize_pblock [get_pblocks pblock_uart_ctrl] -add {RAMB36_X1Y27:RAMB36_X1Y29}\r\n') file.write('set_property SNAPPING_MODE ON [get_pblocks pblock_uart_ctrl]\r\n') file.write('\r\n') def add_rram_ctrl_block(file, FPGA=DEFAULT_FPGA): file.write('create_pblock pblock_rram_ctrl\r\n') file.write('add_cells_to_pblock [get_pblocks pblock_rram_ctrl] [get_cells -quiet [list rram_ctrl instdb]]\r\n') if FPGA == 'VC709': file.write('resize_pblock [get_pblocks pblock_rram_ctrl] -add {SLICE_X170Y0:SLICE_X221Y474}\r\n') file.write('resize_pblock [get_pblocks pblock_rram_ctrl] -add {RAMB18_X11Y0:RAMB18_X14Y189}\r\n') file.write('resize_pblock [get_pblocks pblock_rram_ctrl] -add {RAMB36_X11Y0:RAMB36_X14Y94}\r\n') elif FPGA == 'A735': file.write('resize_pblock [get_pblocks pblock_rram_ctrl] -add {SLICE_X36Y0:SLICE_X65Y99}\r\n') file.write('resize_pblock [get_pblocks pblock_rram_ctrl] -add {RAMB18_X1Y0:RAMB18_X2Y39}\r\n') file.write('resize_pblock [get_pblocks pblock_rram_ctrl] -add {RAMB36_X1Y0:RAMB36_X2Y19}\r\n') elif FPGA == 'A7100': file.write('resize_pblock [get_pblocks pblock_rram_ctrl] -add {SLICE_X52Y0:SLICE_X79Y133}\r\n') file.write('resize_pblock [get_pblocks pblock_rram_ctrl] -add {RAMB18_X1Y0:RAMB18_X2Y51}\r\n') file.write('resize_pblock [get_pblocks pblock_rram_ctrl] -add {RAMB36_X1Y0:RAMB36_X2Y25}\r\n') file.write('set_property SNAPPING_MODE ON [get_pblocks pblock_rram_ctrl]\r\n') file.write('\r\n')
# -*- coding: utf-8 -*- """ Created on Sun Jan 30 22:11:59 2022 @author: Akshatha """ # recursive data structure class TreeNode(): def __init__(self, data): self.parent = None self.data = data self.children = [] def add_child(self, child): self.children.append(child) child.parent = self def print_tree(self,level=0): print(self.data) level += 1 for child in self.children: print('\t'*level,end=' ') child.print_tree(level) def build_tree(): root = TreeNode('Books') category_1 = TreeNode('Mystery') category_1.add_child(TreeNode('Behind her eyes')) category_1.add_child(TreeNode('Black water lilies')) category_2 = TreeNode('Adventure') category_2.add_child(TreeNode('Secret seven series')) category_2.add_child(TreeNode('Famous five series')) category_3 = TreeNode('Science Fiction') category_3.add_child(TreeNode('Project Hail Mary')) category_3.add_child(TreeNode('Deception Point')) root.add_child(category_1) root.add_child(category_2) root.add_child(category_3) return root if __name__ == '__main__': root = build_tree() root.print_tree()
""" Created on Sun Jan 30 22:11:59 2022 @author: Akshatha """ class Treenode: def __init__(self, data): self.parent = None self.data = data self.children = [] def add_child(self, child): self.children.append(child) child.parent = self def print_tree(self, level=0): print(self.data) level += 1 for child in self.children: print('\t' * level, end=' ') child.print_tree(level) def build_tree(): root = tree_node('Books') category_1 = tree_node('Mystery') category_1.add_child(tree_node('Behind her eyes')) category_1.add_child(tree_node('Black water lilies')) category_2 = tree_node('Adventure') category_2.add_child(tree_node('Secret seven series')) category_2.add_child(tree_node('Famous five series')) category_3 = tree_node('Science Fiction') category_3.add_child(tree_node('Project Hail Mary')) category_3.add_child(tree_node('Deception Point')) root.add_child(category_1) root.add_child(category_2) root.add_child(category_3) return root if __name__ == '__main__': root = build_tree() root.print_tree()
class Calculator: def __init__(self, a: int, b: int) -> None: self.a = a self.b = b def suma(self): return self.a + self.b def resta(self): return self.a - self.b def multiplicacion(self): return self.a * self.b def division(self): try: return self.a / self.b except ZeroDivisionError: return('No se puede dividir entre cero') def potencia(self): return self.a ** self.b def raiz(self): if(self.a < 0): return('No se puede sacar raiz a un numero negativo') else: return self.a ** 1/self.b
class Calculator: def __init__(self, a: int, b: int) -> None: self.a = a self.b = b def suma(self): return self.a + self.b def resta(self): return self.a - self.b def multiplicacion(self): return self.a * self.b def division(self): try: return self.a / self.b except ZeroDivisionError: return 'No se puede dividir entre cero' def potencia(self): return self.a ** self.b def raiz(self): if self.a < 0: return 'No se puede sacar raiz a un numero negativo' else: return self.a ** 1 / self.b
class PathNotSetError(Exception): """database path not set error""" def __init__(self,message): super(PathNotSetError, self).__init__(message) self.message = message class SetPasswordError(Exception): """session password not set error""" def __init__(self, message): super(SetPasswordError, self).__init__(message) self.message = message class ValidationError(Exception): """not logged in""" def __init__(self, message): super(ValidationError, self).__init__(message) self.message = message class NotAStringError(Exception): """where clause not a string""" def __init__(self,message): super(NotAStringError,self).__init__(message) self.message = message #################################### ##########postgres################## class NullConnectionError(Exception): """db server is not connected""" def __init__(self,message): super(NullConnectionError,self).__init__(message) self.message = message class NoColumnsGivenError(Exception): def __init__(self, message): super(NoColumnsGivenError, self).__init__(message) self.message = message class NoDataTypesGivenError(Exception): def __init__(self,message): super(NoDataTypesGivenError, self).__init__(message) self.message = message class CountDontMatchError(Exception): def __init__(self,message): super(CountDontMatchError, self).__init__(message) self.message = message class NoPrimaryKeyError(Exception): def __init__(self,message): super(NoPrimaryKeyError, self).__init__(message) self.message = message class DataTypeError(Exception): def __init__(self,message): super(DataTypeError, self).__init__(message) self.message = message class NoValuesGivenError(Exception): def __init__(self, message): super(NoValuesGivenError, self).__init__(message) self.message = message
class Pathnotseterror(Exception): """database path not set error""" def __init__(self, message): super(PathNotSetError, self).__init__(message) self.message = message class Setpassworderror(Exception): """session password not set error""" def __init__(self, message): super(SetPasswordError, self).__init__(message) self.message = message class Validationerror(Exception): """not logged in""" def __init__(self, message): super(ValidationError, self).__init__(message) self.message = message class Notastringerror(Exception): """where clause not a string""" def __init__(self, message): super(NotAStringError, self).__init__(message) self.message = message class Nullconnectionerror(Exception): """db server is not connected""" def __init__(self, message): super(NullConnectionError, self).__init__(message) self.message = message class Nocolumnsgivenerror(Exception): def __init__(self, message): super(NoColumnsGivenError, self).__init__(message) self.message = message class Nodatatypesgivenerror(Exception): def __init__(self, message): super(NoDataTypesGivenError, self).__init__(message) self.message = message class Countdontmatcherror(Exception): def __init__(self, message): super(CountDontMatchError, self).__init__(message) self.message = message class Noprimarykeyerror(Exception): def __init__(self, message): super(NoPrimaryKeyError, self).__init__(message) self.message = message class Datatypeerror(Exception): def __init__(self, message): super(DataTypeError, self).__init__(message) self.message = message class Novaluesgivenerror(Exception): def __init__(self, message): super(NoValuesGivenError, self).__init__(message) self.message = message
RICK_DB_VERSION = ["0", "9", "4"] def get_version(): return ".".join(RICK_DB_VERSION)
rick_db_version = ['0', '9', '4'] def get_version(): return '.'.join(RICK_DB_VERSION)
### Given two strings, determine whether one is permutations of the other # Solution: Two strings are permutations of each other if they have the same characters in different order. # So, you can sort them and compare them # Clarify if they are case sensitive, or if they contain space. # Answer 1: Brute force, sort and compare def permutation_str(str1, str2): if len(str1) != len(str2): return False if sorted(str1) == sorted(str2): return True # Concise answer 2: Count the number of individual characters in each string ## and compare the counts. def string_permutation(s1,s2): """ Edge case: If the strings are not the same length, they are not permutations of each other. Count the occurence of each individual character in each string. If the counts are the same, the strings are permutations of each other. Counts are stored in array of 128 size. This is an assumption that we are using ASCII characters. The number of characters in ASCII is 128. """ if len(s1) != len(s2): return False count_s1 = [0] * 128 for char in s1: count_s1[ord(char)] += 1 count_s2 = [0] * 128 for char in s2: count_s2[ord(char)] += 1 if count_s1 == count_s2: return True else: return False ## There is something off in the implementation: Solved # Test the algorithm on many inputs strings: It works ## Testing the algoritm on different inputs #string_permutation('foo','ofo') ## Output: True #string_permutation('foo','hhdnd') ## Output: False #string_permutation('foo','gbf') ## Output: False #string_permutation('foo','fcd') #Output: False #string_permutation('foo','fog') ## Output: False
def permutation_str(str1, str2): if len(str1) != len(str2): return False if sorted(str1) == sorted(str2): return True def string_permutation(s1, s2): """ Edge case: If the strings are not the same length, they are not permutations of each other. Count the occurence of each individual character in each string. If the counts are the same, the strings are permutations of each other. Counts are stored in array of 128 size. This is an assumption that we are using ASCII characters. The number of characters in ASCII is 128. """ if len(s1) != len(s2): return False count_s1 = [0] * 128 for char in s1: count_s1[ord(char)] += 1 count_s2 = [0] * 128 for char in s2: count_s2[ord(char)] += 1 if count_s1 == count_s2: return True else: return False
#Displays Bot Username ***Required*** name = '#Insert Bot Username Here#' #Bot User ID ***Required*** uid = '#Insert Bot User ID Here#' #Banner List (This is for On-Account-Creation Banner RNG) banner_list = ['https://cdn.discordapp.com/attachments/461057214749081600/468314847147196416/image.gif', 'https://cdn.discordapp.com/attachments/455987115407441921/469294412082446346/image-4.gif', 'https://cdn.discordapp.com/attachments/455987115407441921/469294413332480000/image-5.gif', 'https://cdn.discordapp.com/attachments/455987115407441921/469294414091780106/test3-1.gif'] #Bot Profile URL ***Required*** url = '#Insert the URL of the image you use for the bot here' #Bot Token **REQUIRED (BOT IS NOT RUNNABLE WITHOUT TOKEN)** token = 'Put your Token Here' #Prefix ***REQUIRED*** prefix = '~~' #Color color = 0x00000
name = '#Insert Bot Username Here#' uid = '#Insert Bot User ID Here#' banner_list = ['https://cdn.discordapp.com/attachments/461057214749081600/468314847147196416/image.gif', 'https://cdn.discordapp.com/attachments/455987115407441921/469294412082446346/image-4.gif', 'https://cdn.discordapp.com/attachments/455987115407441921/469294413332480000/image-5.gif', 'https://cdn.discordapp.com/attachments/455987115407441921/469294414091780106/test3-1.gif'] url = '#Insert the URL of the image you use for the bot here' token = 'Put your Token Here' prefix = '~~' color = 0
class YandexAPIError(Exception): error_codes = { 401: "ERR_KEY_INVALID", 402: "ERR_KEY_BLOCKED", 403: "ERR_DAILY_REQ_LIMIT_EXCEEDED", 413: "ERR_TEXT_TOO_LONG", 501: "ERR_LANG_NOT_SUPPORTED", } def __init__(self, response: dict = None): status_code = response.get('code') message = response.get('message') error_name = self.error_codes.get(status_code, "UNKNOWN_ERROR") super(YandexAPIError, self).__init__(status_code, error_name, message) class YandexDictionaryError(Exception): pass
class Yandexapierror(Exception): error_codes = {401: 'ERR_KEY_INVALID', 402: 'ERR_KEY_BLOCKED', 403: 'ERR_DAILY_REQ_LIMIT_EXCEEDED', 413: 'ERR_TEXT_TOO_LONG', 501: 'ERR_LANG_NOT_SUPPORTED'} def __init__(self, response: dict=None): status_code = response.get('code') message = response.get('message') error_name = self.error_codes.get(status_code, 'UNKNOWN_ERROR') super(YandexAPIError, self).__init__(status_code, error_name, message) class Yandexdictionaryerror(Exception): pass
class InsertConflictError(Exception): pass class OptimisticLockError(Exception): pass
class Insertconflicterror(Exception): pass class Optimisticlockerror(Exception): pass
# puzzle easy // https://www.codingame.com/ide/puzzle/sudoku-validator # needed values row_, column_, grid_3x3, sol = [], [], [], [] valid = [1, 2, 3, 4, 5, 6, 7, 8, 9] subgrid = False # needed functions def check(arr): for _ in arr: tmp = valid.copy() for s in _: if s in tmp: tmp.remove(s) if tmp != []: return False return True # sudoku in [row][cal] for i in range(9): tmp = [] for j in input().split(): tmp.append(int(j)) row_+=[tmp] # sudoku in [cal][row] for row in range(len(row_)): tmp = [] for cal in range(len(row_)): tmp.append(row_[cal][row]) column_+=[tmp] # sudoku in 3x3 subgrids for _ in [[1,1],[1,4],[1,7],[4,1],[4,4],[4,7],[7,1],[7,4],[7,7]]: tmp = [row_[_[0]][_[1]]] # root tmp.append(row_[_[0]-1][_[1]]); tmp.append(row_[_[0]+1][_[1]]) # up/ down tmp.append(row_[_[0]][_[1]+1]); tmp.append(row_[_[0]][_[1]-1]) # left/ right tmp.append(row_[_[0]-1][_[1]-1]); tmp.append(row_[_[0]-1][_[1]+1]) # diagonal up tmp.append(row_[_[0]+1][_[1]-1]); tmp.append(row_[_[0]+1][_[1]+1]) # diagonal down if sum(tmp) != 45: subgrid = False; break else: subgrid = True # check if row and column values are different for _ in [row_, column_]: sol.append(check(_)) # print solution if sol[0] is True and sol[1] is True and subgrid is True: print('true') else: print('false')
(row_, column_, grid_3x3, sol) = ([], [], [], []) valid = [1, 2, 3, 4, 5, 6, 7, 8, 9] subgrid = False def check(arr): for _ in arr: tmp = valid.copy() for s in _: if s in tmp: tmp.remove(s) if tmp != []: return False return True for i in range(9): tmp = [] for j in input().split(): tmp.append(int(j)) row_ += [tmp] for row in range(len(row_)): tmp = [] for cal in range(len(row_)): tmp.append(row_[cal][row]) column_ += [tmp] for _ in [[1, 1], [1, 4], [1, 7], [4, 1], [4, 4], [4, 7], [7, 1], [7, 4], [7, 7]]: tmp = [row_[_[0]][_[1]]] tmp.append(row_[_[0] - 1][_[1]]) tmp.append(row_[_[0] + 1][_[1]]) tmp.append(row_[_[0]][_[1] + 1]) tmp.append(row_[_[0]][_[1] - 1]) tmp.append(row_[_[0] - 1][_[1] - 1]) tmp.append(row_[_[0] - 1][_[1] + 1]) tmp.append(row_[_[0] + 1][_[1] - 1]) tmp.append(row_[_[0] + 1][_[1] + 1]) if sum(tmp) != 45: subgrid = False break else: subgrid = True for _ in [row_, column_]: sol.append(check(_)) if sol[0] is True and sol[1] is True and (subgrid is True): print('true') else: print('false')
# # (c) Copyright 2021 Micro Focus or one of its affiliates. # class ErrorMessage: GENERAL_ERROR = "Something went wrong" OA_SERVICE_CAN_NOT_BE_NONE = "service_endpoint can not be empty" MAX_ATTEMPTS_CAN_NOT_BE_NONE = "max_attempts can not be empty" USERNAME_CAN_NOT_BE_NONE = "username can not be empty" PASSWORD_CAN_NOT_BE_NONE = "password can not be empty" OKTA_CLIENT_CAN_NOT_BE_NONE = "client_id can not be empty" OKTA_AUTH_ENDPOINT_CAN_NOT_BE_NONE = "auth_endpont can not be empty" LOGIN_FAILED_BAD_USERNAME_OR_PASSWORD = "Failed to login, please check your okta url, username and password." ERROR_CONFIG_CONFIG_NOT_EXIST = "config file does not exists, please run: va config" ERROR_CONFIG_CONFIG_NOT_READABLE = "config file can not be read, please check permission" ERROR_CONFIG_CONFIG_NOT_WRITEABLE = "config file can not be write, please check permission" ERROR_CREDENTIAL_CONFIG_NOT_EXIST = "credential file does not exists, please run: va config" ERROR_CREDENTIAL_CONFIG_NOT_READABLE = "credential file can not be read, please check permission" ERROR_CREDENTIAL_CONFIG_NOT_WRITEABLE = "credential file can not be write, please check permission" ERROR_STATE_PARAM_VERIFY_FAILED = "failed to verify state param" ERROR_VERIFY_ACCESS_TOKEN_FAIL = "Error in verifying the access_token, please login and try again." ERROR_ACCESS_TOKEN_FILE_NOT_FOUND = "Access token file not found, please login and try again."
class Errormessage: general_error = 'Something went wrong' oa_service_can_not_be_none = 'service_endpoint can not be empty' max_attempts_can_not_be_none = 'max_attempts can not be empty' username_can_not_be_none = 'username can not be empty' password_can_not_be_none = 'password can not be empty' okta_client_can_not_be_none = 'client_id can not be empty' okta_auth_endpoint_can_not_be_none = 'auth_endpont can not be empty' login_failed_bad_username_or_password = 'Failed to login, please check your okta url, username and password.' error_config_config_not_exist = 'config file does not exists, please run: va config' error_config_config_not_readable = 'config file can not be read, please check permission' error_config_config_not_writeable = 'config file can not be write, please check permission' error_credential_config_not_exist = 'credential file does not exists, please run: va config' error_credential_config_not_readable = 'credential file can not be read, please check permission' error_credential_config_not_writeable = 'credential file can not be write, please check permission' error_state_param_verify_failed = 'failed to verify state param' error_verify_access_token_fail = 'Error in verifying the access_token, please login and try again.' error_access_token_file_not_found = 'Access token file not found, please login and try again.'
DEBUG=False # bool value # True for debug output ADC_URL='http://192.168.1.1' # str value # URL to FortiADC Management/API interface ADC_USERNAME='certificate_admin' # str value # Administrator account on FortiADC # Account requires only System Read-Write Access Profile ADC_PASSWORD='ChangeThisPassword' # str value # Administrator account password on FortiADC CERT_NAME='letsencrypt_certificate' # str value # Name of certificate in FortiADC SQUASH_SSL=True # bool value # True to squash SSL warnings
debug = False adc_url = 'http://192.168.1.1' adc_username = 'certificate_admin' adc_password = 'ChangeThisPassword' cert_name = 'letsencrypt_certificate' squash_ssl = True
############################################# # Author: Hongwei Fan # # E-mail: hwnorm@outlook.com # # Homepage: https://github.com/hwfan # ############################################# def format_size(num_size): try: num_size = float(num_size) KB = num_size / 1024 except: return "Error" if KB >= 1024: M = KB / 1024 if M >= 1024: G = M / 1024 return '%.3f GB' % G else: return '%.3f MB' % M else: return '%.3f KB' % KB
def format_size(num_size): try: num_size = float(num_size) kb = num_size / 1024 except: return 'Error' if KB >= 1024: m = KB / 1024 if M >= 1024: g = M / 1024 return '%.3f GB' % G else: return '%.3f MB' % M else: return '%.3f KB' % KB
ACRONYM = "PMC" def promoter(**identifier_properties): unique_data_string = [ identifier_properties.get("name", "NoName"), identifier_properties.get("pos1", "NoPos1"), identifier_properties.get("transcriptionStartSite", {}).get("leftEndPosition", "NoTSSLEND"), identifier_properties.get("transcriptionStartSite", {}).get("rightEndPosition", "NoTSSREND") ] return unique_data_string
acronym = 'PMC' def promoter(**identifier_properties): unique_data_string = [identifier_properties.get('name', 'NoName'), identifier_properties.get('pos1', 'NoPos1'), identifier_properties.get('transcriptionStartSite', {}).get('leftEndPosition', 'NoTSSLEND'), identifier_properties.get('transcriptionStartSite', {}).get('rightEndPosition', 'NoTSSREND')] return unique_data_string
# Configuration values # Edit this file to match your server settings and options config = { 'usenet_server': 'news.easynews.com', 'usenet_port': 119, 'usenet_username': '', 'usenet_password': '', 'database_server': 'localhost', 'database_port': 27017, 'max_run_size': 1000000 # Max number of articles (not NZBs) to process in a single run. }
config = {'usenet_server': 'news.easynews.com', 'usenet_port': 119, 'usenet_username': '', 'usenet_password': '', 'database_server': 'localhost', 'database_port': 27017, 'max_run_size': 1000000}
class TarsError(Exception): pass class SyncError(TarsError): pass class PackageError(TarsError): pass
class Tarserror(Exception): pass class Syncerror(TarsError): pass class Packageerror(TarsError): pass
class Deque: """ Deque implementation using python list as underlying storage """ def __init__(self): """ Creates an empty deque """ self._data = [] def __len__(self): """ Returns the length of the deque """ return len(self._data) def display(self): return self._data def is_empty(self): """ Returns true if the deque is empty, false otherwise """ return len(self._data) == 0 def first(self): """ Returns (but do not remove) the first element from the deque """ if self.is_empty(): raise Empty('Deque is empty') return self._data[-1] def last(self): """ Returns (but do not remove) the last element from the deque """ if self.is_empty(): raise Empty('Deque is empty') return self._data[0] def add_first(self, element): """ Adds an element to the front of the deque """ self._data.append(element) def add_last(self, element): """ Adds an element to the back of the deque """ self._data.insert(0, element) def remove_first(self): """ Removes an element from the front of the deque """ return self._data.pop() def remove_last(self): """ Removes an element from the back of the deque """ return self._data.pop(0) class Empty(Exception): """ Error attempting to access an element from an empty container """ pass
class Deque: """ Deque implementation using python list as underlying storage """ def __init__(self): """ Creates an empty deque """ self._data = [] def __len__(self): """ Returns the length of the deque """ return len(self._data) def display(self): return self._data def is_empty(self): """ Returns true if the deque is empty, false otherwise """ return len(self._data) == 0 def first(self): """ Returns (but do not remove) the first element from the deque """ if self.is_empty(): raise empty('Deque is empty') return self._data[-1] def last(self): """ Returns (but do not remove) the last element from the deque """ if self.is_empty(): raise empty('Deque is empty') return self._data[0] def add_first(self, element): """ Adds an element to the front of the deque """ self._data.append(element) def add_last(self, element): """ Adds an element to the back of the deque """ self._data.insert(0, element) def remove_first(self): """ Removes an element from the front of the deque """ return self._data.pop() def remove_last(self): """ Removes an element from the back of the deque """ return self._data.pop(0) class Empty(Exception): """ Error attempting to access an element from an empty container """ pass
MAGIC = { "xls": "{D0 CF 11}", "html": None }
magic = {'xls': '{D0 CF 11}', 'html': None}
def generate_key(n): letters = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" key = {} cnt = 0 for c in letters: key[c] = letters[(cnt + n) % len(letters)] cnt += 1 return key def encrypt(key, message): cipher = "" for c in message: if c in key: cipher += key[c] else: cipher += c return cipher def get_decryption_key(key): dkey = {} for c in key: dkey[key[c]] = c return dkey key = generate_key(3) cipher = encrypt(key, "YOU ARE AWESOME") print(cipher) dkey = get_decryption_key(key) message = encrypt(dkey, cipher) print(message)
def generate_key(n): letters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' key = {} cnt = 0 for c in letters: key[c] = letters[(cnt + n) % len(letters)] cnt += 1 return key def encrypt(key, message): cipher = '' for c in message: if c in key: cipher += key[c] else: cipher += c return cipher def get_decryption_key(key): dkey = {} for c in key: dkey[key[c]] = c return dkey key = generate_key(3) cipher = encrypt(key, 'YOU ARE AWESOME') print(cipher) dkey = get_decryption_key(key) message = encrypt(dkey, cipher) print(message)
# Library targets for DashToHls. These minimize external dependencies (such # as OpenSSL) so other projects can depend on them without bringing in # unnecessary dependencies. { 'target_defaults': { 'xcode_settings': { 'CLANG_ENABLE_OBJC_ARC': [ 'YES' ], }, }, 'targets': [ { 'target_name': 'DashToHlsLibrary', 'type': 'static_library', 'xcode_settings': { 'GCC_PREFIX_HEADER': 'DashToHls_osx.pch', 'CLANG_CXX_LIBRARY': 'libc++', }, 'direct_dependent_settings': { 'include_dirs': [ '../include', '..', ] }, 'include_dirs': [ '..', ], 'conditions': [ ['OS=="mac"', { 'defines': [ 'USE_AVFRAMEWORK', ], 'sources': [ 'dash_to_hls_api_avframework.h', 'dash_to_hls_api_avframework.mm', ], }], ['OS=="ios"', { 'defines': [ 'USE_AVFRAMEWORK', ], 'sources': [ 'dash_to_hls_api_avframework.h', 'dash_to_hls_api_avframework.mm', ], }], ], 'sources': [ '../include/DashToHlsApi.h', '../include/DashToHlsApiAVFramework.h', 'dash_to_hls_api.cc', 'dash_to_hls_session.h', 'utilities.cc', 'utilities.h', ], 'dependencies': [ 'DashToHlsDash', 'DashToHlsDefaultDiagnosticCallback', 'DashToHlsPs', 'DashToHlsTs', ], }, { 'target_name': 'DashToHlsDash', 'type': 'static_library', 'xcode_settings': { 'GCC_PREFIX_HEADER': 'DashToHls_osx.pch', 'CLANG_CXX_LIBRARY': 'libc++', }, 'include_dirs': [ '..', ], 'direct_dependent_settings': { 'include_dirs': [ '..', ], }, 'sources': [ 'bit_reader.cc', 'bit_reader.h', 'utilities.h', 'utilities.cc', '<!@(find dash -type f -name "*.h")', '<!@(find dash -type f -name "*.cc" ! -name "*_test.cc")', ], }, { 'target_name': 'DashToHlsPs', 'type': 'static_library', 'xcode_settings': { 'GCC_PREFIX_HEADER': 'DashToHls_osx.pch', 'CLANG_CXX_LIBRARY': 'libc++', }, 'include_dirs': [ '..', ], 'sources': [ 'utilities.h', 'utilities.cc', '<!@(find ps -type f -name "*.h")', '<!@(find ps -type f -name "*.cc" ! -name "*_test.cc")', ], }, { 'target_name': 'DashToHlsTs', 'type': 'static_library', 'xcode_settings': { 'GCC_PREFIX_HEADER': 'DashToHls_osx.pch', 'CLANG_CXX_LIBRARY': 'libc++', }, 'include_dirs': [ '..', ], 'sources': [ 'adts/adts_out.cc', 'adts/adts_out.h', 'ts/transport_stream_out.cc', 'ts/transport_stream_out.h', ], }, # Note: If you depend on any of the sub-libraries here, you either need to # depend on this to implement the DashToHlsDefaultDiagnosticCallback # function, or, implement it yourself. Otherwise, the project will fail to # link. { 'target_name': 'DashToHlsDefaultDiagnosticCallback', 'type': 'static_library', 'xcode_settings': { 'GCC_PREFIX_HEADER': 'DashToHls_osx.pch', 'CLANG_CXX_LIBRARY': 'libc++', }, 'sources': [ 'dash_to_hls_default_diagnostic_callback.mm', ], } ] }
{'target_defaults': {'xcode_settings': {'CLANG_ENABLE_OBJC_ARC': ['YES']}}, 'targets': [{'target_name': 'DashToHlsLibrary', 'type': 'static_library', 'xcode_settings': {'GCC_PREFIX_HEADER': 'DashToHls_osx.pch', 'CLANG_CXX_LIBRARY': 'libc++'}, 'direct_dependent_settings': {'include_dirs': ['../include', '..']}, 'include_dirs': ['..'], 'conditions': [['OS=="mac"', {'defines': ['USE_AVFRAMEWORK'], 'sources': ['dash_to_hls_api_avframework.h', 'dash_to_hls_api_avframework.mm']}], ['OS=="ios"', {'defines': ['USE_AVFRAMEWORK'], 'sources': ['dash_to_hls_api_avframework.h', 'dash_to_hls_api_avframework.mm']}]], 'sources': ['../include/DashToHlsApi.h', '../include/DashToHlsApiAVFramework.h', 'dash_to_hls_api.cc', 'dash_to_hls_session.h', 'utilities.cc', 'utilities.h'], 'dependencies': ['DashToHlsDash', 'DashToHlsDefaultDiagnosticCallback', 'DashToHlsPs', 'DashToHlsTs']}, {'target_name': 'DashToHlsDash', 'type': 'static_library', 'xcode_settings': {'GCC_PREFIX_HEADER': 'DashToHls_osx.pch', 'CLANG_CXX_LIBRARY': 'libc++'}, 'include_dirs': ['..'], 'direct_dependent_settings': {'include_dirs': ['..']}, 'sources': ['bit_reader.cc', 'bit_reader.h', 'utilities.h', 'utilities.cc', '<!@(find dash -type f -name "*.h")', '<!@(find dash -type f -name "*.cc" ! -name "*_test.cc")']}, {'target_name': 'DashToHlsPs', 'type': 'static_library', 'xcode_settings': {'GCC_PREFIX_HEADER': 'DashToHls_osx.pch', 'CLANG_CXX_LIBRARY': 'libc++'}, 'include_dirs': ['..'], 'sources': ['utilities.h', 'utilities.cc', '<!@(find ps -type f -name "*.h")', '<!@(find ps -type f -name "*.cc" ! -name "*_test.cc")']}, {'target_name': 'DashToHlsTs', 'type': 'static_library', 'xcode_settings': {'GCC_PREFIX_HEADER': 'DashToHls_osx.pch', 'CLANG_CXX_LIBRARY': 'libc++'}, 'include_dirs': ['..'], 'sources': ['adts/adts_out.cc', 'adts/adts_out.h', 'ts/transport_stream_out.cc', 'ts/transport_stream_out.h']}, {'target_name': 'DashToHlsDefaultDiagnosticCallback', 'type': 'static_library', 'xcode_settings': {'GCC_PREFIX_HEADER': 'DashToHls_osx.pch', 'CLANG_CXX_LIBRARY': 'libc++'}, 'sources': ['dash_to_hls_default_diagnostic_callback.mm']}]}
class DreamingAboutCarrots: def carrotsBetweenCarrots(self, x1, y1, x2, y2): (x1, x2), (y1, y2) = sorted([x1, x2]), sorted([y1, y2]) dx, dy = x2-x1, y2-y1 return sum( (x-x1)*dy - (y-y1)*dx == 0 for x in xrange(x1, x2+1) for y in xrange(y1, y2+1) ) - 2
class Dreamingaboutcarrots: def carrots_between_carrots(self, x1, y1, x2, y2): ((x1, x2), (y1, y2)) = (sorted([x1, x2]), sorted([y1, y2])) (dx, dy) = (x2 - x1, y2 - y1) return sum(((x - x1) * dy - (y - y1) * dx == 0 for x in xrange(x1, x2 + 1) for y in xrange(y1, y2 + 1))) - 2
class Solution: def numFriendRequests(self, ages): """ :type ages: List[int] :rtype: int """ cntr, res = collections.Counter(ages), 0 for A in cntr: for B in cntr: if B <= 0.5 * A + 7 or B > A: continue if A == B: res += cntr[A] *(cntr[A] - 1) else: res += cntr[A] * cntr[B] return res
class Solution: def num_friend_requests(self, ages): """ :type ages: List[int] :rtype: int """ (cntr, res) = (collections.Counter(ages), 0) for a in cntr: for b in cntr: if B <= 0.5 * A + 7 or B > A: continue if A == B: res += cntr[A] * (cntr[A] - 1) else: res += cntr[A] * cntr[B] return res
# TODO: Implement class StorageMan(): """ Storage Manager """ def __init__(self): pass def stroe_info(self): pass def store_result(self): pass def _get_file_path(self): pass
class Storageman: """ Storage Manager """ def __init__(self): pass def stroe_info(self): pass def store_result(self): pass def _get_file_path(self): pass
#spotify spotify_token = "" spotify_client_id = "" user_id='' #youtube #scopes = ["https://www.googleapis.com/auth/youtube.force-ssl"]
spotify_token = '' spotify_client_id = '' user_id = ''
def peak(A): start = 0 end = len(A) - 1 while(start <= end): mid = start + (end - start)//2 if(mid > 0 and mid < len(A)-1): if(A[mid] > A[mid-1] and A[mid] > A[mid+1]): return A[mid] elif(A[mid] < A[mid-1]): end = mid -1 else: start = mid + 1 elif(mid == 0): if(A[0] > A[mid]): return 0 else: return 1 elif(mid == len(A)-1): if(A[-1] > A[len(A) -2]): return len(A)-1 else: return len(A) -2 A = [5, 1, 4, 3, 6, 8, 10, 7, 9] print(peak(A))
def peak(A): start = 0 end = len(A) - 1 while start <= end: mid = start + (end - start) // 2 if mid > 0 and mid < len(A) - 1: if A[mid] > A[mid - 1] and A[mid] > A[mid + 1]: return A[mid] elif A[mid] < A[mid - 1]: end = mid - 1 else: start = mid + 1 elif mid == 0: if A[0] > A[mid]: return 0 else: return 1 elif mid == len(A) - 1: if A[-1] > A[len(A) - 2]: return len(A) - 1 else: return len(A) - 2 a = [5, 1, 4, 3, 6, 8, 10, 7, 9] print(peak(A))