content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#!/usr/bin/env python # -*- coding: utf-8 -*- def read_version(CMakeLists): version = [] with open(CMakeLists, 'r') as fp: for row in fp: if len(version) == 3: break if 'RSGD_MAJOR' in row: version.append(row.split('RSGD_MAJOR')[-1]) elif 'RSGD_MINOR' in row: version.append(row.split('RSGD_MINOR')[-1]) elif 'RSGD_REVISION' in row: version.append(row.split('RSGD_REVISION')[-1]) version = [v.strip().replace(')', '').replace('(', '') for v in version] version = map(int, version) return tuple(version) __package__ = 'version' __author__ = ['Nico Curti (nico.curit2@unibo.it)', "Daniele Dall'Olio (daniele.dallolio@studio.unibo.it)"] VERSION = read_version('./CMakeLists.txt') __version__ = '.'.join(map(str, VERSION))
def read_version(CMakeLists): version = [] with open(CMakeLists, 'r') as fp: for row in fp: if len(version) == 3: break if 'RSGD_MAJOR' in row: version.append(row.split('RSGD_MAJOR')[-1]) elif 'RSGD_MINOR' in row: version.append(row.split('RSGD_MINOR')[-1]) elif 'RSGD_REVISION' in row: version.append(row.split('RSGD_REVISION')[-1]) version = [v.strip().replace(')', '').replace('(', '') for v in version] version = map(int, version) return tuple(version) __package__ = 'version' __author__ = ['Nico Curti (nico.curit2@unibo.it)', "Daniele Dall'Olio (daniele.dallolio@studio.unibo.it)"] version = read_version('./CMakeLists.txt') __version__ = '.'.join(map(str, VERSION))
""" File: a_to_z.py Prompts the user for a file name, then outputs each of the unique words from the file in alphabetical order """ unique = [] input_filename = input('Enter the input file name: ') print() with open(input_filename, "r") as f: lines = f.readlines() for line in lines: words = line.split() for word in words: word = word.strip() if word not in unique: unique.append(word) unique = sorted(unique) for i in unique: print(i)
""" File: a_to_z.py Prompts the user for a file name, then outputs each of the unique words from the file in alphabetical order """ unique = [] input_filename = input('Enter the input file name: ') print() with open(input_filename, 'r') as f: lines = f.readlines() for line in lines: words = line.split() for word in words: word = word.strip() if word not in unique: unique.append(word) unique = sorted(unique) for i in unique: print(i)
""" opcode module - potentially shared between dis and other modules which operate on bytecodes (e.g. peephole optimizers). """ __all__ = ["cmp_op", "hasconst", "hasname", "hasjrel", "hasjabs", "haslocal", "hascompare", "hasfree", "opname", "opmap", "HAVE_ARGUMENT", "EXTENDED_ARG"] cmp_op = ('<', '<=', '==', '!=', '>', '>=', 'in', 'not in', 'is', 'is not', 'exception match', 'BAD') hasconst = [] hasname = [] hasjrel = [] hasjabs = [] haslocal = [] hascompare = [] hasfree = [] opmap = {} opname = [''] * 256 for op in range(256): opname[op] = '<%r>' % (op,) del op def def_op(name, op): opname[op] = name opmap[name] = op def name_op(name, op): def_op(name, op) hasname.append(op) def jrel_op(name, op): def_op(name, op) hasjrel.append(op) def jabs_op(name, op): def_op(name, op) hasjabs.append(op) # Instruction opcodes for compiled code # Blank lines correspond to available opcodes def_op('STOP_CODE', 0) def_op('POP_TOP', 1) def_op('ROT_TWO', 2) def_op('ROT_THREE', 3) def_op('DUP_TOP', 4) def_op('ROT_FOUR', 5) def_op('NOP', 9) def_op('UNARY_POSITIVE', 10) def_op('UNARY_NEGATIVE', 11) def_op('UNARY_NOT', 12) def_op('UNARY_CONVERT', 13) def_op('UNARY_INVERT', 15) def_op('DUP_TOP_TWO', 16) def_op('DUP_TOP_THREE', 17) def_op('LIST_APPEND', 18) def_op('BINARY_POWER', 19) def_op('BINARY_MULTIPLY', 20) def_op('BINARY_DIVIDE', 21) def_op('BINARY_MODULO', 22) def_op('BINARY_ADD', 23) def_op('BINARY_SUBTRACT', 24) def_op('BINARY_SUBSCR', 25) def_op('BINARY_FLOOR_DIVIDE', 26) def_op('BINARY_TRUE_DIVIDE', 27) def_op('INPLACE_FLOOR_DIVIDE', 28) def_op('INPLACE_TRUE_DIVIDE', 29) def_op('SLICE_NONE', 30) def_op('SLICE_LEFT', 31) def_op('SLICE_RIGHT', 32) def_op('SLICE_BOTH', 33) def_op('RAISE_VARARGS_ZERO', 34) def_op('RAISE_VARARGS_ONE', 35) def_op('RAISE_VARARGS_TWO', 36) def_op('RAISE_VARARGS_THREE', 37) def_op('BUILD_SLICE_TWO', 38) def_op('BUILD_SLICE_THREE', 39) def_op('STORE_SLICE_NONE', 40) def_op('STORE_SLICE_LEFT', 41) def_op('STORE_SLICE_RIGHT', 42) def_op('STORE_SLICE_BOTH', 43) def_op('DELETE_SLICE_NONE', 50) def_op('DELETE_SLICE_LEFT', 51) def_op('DELETE_SLICE_RIGHT', 52) def_op('DELETE_SLICE_BOTH', 53) def_op('STORE_MAP', 54) def_op('INPLACE_ADD', 55) def_op('INPLACE_SUBTRACT', 56) def_op('INPLACE_MULTIPLY', 57) def_op('INPLACE_DIVIDE', 58) def_op('INPLACE_MODULO', 59) def_op('STORE_SUBSCR', 60) def_op('DELETE_SUBSCR', 61) def_op('BINARY_LSHIFT', 62) def_op('BINARY_RSHIFT', 63) def_op('BINARY_AND', 64) def_op('BINARY_XOR', 65) def_op('BINARY_OR', 66) def_op('INPLACE_POWER', 67) def_op('GET_ITER', 68) # def_op('PRINT_EXPR', 70) Replaced with the #@displayhook function. # def_op('PRINT_ITEM', 71) Other PRINT_* opcodes replaced by #@print_stmt(). # def_op('PRINT_NEWLINE', 72) # def_op('PRINT_ITEM_TO', 73) # def_op('PRINT_NEWLINE_TO', 74) def_op('INPLACE_LSHIFT', 75) def_op('INPLACE_RSHIFT', 76) def_op('INPLACE_AND', 77) def_op('INPLACE_XOR', 78) def_op('INPLACE_OR', 79) def_op('BREAK_LOOP', 80) def_op('WITH_CLEANUP', 81) # def_op('LOAD_LOCALS', 82) Replaced with a function call to #@locals. def_op('RETURN_VALUE', 83) # def_op('IMPORT_STAR', 84) Replaced with a function call to #@import_star. # def_op('EXEC_STMT', 85) Replaced with a function call to #@exec. def_op('YIELD_VALUE', 86) def_op('POP_BLOCK', 87) def_op('END_FINALLY', 88) # def_op('BUILD_CLASS', xxx) Replaced with a function call to #@buildclass. def_op('IMPORT_NAME', 89) HAVE_ARGUMENT = 90 # Opcodes from here have an argument: name_op('STORE_NAME', 90) # Index in name list name_op('DELETE_NAME', 91) # "" def_op('UNPACK_SEQUENCE', 92) # Number of tuple items jrel_op('FOR_ITER', 93) name_op('STORE_ATTR', 95) # Index in name list name_op('DELETE_ATTR', 96) # "" name_op('STORE_GLOBAL', 97) # "" name_op('DELETE_GLOBAL', 98) # "" def_op('LOAD_CONST', 100) # Index in const list hasconst.append(100) name_op('LOAD_NAME', 101) # Index in name list def_op('BUILD_TUPLE', 102) # Number of tuple items def_op('BUILD_LIST', 103) # Number of list items def_op('BUILD_MAP', 104) # Number of dict entries (upto 255) name_op('LOAD_ATTR', 105) # Index in name list def_op('COMPARE_OP', 106) # Comparison operator hascompare.append(106) # name_op('IMPORT_FROM', 108) # Replaced by #@import_from. jrel_op('JUMP_FORWARD', 110) # Number of bytes to skip jabs_op('JUMP_IF_FALSE_OR_POP', 111) # Target byte offset from beginning of code jabs_op('JUMP_IF_TRUE_OR_POP', 112) # "" jabs_op('JUMP_ABSOLUTE', 113) # "" jabs_op('POP_JUMP_IF_FALSE', 114) # "" jabs_op('POP_JUMP_IF_TRUE', 115) # "" name_op('LOAD_GLOBAL', 116) # Index in name list jabs_op('CONTINUE_LOOP', 119) # Target address jrel_op('SETUP_LOOP', 120) # Distance to target address jrel_op('SETUP_EXCEPT', 121) # "" jrel_op('SETUP_FINALLY', 122) # "" def_op('LOAD_FAST', 124) # Local variable number haslocal.append(124) def_op('STORE_FAST', 125) # Local variable number haslocal.append(125) def_op('DELETE_FAST', 126) # Local variable number haslocal.append(126) def_op('CALL_FUNCTION', 131) # #args + (#kwargs << 8) # def_op('MAKE_FUNCTION', 132) Replaced by #@make_function calls. def_op('MAKE_CLOSURE', 134) def_op('LOAD_CLOSURE', 135) hasfree.append(135) def_op('LOAD_DEREF', 136) hasfree.append(136) def_op('STORE_DEREF', 137) hasfree.append(137) def_op('CALL_FUNCTION_VAR', 140) # #args + (#kwargs << 8) def_op('CALL_FUNCTION_KW', 141) # #args + (#kwargs << 8) def_op('CALL_FUNCTION_VAR_KW', 142) # #args + (#kwargs << 8) def_op('EXTENDED_ARG', 143) EXTENDED_ARG = 143 del def_op, name_op, jrel_op, jabs_op
""" opcode module - potentially shared between dis and other modules which operate on bytecodes (e.g. peephole optimizers). """ __all__ = ['cmp_op', 'hasconst', 'hasname', 'hasjrel', 'hasjabs', 'haslocal', 'hascompare', 'hasfree', 'opname', 'opmap', 'HAVE_ARGUMENT', 'EXTENDED_ARG'] cmp_op = ('<', '<=', '==', '!=', '>', '>=', 'in', 'not in', 'is', 'is not', 'exception match', 'BAD') hasconst = [] hasname = [] hasjrel = [] hasjabs = [] haslocal = [] hascompare = [] hasfree = [] opmap = {} opname = [''] * 256 for op in range(256): opname[op] = '<%r>' % (op,) del op def def_op(name, op): opname[op] = name opmap[name] = op def name_op(name, op): def_op(name, op) hasname.append(op) def jrel_op(name, op): def_op(name, op) hasjrel.append(op) def jabs_op(name, op): def_op(name, op) hasjabs.append(op) def_op('STOP_CODE', 0) def_op('POP_TOP', 1) def_op('ROT_TWO', 2) def_op('ROT_THREE', 3) def_op('DUP_TOP', 4) def_op('ROT_FOUR', 5) def_op('NOP', 9) def_op('UNARY_POSITIVE', 10) def_op('UNARY_NEGATIVE', 11) def_op('UNARY_NOT', 12) def_op('UNARY_CONVERT', 13) def_op('UNARY_INVERT', 15) def_op('DUP_TOP_TWO', 16) def_op('DUP_TOP_THREE', 17) def_op('LIST_APPEND', 18) def_op('BINARY_POWER', 19) def_op('BINARY_MULTIPLY', 20) def_op('BINARY_DIVIDE', 21) def_op('BINARY_MODULO', 22) def_op('BINARY_ADD', 23) def_op('BINARY_SUBTRACT', 24) def_op('BINARY_SUBSCR', 25) def_op('BINARY_FLOOR_DIVIDE', 26) def_op('BINARY_TRUE_DIVIDE', 27) def_op('INPLACE_FLOOR_DIVIDE', 28) def_op('INPLACE_TRUE_DIVIDE', 29) def_op('SLICE_NONE', 30) def_op('SLICE_LEFT', 31) def_op('SLICE_RIGHT', 32) def_op('SLICE_BOTH', 33) def_op('RAISE_VARARGS_ZERO', 34) def_op('RAISE_VARARGS_ONE', 35) def_op('RAISE_VARARGS_TWO', 36) def_op('RAISE_VARARGS_THREE', 37) def_op('BUILD_SLICE_TWO', 38) def_op('BUILD_SLICE_THREE', 39) def_op('STORE_SLICE_NONE', 40) def_op('STORE_SLICE_LEFT', 41) def_op('STORE_SLICE_RIGHT', 42) def_op('STORE_SLICE_BOTH', 43) def_op('DELETE_SLICE_NONE', 50) def_op('DELETE_SLICE_LEFT', 51) def_op('DELETE_SLICE_RIGHT', 52) def_op('DELETE_SLICE_BOTH', 53) def_op('STORE_MAP', 54) def_op('INPLACE_ADD', 55) def_op('INPLACE_SUBTRACT', 56) def_op('INPLACE_MULTIPLY', 57) def_op('INPLACE_DIVIDE', 58) def_op('INPLACE_MODULO', 59) def_op('STORE_SUBSCR', 60) def_op('DELETE_SUBSCR', 61) def_op('BINARY_LSHIFT', 62) def_op('BINARY_RSHIFT', 63) def_op('BINARY_AND', 64) def_op('BINARY_XOR', 65) def_op('BINARY_OR', 66) def_op('INPLACE_POWER', 67) def_op('GET_ITER', 68) def_op('INPLACE_LSHIFT', 75) def_op('INPLACE_RSHIFT', 76) def_op('INPLACE_AND', 77) def_op('INPLACE_XOR', 78) def_op('INPLACE_OR', 79) def_op('BREAK_LOOP', 80) def_op('WITH_CLEANUP', 81) def_op('RETURN_VALUE', 83) def_op('YIELD_VALUE', 86) def_op('POP_BLOCK', 87) def_op('END_FINALLY', 88) def_op('IMPORT_NAME', 89) have_argument = 90 name_op('STORE_NAME', 90) name_op('DELETE_NAME', 91) def_op('UNPACK_SEQUENCE', 92) jrel_op('FOR_ITER', 93) name_op('STORE_ATTR', 95) name_op('DELETE_ATTR', 96) name_op('STORE_GLOBAL', 97) name_op('DELETE_GLOBAL', 98) def_op('LOAD_CONST', 100) hasconst.append(100) name_op('LOAD_NAME', 101) def_op('BUILD_TUPLE', 102) def_op('BUILD_LIST', 103) def_op('BUILD_MAP', 104) name_op('LOAD_ATTR', 105) def_op('COMPARE_OP', 106) hascompare.append(106) jrel_op('JUMP_FORWARD', 110) jabs_op('JUMP_IF_FALSE_OR_POP', 111) jabs_op('JUMP_IF_TRUE_OR_POP', 112) jabs_op('JUMP_ABSOLUTE', 113) jabs_op('POP_JUMP_IF_FALSE', 114) jabs_op('POP_JUMP_IF_TRUE', 115) name_op('LOAD_GLOBAL', 116) jabs_op('CONTINUE_LOOP', 119) jrel_op('SETUP_LOOP', 120) jrel_op('SETUP_EXCEPT', 121) jrel_op('SETUP_FINALLY', 122) def_op('LOAD_FAST', 124) haslocal.append(124) def_op('STORE_FAST', 125) haslocal.append(125) def_op('DELETE_FAST', 126) haslocal.append(126) def_op('CALL_FUNCTION', 131) def_op('MAKE_CLOSURE', 134) def_op('LOAD_CLOSURE', 135) hasfree.append(135) def_op('LOAD_DEREF', 136) hasfree.append(136) def_op('STORE_DEREF', 137) hasfree.append(137) def_op('CALL_FUNCTION_VAR', 140) def_op('CALL_FUNCTION_KW', 141) def_op('CALL_FUNCTION_VAR_KW', 142) def_op('EXTENDED_ARG', 143) extended_arg = 143 del def_op, name_op, jrel_op, jabs_op
Experiment(description='Testing the pure linear kernel', data_dir='../data/tsdlr/', max_depth=10, random_order=False, k=1, debug=False, local_computation=False, n_rand=9, sd=2, jitter_sd=0.1, max_jobs=500, verbose=False, make_predictions=False, skip_complete=True, results_dir='../results/2013-10-01-pure-lin/', iters=250, base_kernels='SE,PureLin,Const,Exp,Fourier,Noise', zero_mean=True, random_seed=1, period_heuristic=5, subset=True, subset_size=250, full_iters=10, bundle_size=5, additive_form=True, model_noise=True, no_noise=True)
experiment(description='Testing the pure linear kernel', data_dir='../data/tsdlr/', max_depth=10, random_order=False, k=1, debug=False, local_computation=False, n_rand=9, sd=2, jitter_sd=0.1, max_jobs=500, verbose=False, make_predictions=False, skip_complete=True, results_dir='../results/2013-10-01-pure-lin/', iters=250, base_kernels='SE,PureLin,Const,Exp,Fourier,Noise', zero_mean=True, random_seed=1, period_heuristic=5, subset=True, subset_size=250, full_iters=10, bundle_size=5, additive_form=True, model_noise=True, no_noise=True)
class FuzzyPaletteInvalidRepresentation(Exception): """ An Exception indicating that not enough classes have been provided to represent the fuzzy sets. """ def __init__(self, provided_labels: int, needed_labels: int): super().__init__(f"{needed_labels} labels are needed to represent the selected method. " f"Only {provided_labels} are provided.")
class Fuzzypaletteinvalidrepresentation(Exception): """ An Exception indicating that not enough classes have been provided to represent the fuzzy sets. """ def __init__(self, provided_labels: int, needed_labels: int): super().__init__(f'{needed_labels} labels are needed to represent the selected method. Only {provided_labels} are provided.')
class Observer: def update(self, obj, *args, **kwargs): raise NotImplemented class Observable: def __init__(self): self._observers = [] def add_observer(self, observer): self._observers.append(observer) def remove_observer(self, observer): self._observers.remove(observer) def notify_observer(self, *args, **kwargs): for observer in self._observers: observer.update(self, *args, **kwargs) class Task1: def __init__(self): self.name = self.__class__.__name__ self.state = "Running" def mark_complete(self): print(f"Marking {self.name} complete.") self.state = "Complete" class Task2: def __init__(self): self.name = self.__class__.__name__ self.state = "Running" def mark_complete(self): print(f"Marking {self.name} complete.") self.state = "Complete" class Task3: def __init__(self): self.name = self.__class__.__name__ self.state = "Running" def mark_complete(self): print(f"Marking {self.name} complete.") self.state = "Complete" class TaskAdapter(Observable): _initialized = False def __init__(self, task, **kwargs): super().__init__() self.task = task for key, val in kwargs.items(): func = getattr(self.task, val) self.__setattr__(key, func) self._initialized = True def __getattr__(self, item): return getattr(self.task, item) def __setattr__(self, key, value): if not self._initialized: super().__setattr__(key, value) else: setattr(self.task, key, value) self.notify_observer(key=key, value=value, msg="Attribute Change") # notifying observer class Developer(Observer): def update(self, obj, *args, **kwargs): print("\nUpdate Received...") print(f'You received an update from {obj} with info: {args}, {kwargs}') class TaskFacade: task_adapters = None @classmethod def create_tasks(cls): print("Initializing tasks...") cls.task_adapters = [ TaskAdapter(Task1(), complete='mark_complete'), TaskAdapter(Task2(), complete='mark_complete'), TaskAdapter(Task3(), complete='mark_complete') ] @classmethod def mark_all_complete(cls): print("Marking all tasks as complete.") for adapter in cls.task_adapters: adapter.mark_complete() adapter.notify_observer(name=adapter.name, state=adapter.state, msg="Task complete") @classmethod def monitor_task(cls, observer): print('Adding observers...') for eachAdapter in cls.task_adapters: eachAdapter.add_observer(observer) if __name__ == '__main__': dev = Developer() TaskFacade.create_tasks() TaskFacade.monitor_task(dev) TaskFacade.mark_all_complete()
class Observer: def update(self, obj, *args, **kwargs): raise NotImplemented class Observable: def __init__(self): self._observers = [] def add_observer(self, observer): self._observers.append(observer) def remove_observer(self, observer): self._observers.remove(observer) def notify_observer(self, *args, **kwargs): for observer in self._observers: observer.update(self, *args, **kwargs) class Task1: def __init__(self): self.name = self.__class__.__name__ self.state = 'Running' def mark_complete(self): print(f'Marking {self.name} complete.') self.state = 'Complete' class Task2: def __init__(self): self.name = self.__class__.__name__ self.state = 'Running' def mark_complete(self): print(f'Marking {self.name} complete.') self.state = 'Complete' class Task3: def __init__(self): self.name = self.__class__.__name__ self.state = 'Running' def mark_complete(self): print(f'Marking {self.name} complete.') self.state = 'Complete' class Taskadapter(Observable): _initialized = False def __init__(self, task, **kwargs): super().__init__() self.task = task for (key, val) in kwargs.items(): func = getattr(self.task, val) self.__setattr__(key, func) self._initialized = True def __getattr__(self, item): return getattr(self.task, item) def __setattr__(self, key, value): if not self._initialized: super().__setattr__(key, value) else: setattr(self.task, key, value) self.notify_observer(key=key, value=value, msg='Attribute Change') class Developer(Observer): def update(self, obj, *args, **kwargs): print('\nUpdate Received...') print(f'You received an update from {obj} with info: {args}, {kwargs}') class Taskfacade: task_adapters = None @classmethod def create_tasks(cls): print('Initializing tasks...') cls.task_adapters = [task_adapter(task1(), complete='mark_complete'), task_adapter(task2(), complete='mark_complete'), task_adapter(task3(), complete='mark_complete')] @classmethod def mark_all_complete(cls): print('Marking all tasks as complete.') for adapter in cls.task_adapters: adapter.mark_complete() adapter.notify_observer(name=adapter.name, state=adapter.state, msg='Task complete') @classmethod def monitor_task(cls, observer): print('Adding observers...') for each_adapter in cls.task_adapters: eachAdapter.add_observer(observer) if __name__ == '__main__': dev = developer() TaskFacade.create_tasks() TaskFacade.monitor_task(dev) TaskFacade.mark_all_complete()
def my_func(): result = 3 * 2 return result print(my_func()) def format_name(f_name, l_name): """Take first and last name and format it and returns title version""" name = '' name += f_name.title() name += ' ' name += l_name.title() return name print(format_name('eddie', 'wang'))
def my_func(): result = 3 * 2 return result print(my_func()) def format_name(f_name, l_name): """Take first and last name and format it and returns title version""" name = '' name += f_name.title() name += ' ' name += l_name.title() return name print(format_name('eddie', 'wang'))
class ConstraintDeduplicatorMixin(object): def __init__(self, *args, **kwargs): super(ConstraintDeduplicatorMixin, self).__init__(*args, **kwargs) self._constraint_hashes = set() def _blank_copy(self, c): super(ConstraintDeduplicatorMixin, self)._blank_copy(c) c._constraint_hashes = set() def _copy(self, c): super(ConstraintDeduplicatorMixin, self)._copy(c) c._constraint_hashes = set(self._constraint_hashes) # # Serialization # def _ana_getstate(self): return self._constraint_hashes, super(ConstraintDeduplicatorMixin, self)._ana_getstate() def _ana_setstate(self, s): self._constraint_hashes, base_state = s super(ConstraintDeduplicatorMixin, self)._ana_setstate(base_state) def simplify(self, **kwargs): added = super(ConstraintDeduplicatorMixin, self).simplify(**kwargs) # we only add to the constraint hashes because we want to # prevent previous (now simplified) constraints from # being re-added self._constraint_hashes.update(map(hash, added)) return added def add(self, constraints, **kwargs): filtered = tuple(c for c in constraints if hash(c) not in self._constraint_hashes) if len(filtered) == 0: return filtered added = super(ConstraintDeduplicatorMixin, self).add(filtered, **kwargs) self._constraint_hashes.update(map(hash, added)) return added
class Constraintdeduplicatormixin(object): def __init__(self, *args, **kwargs): super(ConstraintDeduplicatorMixin, self).__init__(*args, **kwargs) self._constraint_hashes = set() def _blank_copy(self, c): super(ConstraintDeduplicatorMixin, self)._blank_copy(c) c._constraint_hashes = set() def _copy(self, c): super(ConstraintDeduplicatorMixin, self)._copy(c) c._constraint_hashes = set(self._constraint_hashes) def _ana_getstate(self): return (self._constraint_hashes, super(ConstraintDeduplicatorMixin, self)._ana_getstate()) def _ana_setstate(self, s): (self._constraint_hashes, base_state) = s super(ConstraintDeduplicatorMixin, self)._ana_setstate(base_state) def simplify(self, **kwargs): added = super(ConstraintDeduplicatorMixin, self).simplify(**kwargs) self._constraint_hashes.update(map(hash, added)) return added def add(self, constraints, **kwargs): filtered = tuple((c for c in constraints if hash(c) not in self._constraint_hashes)) if len(filtered) == 0: return filtered added = super(ConstraintDeduplicatorMixin, self).add(filtered, **kwargs) self._constraint_hashes.update(map(hash, added)) return added
def chainResult(num): while num != 1 and num != 89: s = str(num) num = 0 for c in s: num += int(c) * int(c) return num count = 0 for num in range(1,10000000): if chainResult(num) == 89: count += 1 print(count)
def chain_result(num): while num != 1 and num != 89: s = str(num) num = 0 for c in s: num += int(c) * int(c) return num count = 0 for num in range(1, 10000000): if chain_result(num) == 89: count += 1 print(count)
""" Time: O(N) Space: O(1) Keep updating the minimum element (`min1`) and the second minimum element (`min2`). When a new element comes up there are 3 possibilities. 0. Equals to min1 or min2 => do nothing. 1. Smaller than min1 => update min1. 2. Larger than min1 and smaller than min2 => update min2. 3. Larger than min2 => return True. """ class Solution(object): def increasingTriplet(self, nums): min1 = min2 = float('inf') for n in nums: if n<min1: min1 = n elif min1<n and n<min2: min2 = n elif min2<n: return True return False
""" Time: O(N) Space: O(1) Keep updating the minimum element (`min1`) and the second minimum element (`min2`). When a new element comes up there are 3 possibilities. 0. Equals to min1 or min2 => do nothing. 1. Smaller than min1 => update min1. 2. Larger than min1 and smaller than min2 => update min2. 3. Larger than min2 => return True. """ class Solution(object): def increasing_triplet(self, nums): min1 = min2 = float('inf') for n in nums: if n < min1: min1 = n elif min1 < n and n < min2: min2 = n elif min2 < n: return True return False
""" Created on 12.02.2010 @author: jupp """ def compute_similarity(lattice): similarity_index = {} for c1 in lattice: for c2 in lattice: if not (c1.concept_id in similarity_index and c2.concept_id in similarity_index[c1.concept_id]): if c1.concept_id not in similarity_index: similarity_index[c1.concept_id] = {} if c2.concept_id not in similarity_index: similarity_index[c2.concept_id] = {} if c1 == c2: similarity_index[c1.concept_id][c2.concept_id] = similarity_index[c2.concept_id][c1.concept_id] = .0 continue n1 = float(len(set(c1.extent).intersection(set(c2.extent)))) d1 = float(len(set(c1.extent))+len(set(c2.extent))) n2 = float(len(set(c1.intent).intersection(set(c2.intent)))) d2 = float(len(set(c1.intent))+len(set(c2.intent))) p1 = 0 p2 = 0 if d1 != 0: p1 = n1 / d1 if d2 != 0: p2 = n2 / d2 sim = p1 + p2 similarity_index[c1.concept_id][c2.concept_id] = similarity_index[c2.concept_id][c1.concept_id] = sim return similarity_index
""" Created on 12.02.2010 @author: jupp """ def compute_similarity(lattice): similarity_index = {} for c1 in lattice: for c2 in lattice: if not (c1.concept_id in similarity_index and c2.concept_id in similarity_index[c1.concept_id]): if c1.concept_id not in similarity_index: similarity_index[c1.concept_id] = {} if c2.concept_id not in similarity_index: similarity_index[c2.concept_id] = {} if c1 == c2: similarity_index[c1.concept_id][c2.concept_id] = similarity_index[c2.concept_id][c1.concept_id] = 0.0 continue n1 = float(len(set(c1.extent).intersection(set(c2.extent)))) d1 = float(len(set(c1.extent)) + len(set(c2.extent))) n2 = float(len(set(c1.intent).intersection(set(c2.intent)))) d2 = float(len(set(c1.intent)) + len(set(c2.intent))) p1 = 0 p2 = 0 if d1 != 0: p1 = n1 / d1 if d2 != 0: p2 = n2 / d2 sim = p1 + p2 similarity_index[c1.concept_id][c2.concept_id] = similarity_index[c2.concept_id][c1.concept_id] = sim return similarity_index
""" ccextractor-web | forms.py Author : Saurabh Shrivastava Email : saurabh.shrivastava54+ccextractorweb[at]gmail.com Link : https://github.com/saurabhshri """
""" ccextractor-web | forms.py Author : Saurabh Shrivastava Email : saurabh.shrivastava54+ccextractorweb[at]gmail.com Link : https://github.com/saurabhshri """
def solution(board, moves): basket = [] answer = 0 for move in moves: for row in board: if row[move - 1] != 0: basket.append(row[move - 1]) row[move - 1] = 0 if len(basket) >= 2 and basket[-1] == basket[-2]: basket.pop() basket.pop() answer += 1 break return answer * 2
def solution(board, moves): basket = [] answer = 0 for move in moves: for row in board: if row[move - 1] != 0: basket.append(row[move - 1]) row[move - 1] = 0 if len(basket) >= 2 and basket[-1] == basket[-2]: basket.pop() basket.pop() answer += 1 break return answer * 2
class Const: board_width = 19 board_height = 19 n_in_row = 5 # n to win! train_core = "keras" check_freq = 10 # auto save current model check_freq_best = 500 # auto save best model
class Const: board_width = 19 board_height = 19 n_in_row = 5 train_core = 'keras' check_freq = 10 check_freq_best = 500
# -*- coding: utf-8 -*- # Copyright 2019 Julian Betz # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. class Language: """Resources of a specific language. Stores information about the language and provides methods for text analysis that are tailored to that language. """ _LANGUAGES = dict() def __init__(self, code, name, *, loader, tokenizer, extractor, parallel_extractor): if code in Language._LANGUAGES: raise ValueError('Language code has to be unique') self._CODE = code self._NAME = name self._LOADER = loader self._TOKENIZER = tokenizer self._EXTRACTOR = extractor self._PARALLEL_EXTRACTOR = parallel_extractor Language._LANGUAGES[code] = self @staticmethod def by_code(code): """Look up a language by its unique identifier.""" return Language._LANGUAGES[code] @property def code(self): """The unique identifier of this language. This is usually the ISO 639-3 language code of this language. """ return self._CODE @property def load(self): """Function to load corpus sentences in this language. The order of sentences is randomized (independently of the number of samples requested and consistently in between calls requesting the same number of samples). Does not necessarily load the sentences themselves, but may provide IDs if :py:meth:`tokenize`, :py:meth:`extract` and :py:meth:`extract_parallel` can handle this format. :param int n_samples: The number of sample sentences to load. If ``None``, load all samples. :return: A tuple of sentences or sentence IDs. """ return self._LOADER @property def tokenize(self): """Function to tokenize a sentence in this language. :param sentence: A sentence or sentence ID. :return: A tuple of tuples of tokens. A token is represented as a dictionary of the following form: .. code-block:: python { 'surface_form': {'graphic': ..., 'phonetic': ...}, 'base_form': {'graphic': ..., 'phonetic': ...}, 'lemma': {'graphic': ..., 'phonetic': ...}, 'pos': <list of POS tags as strings>, 'inflection': <list of POS/inflection tags> } "Surface form" refers to the graphic variant used in an original document and its pronunciation. "Base form" refers to a lemmatized version of the surface form. "Lemma" a normalized version of the base form. (In Japanese, for example, there is a single lemma for multiple graphical variants of the base form which mean the same thing.) The POS and inflection lists are meant to be read by a :class:`..features.tree.TemplateTree`. """ return self._TOKENIZER @property def extract(self): """Function to turn an iterable of tokens into language model input. Differs from :meth:`extract_parallel` only for character-level extracts. :param tokens: An iterable of tokens (see :meth:`tokenize` for the token representation). :return: An iterable of token identifiers that is understood by the language model. """ return self._EXTRACTOR @property def extract_parallel(self): """Function to turn an iterable of tokens into language model input. Differs from :meth:`extract` only for character-level extracts. :param tokens: An iterable of tokens (see :meth:`tokenize` for the token representation). :return: An iterable of token identifiers that are understood by the language model. """ return self._PARALLEL_EXTRACTOR def __repr__(self): return '<%s %s>' % (type(self).__name__, self._CODE) def __str__(self): return self._NAME
class Language: """Resources of a specific language. Stores information about the language and provides methods for text analysis that are tailored to that language. """ _languages = dict() def __init__(self, code, name, *, loader, tokenizer, extractor, parallel_extractor): if code in Language._LANGUAGES: raise value_error('Language code has to be unique') self._CODE = code self._NAME = name self._LOADER = loader self._TOKENIZER = tokenizer self._EXTRACTOR = extractor self._PARALLEL_EXTRACTOR = parallel_extractor Language._LANGUAGES[code] = self @staticmethod def by_code(code): """Look up a language by its unique identifier.""" return Language._LANGUAGES[code] @property def code(self): """The unique identifier of this language. This is usually the ISO 639-3 language code of this language. """ return self._CODE @property def load(self): """Function to load corpus sentences in this language. The order of sentences is randomized (independently of the number of samples requested and consistently in between calls requesting the same number of samples). Does not necessarily load the sentences themselves, but may provide IDs if :py:meth:`tokenize`, :py:meth:`extract` and :py:meth:`extract_parallel` can handle this format. :param int n_samples: The number of sample sentences to load. If ``None``, load all samples. :return: A tuple of sentences or sentence IDs. """ return self._LOADER @property def tokenize(self): """Function to tokenize a sentence in this language. :param sentence: A sentence or sentence ID. :return: A tuple of tuples of tokens. A token is represented as a dictionary of the following form: .. code-block:: python { 'surface_form': {'graphic': ..., 'phonetic': ...}, 'base_form': {'graphic': ..., 'phonetic': ...}, 'lemma': {'graphic': ..., 'phonetic': ...}, 'pos': <list of POS tags as strings>, 'inflection': <list of POS/inflection tags> } "Surface form" refers to the graphic variant used in an original document and its pronunciation. "Base form" refers to a lemmatized version of the surface form. "Lemma" a normalized version of the base form. (In Japanese, for example, there is a single lemma for multiple graphical variants of the base form which mean the same thing.) The POS and inflection lists are meant to be read by a :class:`..features.tree.TemplateTree`. """ return self._TOKENIZER @property def extract(self): """Function to turn an iterable of tokens into language model input. Differs from :meth:`extract_parallel` only for character-level extracts. :param tokens: An iterable of tokens (see :meth:`tokenize` for the token representation). :return: An iterable of token identifiers that is understood by the language model. """ return self._EXTRACTOR @property def extract_parallel(self): """Function to turn an iterable of tokens into language model input. Differs from :meth:`extract` only for character-level extracts. :param tokens: An iterable of tokens (see :meth:`tokenize` for the token representation). :return: An iterable of token identifiers that are understood by the language model. """ return self._PARALLEL_EXTRACTOR def __repr__(self): return '<%s %s>' % (type(self).__name__, self._CODE) def __str__(self): return self._NAME
def insertion_sort(lst): """ Sorts list using insertion sort :param lst: list of unsorted elements :return comp: number of comparisons """ comp = 0 for i in range(1, len(lst)): key = lst[i] j = i - 1 cur_comp = 0 while j >= 0 and key < lst[j]: lst[j + 1] = lst[j] j -= 1 cur_comp += 1 comp += cur_comp if cur_comp == 0: comp += 1 lst[j + 1] = key return comp
def insertion_sort(lst): """ Sorts list using insertion sort :param lst: list of unsorted elements :return comp: number of comparisons """ comp = 0 for i in range(1, len(lst)): key = lst[i] j = i - 1 cur_comp = 0 while j >= 0 and key < lst[j]: lst[j + 1] = lst[j] j -= 1 cur_comp += 1 comp += cur_comp if cur_comp == 0: comp += 1 lst[j + 1] = key return comp
# Financial events the contract logs Transfer: __log__({_from: indexed(address), _to: indexed(address), _value: currency_value}) Buy: __log__({_buyer: indexed(address), _buy_order: currency_value}) Sell: __log__({_seller: indexed(address), _sell_order: currency_value}) Pay: __log__({_vendor: indexed(address), _amount: wei_value}) # Own shares of a company! company: public(address) total_shares: public(currency_value) price: public(int128 (wei / currency)) # Store ledger of stockholder holdings holdings: currency_value[address] # Setup company @public def __init__(_company: address, _total_shares: currency_value, initial_price: int128(wei / currency) ): assert _total_shares > 0 assert initial_price > 0 self.company = _company self.total_shares = _total_shares self.price = initial_price # Company holds all the shares at first, but can sell them all self.holdings[self.company] = _total_shares @public @constant def stock_available() -> currency_value: return self.holdings[self.company] # Give value to company and get stock in return @public @payable def buy_stock(): # Note: full amount is given to company (no fractional shares), # so be sure to send exact amount to buy shares buy_order: currency_value = floor(msg.value / self.price) # rounds down # There are enough shares to buy assert self.stock_available() >= buy_order # Take the shares off the market and give to stockholder self.holdings[self.company] -= buy_order self.holdings[msg.sender] += buy_order # Log the buy event log.Buy(msg.sender, buy_order) # So someone can find out how much they have @public @constant def get_holding(_stockholder: address) -> currency_value: return self.holdings[_stockholder] # The amount the company has on hand in cash @public @constant def cash() -> wei_value: return self.balance # Give stock back to company and get my money back! @public def sell_stock(sell_order: currency_value): assert sell_order > 0 # Otherwise, will fail at send() below # Can only sell as much stock as you own assert self.get_holding(msg.sender) >= sell_order # Company can pay you assert self.cash() >= (sell_order * self.price) # Sell the stock, send the proceeds to the user # and put the stock back on the market self.holdings[msg.sender] -= sell_order self.holdings[self.company] += sell_order send(msg.sender, sell_order * self.price) # Log sell event log.Sell(msg.sender, sell_order) # Transfer stock from one stockholder to another # (Assumes the receiver is given some compensation, but not enforced) @public def transfer_stock(receiver: address, transfer_order: currency_value): assert transfer_order > 0 # AUDIT revealed this! # Can only trade as much stock as you own assert self.get_holding(msg.sender) >= transfer_order # Debit sender's stock and add to receiver's address self.holdings[msg.sender] -= transfer_order self.holdings[receiver] += transfer_order # Log the transfer event log.Transfer(msg.sender, receiver, transfer_order) # Allows the company to pay someone for services rendered @public def pay_bill(vendor: address, amount: wei_value): # Only the company can pay people assert msg.sender == self.company # And only if there's enough to pay them with assert self.cash() >= amount # Pay the bill! send(vendor, amount) # Log payment event log.Pay(vendor, amount) # The amount a company has raised in the stock offering @public @constant def debt() -> wei_value: return (self.total_shares - self.holdings[self.company]) * self.price # The balance sheet of the company @public @constant def worth() -> wei_value: return self.cash() - self.debt()
transfer: __log__({_from: indexed(address), _to: indexed(address), _value: currency_value}) buy: __log__({_buyer: indexed(address), _buy_order: currency_value}) sell: __log__({_seller: indexed(address), _sell_order: currency_value}) pay: __log__({_vendor: indexed(address), _amount: wei_value}) company: public(address) total_shares: public(currency_value) price: public(int128(wei / currency)) holdings: currency_value[address] @public def __init__(_company: address, _total_shares: currency_value, initial_price: int128(wei / currency)): assert _total_shares > 0 assert initial_price > 0 self.company = _company self.total_shares = _total_shares self.price = initial_price self.holdings[self.company] = _total_shares @public @constant def stock_available() -> currency_value: return self.holdings[self.company] @public @payable def buy_stock(): buy_order: currency_value = floor(msg.value / self.price) assert self.stock_available() >= buy_order self.holdings[self.company] -= buy_order self.holdings[msg.sender] += buy_order log.Buy(msg.sender, buy_order) @public @constant def get_holding(_stockholder: address) -> currency_value: return self.holdings[_stockholder] @public @constant def cash() -> wei_value: return self.balance @public def sell_stock(sell_order: currency_value): assert sell_order > 0 assert self.get_holding(msg.sender) >= sell_order assert self.cash() >= sell_order * self.price self.holdings[msg.sender] -= sell_order self.holdings[self.company] += sell_order send(msg.sender, sell_order * self.price) log.Sell(msg.sender, sell_order) @public def transfer_stock(receiver: address, transfer_order: currency_value): assert transfer_order > 0 assert self.get_holding(msg.sender) >= transfer_order self.holdings[msg.sender] -= transfer_order self.holdings[receiver] += transfer_order log.Transfer(msg.sender, receiver, transfer_order) @public def pay_bill(vendor: address, amount: wei_value): assert msg.sender == self.company assert self.cash() >= amount send(vendor, amount) log.Pay(vendor, amount) @public @constant def debt() -> wei_value: return (self.total_shares - self.holdings[self.company]) * self.price @public @constant def worth() -> wei_value: return self.cash() - self.debt()
n = int(input("Enter the number of of rows: ")) for i in range(1,n+1): for j in range(1,i+1): print(j,end="") print()
n = int(input('Enter the number of of rows: ')) for i in range(1, n + 1): for j in range(1, i + 1): print(j, end='') print()
def verify_format(_, res): return res def format_index(body): # pragma: no cover """Format index data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = { 'id': body['id'].split('/', 1)[-1], 'fields': body['fields'] } if 'type' in body: result['type'] = body['type'] if 'name' in body: result['name'] = body['name'] if 'deduplicate' in body: result['deduplicate'] = body['deduplicate'] if 'sparse' in body: result['sparse'] = body['sparse'] if 'unique' in body: result['unique'] = body['unique'] if 'minLength' in body: result['min_length'] = body['minLength'] if 'geoJson' in body: result['geo_json'] = body['geoJson'] if 'ignoreNull' in body: result['ignore_none'] = body['ignoreNull'] if 'selectivityEstimate' in body: result['selectivity'] = body['selectivityEstimate'] if 'isNewlyCreated' in body: result['new'] = body['isNewlyCreated'] if 'expireAfter' in body: result['expiry_time'] = body['expireAfter'] if 'inBackground' in body: result['in_background'] = body['inBackground'] if 'bestIndexedLevel' in body: result['best_indexed_level'] = body['bestIndexedLevel'] if 'worstIndexedLevel' in body: result['worst_indexed_level'] = body['worstIndexedLevel'] if 'maxNumCoverCells' in body: result['max_num_cover_cells'] = body['maxNumCoverCells'] return verify_format(body, result) def format_key_options(body): # pragma: no cover """Format collection key options data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'type' in body: result['key_generator'] = body['type'] if 'increment' in body: result['key_increment'] = body['increment'] if 'offset' in body: result['key_offset'] = body['offset'] if 'allowUserKeys' in body: result['user_keys'] = body['allowUserKeys'] if 'lastValue' in body: result['key_last_value'] = body['lastValue'] return verify_format(body, result) def format_database(body): # pragma: no cover """Format databases info. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'id' in body: result['id'] = body['id'] if 'name' in body: result['name'] = body['name'] if 'path' in body: result['path'] = body['path'] if 'system' in body: result['system'] = body['system'] if 'isSystem' in body: result['system'] = body['isSystem'] # Cluster only if 'sharding' in body: result['sharding'] = body['sharding'] if 'replicationFactor' in body: result['replication_factor'] = body['replicationFactor'] if 'writeConcern' in body: result['write_concern'] = body['writeConcern'] return verify_format(body, result) def format_collection(body): # pragma: no cover """Format collection data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'id' in body: result['id'] = body['id'] if 'objectId' in body: result['object_id'] = body['objectId'] if 'name' in body: result['name'] = body['name'] if 'isSystem' in body: result['system'] = body['isSystem'] if 'isSmart' in body: result['smart'] = body['isSmart'] if 'type' in body: result['type'] = body['type'] result['edge'] = body['type'] == 3 if 'waitForSync' in body: result['sync'] = body['waitForSync'] if 'status' in body: result['status'] = body['status'] if 'statusString' in body: result['status_string'] = body['statusString'] if 'globallyUniqueId' in body: result['global_id'] = body['globallyUniqueId'] if 'cacheEnabled' in body: result['cache'] = body['cacheEnabled'] if 'replicationFactor' in body: result['replication_factor'] = body['replicationFactor'] if 'minReplicationFactor' in body: result['min_replication_factor'] = body['minReplicationFactor'] if 'writeConcern' in body: result['write_concern'] = body['writeConcern'] # MMFiles only if 'doCompact' in body: result['compact'] = body['doCompact'] if 'journalSize' in body: result['journal_size'] = body['journalSize'] if 'isVolatile' in body: result['volatile'] = body['isVolatile'] if 'indexBuckets' in body: result['index_bucket_count'] = body['indexBuckets'] # Cluster only if 'shards' in body: result['shards'] = body['shards'] if 'replicationFactor' in body: result['replication_factor'] = body['replicationFactor'] if 'numberOfShards' in body: result['shard_count'] = body['numberOfShards'] if 'shardKeys' in body: result['shard_fields'] = body['shardKeys'] if 'distributeShardsLike' in body: result['shard_like'] = body['distributeShardsLike'] if 'shardingStrategy' in body: result['sharding_strategy'] = body['shardingStrategy'] if 'smartJoinAttribute' in body: result['smart_join_attribute'] = body['smartJoinAttribute'] # Key Generator if 'keyOptions' in body: result['key_options'] = format_key_options(body['keyOptions']) # Replication only if 'cid' in body: result['cid'] = body['cid'] if 'version' in body: result['version'] = body['version'] if 'allowUserKeys' in body: result['user_keys'] = body['allowUserKeys'] if 'planId' in body: result['plan_id'] = body['planId'] if 'deleted' in body: result['deleted'] = body['deleted'] # New in 3.7 if 'syncByRevision' in body: result['sync_by_revision'] = body['syncByRevision'] if 'tempObjectId' in body: result['temp_object_id'] = body['tempObjectId'] if 'usesRevisionsAsDocumentIds' in body: result['rev_as_id'] = body['usesRevisionsAsDocumentIds'] if 'isDisjoint' in body: result['disjoint'] = body['isDisjoint'] if 'isSmartChild' in body: result['smart_child'] = body['isSmartChild'] if 'minRevision' in body: result['min_revision'] = body['minRevision'] if 'schema' in body: result['schema'] = body['schema'] return verify_format(body, result) def format_aql_cache(body): """Format AQL cache data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = { 'mode': body['mode'], 'max_results': body['maxResults'], 'max_results_size': body['maxResultsSize'], 'max_entry_size': body['maxEntrySize'], 'include_system': body['includeSystem'] } return verify_format(body, result) def format_wal_properties(body): # pragma: no cover """Format WAL properties. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'allowOversizeEntries' in body: result['oversized_ops'] = body['allowOversizeEntries'] if 'logfileSize' in body: result['log_size'] = body['logfileSize'] if 'historicLogfiles' in body: result['historic_logs'] = body['historicLogfiles'] if 'reserveLogfiles' in body: result['reserve_logs'] = body['reserveLogfiles'] if 'syncInterval' in body: result['sync_interval'] = body['syncInterval'] if 'throttleWait' in body: result['throttle_wait'] = body['throttleWait'] if 'throttleWhenPending' in body: result['throttle_limit'] = body['throttleWhenPending'] return verify_format(body, result) def format_wal_transactions(body): # pragma: no cover """Format WAL transactions. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'minLastCollected' in body: result['last_collected'] = body['minLastCollected'] if 'minLastSealed' in body: result['last_sealed'] = body['minLastSealed'] if 'runningTransactions' in body: result['count'] = body['runningTransactions'] return verify_format(body, result) def format_aql_query(body): # pragma: no cover """Format AQL query data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {'id': body['id'], 'query': body['query']} if 'started' in body: result['started'] = body['started'] if 'state' in body: result['state'] = body['state'] if 'stream' in body: result['stream'] = body['stream'] if 'bindVars' in body: result['bind_vars'] = body['bindVars'] if 'runTime' in body: result['runtime'] = body['runTime'] return verify_format(body, result) def format_aql_tracking(body): # pragma: no cover """Format AQL tracking data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'enabled' in body: result['enabled'] = body['enabled'] if 'maxQueryStringLength' in body: result['max_query_string_length'] = body['maxQueryStringLength'] if 'maxSlowQueries' in body: result['max_slow_queries'] = body['maxSlowQueries'] if 'slowQueryThreshold' in body: result['slow_query_threshold'] = body['slowQueryThreshold'] if 'slowStreamingQueryThreshold' in body: result['slow_streaming_query_threshold'] = \ body['slowStreamingQueryThreshold'] if 'trackBindVars' in body: result['track_bind_vars'] = body['trackBindVars'] if 'trackSlowQueries' in body: result['track_slow_queries'] = body['trackSlowQueries'] return verify_format(body, result) def format_tick_values(body): # pragma: no cover """Format tick data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'tickMin' in body: result['tick_min'] = body['tickMin'] if 'tickMax' in body: result['tick_max'] = body['tickMax'] if 'tick' in body: result['tick'] = body['tick'] if 'time' in body: result['time'] = body['time'] if 'server' in body: result['server'] = format_server_info(body['server']) return verify_format(body, result) def format_server_info(body): # pragma: no cover """Format server data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ return {'version': body['version'], 'server_id': body['serverId']} def format_replication_applier_config(body): # pragma: no cover """Format replication applier configuration data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'endpoint' in body: result['endpoint'] = body['endpoint'] if 'database' in body: result['database'] = body['database'] if 'username' in body: result['username'] = body['username'] if 'verbose' in body: result['verbose'] = body['verbose'] if 'incremental' in body: result['incremental'] = body['incremental'] if 'requestTimeout' in body: result['request_timeout'] = body['requestTimeout'] if 'connectTimeout' in body: result['connect_timeout'] = body['connectTimeout'] if 'ignoreErrors' in body: result['ignore_errors'] = body['ignoreErrors'] if 'maxConnectRetries' in body: result['max_connect_retries'] = body['maxConnectRetries'] if 'lockTimeoutRetries' in body: result['lock_timeout_retries'] = body['lockTimeoutRetries'] if 'sslProtocol' in body: result['ssl_protocol'] = body['sslProtocol'] if 'chunkSize' in body: result['chunk_size'] = body['chunkSize'] if 'skipCreateDrop' in body: result['skip_create_drop'] = body['skipCreateDrop'] if 'autoStart' in body: result['auto_start'] = body['autoStart'] if 'adaptivePolling' in body: result['adaptive_polling'] = body['adaptivePolling'] if 'autoResync' in body: result['auto_resync'] = body['autoResync'] if 'autoResyncRetries' in body: result['auto_resync_retries'] = body['autoResyncRetries'] if 'maxPacketSize' in body: result['max_packet_size'] = body['maxPacketSize'] if 'includeSystem' in body: result['include_system'] = body['includeSystem'] if 'includeFoxxQueues' in body: result['include_foxx_queues'] = body['includeFoxxQueues'] if 'requireFromPresent' in body: result['require_from_present'] = body['requireFromPresent'] if 'restrictType' in body: result['restrict_type'] = body['restrictType'] if 'restrictCollections' in body: result['restrict_collections'] = body['restrictCollections'] if 'connectionRetryWaitTime' in body: result['connection_retry_wait_time'] = body['connectionRetryWaitTime'] if 'initialSyncMaxWaitTime' in body: result['initial_sync_max_wait_time'] = body['initialSyncMaxWaitTime'] if 'idleMinWaitTime' in body: result['idle_min_wait_time'] = body['idleMinWaitTime'] if 'idleMaxWaitTime' in body: result['idle_max_wait_time'] = body['idleMaxWaitTime'] return verify_format(body, result) def format_applier_progress(body): # pragma: no cover """Format replication applier progress data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'time' in body: result['time'] = body['time'] if 'message' in body: result['message'] = body['message'] if 'failedConnects' in body: result['failed_connects'] = body['failedConnects'] return verify_format(body, result) def format_applier_error(body): # pragma: no cover """Format replication applier error data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'errorNum' in body: result['error_num'] = body['errorNum'] if 'errorMessage' in body: result['error_message'] = body['errorMessage'] if 'time' in body: result['time'] = body['time'] return verify_format(body, result) def format_applier_state_details(body): # pragma: no cover """Format replication applier state details. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'started' in body: result['started'] = body['started'] if 'running' in body: result['running'] = body['running'] if 'phase' in body: result['phase'] = body['phase'] if 'time' in body: result['time'] = body['time'] if 'safeResumeTick' in body: result['safe_resume_tick'] = body['safeResumeTick'] if 'ticksBehind' in body: result['ticks_behind'] = body['ticksBehind'] if 'lastAppliedContinuousTick' in body: result['last_applied_continuous_tick'] = \ body['lastAppliedContinuousTick'] if 'lastProcessedContinuousTick' in body: result['last_processed_continuous_tick'] = \ body['lastProcessedContinuousTick'] if 'lastAvailableContinuousTick' in body: result['last_available_continuous_tick'] = \ body['lastAvailableContinuousTick'] if 'progress' in body: result['progress'] = format_applier_progress(body['progress']) if 'totalRequests' in body: result['total_requests'] = body['totalRequests'] if 'totalFailedConnects' in body: result['total_failed_connects'] = body['totalFailedConnects'] if 'totalEvents' in body: result['total_events'] = body['totalEvents'] if 'totalDocuments' in body: result['total_documents'] = body['totalDocuments'] if 'totalRemovals' in body: result['total_removals'] = body['totalRemovals'] if 'totalResyncs' in body: result['total_resyncs'] = body['totalResyncs'] if 'totalOperationsExcluded' in body: result['total_operations_excluded'] = body['totalOperationsExcluded'] if 'totalApplyTime' in body: result['total_apply_time'] = body['totalApplyTime'] if 'averageApplyTime' in body: result['average_apply_time'] = body['averageApplyTime'] if 'totalFetchTime' in body: result['total_fetch_time'] = body['totalFetchTime'] if 'averageFetchTime' in body: result['average_fetch_time'] = body['averageFetchTime'] if 'lastError' in body: result['last_error'] = format_applier_error(body['lastError']) return verify_format(body, result) def format_replication_applier_state(body): # pragma: no cover """Format replication applier state. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'endpoint' in body: result['endpoint'] = body['endpoint'] if 'database' in body: result['database'] = body['database'] if 'username' in body: result['username'] = body['username'] if 'state' in body: result['state'] = format_applier_state_details(body['state']) if 'server' in body: result['server'] = format_server_info(body['server']) return verify_format(body, result) def format_replication_state(body): # pragma: no cover """Format replication state. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ if not isinstance(body, dict): return body result = {} if 'running' in body: result['running'] = body['running'] if 'time' in body: result['time'] = body['time'] if 'lastLogTick' in body: result['last_log_tick'] = body['lastLogTick'] if 'totalEvents' in body: result['total_events'] = body['totalEvents'] if 'lastUncommittedLogTick' in body: result['last_uncommitted_log_tick'] = body['lastUncommittedLogTick'] return verify_format(body, result) def format_replication_logger_state(body): # pragma: no cover """Format replication collection data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'state' in body: result['state'] = format_replication_state(body['state']) if 'server' in body: result['server'] = format_server_info(body['server']) if 'clients' in body: result['clients'] = body['clients'] return verify_format(body, result) def format_replication_collection(body): # pragma: no cover """Format replication collection data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'planVersion' in body: result['plan_version'] = body['planVersion'] if 'isReady' in body: result['is_ready'] = body['isReady'] if 'allInSync' in body: result['all_in_sync'] = body['allInSync'] if 'indexes' in body: result['indexes'] = [format_index(index) for index in body['indexes']] if 'parameters' in body: result['parameters'] = format_collection(body['parameters']) return verify_format(body, result) def format_replication_database(body): # pragma: no cover """Format replication database data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = { 'id': body['id'], 'name': body['name'], 'collections': [ format_replication_collection(col) for col in body['collections'] ], 'views': [format_view(view) for view in body['views']] } if 'properties' in body: result['properties'] = format_database(body['properties']) return verify_format(body, result) def format_replication_inventory(body): # pragma: no cover """Format replication inventory data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'tick' in body: result['tick'] = body['tick'] if 'state' in body: result['state'] = format_replication_state(body['state']) if 'databases' in body: result['databases'] = { k: format_replication_database(v) for k, v in body['databases'].items() } if 'collections' in body: result['collections'] = [ format_replication_collection(col) for col in body['collections'] ] if 'views' in body: result['views'] = [format_view(view) for view in body['views']] if 'properties' in body: result['properties'] = format_database(body['properties']) return verify_format(body, result) def format_replication_sync(body): # pragma: no cover """Format replication sync result. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'collections' in body: result['collections'] = body['collections'] if 'lastLogTick' in body: result['last_log_tick'] = body['lastLogTick'] return verify_format(body, result) def format_replication_header(headers): # pragma: no cover """Format replication headers. :param headers: Request headers. :type headers: dict :return: Formatted body. :rtype: dict """ headers = {k.lower(): v for k, v in headers.items()} result = {} if 'x-arango-replication-frompresent' in headers: result['from_present'] = \ headers['x-arango-replication-frompresent'] == 'true' if 'x-arango-replication-lastincluded' in headers: result['last_included'] = \ headers['x-arango-replication-lastincluded'] if 'x-arango-replication-lastscanned' in headers: result['last_scanned'] = \ headers['x-arango-replication-lastscanned'] if 'x-arango-replication-lasttick' in headers: result['last_tick'] = \ headers['x-arango-replication-lasttick'] if 'x-arango-replication-active' in headers: result['active'] = \ headers['x-arango-replication-active'] == 'true' if 'x-arango-replication-checkmore' in headers: result['check_more'] = \ headers['x-arango-replication-checkmore'] == 'true' return result def format_view_link(body): # pragma: no cover """Format view link data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'analyzers' in body: result['analyzers'] = body['analyzers'] if 'fields' in body: result['fields'] = body['fields'] if 'includeAllFields' in body: result['include_all_fields'] = body['includeAllFields'] if 'trackListPositions' in body: result['track_list_positions'] = body['trackListPositions'] if 'storeValues' in body: result['store_values'] = body['storeValues'] return verify_format(body, result) def format_view_consolidation_policy(body): # pragma: no cover """Format view consolidation policy data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'type' in body: result['type'] = body['type'] if 'threshold' in body: result['threshold'] = body['threshold'] if 'segmentsMin' in body: result['segments_min'] = body['segmentsMin'] if 'segmentsMax' in body: result['segments_max'] = body['segmentsMax'] if 'segmentsBytesMax' in body: result['segments_bytes_max'] = body['segmentsBytesMax'] if 'segmentsBytesFloor' in body: result['segments_bytes_floor'] = body['segmentsBytesFloor'] if 'minScore' in body: result['min_score'] = body['minScore'] return verify_format(body, result) def format_view(body): # pragma: no cover """Format view data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'globallyUniqueId' in body: result['global_id'] = body['globallyUniqueId'] if 'id' in body: result['id'] = body['id'] if 'name' in body: result['name'] = body['name'] if 'type' in body: result['type'] = body['type'] if 'cleanupIntervalStep' in body: result['cleanup_interval_step'] = body['cleanupIntervalStep'] if 'commitIntervalMsec' in body: result['commit_interval_msec'] = body['commitIntervalMsec'] if 'consolidationIntervalMsec' in body: result['consolidation_interval_msec'] = \ body['consolidationIntervalMsec'] if 'consolidationPolicy' in body: result['consolidation_policy'] = \ format_view_consolidation_policy(body['consolidationPolicy']) if 'primarySort' in body: result['primary_sort'] = body['primarySort'] if 'primarySortCompression' in body: result['primary_sort_compression'] = body['primarySortCompression'] if 'storedValues' in body: result['stored_values'] = body['storedValues'] if 'writebufferIdle' in body: result['writebuffer_idle'] = body['writebufferIdle'] if 'writebufferActive' in body: result['writebuffer_active'] = body['writebufferActive'] if 'writebufferSizeMax' in body: result['writebuffer_max_size'] = body['writebufferSizeMax'] if 'links' in body: result['links'] = {link_key: format_view_link(link_content) for link_key, link_content in body['links'].items()} return verify_format(body, result) def format_vertex(body): # pragma: no cover """Format vertex data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ vertex = body['vertex'] if '_oldRev' in vertex: vertex['_old_rev'] = vertex.pop('_oldRev') if 'new' in body or 'old' in body: result = {'vertex': vertex} if 'new' in body: result['new'] = body['new'] if 'old' in body: result['old'] = body['old'] return result else: return vertex def format_edge(body): # pragma: no cover """Format edge data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ edge = body['edge'] if '_oldRev' in edge: edge['_old_rev'] = edge.pop('_oldRev') if 'new' in body or 'old' in body: result = {'edge': edge} if 'new' in body: result['new'] = body['new'] if 'old' in body: result['old'] = body['old'] return result else: return edge def format_tls(body): # pragma: no cover """Format TLS data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = body return verify_format(body, result)
def verify_format(_, res): return res def format_index(body): """Format index data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {'id': body['id'].split('/', 1)[-1], 'fields': body['fields']} if 'type' in body: result['type'] = body['type'] if 'name' in body: result['name'] = body['name'] if 'deduplicate' in body: result['deduplicate'] = body['deduplicate'] if 'sparse' in body: result['sparse'] = body['sparse'] if 'unique' in body: result['unique'] = body['unique'] if 'minLength' in body: result['min_length'] = body['minLength'] if 'geoJson' in body: result['geo_json'] = body['geoJson'] if 'ignoreNull' in body: result['ignore_none'] = body['ignoreNull'] if 'selectivityEstimate' in body: result['selectivity'] = body['selectivityEstimate'] if 'isNewlyCreated' in body: result['new'] = body['isNewlyCreated'] if 'expireAfter' in body: result['expiry_time'] = body['expireAfter'] if 'inBackground' in body: result['in_background'] = body['inBackground'] if 'bestIndexedLevel' in body: result['best_indexed_level'] = body['bestIndexedLevel'] if 'worstIndexedLevel' in body: result['worst_indexed_level'] = body['worstIndexedLevel'] if 'maxNumCoverCells' in body: result['max_num_cover_cells'] = body['maxNumCoverCells'] return verify_format(body, result) def format_key_options(body): """Format collection key options data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'type' in body: result['key_generator'] = body['type'] if 'increment' in body: result['key_increment'] = body['increment'] if 'offset' in body: result['key_offset'] = body['offset'] if 'allowUserKeys' in body: result['user_keys'] = body['allowUserKeys'] if 'lastValue' in body: result['key_last_value'] = body['lastValue'] return verify_format(body, result) def format_database(body): """Format databases info. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'id' in body: result['id'] = body['id'] if 'name' in body: result['name'] = body['name'] if 'path' in body: result['path'] = body['path'] if 'system' in body: result['system'] = body['system'] if 'isSystem' in body: result['system'] = body['isSystem'] if 'sharding' in body: result['sharding'] = body['sharding'] if 'replicationFactor' in body: result['replication_factor'] = body['replicationFactor'] if 'writeConcern' in body: result['write_concern'] = body['writeConcern'] return verify_format(body, result) def format_collection(body): """Format collection data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'id' in body: result['id'] = body['id'] if 'objectId' in body: result['object_id'] = body['objectId'] if 'name' in body: result['name'] = body['name'] if 'isSystem' in body: result['system'] = body['isSystem'] if 'isSmart' in body: result['smart'] = body['isSmart'] if 'type' in body: result['type'] = body['type'] result['edge'] = body['type'] == 3 if 'waitForSync' in body: result['sync'] = body['waitForSync'] if 'status' in body: result['status'] = body['status'] if 'statusString' in body: result['status_string'] = body['statusString'] if 'globallyUniqueId' in body: result['global_id'] = body['globallyUniqueId'] if 'cacheEnabled' in body: result['cache'] = body['cacheEnabled'] if 'replicationFactor' in body: result['replication_factor'] = body['replicationFactor'] if 'minReplicationFactor' in body: result['min_replication_factor'] = body['minReplicationFactor'] if 'writeConcern' in body: result['write_concern'] = body['writeConcern'] if 'doCompact' in body: result['compact'] = body['doCompact'] if 'journalSize' in body: result['journal_size'] = body['journalSize'] if 'isVolatile' in body: result['volatile'] = body['isVolatile'] if 'indexBuckets' in body: result['index_bucket_count'] = body['indexBuckets'] if 'shards' in body: result['shards'] = body['shards'] if 'replicationFactor' in body: result['replication_factor'] = body['replicationFactor'] if 'numberOfShards' in body: result['shard_count'] = body['numberOfShards'] if 'shardKeys' in body: result['shard_fields'] = body['shardKeys'] if 'distributeShardsLike' in body: result['shard_like'] = body['distributeShardsLike'] if 'shardingStrategy' in body: result['sharding_strategy'] = body['shardingStrategy'] if 'smartJoinAttribute' in body: result['smart_join_attribute'] = body['smartJoinAttribute'] if 'keyOptions' in body: result['key_options'] = format_key_options(body['keyOptions']) if 'cid' in body: result['cid'] = body['cid'] if 'version' in body: result['version'] = body['version'] if 'allowUserKeys' in body: result['user_keys'] = body['allowUserKeys'] if 'planId' in body: result['plan_id'] = body['planId'] if 'deleted' in body: result['deleted'] = body['deleted'] if 'syncByRevision' in body: result['sync_by_revision'] = body['syncByRevision'] if 'tempObjectId' in body: result['temp_object_id'] = body['tempObjectId'] if 'usesRevisionsAsDocumentIds' in body: result['rev_as_id'] = body['usesRevisionsAsDocumentIds'] if 'isDisjoint' in body: result['disjoint'] = body['isDisjoint'] if 'isSmartChild' in body: result['smart_child'] = body['isSmartChild'] if 'minRevision' in body: result['min_revision'] = body['minRevision'] if 'schema' in body: result['schema'] = body['schema'] return verify_format(body, result) def format_aql_cache(body): """Format AQL cache data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {'mode': body['mode'], 'max_results': body['maxResults'], 'max_results_size': body['maxResultsSize'], 'max_entry_size': body['maxEntrySize'], 'include_system': body['includeSystem']} return verify_format(body, result) def format_wal_properties(body): """Format WAL properties. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'allowOversizeEntries' in body: result['oversized_ops'] = body['allowOversizeEntries'] if 'logfileSize' in body: result['log_size'] = body['logfileSize'] if 'historicLogfiles' in body: result['historic_logs'] = body['historicLogfiles'] if 'reserveLogfiles' in body: result['reserve_logs'] = body['reserveLogfiles'] if 'syncInterval' in body: result['sync_interval'] = body['syncInterval'] if 'throttleWait' in body: result['throttle_wait'] = body['throttleWait'] if 'throttleWhenPending' in body: result['throttle_limit'] = body['throttleWhenPending'] return verify_format(body, result) def format_wal_transactions(body): """Format WAL transactions. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'minLastCollected' in body: result['last_collected'] = body['minLastCollected'] if 'minLastSealed' in body: result['last_sealed'] = body['minLastSealed'] if 'runningTransactions' in body: result['count'] = body['runningTransactions'] return verify_format(body, result) def format_aql_query(body): """Format AQL query data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {'id': body['id'], 'query': body['query']} if 'started' in body: result['started'] = body['started'] if 'state' in body: result['state'] = body['state'] if 'stream' in body: result['stream'] = body['stream'] if 'bindVars' in body: result['bind_vars'] = body['bindVars'] if 'runTime' in body: result['runtime'] = body['runTime'] return verify_format(body, result) def format_aql_tracking(body): """Format AQL tracking data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'enabled' in body: result['enabled'] = body['enabled'] if 'maxQueryStringLength' in body: result['max_query_string_length'] = body['maxQueryStringLength'] if 'maxSlowQueries' in body: result['max_slow_queries'] = body['maxSlowQueries'] if 'slowQueryThreshold' in body: result['slow_query_threshold'] = body['slowQueryThreshold'] if 'slowStreamingQueryThreshold' in body: result['slow_streaming_query_threshold'] = body['slowStreamingQueryThreshold'] if 'trackBindVars' in body: result['track_bind_vars'] = body['trackBindVars'] if 'trackSlowQueries' in body: result['track_slow_queries'] = body['trackSlowQueries'] return verify_format(body, result) def format_tick_values(body): """Format tick data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'tickMin' in body: result['tick_min'] = body['tickMin'] if 'tickMax' in body: result['tick_max'] = body['tickMax'] if 'tick' in body: result['tick'] = body['tick'] if 'time' in body: result['time'] = body['time'] if 'server' in body: result['server'] = format_server_info(body['server']) return verify_format(body, result) def format_server_info(body): """Format server data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ return {'version': body['version'], 'server_id': body['serverId']} def format_replication_applier_config(body): """Format replication applier configuration data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'endpoint' in body: result['endpoint'] = body['endpoint'] if 'database' in body: result['database'] = body['database'] if 'username' in body: result['username'] = body['username'] if 'verbose' in body: result['verbose'] = body['verbose'] if 'incremental' in body: result['incremental'] = body['incremental'] if 'requestTimeout' in body: result['request_timeout'] = body['requestTimeout'] if 'connectTimeout' in body: result['connect_timeout'] = body['connectTimeout'] if 'ignoreErrors' in body: result['ignore_errors'] = body['ignoreErrors'] if 'maxConnectRetries' in body: result['max_connect_retries'] = body['maxConnectRetries'] if 'lockTimeoutRetries' in body: result['lock_timeout_retries'] = body['lockTimeoutRetries'] if 'sslProtocol' in body: result['ssl_protocol'] = body['sslProtocol'] if 'chunkSize' in body: result['chunk_size'] = body['chunkSize'] if 'skipCreateDrop' in body: result['skip_create_drop'] = body['skipCreateDrop'] if 'autoStart' in body: result['auto_start'] = body['autoStart'] if 'adaptivePolling' in body: result['adaptive_polling'] = body['adaptivePolling'] if 'autoResync' in body: result['auto_resync'] = body['autoResync'] if 'autoResyncRetries' in body: result['auto_resync_retries'] = body['autoResyncRetries'] if 'maxPacketSize' in body: result['max_packet_size'] = body['maxPacketSize'] if 'includeSystem' in body: result['include_system'] = body['includeSystem'] if 'includeFoxxQueues' in body: result['include_foxx_queues'] = body['includeFoxxQueues'] if 'requireFromPresent' in body: result['require_from_present'] = body['requireFromPresent'] if 'restrictType' in body: result['restrict_type'] = body['restrictType'] if 'restrictCollections' in body: result['restrict_collections'] = body['restrictCollections'] if 'connectionRetryWaitTime' in body: result['connection_retry_wait_time'] = body['connectionRetryWaitTime'] if 'initialSyncMaxWaitTime' in body: result['initial_sync_max_wait_time'] = body['initialSyncMaxWaitTime'] if 'idleMinWaitTime' in body: result['idle_min_wait_time'] = body['idleMinWaitTime'] if 'idleMaxWaitTime' in body: result['idle_max_wait_time'] = body['idleMaxWaitTime'] return verify_format(body, result) def format_applier_progress(body): """Format replication applier progress data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'time' in body: result['time'] = body['time'] if 'message' in body: result['message'] = body['message'] if 'failedConnects' in body: result['failed_connects'] = body['failedConnects'] return verify_format(body, result) def format_applier_error(body): """Format replication applier error data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'errorNum' in body: result['error_num'] = body['errorNum'] if 'errorMessage' in body: result['error_message'] = body['errorMessage'] if 'time' in body: result['time'] = body['time'] return verify_format(body, result) def format_applier_state_details(body): """Format replication applier state details. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'started' in body: result['started'] = body['started'] if 'running' in body: result['running'] = body['running'] if 'phase' in body: result['phase'] = body['phase'] if 'time' in body: result['time'] = body['time'] if 'safeResumeTick' in body: result['safe_resume_tick'] = body['safeResumeTick'] if 'ticksBehind' in body: result['ticks_behind'] = body['ticksBehind'] if 'lastAppliedContinuousTick' in body: result['last_applied_continuous_tick'] = body['lastAppliedContinuousTick'] if 'lastProcessedContinuousTick' in body: result['last_processed_continuous_tick'] = body['lastProcessedContinuousTick'] if 'lastAvailableContinuousTick' in body: result['last_available_continuous_tick'] = body['lastAvailableContinuousTick'] if 'progress' in body: result['progress'] = format_applier_progress(body['progress']) if 'totalRequests' in body: result['total_requests'] = body['totalRequests'] if 'totalFailedConnects' in body: result['total_failed_connects'] = body['totalFailedConnects'] if 'totalEvents' in body: result['total_events'] = body['totalEvents'] if 'totalDocuments' in body: result['total_documents'] = body['totalDocuments'] if 'totalRemovals' in body: result['total_removals'] = body['totalRemovals'] if 'totalResyncs' in body: result['total_resyncs'] = body['totalResyncs'] if 'totalOperationsExcluded' in body: result['total_operations_excluded'] = body['totalOperationsExcluded'] if 'totalApplyTime' in body: result['total_apply_time'] = body['totalApplyTime'] if 'averageApplyTime' in body: result['average_apply_time'] = body['averageApplyTime'] if 'totalFetchTime' in body: result['total_fetch_time'] = body['totalFetchTime'] if 'averageFetchTime' in body: result['average_fetch_time'] = body['averageFetchTime'] if 'lastError' in body: result['last_error'] = format_applier_error(body['lastError']) return verify_format(body, result) def format_replication_applier_state(body): """Format replication applier state. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'endpoint' in body: result['endpoint'] = body['endpoint'] if 'database' in body: result['database'] = body['database'] if 'username' in body: result['username'] = body['username'] if 'state' in body: result['state'] = format_applier_state_details(body['state']) if 'server' in body: result['server'] = format_server_info(body['server']) return verify_format(body, result) def format_replication_state(body): """Format replication state. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ if not isinstance(body, dict): return body result = {} if 'running' in body: result['running'] = body['running'] if 'time' in body: result['time'] = body['time'] if 'lastLogTick' in body: result['last_log_tick'] = body['lastLogTick'] if 'totalEvents' in body: result['total_events'] = body['totalEvents'] if 'lastUncommittedLogTick' in body: result['last_uncommitted_log_tick'] = body['lastUncommittedLogTick'] return verify_format(body, result) def format_replication_logger_state(body): """Format replication collection data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'state' in body: result['state'] = format_replication_state(body['state']) if 'server' in body: result['server'] = format_server_info(body['server']) if 'clients' in body: result['clients'] = body['clients'] return verify_format(body, result) def format_replication_collection(body): """Format replication collection data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'planVersion' in body: result['plan_version'] = body['planVersion'] if 'isReady' in body: result['is_ready'] = body['isReady'] if 'allInSync' in body: result['all_in_sync'] = body['allInSync'] if 'indexes' in body: result['indexes'] = [format_index(index) for index in body['indexes']] if 'parameters' in body: result['parameters'] = format_collection(body['parameters']) return verify_format(body, result) def format_replication_database(body): """Format replication database data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {'id': body['id'], 'name': body['name'], 'collections': [format_replication_collection(col) for col in body['collections']], 'views': [format_view(view) for view in body['views']]} if 'properties' in body: result['properties'] = format_database(body['properties']) return verify_format(body, result) def format_replication_inventory(body): """Format replication inventory data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'tick' in body: result['tick'] = body['tick'] if 'state' in body: result['state'] = format_replication_state(body['state']) if 'databases' in body: result['databases'] = {k: format_replication_database(v) for (k, v) in body['databases'].items()} if 'collections' in body: result['collections'] = [format_replication_collection(col) for col in body['collections']] if 'views' in body: result['views'] = [format_view(view) for view in body['views']] if 'properties' in body: result['properties'] = format_database(body['properties']) return verify_format(body, result) def format_replication_sync(body): """Format replication sync result. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'collections' in body: result['collections'] = body['collections'] if 'lastLogTick' in body: result['last_log_tick'] = body['lastLogTick'] return verify_format(body, result) def format_replication_header(headers): """Format replication headers. :param headers: Request headers. :type headers: dict :return: Formatted body. :rtype: dict """ headers = {k.lower(): v for (k, v) in headers.items()} result = {} if 'x-arango-replication-frompresent' in headers: result['from_present'] = headers['x-arango-replication-frompresent'] == 'true' if 'x-arango-replication-lastincluded' in headers: result['last_included'] = headers['x-arango-replication-lastincluded'] if 'x-arango-replication-lastscanned' in headers: result['last_scanned'] = headers['x-arango-replication-lastscanned'] if 'x-arango-replication-lasttick' in headers: result['last_tick'] = headers['x-arango-replication-lasttick'] if 'x-arango-replication-active' in headers: result['active'] = headers['x-arango-replication-active'] == 'true' if 'x-arango-replication-checkmore' in headers: result['check_more'] = headers['x-arango-replication-checkmore'] == 'true' return result def format_view_link(body): """Format view link data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'analyzers' in body: result['analyzers'] = body['analyzers'] if 'fields' in body: result['fields'] = body['fields'] if 'includeAllFields' in body: result['include_all_fields'] = body['includeAllFields'] if 'trackListPositions' in body: result['track_list_positions'] = body['trackListPositions'] if 'storeValues' in body: result['store_values'] = body['storeValues'] return verify_format(body, result) def format_view_consolidation_policy(body): """Format view consolidation policy data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'type' in body: result['type'] = body['type'] if 'threshold' in body: result['threshold'] = body['threshold'] if 'segmentsMin' in body: result['segments_min'] = body['segmentsMin'] if 'segmentsMax' in body: result['segments_max'] = body['segmentsMax'] if 'segmentsBytesMax' in body: result['segments_bytes_max'] = body['segmentsBytesMax'] if 'segmentsBytesFloor' in body: result['segments_bytes_floor'] = body['segmentsBytesFloor'] if 'minScore' in body: result['min_score'] = body['minScore'] return verify_format(body, result) def format_view(body): """Format view data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = {} if 'globallyUniqueId' in body: result['global_id'] = body['globallyUniqueId'] if 'id' in body: result['id'] = body['id'] if 'name' in body: result['name'] = body['name'] if 'type' in body: result['type'] = body['type'] if 'cleanupIntervalStep' in body: result['cleanup_interval_step'] = body['cleanupIntervalStep'] if 'commitIntervalMsec' in body: result['commit_interval_msec'] = body['commitIntervalMsec'] if 'consolidationIntervalMsec' in body: result['consolidation_interval_msec'] = body['consolidationIntervalMsec'] if 'consolidationPolicy' in body: result['consolidation_policy'] = format_view_consolidation_policy(body['consolidationPolicy']) if 'primarySort' in body: result['primary_sort'] = body['primarySort'] if 'primarySortCompression' in body: result['primary_sort_compression'] = body['primarySortCompression'] if 'storedValues' in body: result['stored_values'] = body['storedValues'] if 'writebufferIdle' in body: result['writebuffer_idle'] = body['writebufferIdle'] if 'writebufferActive' in body: result['writebuffer_active'] = body['writebufferActive'] if 'writebufferSizeMax' in body: result['writebuffer_max_size'] = body['writebufferSizeMax'] if 'links' in body: result['links'] = {link_key: format_view_link(link_content) for (link_key, link_content) in body['links'].items()} return verify_format(body, result) def format_vertex(body): """Format vertex data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ vertex = body['vertex'] if '_oldRev' in vertex: vertex['_old_rev'] = vertex.pop('_oldRev') if 'new' in body or 'old' in body: result = {'vertex': vertex} if 'new' in body: result['new'] = body['new'] if 'old' in body: result['old'] = body['old'] return result else: return vertex def format_edge(body): """Format edge data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ edge = body['edge'] if '_oldRev' in edge: edge['_old_rev'] = edge.pop('_oldRev') if 'new' in body or 'old' in body: result = {'edge': edge} if 'new' in body: result['new'] = body['new'] if 'old' in body: result['old'] = body['old'] return result else: return edge def format_tls(body): """Format TLS data. :param body: Input body. :type body: dict :return: Formatted body. :rtype: dict """ result = body return verify_format(body, result)
# exc. 9.1.2 def file_options(file_name, task): if task == 'sort': edit_file = open(file_name, 'r') file_list = edit_file.read().split(' ') print(sorted(file_list)) edit_file.close() elif task == 'rev': edit_file = open(file_name, 'r') for line in edit_file: print(line[::-1]) edit_file.close() elif task == 'last': n = int(input('Enter a number: ')) n = n * (-1) file_list = [] edit_file = open(file_name, 'r') for line in edit_file: file_list += [line] file_list = file_list[n:] for line in file_list: print(line) #print(file_list[n:], sep="\n") def main(): file_name = "C:\\Users\\user\\Desktop\\sampleFile.txt" task = input('Enter a task: ') file_options(file_name, task) if __name__ == '__main__': main()
def file_options(file_name, task): if task == 'sort': edit_file = open(file_name, 'r') file_list = edit_file.read().split(' ') print(sorted(file_list)) edit_file.close() elif task == 'rev': edit_file = open(file_name, 'r') for line in edit_file: print(line[::-1]) edit_file.close() elif task == 'last': n = int(input('Enter a number: ')) n = n * -1 file_list = [] edit_file = open(file_name, 'r') for line in edit_file: file_list += [line] file_list = file_list[n:] for line in file_list: print(line) def main(): file_name = 'C:\\Users\\user\\Desktop\\sampleFile.txt' task = input('Enter a task: ') file_options(file_name, task) if __name__ == '__main__': main()
# Singly Linked List class Node: def __init__(self, value): self.value = value self.next = None class LinkedList: def __init__(self): self.head = None def __repr__(self): node = self.head nodes = [] while node is not None: nodes.append(node.value) node = node.next nodes.append("None") return " -> ".join(nodes) llist = LinkedList() first_node = Node("a") second_node = Node("b") third_node = Node("c") llist.head = first_node first_node.next = second_node second_node.next = third_node print(llist)
class Node: def __init__(self, value): self.value = value self.next = None class Linkedlist: def __init__(self): self.head = None def __repr__(self): node = self.head nodes = [] while node is not None: nodes.append(node.value) node = node.next nodes.append('None') return ' -> '.join(nodes) llist = linked_list() first_node = node('a') second_node = node('b') third_node = node('c') llist.head = first_node first_node.next = second_node second_node.next = third_node print(llist)
# -*- coding: utf-8 -*- """Top-level package for pyqmc.""" __author__ = """Maxime Godin""" __email__ = 'maximegodin@polytechnique.org' __version__ = '0.1.0'
"""Top-level package for pyqmc.""" __author__ = 'Maxime Godin' __email__ = 'maximegodin@polytechnique.org' __version__ = '0.1.0'
# Fibonacci Sequence: 0 1 1 2 3 5 8 13 ... def fibonacci(num): if num == 1: return 0 if num == 2: return 1 return fibonacci(num-1) + fibonacci(num-2) print(fibonacci(1)) print(fibonacci(2)) print(fibonacci(3)) print(fibonacci(4)) print(fibonacci(5))
def fibonacci(num): if num == 1: return 0 if num == 2: return 1 return fibonacci(num - 1) + fibonacci(num - 2) print(fibonacci(1)) print(fibonacci(2)) print(fibonacci(3)) print(fibonacci(4)) print(fibonacci(5))
cities = [ 'Sao Paulo', 'Rio de Janeiro', 'Salvador', 'Fortaleza', 'Belo Horizonte', 'Brasilia', 'Curitiba', 'Manaus', 'Recife', 'Belem', 'Porto Alegre', 'Goiania', 'Guarulhos', 'Campinas', 'Nova Iguacu', 'Maceio', 'Sao Luis', 'Duque de Caxias', 'Natal', 'Teresina', 'Sao Bernardo do Campo', 'Campo Grande', 'Jaboatao', 'Osasco', 'Santo Andre', 'Joao Pessoa', 'Jaboatao dos Guararapes', 'Contagem', 'Ribeirao Preto', 'Sao Jose dos Campos', 'Uberlandia', 'Sorocaba', 'Cuiaba', 'Aparecida de Goiania', 'Aracaju', 'Feira de Santana', 'Londrina', 'Juiz de Fora', 'Belford Roxo', 'Joinville', 'Niteroi', 'Sao Joao de Meriti', 'Ananindeua', 'Florianopolis', 'Santos', 'Ribeirao das Neves', 'Vila Velha', 'Serra', 'Diadema', 'Campos dos Goytacazes', 'Maua', 'Betim', 'Caxias do Sul', 'Sao Jose do Rio Preto', 'Olinda', 'Carapicuiba', 'Campina Grande', 'Piracicaba', 'Macapa', 'Itaquaquecetuba', 'Bauru', 'Montes Claros', 'Canoas', 'Mogi das Cruzes', 'Sao Vicente', 'Jundiai', 'Pelotas', 'Anapolis', 'Vitoria', 'Maringa', 'Guaruja', 'Porto Velho', 'Franca', 'Blumenau', 'Foz do Iguacu', 'Ponta Grossa', 'Paulista', 'Limeira', 'Viamao', 'Suzano', 'Caucaia', 'Petropolis', 'Uberaba', 'Rio Branco', 'Cascavel', 'Novo Hamburgo', 'Vitoria da Conquista', 'Barueri', 'Taubate', 'Governador Valadares', 'Praia Grande', 'Varzea Grande', 'Volta Redonda', 'Santa Maria', 'Santa Luzia', 'Gravatai', 'Caruaru', 'Boa Vista', 'Ipatinga', 'Sumare', 'Juazeiro do Norte', 'Embu', 'Imperatriz', 'Colombo', 'Taboao da Serra', 'Jacarei', 'Marilia', 'Presidente Prudente', 'Sao Leopoldo', 'Itabuna', 'Sao Carlos', 'Hortolandia', 'Mossoro', 'Itapevi', 'Sete Lagoas', 'Sao Jose', 'Palmas', 'Americana', 'Petrolina', 'Divinopolis', 'Maracanau', 'Planaltina', 'Santarem', 'Camacari', "Santa Barbara d'Oeste", 'Rio Grande', 'Cachoeiro de Itapemirim', 'Itaborai', 'Rio Claro', 'Indaiatuba', 'Passo Fundo', 'Cotia', 'Francisco Morato', 'Aracatuba', 'Araraquara', 'Ferraz de Vasconcelos', 'Arapiraca', 'Lages', 'Barra Mansa', 'Nossa Senhora do Socorro', 'Dourados', 'Criciuma', 'Chapeco', 'Barreiras', 'Sobral', 'Itajai', 'Ilheus', 'Angra dos Reis', 'Nova Friburgo', 'Rondonopolis', 'Itapecerica da Serra', 'Guarapuava', 'Parnamirim', 'Caxias', 'Nilopolis', 'Pocos de Caldas', 'Maraba', 'Luziania', 'Cabo', 'Macae', 'Ibirite', 'Lauro de Freitas', 'Paranagua', 'Parnaiba', 'Itu', 'Castanhal', 'Sao Caetano do Sul', 'Queimados', 'Pindamonhangaba', 'Sapucaia', 'Jaragua do Sul', 'Mogi Guacu', 'Jequie', 'Itapetininga', 'Patos de Minas', 'Braganca Paulista', 'Timon', 'Sao Jose dos Pinhais', 'Teresopolis', 'Uruguaiana', 'Porto Seguro', 'Alagoinhas', 'Palhoca', 'Barbacena', 'Cachoeirinha', 'Santa Rita', 'Toledo', 'Jau', 'Cubatao', 'Pinhais', 'Simoes Filho', 'Varginha', 'Sinop', 'Pouso Alegre', 'Eunapolis', 'Botucatu', 'Jandira', 'Ribeirao Pires', 'Conselheiro Lafaiete', 'Resende', 'Araucaria', 'Atibaia', 'Varzea Paulista', 'Garanhuns', 'Araruama', 'Catanduva', 'Franco da Rocha', 'Cabo Frio', 'Ji Parana', 'Araras', 'Poa', 'Vitoria de Santo Antao', 'Umuarama', 'Apucarana', 'Santa Cruz do Sul', 'Guaratingueta', 'Linhares', 'Araguaina', 'Esmeraldas', 'Birigui', 'Assis', 'Barretos', 'Colatina', 'Teofilo Otoni', 'Guaiba', 'Guarapari', 'Coronel Fabriciano', 'Itaguai', 'Rio das Ostras', 'Itabira', 'Votorantim', 'Sertaozinho', 'Santana de Parnaiba', 'Bage', 'Passos', 'Salto', 'Uba', 'Ourinhos', 'Trindade', 'Arapongas', 'Araguari', 'Corumba', 'Erechim', 'Japeri', 'Vespasiano', 'Campo Largo', 'Tatui', 'Patos', 'Timoteo', 'Muriae', 'Cambe', 'Bayeux', 'Bento Goncalves', 'Caraguatatuba', 'Itanhaem', 'Santana do Livramento', 'Almirante Tamandare', 'Planaltina', 'Crato', 'Valinhos', 'Sao Lourenco da Mata', 'Nova Lima', 'Brusque', 'Barra do Pirai', 'Alegrete', 'Caieiras', 'Barra do Corda', 'Igarassu', 'Paulo Afonso', 'Ituiutaba', 'Esteio', 'Sarandi', 'Itaperuna', 'Santana', 'Jardim Paulista', 'Codo', 'Araxa', 'Abreu e Lima', 'Itajuba', 'Lavras', 'Avare', 'Formosa', 'Leme', 'Cruzeiro do Sul', 'Itumbiara', 'Marica', 'Ubatuba', 'Tres Lagoas', 'Sao Joao del Rei', 'Mogi Mirim', 'Abaetetuba', 'Sao Bento do Sul', 'Itauna', 'Sao Mateus', 'Jatai', 'Sao Joao da Boa Vista', 'Lorena', 'Santa Cruz do Capibaribe', 'Sao Sebastiao', 'Tucurui', 'Embu Guacu', 'Sapiranga', 'Para de Minas', 'Campo Mourao', 'Cachoeira do Sul', 'Santo Antonio de Jesus', 'Paranavai', 'Joao Monlevade', 'Matao', 'Bacabal', 'Cacapava', 'Aruja', 'Cruzeiro', 'Patrocinio', 'Tres Rios', 'Bebedouro', 'Sao Cristovao', 'Alfenas', 'Ijui', 'Altamira', 'Paracatu', 'Carpina', 'Iguatu', 'Votuporanga', 'Paragominas', 'Lins', 'Jaboticabal', 'Vicosa', 'Sao Sebastiao do Paraiso', 'Balsas', 'Itatiba', 'Santa Ines', 'Tubarao', 'Pato Branco', 'Paulinia', 'Lajeado', 'Cruz Alta', 'Aquiraz', 'Itacoatiara', 'Gurupi', 'Itaituba', 'Santo Angelo', 'Parintins', 'Curvelo', 'Itabaiana', 'Cacador', 'Ouro Preto', 'Caldas Novas', 'Irece', 'Catalao', 'Tres Coracoes', 'Rio Largo', 'Vilhena', 'Valenca', 'Peruibe', 'Itapeva', 'Cataguases', 'Saquarema', 'Tupa', 'Fernandopolis', 'Senador Canedo', 'Itapira', 'Gravata', 'Valenca', 'Pirassununga', 'Unai', 'Caratinga', 'Itapetinga', 'Mococa', 'Sao Borja', 'Carazinho', 'Santa Rosa', 'Telemaco Borba', 'Guanambi', 'Aracruz', 'Ariquemes', 'Farroupilha', 'Francisco Beltrao', 'Picos', 'Lencois Paulista', 'Arcoverde', 'Braganca', 'Vacaria', 'Cajamar', 'Janauba', 'Vinhedo', 'Formiga', 'Cianorte', 'Nova Vicosa', 'Itapipoca', 'Ponta Pora', 'Estancia', 'Cacoal', 'Sao Gabriel', 'Concordia', 'Pacatuba', 'Viana', 'Sao Pedro da Aldeia', 'Caico', 'Seropedica' ]
cities = ['Sao Paulo', 'Rio de Janeiro', 'Salvador', 'Fortaleza', 'Belo Horizonte', 'Brasilia', 'Curitiba', 'Manaus', 'Recife', 'Belem', 'Porto Alegre', 'Goiania', 'Guarulhos', 'Campinas', 'Nova Iguacu', 'Maceio', 'Sao Luis', 'Duque de Caxias', 'Natal', 'Teresina', 'Sao Bernardo do Campo', 'Campo Grande', 'Jaboatao', 'Osasco', 'Santo Andre', 'Joao Pessoa', 'Jaboatao dos Guararapes', 'Contagem', 'Ribeirao Preto', 'Sao Jose dos Campos', 'Uberlandia', 'Sorocaba', 'Cuiaba', 'Aparecida de Goiania', 'Aracaju', 'Feira de Santana', 'Londrina', 'Juiz de Fora', 'Belford Roxo', 'Joinville', 'Niteroi', 'Sao Joao de Meriti', 'Ananindeua', 'Florianopolis', 'Santos', 'Ribeirao das Neves', 'Vila Velha', 'Serra', 'Diadema', 'Campos dos Goytacazes', 'Maua', 'Betim', 'Caxias do Sul', 'Sao Jose do Rio Preto', 'Olinda', 'Carapicuiba', 'Campina Grande', 'Piracicaba', 'Macapa', 'Itaquaquecetuba', 'Bauru', 'Montes Claros', 'Canoas', 'Mogi das Cruzes', 'Sao Vicente', 'Jundiai', 'Pelotas', 'Anapolis', 'Vitoria', 'Maringa', 'Guaruja', 'Porto Velho', 'Franca', 'Blumenau', 'Foz do Iguacu', 'Ponta Grossa', 'Paulista', 'Limeira', 'Viamao', 'Suzano', 'Caucaia', 'Petropolis', 'Uberaba', 'Rio Branco', 'Cascavel', 'Novo Hamburgo', 'Vitoria da Conquista', 'Barueri', 'Taubate', 'Governador Valadares', 'Praia Grande', 'Varzea Grande', 'Volta Redonda', 'Santa Maria', 'Santa Luzia', 'Gravatai', 'Caruaru', 'Boa Vista', 'Ipatinga', 'Sumare', 'Juazeiro do Norte', 'Embu', 'Imperatriz', 'Colombo', 'Taboao da Serra', 'Jacarei', 'Marilia', 'Presidente Prudente', 'Sao Leopoldo', 'Itabuna', 'Sao Carlos', 'Hortolandia', 'Mossoro', 'Itapevi', 'Sete Lagoas', 'Sao Jose', 'Palmas', 'Americana', 'Petrolina', 'Divinopolis', 'Maracanau', 'Planaltina', 'Santarem', 'Camacari', "Santa Barbara d'Oeste", 'Rio Grande', 'Cachoeiro de Itapemirim', 'Itaborai', 'Rio Claro', 'Indaiatuba', 'Passo Fundo', 'Cotia', 'Francisco Morato', 'Aracatuba', 'Araraquara', 'Ferraz de Vasconcelos', 'Arapiraca', 'Lages', 'Barra Mansa', 'Nossa Senhora do Socorro', 'Dourados', 'Criciuma', 'Chapeco', 'Barreiras', 'Sobral', 'Itajai', 'Ilheus', 'Angra dos Reis', 'Nova Friburgo', 'Rondonopolis', 'Itapecerica da Serra', 'Guarapuava', 'Parnamirim', 'Caxias', 'Nilopolis', 'Pocos de Caldas', 'Maraba', 'Luziania', 'Cabo', 'Macae', 'Ibirite', 'Lauro de Freitas', 'Paranagua', 'Parnaiba', 'Itu', 'Castanhal', 'Sao Caetano do Sul', 'Queimados', 'Pindamonhangaba', 'Sapucaia', 'Jaragua do Sul', 'Mogi Guacu', 'Jequie', 'Itapetininga', 'Patos de Minas', 'Braganca Paulista', 'Timon', 'Sao Jose dos Pinhais', 'Teresopolis', 'Uruguaiana', 'Porto Seguro', 'Alagoinhas', 'Palhoca', 'Barbacena', 'Cachoeirinha', 'Santa Rita', 'Toledo', 'Jau', 'Cubatao', 'Pinhais', 'Simoes Filho', 'Varginha', 'Sinop', 'Pouso Alegre', 'Eunapolis', 'Botucatu', 'Jandira', 'Ribeirao Pires', 'Conselheiro Lafaiete', 'Resende', 'Araucaria', 'Atibaia', 'Varzea Paulista', 'Garanhuns', 'Araruama', 'Catanduva', 'Franco da Rocha', 'Cabo Frio', 'Ji Parana', 'Araras', 'Poa', 'Vitoria de Santo Antao', 'Umuarama', 'Apucarana', 'Santa Cruz do Sul', 'Guaratingueta', 'Linhares', 'Araguaina', 'Esmeraldas', 'Birigui', 'Assis', 'Barretos', 'Colatina', 'Teofilo Otoni', 'Guaiba', 'Guarapari', 'Coronel Fabriciano', 'Itaguai', 'Rio das Ostras', 'Itabira', 'Votorantim', 'Sertaozinho', 'Santana de Parnaiba', 'Bage', 'Passos', 'Salto', 'Uba', 'Ourinhos', 'Trindade', 'Arapongas', 'Araguari', 'Corumba', 'Erechim', 'Japeri', 'Vespasiano', 'Campo Largo', 'Tatui', 'Patos', 'Timoteo', 'Muriae', 'Cambe', 'Bayeux', 'Bento Goncalves', 'Caraguatatuba', 'Itanhaem', 'Santana do Livramento', 'Almirante Tamandare', 'Planaltina', 'Crato', 'Valinhos', 'Sao Lourenco da Mata', 'Nova Lima', 'Brusque', 'Barra do Pirai', 'Alegrete', 'Caieiras', 'Barra do Corda', 'Igarassu', 'Paulo Afonso', 'Ituiutaba', 'Esteio', 'Sarandi', 'Itaperuna', 'Santana', 'Jardim Paulista', 'Codo', 'Araxa', 'Abreu e Lima', 'Itajuba', 'Lavras', 'Avare', 'Formosa', 'Leme', 'Cruzeiro do Sul', 'Itumbiara', 'Marica', 'Ubatuba', 'Tres Lagoas', 'Sao Joao del Rei', 'Mogi Mirim', 'Abaetetuba', 'Sao Bento do Sul', 'Itauna', 'Sao Mateus', 'Jatai', 'Sao Joao da Boa Vista', 'Lorena', 'Santa Cruz do Capibaribe', 'Sao Sebastiao', 'Tucurui', 'Embu Guacu', 'Sapiranga', 'Para de Minas', 'Campo Mourao', 'Cachoeira do Sul', 'Santo Antonio de Jesus', 'Paranavai', 'Joao Monlevade', 'Matao', 'Bacabal', 'Cacapava', 'Aruja', 'Cruzeiro', 'Patrocinio', 'Tres Rios', 'Bebedouro', 'Sao Cristovao', 'Alfenas', 'Ijui', 'Altamira', 'Paracatu', 'Carpina', 'Iguatu', 'Votuporanga', 'Paragominas', 'Lins', 'Jaboticabal', 'Vicosa', 'Sao Sebastiao do Paraiso', 'Balsas', 'Itatiba', 'Santa Ines', 'Tubarao', 'Pato Branco', 'Paulinia', 'Lajeado', 'Cruz Alta', 'Aquiraz', 'Itacoatiara', 'Gurupi', 'Itaituba', 'Santo Angelo', 'Parintins', 'Curvelo', 'Itabaiana', 'Cacador', 'Ouro Preto', 'Caldas Novas', 'Irece', 'Catalao', 'Tres Coracoes', 'Rio Largo', 'Vilhena', 'Valenca', 'Peruibe', 'Itapeva', 'Cataguases', 'Saquarema', 'Tupa', 'Fernandopolis', 'Senador Canedo', 'Itapira', 'Gravata', 'Valenca', 'Pirassununga', 'Unai', 'Caratinga', 'Itapetinga', 'Mococa', 'Sao Borja', 'Carazinho', 'Santa Rosa', 'Telemaco Borba', 'Guanambi', 'Aracruz', 'Ariquemes', 'Farroupilha', 'Francisco Beltrao', 'Picos', 'Lencois Paulista', 'Arcoverde', 'Braganca', 'Vacaria', 'Cajamar', 'Janauba', 'Vinhedo', 'Formiga', 'Cianorte', 'Nova Vicosa', 'Itapipoca', 'Ponta Pora', 'Estancia', 'Cacoal', 'Sao Gabriel', 'Concordia', 'Pacatuba', 'Viana', 'Sao Pedro da Aldeia', 'Caico', 'Seropedica']
##############class##################### class Board: """ This class defines the board object used in the game""" ##############constructeur################## def __init__(self): #self.boardTab = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0] self.boardDic = {"A1":[0,"A2"],"A2":[0,"A3"],"A3":[0,"A4"],"A4":[0,"C1"],"A5":[0,"A6","C8"],"A6":[0,"Safe","A5"],"B5":[0,"B6","C8"],"B6":[0,"Safe","B5"],"B1":[0,"B2"],"B2":[0,"B3"],"B3":[0,"B4"],"B4":[0,"C1"],"C1":[0,"C2"],"C2":[0,"C3"],"C3":[0,"C4"],"C4":[0,"C5"],"C5":[0,"C6"],"C6":[0,"C7","C5"],"C7":[0,"C8","C6"],"C8":[0,"B5","A5","C7"]} self.specialSquares = ["A4","B4","C4"] def show(self): # function purpose: Pretty print the board # input: none print("""P1 : [A4: %s][A3: %s][A2: %s][A1: %s] [A6: %s][A5: %s] \n [C1: %s][C2: %s][C3: %s][C4: %s][C5: %s][C6: %s][C7: %s][C8: %s] \nP2 : [B4: %s][B3: %s][B2: %s][B1: %s] [B6: %s][B5: %s] """ % (self.boardDic["A4"][0],self.boardDic["A3"][0],self.boardDic["A2"][0],self.boardDic["A1"][0],self.boardDic["A5"][0],self.boardDic["A6"][0],self.boardDic["C1"][0],self.boardDic["C2"][0],self.boardDic["C3"][0],self.boardDic["C4"][0],self.boardDic["C5"][0],self.boardDic["C6"][0],self.boardDic["C7"][0],self.boardDic["C8"][0],self.boardDic["B4"][0],self.boardDic["B3"][0],self.boardDic["B2"][0],self.boardDic["B1"][0],self.boardDic["B5"][0],self.boardDic["B6"][0])) def placePawn(self,player,position): # function purpose: Place the players pawn on the given position on the board, after checking if it's possible # input: - player: player number # - position: label of one of the board squares if( not self.checkIsValidPosition(position)): return "invalid position" if (self.boardDic[position][0] == player ): return "MoveKO" elif (self.boardDic[position][0] == 0 ): self.boardDic[position][0] = player return "MoveOK" else: self.boardDic[position][0] = player return "ReplaceOK" def checkIsValidPosition(self,position): # function purpose: Check if the given position is a valid square on the board # input: - position: Value of the position of which we want to check the existence return position in self.boardDic def removePawn(self,position): # function purpose: Remove pawn from the board for a given board position # input: - position: label of one of the board squares if( not self.checkIsValidPosition(position)): return "invalid position" self.boardDic[position][0] = 0 return "OK" def getSquareState(self,position): # function purpose: returns the state of the square at the given position (0:not used 1: Player1 pawn 2: Player2 pawn) # input: - position: label of one of the board squares if (not self.checkIsValidPosition(position)): return "invalid position" return self.boardDic[position][0] def getNextSquare(self,player,position): # function purpose: returns the square that is next to the given one on the board (going forward) depending on the player # input: - position: label of one of the board squares # - player: player number if (not self.checkIsValidPosition(position)): return "invalid position" if (not 0<player<3): return "invalid player number" if (position == "C8"): if (player == 1): return self.boardDic[position][2] else: return self.boardDic[position][1] else: return self.boardDic[position][1] def getPreviousSquare(self,player,position): # function purpose: returns the square previous to the given one on the board (going forward) depending on the player # input: - position: label of one of the board squares # - player: player number if (not self.checkIsValidPosition(position)): return "invalid position" if (not 0 < player < 3): return "invalid player number" return self.boardDic[position][2] def isSpecialSquare(self,position): # function purpose: Indicates if the given square on the board is a special square # input: - position: label of one of the board squares return position in self.specialSquares
class Board: """ This class defines the board object used in the game""" def __init__(self): self.boardDic = {'A1': [0, 'A2'], 'A2': [0, 'A3'], 'A3': [0, 'A4'], 'A4': [0, 'C1'], 'A5': [0, 'A6', 'C8'], 'A6': [0, 'Safe', 'A5'], 'B5': [0, 'B6', 'C8'], 'B6': [0, 'Safe', 'B5'], 'B1': [0, 'B2'], 'B2': [0, 'B3'], 'B3': [0, 'B4'], 'B4': [0, 'C1'], 'C1': [0, 'C2'], 'C2': [0, 'C3'], 'C3': [0, 'C4'], 'C4': [0, 'C5'], 'C5': [0, 'C6'], 'C6': [0, 'C7', 'C5'], 'C7': [0, 'C8', 'C6'], 'C8': [0, 'B5', 'A5', 'C7']} self.specialSquares = ['A4', 'B4', 'C4'] def show(self): print('P1 : [A4: %s][A3: %s][A2: %s][A1: %s] [A6: %s][A5: %s] \n [C1: %s][C2: %s][C3: %s][C4: %s][C5: %s][C6: %s][C7: %s][C8: %s] \nP2 : [B4: %s][B3: %s][B2: %s][B1: %s] [B6: %s][B5: %s]\n ' % (self.boardDic['A4'][0], self.boardDic['A3'][0], self.boardDic['A2'][0], self.boardDic['A1'][0], self.boardDic['A5'][0], self.boardDic['A6'][0], self.boardDic['C1'][0], self.boardDic['C2'][0], self.boardDic['C3'][0], self.boardDic['C4'][0], self.boardDic['C5'][0], self.boardDic['C6'][0], self.boardDic['C7'][0], self.boardDic['C8'][0], self.boardDic['B4'][0], self.boardDic['B3'][0], self.boardDic['B2'][0], self.boardDic['B1'][0], self.boardDic['B5'][0], self.boardDic['B6'][0])) def place_pawn(self, player, position): if not self.checkIsValidPosition(position): return 'invalid position' if self.boardDic[position][0] == player: return 'MoveKO' elif self.boardDic[position][0] == 0: self.boardDic[position][0] = player return 'MoveOK' else: self.boardDic[position][0] = player return 'ReplaceOK' def check_is_valid_position(self, position): return position in self.boardDic def remove_pawn(self, position): if not self.checkIsValidPosition(position): return 'invalid position' self.boardDic[position][0] = 0 return 'OK' def get_square_state(self, position): if not self.checkIsValidPosition(position): return 'invalid position' return self.boardDic[position][0] def get_next_square(self, player, position): if not self.checkIsValidPosition(position): return 'invalid position' if not 0 < player < 3: return 'invalid player number' if position == 'C8': if player == 1: return self.boardDic[position][2] else: return self.boardDic[position][1] else: return self.boardDic[position][1] def get_previous_square(self, player, position): if not self.checkIsValidPosition(position): return 'invalid position' if not 0 < player < 3: return 'invalid player number' return self.boardDic[position][2] def is_special_square(self, position): return position in self.specialSquares
__all__ = ('BaseIDGenerationStrategy', ) class BaseIDGenerationStrategy: def get_next_id(self, instance): raise NotImplementedError
__all__ = ('BaseIDGenerationStrategy',) class Baseidgenerationstrategy: def get_next_id(self, instance): raise NotImplementedError
# coding=utf-8 n, m = map(int, input().split()) s = [ list(str(input())) for _ in range(n) ] add = [[1, 0],[-1, 0],[0, 1],[0, -1]] ans = 'Yes' for i in range(n): for j in range(m): if s[i][j] == '.': continue mid = False for k in range(4): ii = i + add[k][0] jj = j + add[k][1] if ii >= 0 and jj < m and ii < n and jj >= 0: if s[ii][jj] == '#': mid = True if not mid: ans = 'No';break print(ans)
(n, m) = map(int, input().split()) s = [list(str(input())) for _ in range(n)] add = [[1, 0], [-1, 0], [0, 1], [0, -1]] ans = 'Yes' for i in range(n): for j in range(m): if s[i][j] == '.': continue mid = False for k in range(4): ii = i + add[k][0] jj = j + add[k][1] if ii >= 0 and jj < m and (ii < n) and (jj >= 0): if s[ii][jj] == '#': mid = True if not mid: ans = 'No' break print(ans)
orbits = dict() with open('input.txt') as f: for line in f: center, satellite = line.strip().split(")") orbits[satellite] = center def calc_distance_to_com(orbs, sat): dist = 1 cent = orbs[sat] while cent != "COM": cent = orbs[cent] dist += 1 return dist def find_route_to_com(orbs, sat): route = [orbs[sat]] while route[0] != "COM": route.insert(0, orbs[route[0]]) return route checksum = 0 for satellite in orbits.keys(): checksum += calc_distance_to_com(orbits, satellite) print("checksum = %d" % checksum) route_me = find_route_to_com(orbits, "YOU") route_santa = find_route_to_com(orbits, "SAN") while route_me[0] == route_santa[0]: route_me = route_me[1:] route_santa = route_santa[1:] # Now the tricky piece. We need to count the number of transfers between nodes, # which is N-1 for N nodes. So the total number of transfers to traverse both # branches is (len(route_me) -1) + (len(route_santa) -1). Our branches don't # include their common node, which adds two more transfers, that are required # to switch between branches, thus the total number of transfers is just # len(route_me) + len(route_santa) print("transfers = %d" % (len(route_me) + len(route_santa)))
orbits = dict() with open('input.txt') as f: for line in f: (center, satellite) = line.strip().split(')') orbits[satellite] = center def calc_distance_to_com(orbs, sat): dist = 1 cent = orbs[sat] while cent != 'COM': cent = orbs[cent] dist += 1 return dist def find_route_to_com(orbs, sat): route = [orbs[sat]] while route[0] != 'COM': route.insert(0, orbs[route[0]]) return route checksum = 0 for satellite in orbits.keys(): checksum += calc_distance_to_com(orbits, satellite) print('checksum = %d' % checksum) route_me = find_route_to_com(orbits, 'YOU') route_santa = find_route_to_com(orbits, 'SAN') while route_me[0] == route_santa[0]: route_me = route_me[1:] route_santa = route_santa[1:] print('transfers = %d' % (len(route_me) + len(route_santa)))
class ParseError(Exception) : """Super class for exception classes used in Parsers package. """ def __init__(self, file='', msg=''): self.file = str(file) self.msg = str(msg) def __str__(self): if self.msg : s = self.msg + ': ' else : s = '' return s+self.file
class Parseerror(Exception): """Super class for exception classes used in Parsers package. """ def __init__(self, file='', msg=''): self.file = str(file) self.msg = str(msg) def __str__(self): if self.msg: s = self.msg + ': ' else: s = '' return s + self.file
# Commonly used java test dependencies def java_test_repositories(): native.maven_jar( name = "junit", artifact = "junit:junit:4.12", sha1 = "2973d150c0dc1fefe998f834810d68f278ea58ec", ) native.maven_jar( name = "hamcrest_core", artifact = "org.hamcrest:hamcrest-core:1.3", sha1 = "42a25dc3219429f0e5d060061f71acb49bf010a0", ) native.maven_jar( name = "org_mockito_mockito", artifact = "org.mockito:mockito-all:1.10.19", sha1 = "539df70269cc254a58cccc5d8e43286b4a73bf30", )
def java_test_repositories(): native.maven_jar(name='junit', artifact='junit:junit:4.12', sha1='2973d150c0dc1fefe998f834810d68f278ea58ec') native.maven_jar(name='hamcrest_core', artifact='org.hamcrest:hamcrest-core:1.3', sha1='42a25dc3219429f0e5d060061f71acb49bf010a0') native.maven_jar(name='org_mockito_mockito', artifact='org.mockito:mockito-all:1.10.19', sha1='539df70269cc254a58cccc5d8e43286b4a73bf30')
# # PySNMP MIB module CISCO-VLAN-BRIDGING-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/CISCO-VLAN-BRIDGING-MIB # Produced by pysmi-0.3.4 at Mon Apr 29 18:02:27 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") ValueRangeConstraint, SingleValueConstraint, ConstraintsUnion, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "ValueRangeConstraint", "SingleValueConstraint", "ConstraintsUnion", "ValueSizeConstraint", "ConstraintsIntersection") ciscoMgmt, = mibBuilder.importSymbols("CISCO-SMI", "ciscoMgmt") CiscoPortList, = mibBuilder.importSymbols("CISCO-TC", "CiscoPortList") vtpVlanIndex, = mibBuilder.importSymbols("CISCO-VTP-MIB", "vtpVlanIndex") ModuleCompliance, ObjectGroup, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ModuleCompliance", "ObjectGroup", "NotificationGroup") TimeTicks, Bits, ModuleIdentity, Counter64, Counter32, IpAddress, MibIdentifier, iso, Gauge32, Integer32, ObjectIdentity, NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "TimeTicks", "Bits", "ModuleIdentity", "Counter64", "Counter32", "IpAddress", "MibIdentifier", "iso", "Gauge32", "Integer32", "ObjectIdentity", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Unsigned32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") ciscoVlanBridgingMIB = ModuleIdentity((1, 3, 6, 1, 4, 1, 9, 9, 56)) ciscoVlanBridgingMIB.setRevisions(('2003-08-22 00:00', '1996-09-12 00:00',)) if mibBuilder.loadTexts: ciscoVlanBridgingMIB.setLastUpdated('200308220000Z') if mibBuilder.loadTexts: ciscoVlanBridgingMIB.setOrganization('Cisco Systems, Inc.') ciscoVlanBridgingMIBObjects = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 56, 1)) cvbStp = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 56, 1, 1)) cvbStpTable = MibTable((1, 3, 6, 1, 4, 1, 9, 9, 56, 1, 1, 1), ) if mibBuilder.loadTexts: cvbStpTable.setStatus('current') cvbStpEntry = MibTableRow((1, 3, 6, 1, 4, 1, 9, 9, 56, 1, 1, 1, 1), ).setIndexNames((0, "CISCO-VTP-MIB", "vtpVlanIndex")) if mibBuilder.loadTexts: cvbStpEntry.setStatus('current') cvbStpForwardingMap = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 56, 1, 1, 1, 1, 2), OctetString().subtype(subtypeSpec=ValueSizeConstraint(0, 128))).setMaxAccess("readonly") if mibBuilder.loadTexts: cvbStpForwardingMap.setStatus('deprecated') cvbStpForwardingMap2k = MibTableColumn((1, 3, 6, 1, 4, 1, 9, 9, 56, 1, 1, 1, 1, 3), CiscoPortList()).setMaxAccess("readonly") if mibBuilder.loadTexts: cvbStpForwardingMap2k.setStatus('current') ciscoVlanBridgingMIBConformance = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 56, 3)) ciscoVlanBridgingMIBCompliances = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 56, 3, 1)) ciscoVlanBridgingMIBGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 9, 9, 56, 3, 2)) ciscoVlanBridgingMIBCompliance = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 56, 3, 1, 1)).setObjects(("CISCO-VLAN-BRIDGING-MIB", "ciscoVlanBridgingMIBGroup")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoVlanBridgingMIBCompliance = ciscoVlanBridgingMIBCompliance.setStatus('deprecated') ciscoVlanBridgingMIBCompliance2 = ModuleCompliance((1, 3, 6, 1, 4, 1, 9, 9, 56, 3, 1, 2)).setObjects(("CISCO-VLAN-BRIDGING-MIB", "ciscoVlanBridgingMIBGroup2")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoVlanBridgingMIBCompliance2 = ciscoVlanBridgingMIBCompliance2.setStatus('current') ciscoVlanBridgingMIBGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 56, 3, 2, 1)).setObjects(("CISCO-VLAN-BRIDGING-MIB", "cvbStpForwardingMap")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoVlanBridgingMIBGroup = ciscoVlanBridgingMIBGroup.setStatus('deprecated') ciscoVlanBridgingMIBGroup2 = ObjectGroup((1, 3, 6, 1, 4, 1, 9, 9, 56, 3, 2, 2)).setObjects(("CISCO-VLAN-BRIDGING-MIB", "cvbStpForwardingMap2k")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): ciscoVlanBridgingMIBGroup2 = ciscoVlanBridgingMIBGroup2.setStatus('current') mibBuilder.exportSymbols("CISCO-VLAN-BRIDGING-MIB", PYSNMP_MODULE_ID=ciscoVlanBridgingMIB, ciscoVlanBridgingMIB=ciscoVlanBridgingMIB, cvbStp=cvbStp, ciscoVlanBridgingMIBCompliance=ciscoVlanBridgingMIBCompliance, ciscoVlanBridgingMIBConformance=ciscoVlanBridgingMIBConformance, cvbStpForwardingMap2k=cvbStpForwardingMap2k, ciscoVlanBridgingMIBCompliance2=ciscoVlanBridgingMIBCompliance2, ciscoVlanBridgingMIBGroup2=ciscoVlanBridgingMIBGroup2, cvbStpEntry=cvbStpEntry, cvbStpForwardingMap=cvbStpForwardingMap, ciscoVlanBridgingMIBGroup=ciscoVlanBridgingMIBGroup, ciscoVlanBridgingMIBCompliances=ciscoVlanBridgingMIBCompliances, cvbStpTable=cvbStpTable, ciscoVlanBridgingMIBGroups=ciscoVlanBridgingMIBGroups, ciscoVlanBridgingMIBObjects=ciscoVlanBridgingMIBObjects)
(object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (value_range_constraint, single_value_constraint, constraints_union, value_size_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'ValueRangeConstraint', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueSizeConstraint', 'ConstraintsIntersection') (cisco_mgmt,) = mibBuilder.importSymbols('CISCO-SMI', 'ciscoMgmt') (cisco_port_list,) = mibBuilder.importSymbols('CISCO-TC', 'CiscoPortList') (vtp_vlan_index,) = mibBuilder.importSymbols('CISCO-VTP-MIB', 'vtpVlanIndex') (module_compliance, object_group, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ModuleCompliance', 'ObjectGroup', 'NotificationGroup') (time_ticks, bits, module_identity, counter64, counter32, ip_address, mib_identifier, iso, gauge32, integer32, object_identity, notification_type, mib_scalar, mib_table, mib_table_row, mib_table_column, unsigned32) = mibBuilder.importSymbols('SNMPv2-SMI', 'TimeTicks', 'Bits', 'ModuleIdentity', 'Counter64', 'Counter32', 'IpAddress', 'MibIdentifier', 'iso', 'Gauge32', 'Integer32', 'ObjectIdentity', 'NotificationType', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Unsigned32') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') cisco_vlan_bridging_mib = module_identity((1, 3, 6, 1, 4, 1, 9, 9, 56)) ciscoVlanBridgingMIB.setRevisions(('2003-08-22 00:00', '1996-09-12 00:00')) if mibBuilder.loadTexts: ciscoVlanBridgingMIB.setLastUpdated('200308220000Z') if mibBuilder.loadTexts: ciscoVlanBridgingMIB.setOrganization('Cisco Systems, Inc.') cisco_vlan_bridging_mib_objects = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 56, 1)) cvb_stp = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 56, 1, 1)) cvb_stp_table = mib_table((1, 3, 6, 1, 4, 1, 9, 9, 56, 1, 1, 1)) if mibBuilder.loadTexts: cvbStpTable.setStatus('current') cvb_stp_entry = mib_table_row((1, 3, 6, 1, 4, 1, 9, 9, 56, 1, 1, 1, 1)).setIndexNames((0, 'CISCO-VTP-MIB', 'vtpVlanIndex')) if mibBuilder.loadTexts: cvbStpEntry.setStatus('current') cvb_stp_forwarding_map = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 56, 1, 1, 1, 1, 2), octet_string().subtype(subtypeSpec=value_size_constraint(0, 128))).setMaxAccess('readonly') if mibBuilder.loadTexts: cvbStpForwardingMap.setStatus('deprecated') cvb_stp_forwarding_map2k = mib_table_column((1, 3, 6, 1, 4, 1, 9, 9, 56, 1, 1, 1, 1, 3), cisco_port_list()).setMaxAccess('readonly') if mibBuilder.loadTexts: cvbStpForwardingMap2k.setStatus('current') cisco_vlan_bridging_mib_conformance = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 56, 3)) cisco_vlan_bridging_mib_compliances = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 56, 3, 1)) cisco_vlan_bridging_mib_groups = mib_identifier((1, 3, 6, 1, 4, 1, 9, 9, 56, 3, 2)) cisco_vlan_bridging_mib_compliance = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 56, 3, 1, 1)).setObjects(('CISCO-VLAN-BRIDGING-MIB', 'ciscoVlanBridgingMIBGroup')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_vlan_bridging_mib_compliance = ciscoVlanBridgingMIBCompliance.setStatus('deprecated') cisco_vlan_bridging_mib_compliance2 = module_compliance((1, 3, 6, 1, 4, 1, 9, 9, 56, 3, 1, 2)).setObjects(('CISCO-VLAN-BRIDGING-MIB', 'ciscoVlanBridgingMIBGroup2')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_vlan_bridging_mib_compliance2 = ciscoVlanBridgingMIBCompliance2.setStatus('current') cisco_vlan_bridging_mib_group = object_group((1, 3, 6, 1, 4, 1, 9, 9, 56, 3, 2, 1)).setObjects(('CISCO-VLAN-BRIDGING-MIB', 'cvbStpForwardingMap')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_vlan_bridging_mib_group = ciscoVlanBridgingMIBGroup.setStatus('deprecated') cisco_vlan_bridging_mib_group2 = object_group((1, 3, 6, 1, 4, 1, 9, 9, 56, 3, 2, 2)).setObjects(('CISCO-VLAN-BRIDGING-MIB', 'cvbStpForwardingMap2k')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): cisco_vlan_bridging_mib_group2 = ciscoVlanBridgingMIBGroup2.setStatus('current') mibBuilder.exportSymbols('CISCO-VLAN-BRIDGING-MIB', PYSNMP_MODULE_ID=ciscoVlanBridgingMIB, ciscoVlanBridgingMIB=ciscoVlanBridgingMIB, cvbStp=cvbStp, ciscoVlanBridgingMIBCompliance=ciscoVlanBridgingMIBCompliance, ciscoVlanBridgingMIBConformance=ciscoVlanBridgingMIBConformance, cvbStpForwardingMap2k=cvbStpForwardingMap2k, ciscoVlanBridgingMIBCompliance2=ciscoVlanBridgingMIBCompliance2, ciscoVlanBridgingMIBGroup2=ciscoVlanBridgingMIBGroup2, cvbStpEntry=cvbStpEntry, cvbStpForwardingMap=cvbStpForwardingMap, ciscoVlanBridgingMIBGroup=ciscoVlanBridgingMIBGroup, ciscoVlanBridgingMIBCompliances=ciscoVlanBridgingMIBCompliances, cvbStpTable=cvbStpTable, ciscoVlanBridgingMIBGroups=ciscoVlanBridgingMIBGroups, ciscoVlanBridgingMIBObjects=ciscoVlanBridgingMIBObjects)
def run(): # nombre = input('Escribe tu nombre: ') # for letra in nombre: # print(letra) frase = input('Escribe una frase: ') for c in frase: print(c.upper()) if __name__ == '__main__': run()
def run(): frase = input('Escribe una frase: ') for c in frase: print(c.upper()) if __name__ == '__main__': run()
def choose6(n,k): #computes nCk, the number of combinations n choose k result = 1 for i in range(n): result*=(i+1) for i in range(k): result/=(i+1) for i in range(n-k): result/=(i+1) return result
def choose6(n, k): result = 1 for i in range(n): result *= i + 1 for i in range(k): result /= i + 1 for i in range(n - k): result /= i + 1 return result
class ResultSet(list): """A list like object that holds results from a Unsplash API query.""" class Model(object): def __init__(self, **kwargs): self._repr_values = ["id"] @classmethod def parse(cls, data): """Parse a JSON object into a model instance.""" raise NotImplementedError @classmethod def parse_list(cls, data): """Parse a list of JSON objects into a result set of model instances.""" results = ResultSet() data = data or [] for obj in data: if obj: results.append(cls.parse(obj)) return results def __repr__(self): items = filter(lambda x: x[0] in self._repr_values, vars(self).items()) state = ['%s=%s' % (k, repr(v)) for (k, v) in items] return '%s(%s)' % (self.__class__.__name__, ', '.join(state)) class Photo(Model): @classmethod def parse(cls, data): data = data or {} photo = cls() if data else None for key, value in data.items(): if not value: setattr(photo, key, value) continue if key == "user": user = User.parse(value) setattr(photo, key, user) elif key == "exif": exif = Exif.parse(value) setattr(photo, key, exif) elif key in ["urls", "links"]: link = Link.parse(value) setattr(photo, key, link) elif key == "location": location = Location.parse(value) setattr(photo, key, location) else: setattr(photo, key, value) return photo class Exif(Model): def __init__(self, **kwargs): super(Exif, self).__init__(**kwargs) self._repr_values = ["make", "model"] @classmethod def parse(cls, data): data = data or {} exif = cls() if data else None for key, value in data.items(): setattr(exif, key, value) return exif class Link(Model): def __init__(self, **kwargs): super(Link, self).__init__(**kwargs) self._repr_values = ["html", "raw", "url"] @classmethod def parse(cls, data): data = data or {} link = cls() if data else None for key, value in data.items(): setattr(link, key, value) return link class Location(Model): def __init__(self, **kwargs): super(Location, self).__init__(**kwargs) self._repr_values = ["title"] @classmethod def parse(cls, data): data = data or {} location = cls() if data else None for key, value in data.items(): setattr(location, key, value) return location class User(Model): def __init__(self, **kwargs): super(User, self).__init__(**kwargs) self._repr_values = ["id", "name", "username"] @classmethod def parse(cls, data): data = data or {} user = cls() if data else None for key, value in data.items(): if not value: setattr(user, key, value) continue if key in ["links", "profile_image"]: link = Link.parse(value) setattr(user, key, link) elif key == "photos": photo = Photo.parse_list(value) setattr(user, key, photo) else: setattr(user, key, value) return user class Stat(Model): def __init__(self, **kwargs): super(Stat, self).__init__(**kwargs) self._repr_values = ["total_photos", "photo_downloads"] @classmethod def parse(cls, data): data = data or {} stat = cls() if data else None for key, value in data.items(): if not value: setattr(stat, key, value) continue if key == "links": link = Link.parse(value) setattr(stat, key, link) else: setattr(stat, key, value) return stat class Collection(Model): def __init__(self, **kwargs): super(Collection, self).__init__(**kwargs) self._repr_values = ["id", "title"] @classmethod def parse(cls, data): data = data or {} collection = cls() if data else None for key, value in data.items(): if not value: setattr(collection, key, value) continue if key == "cover_photo": photo = Photo.parse(value) setattr(collection, key, photo) elif key == "user": user = User.parse(value) setattr(collection, key, user) elif key == "links": link = Link.parse(value) setattr(collection, key, link) else: setattr(collection, key, value) return collection
class Resultset(list): """A list like object that holds results from a Unsplash API query.""" class Model(object): def __init__(self, **kwargs): self._repr_values = ['id'] @classmethod def parse(cls, data): """Parse a JSON object into a model instance.""" raise NotImplementedError @classmethod def parse_list(cls, data): """Parse a list of JSON objects into a result set of model instances.""" results = result_set() data = data or [] for obj in data: if obj: results.append(cls.parse(obj)) return results def __repr__(self): items = filter(lambda x: x[0] in self._repr_values, vars(self).items()) state = ['%s=%s' % (k, repr(v)) for (k, v) in items] return '%s(%s)' % (self.__class__.__name__, ', '.join(state)) class Photo(Model): @classmethod def parse(cls, data): data = data or {} photo = cls() if data else None for (key, value) in data.items(): if not value: setattr(photo, key, value) continue if key == 'user': user = User.parse(value) setattr(photo, key, user) elif key == 'exif': exif = Exif.parse(value) setattr(photo, key, exif) elif key in ['urls', 'links']: link = Link.parse(value) setattr(photo, key, link) elif key == 'location': location = Location.parse(value) setattr(photo, key, location) else: setattr(photo, key, value) return photo class Exif(Model): def __init__(self, **kwargs): super(Exif, self).__init__(**kwargs) self._repr_values = ['make', 'model'] @classmethod def parse(cls, data): data = data or {} exif = cls() if data else None for (key, value) in data.items(): setattr(exif, key, value) return exif class Link(Model): def __init__(self, **kwargs): super(Link, self).__init__(**kwargs) self._repr_values = ['html', 'raw', 'url'] @classmethod def parse(cls, data): data = data or {} link = cls() if data else None for (key, value) in data.items(): setattr(link, key, value) return link class Location(Model): def __init__(self, **kwargs): super(Location, self).__init__(**kwargs) self._repr_values = ['title'] @classmethod def parse(cls, data): data = data or {} location = cls() if data else None for (key, value) in data.items(): setattr(location, key, value) return location class User(Model): def __init__(self, **kwargs): super(User, self).__init__(**kwargs) self._repr_values = ['id', 'name', 'username'] @classmethod def parse(cls, data): data = data or {} user = cls() if data else None for (key, value) in data.items(): if not value: setattr(user, key, value) continue if key in ['links', 'profile_image']: link = Link.parse(value) setattr(user, key, link) elif key == 'photos': photo = Photo.parse_list(value) setattr(user, key, photo) else: setattr(user, key, value) return user class Stat(Model): def __init__(self, **kwargs): super(Stat, self).__init__(**kwargs) self._repr_values = ['total_photos', 'photo_downloads'] @classmethod def parse(cls, data): data = data or {} stat = cls() if data else None for (key, value) in data.items(): if not value: setattr(stat, key, value) continue if key == 'links': link = Link.parse(value) setattr(stat, key, link) else: setattr(stat, key, value) return stat class Collection(Model): def __init__(self, **kwargs): super(Collection, self).__init__(**kwargs) self._repr_values = ['id', 'title'] @classmethod def parse(cls, data): data = data or {} collection = cls() if data else None for (key, value) in data.items(): if not value: setattr(collection, key, value) continue if key == 'cover_photo': photo = Photo.parse(value) setattr(collection, key, photo) elif key == 'user': user = User.parse(value) setattr(collection, key, user) elif key == 'links': link = Link.parse(value) setattr(collection, key, link) else: setattr(collection, key, value) return collection
class Rect(object): def __init__(self, cx, cy, width, height, confidence): self.cx = cx self.cy = cy self.width = width self.height = height self.confidence = confidence self.true_confidence = confidence def overlaps(self, other): if abs(self.cx - other.cx) > (self.width + other.width) / 1.5: return False elif abs(self.cy - other.cy) > (self.height + other.height) / 2.0: return False else: return True def distance(self, other): return sum( map( abs, [ self.cx - other.cx, self.cy - other.cy, self.width - other.width, self.height - other.height ] ) ) def intersection(self, other): left = max(self.cx - self.width / 2., other.cx - other.width / 2.) right = min(self.cx + self.width / 2., other.cx + other.width / 2.) width = max(right - left, 0) top = max(self.cy - self.height / 2., other.cy - other.height / 2.) bottom = min(self.cy + self.height / 2., other.cy + other.height / 2.) height = max(bottom - top, 0) return width * height def area(self): return self.height * self.width def union(self, other): return self.area() + other.area() - self.intersection(other) def iou(self, other): return self.intersection(other) / self.union(other) def __eq__(self, other): return ( self.cx == other.cx and self.cy == other.cy and self.width == other.width and self.height == other.height and self.confidence == other.confidence )
class Rect(object): def __init__(self, cx, cy, width, height, confidence): self.cx = cx self.cy = cy self.width = width self.height = height self.confidence = confidence self.true_confidence = confidence def overlaps(self, other): if abs(self.cx - other.cx) > (self.width + other.width) / 1.5: return False elif abs(self.cy - other.cy) > (self.height + other.height) / 2.0: return False else: return True def distance(self, other): return sum(map(abs, [self.cx - other.cx, self.cy - other.cy, self.width - other.width, self.height - other.height])) def intersection(self, other): left = max(self.cx - self.width / 2.0, other.cx - other.width / 2.0) right = min(self.cx + self.width / 2.0, other.cx + other.width / 2.0) width = max(right - left, 0) top = max(self.cy - self.height / 2.0, other.cy - other.height / 2.0) bottom = min(self.cy + self.height / 2.0, other.cy + other.height / 2.0) height = max(bottom - top, 0) return width * height def area(self): return self.height * self.width def union(self, other): return self.area() + other.area() - self.intersection(other) def iou(self, other): return self.intersection(other) / self.union(other) def __eq__(self, other): return self.cx == other.cx and self.cy == other.cy and (self.width == other.width) and (self.height == other.height) and (self.confidence == other.confidence)
class Transformer: def __init__(self, name, allegiance, strength, intelligence, speed, endurance, rank, courage, firepower, skill): """Initialization function for a Transformer.""" self.name = name self.allegiance = allegiance self.strength = strength self.intelligence = intelligence self.speed = speed self.endurance = endurance self.rank = rank self.courage = courage self.firepower = firepower self.skill = skill self.rating = strength + intelligence + speed + endurance + firepower self.alive = True def fight(self, opponent): """Determines, between two transformers, who is the winner based on the following conditions.""" winner = None if (self.name == 'Optimus Prime' or self.name == 'Predaking') and \ (opponent.name == 'Optimus Prime' or opponent.name == 'Predaking'): winner = 'Optoking' elif self.name == 'Optimus Prime' or self.name == 'Predaking': winner = self elif opponent.name == 'Optimus Prime' or opponent.name == 'Predaking': winner = opponent elif self.courage - opponent.courage >= 4 and self.strength - opponent.strength >= 3: winner = self elif opponent.courage - self.courage >= 4 and opponent.strength - self.strength >= 3: winner = opponent elif self.skill - opponent.skill >= 3: winner = self elif opponent.skill - self.skill >= 3: winner = opponent elif self.rating > opponent.rating: winner = self elif self.rating < opponent.rating: winner = opponent else: winner = 'Tie' self.alive = False opponent.alive = False if winner == self: opponent.alive = False elif winner == opponent: self.alive = False return winner
class Transformer: def __init__(self, name, allegiance, strength, intelligence, speed, endurance, rank, courage, firepower, skill): """Initialization function for a Transformer.""" self.name = name self.allegiance = allegiance self.strength = strength self.intelligence = intelligence self.speed = speed self.endurance = endurance self.rank = rank self.courage = courage self.firepower = firepower self.skill = skill self.rating = strength + intelligence + speed + endurance + firepower self.alive = True def fight(self, opponent): """Determines, between two transformers, who is the winner based on the following conditions.""" winner = None if (self.name == 'Optimus Prime' or self.name == 'Predaking') and (opponent.name == 'Optimus Prime' or opponent.name == 'Predaking'): winner = 'Optoking' elif self.name == 'Optimus Prime' or self.name == 'Predaking': winner = self elif opponent.name == 'Optimus Prime' or opponent.name == 'Predaking': winner = opponent elif self.courage - opponent.courage >= 4 and self.strength - opponent.strength >= 3: winner = self elif opponent.courage - self.courage >= 4 and opponent.strength - self.strength >= 3: winner = opponent elif self.skill - opponent.skill >= 3: winner = self elif opponent.skill - self.skill >= 3: winner = opponent elif self.rating > opponent.rating: winner = self elif self.rating < opponent.rating: winner = opponent else: winner = 'Tie' self.alive = False opponent.alive = False if winner == self: opponent.alive = False elif winner == opponent: self.alive = False return winner
def main(request, response): headers = [("Content-Type", "text/plain")] command = request.GET.first("cmd").lower(); test_id = request.GET.first("id") header = request.GET.first("header") if command == "put": request.server.stash.put(test_id, request.headers.get(header, "")) elif command == "get": stashed_header = request.server.stash.take(test_id) if stashed_header is not None: headers.append(("x-request-" + header, stashed_header )) else: response.set_error(400, "Bad Command") return "ERROR: Bad Command!" return headers, ""
def main(request, response): headers = [('Content-Type', 'text/plain')] command = request.GET.first('cmd').lower() test_id = request.GET.first('id') header = request.GET.first('header') if command == 'put': request.server.stash.put(test_id, request.headers.get(header, '')) elif command == 'get': stashed_header = request.server.stash.take(test_id) if stashed_header is not None: headers.append(('x-request-' + header, stashed_header)) else: response.set_error(400, 'Bad Command') return 'ERROR: Bad Command!' return (headers, '')
no_steps = 359 pos = 0 lst = [0] for x in range(1, 50000001): pos += no_steps pos %= len(lst) lst.insert(pos+1, x) pos += 1 print(lst[lst.index(0)+1])
no_steps = 359 pos = 0 lst = [0] for x in range(1, 50000001): pos += no_steps pos %= len(lst) lst.insert(pos + 1, x) pos += 1 print(lst[lst.index(0) + 1])
#!/usr/bin/env python # AUTHOR: jo # DATE: 2019-08-12 # DESCRIPTION: Tuse homework assignment #1. def partitionOnZeroSumAndMax(row): # Ex. Passing in [1,1,0,1] returns [2,0,1]. # max([2,0,1]) -> 2 localSums = [0] for val in row: if val != 0: localSums.append(localSums.pop() + val) else: localSums.append(0) return max(localSums) def getDistanceAndMax(matrix): # Initialize empty array with identical dimensions as input. matrix_distance = [ [None for row in range(len(matrix))] for column in range(len(matrix[0])) ] for row in range(len(matrix)): for column in range(len(matrix[row])): # Top row stays the same, and for any coordinate that's zero. if (row == 0) or (matrix[row][column] == 0): matrix_distance[row][column] = matrix[row][column] else: distance = 0 # Iterate in reverse, from bottom to top. for row_range in range(row, -1, -1): if matrix[row_range][column] == 1: distance += 1 # Being explicit here to handle zero. # elif can be replaced with "else: break" instead. elif matrix[row_range][column] == 0: break matrix_distance[row][column] = distance return {'distance' : matrix_distance, 'max_score': max(partitionOnZeroSumAndMax(row) for row in matrix_distance) } if __name__ == '__main__': snoots = [ [1, 0, 1], [0, 1, 1], [1, 1, 1] ] winkler = [ [1, 0, 0], [1, 1, 1], [0, 1, 0] ] tootSnoots = [1,1,0,1] toodles = [ [1,1,0,1], [1,1,0,1], [1,1,0,1], [1,1,0,1] ] print(getDistanceAndMax(snoots)) print(getDistanceAndMax(winkler)) print(partitionOnZeroSumAndMax(tootSnoots)) print(getDistanceAndMax(toodles))
def partition_on_zero_sum_and_max(row): local_sums = [0] for val in row: if val != 0: localSums.append(localSums.pop() + val) else: localSums.append(0) return max(localSums) def get_distance_and_max(matrix): matrix_distance = [[None for row in range(len(matrix))] for column in range(len(matrix[0]))] for row in range(len(matrix)): for column in range(len(matrix[row])): if row == 0 or matrix[row][column] == 0: matrix_distance[row][column] = matrix[row][column] else: distance = 0 for row_range in range(row, -1, -1): if matrix[row_range][column] == 1: distance += 1 elif matrix[row_range][column] == 0: break matrix_distance[row][column] = distance return {'distance': matrix_distance, 'max_score': max((partition_on_zero_sum_and_max(row) for row in matrix_distance))} if __name__ == '__main__': snoots = [[1, 0, 1], [0, 1, 1], [1, 1, 1]] winkler = [[1, 0, 0], [1, 1, 1], [0, 1, 0]] toot_snoots = [1, 1, 0, 1] toodles = [[1, 1, 0, 1], [1, 1, 0, 1], [1, 1, 0, 1], [1, 1, 0, 1]] print(get_distance_and_max(snoots)) print(get_distance_and_max(winkler)) print(partition_on_zero_sum_and_max(tootSnoots)) print(get_distance_and_max(toodles))
#!/usr/bin/env python2 def main(): n = input('') for i in range(0, n): rows = input('') matrix = [] for j in range(0, rows): matrix.append([int(x) for x in raw_input('').split()]) print(weight(matrix, 0, 0)) def weight(matrix, i, j): #print('weight called with', i, j) if i < len(matrix)-1: return matrix[i][j] + max(weight(matrix, i+1, j), weight(matrix, i+1, j+1)) else: return matrix[i][j] if __name__ == "__main__": main()
def main(): n = input('') for i in range(0, n): rows = input('') matrix = [] for j in range(0, rows): matrix.append([int(x) for x in raw_input('').split()]) print(weight(matrix, 0, 0)) def weight(matrix, i, j): if i < len(matrix) - 1: return matrix[i][j] + max(weight(matrix, i + 1, j), weight(matrix, i + 1, j + 1)) else: return matrix[i][j] if __name__ == '__main__': main()
"""This module consist of API Groups. All the REST APIs are divided into several groups 1) Access 2) General 3) Organization 4) Service 5) Service Action Each group has a set of APIs with their own models and schemas. """
"""This module consist of API Groups. All the REST APIs are divided into several groups 1) Access 2) General 3) Organization 4) Service 5) Service Action Each group has a set of APIs with their own models and schemas. """
codon_protein = { "AUG": "Methionine", "UUU": "Phenylalanine", "UUC": "Phenylalanine", "UUA": "Leucine", "UUG": "Leucine", "UCU": "Serine", "UCG": "Serine", "UCC": "Serine", "UCA": "Serine", "UAU": "Tyrosine", "UAC": "Tyrosine", "UGU": "Cysteine", "UGC": "Cysteine", "UGG": "Tryptophan", "UAA": None, "UAG": None, "UGA": None } def proteins(strand: str): codons = get_codons(strand) result = [] for codon in codons: protein = codon_protein[codon] if protein is None: break if protein not in result: result.append(protein) return result def get_codons(strand): chunk_size = 3 codons = [strand[i:i + chunk_size] for i in range(0, len(strand), chunk_size)] return codons
codon_protein = {'AUG': 'Methionine', 'UUU': 'Phenylalanine', 'UUC': 'Phenylalanine', 'UUA': 'Leucine', 'UUG': 'Leucine', 'UCU': 'Serine', 'UCG': 'Serine', 'UCC': 'Serine', 'UCA': 'Serine', 'UAU': 'Tyrosine', 'UAC': 'Tyrosine', 'UGU': 'Cysteine', 'UGC': 'Cysteine', 'UGG': 'Tryptophan', 'UAA': None, 'UAG': None, 'UGA': None} def proteins(strand: str): codons = get_codons(strand) result = [] for codon in codons: protein = codon_protein[codon] if protein is None: break if protein not in result: result.append(protein) return result def get_codons(strand): chunk_size = 3 codons = [strand[i:i + chunk_size] for i in range(0, len(strand), chunk_size)] return codons
# Copyright 2017-2022 Lawrence Livermore National Security, LLC and other # Hatchet Project Developers. See the top-level LICENSE file for details. # # SPDX-License-Identifier: MIT __version_info__ = ("2022", "1", "0") __version__ = ".".join(__version_info__)
__version_info__ = ('2022', '1', '0') __version__ = '.'.join(__version_info__)
# Time: O(n) # Space: O(1) class Solution(object): # @param {TreeNode} root # @param {TreeNode} p # @param {TreeNode} q # @return {TreeNode} def lowestCommonAncestor(self, root, p, q): s, b = sorted([p.val, q.val]) while not s <= root.val <= b: # Keep searching since root is outside of [s, b]. root = root.left if s <= root.val else root.right # s <= root.val <= b. return root
class Solution(object): def lowest_common_ancestor(self, root, p, q): (s, b) = sorted([p.val, q.val]) while not s <= root.val <= b: root = root.left if s <= root.val else root.right return root
n = int(input()) nsum = 0 for i in range(1, n+1): nsum += i if nsum == 1: print('BOWWOW') elif nsum <= 3: print('WANWAN') else: for i in range(2, n+1): if n % i == 0: print('BOWWOW') break else: print('WANWAN')
n = int(input()) nsum = 0 for i in range(1, n + 1): nsum += i if nsum == 1: print('BOWWOW') elif nsum <= 3: print('WANWAN') else: for i in range(2, n + 1): if n % i == 0: print('BOWWOW') break else: print('WANWAN')
#!/usr/bin/env python3 def find_array_intersection(A, B): ai = 0 bi = 0 ret = [] while ai < len(A) and bi < len(B): if A[ai] < B[bi]: ai += 1 elif A[ai] > B[bi]: bi += 1 else: ret.append(A[ai]) v = A[ai] while ai < len(A) and A[ai] == v: ai += 1 while bi < len(B) and B[bi] == v: bi += 1 return ret A = [1, 2, 3, 4, 4, 5, 7, 8, 10] B = [3, 4, 8, 9, 9, 10, 13] print(find_array_intersection(A, B))
def find_array_intersection(A, B): ai = 0 bi = 0 ret = [] while ai < len(A) and bi < len(B): if A[ai] < B[bi]: ai += 1 elif A[ai] > B[bi]: bi += 1 else: ret.append(A[ai]) v = A[ai] while ai < len(A) and A[ai] == v: ai += 1 while bi < len(B) and B[bi] == v: bi += 1 return ret a = [1, 2, 3, 4, 4, 5, 7, 8, 10] b = [3, 4, 8, 9, 9, 10, 13] print(find_array_intersection(A, B))
""" --- Day 18: Duet --- You discover a tablet containing some strange assembly code labeled simply "Duet". Rather than bother the sound card with it, you decide to run the code yourself. Unfortunately, you don't see any documentation, so you're left to figure out what the instructions mean on your own. It seems like the assembly is meant to operate on a set of registers that are each named with a single letter and that can each hold a single integer. You suppose each register should start with a value of 0. There aren't that many instructions, so it shouldn't be hard to figure out what they do. Here's what you determine: snd X plays a sound with a frequency equal to the value of X. set X Y sets register X to the value of Y. add X Y increases register X by the value of Y. mul X Y sets register X to the result of multiplying the value contained in register X by the value of Y. mod X Y sets register X to the remainder of dividing the value contained in register X by the value of Y (that is, it sets X to the result of X modulo Y). rcv X recovers the frequency of the last sound played, but only when the value of X is not zero. (If it is zero, the command does nothing.) jgz X Y jumps with an offset of the value of Y, but only if the value of X is greater than zero. (An offset of 2 skips the next instruction, an offset of -1 jumps to the previous instruction, and so on.) Many of the instructions can take either a register (a single letter) or a number. The value of a register is the integer it contains; the value of a number is that number. After each jump instruction, the program continues with the instruction to which the jump jumped. After any other instruction, the program continues with the next instruction. Continuing (or jumping) off either end of the program terminates it. For example: set a 1 add a 2 mul a a mod a 5 snd a set a 0 rcv a jgz a -1 set a 1 jgz a -2 The first four instructions set a to 1, add 2 to it, square it, and then set it to itself modulo 5, resulting in a value of 4. Then, a sound with frequency 4 (the value of a) is played. After that, a is set to 0, causing the subsequent rcv and jgz instructions to both be skipped (rcv because a is 0, and jgz because a is not greater than 0). Finally, a is set to 1, causing the next jgz instruction to activate, jumping back two instructions to another jump, which jumps again to the rcv, which ultimately triggers the recover operation. At the time the recover operation is executed, the frequency of the last sound played is 4. What is the value of the recovered frequency (the value of the most recently played sound) the first time a rcv instruction is executed with a non-zero value? --- Part Two --- As you congratulate yourself for a job well done, you notice that the documentation has been on the back of the tablet this entire time. While you actually got most of the instructions correct, there are a few key differences. This assembly code isn't about sound at all - it's meant to be run twice at the same time. Each running copy of the program has its own set of registers and follows the code independently - in fact, the programs don't even necessarily run at the same speed. To coordinate, they use the send (snd) and receive (rcv) instructions: snd X sends the value of X to the other program. These values wait in a queue until that program is ready to receive them. Each program has its own message queue, so a program can never receive a message it sent. rcv X receives the next value and stores it in register X. If no values are in the queue, the program waits for a value to be sent to it. Programs do not continue to the next instruction until they have received a value. Values are received in the order they are sent. Each program also has its own program ID (one 0 and the other 1); the register p should begin with this value. For example: snd 1 snd 2 snd p rcv a rcv b rcv c rcv d Both programs begin by sending three values to the other. Program 0 sends 1, 2, 0; program 1 sends 1, 2, 1. Then, each program receives a value (both 1) and stores it in a, receives another value (both 2) and stores it in b, and then each receives the program ID of the other program (program 0 receives 1; program 1 receives 0) and stores it in c. Each program now sees a different value in its own copy of register c. Finally, both programs try to rcv a fourth time, but no data is waiting for either of them, and they reach a deadlock. When this happens, both programs terminate. It should be noted that it would be equally valid for the programs to run at different speeds; for example, program 0 might have sent all three values and then stopped at the first rcv before program 1 executed even its first instruction. Once both of your programs have terminated (regardless of what caused them to do so), how many times did program 1 send a value? """ def read(): with open('inputs/day18.txt') as fd: return fd.readlines() def parse(lines): l = [] for line in lines: inst, *params = line.strip().split() l.append((inst, params)) return l test_input = """set a 1 add a 2 mul a a mod a 5 snd a set a 0 rcv a jgz a -1 set a 1 jgz a -2""".splitlines() test_input2 = """snd 1 snd 2 snd p rcv a rcv b rcv c rcv d""".splitlines() class Reg(dict): def __missing__(self, key): try: v = int(key) except ValueError: v = 0 self[key] = 0 return v class Register: def __init__(self): self.reg = Reg() self.INSTRUCTIONS = {'snd': self.send, 'set': self.set, 'add': self.add, 'mul': self.mul, 'mod': self.mod, 'rcv': self.recover, 'jgz': self.jump} self.last_played = None self.recovered = None self.instructions = None self.pos = 0 def send(self, reg): self.last_played = self.reg[reg] def set(self, reg, val): self.reg[reg] = self.reg[val] def add(self, reg, val): self.reg[reg] += self.reg[val] def mul(self, reg1, reg2): self.reg[reg1] *= self.reg[reg2] def mod(self, reg, val): self.reg[reg] = self.reg[reg] % self.reg[val] def recover(self, reg): if self.reg[reg] != 0: return self.last_played def jump(self, reg, val): if self.reg[reg] > 0: self.pos += self.reg[val] -1 def operate(self, instructions): self.instructions = instructions self.pos = 0 while True: inst, params = self.instructions[self.pos] r = self.INSTRUCTIONS[inst](*params) if r is not None: return r self.pos += 1 if self.pos < 0 or self.pos >= len(self.instructions): break return self.last_played def test1(): r = Register() assert 4 == r.operate(parse(test_input)) def part1(): r = Register() print(r.operate(parse(read()))) class Register2(Register): def __init__(self, read, write, id, instructions): self.read_queue = read self.write_queue = write self.sends = 0 self.blocked = False super().__init__() self.reg['p'] = id self.instructions = instructions self.ended = False self.waiting = False self.pos = 0 def send(self, reg): self.write_queue.append(self.reg[reg]) self.sends += 1 def recover(self, reg): self.reg[reg] = self.read_queue.pop(0) def operate(self): """Return True if it is ended or blocked""" if self.ended: return True inst, params = self.instructions[self.pos] if inst == 'rcv' and len(self.read_queue) == 0: return True self.INSTRUCTIONS[inst](*params) self.pos += 1 if self.pos < 0 or self.pos >= len(self.instructions): self.ended = True return False def dual(input): d1 = [] d2 = [] r0 = Register2(d1, d2, 0, input) r1 = Register2(d2, d1, 1, input) while True: if r0.operate() and r1.operate(): return r1.sends def test2(): assert 3 == dual(parse(test_input2)) def part2(): print(dual(parse(read()))) if __name__ == '__main__': # test1() # part1() # test2() part2()
""" --- Day 18: Duet --- You discover a tablet containing some strange assembly code labeled simply "Duet". Rather than bother the sound card with it, you decide to run the code yourself. Unfortunately, you don't see any documentation, so you're left to figure out what the instructions mean on your own. It seems like the assembly is meant to operate on a set of registers that are each named with a single letter and that can each hold a single integer. You suppose each register should start with a value of 0. There aren't that many instructions, so it shouldn't be hard to figure out what they do. Here's what you determine: snd X plays a sound with a frequency equal to the value of X. set X Y sets register X to the value of Y. add X Y increases register X by the value of Y. mul X Y sets register X to the result of multiplying the value contained in register X by the value of Y. mod X Y sets register X to the remainder of dividing the value contained in register X by the value of Y (that is, it sets X to the result of X modulo Y). rcv X recovers the frequency of the last sound played, but only when the value of X is not zero. (If it is zero, the command does nothing.) jgz X Y jumps with an offset of the value of Y, but only if the value of X is greater than zero. (An offset of 2 skips the next instruction, an offset of -1 jumps to the previous instruction, and so on.) Many of the instructions can take either a register (a single letter) or a number. The value of a register is the integer it contains; the value of a number is that number. After each jump instruction, the program continues with the instruction to which the jump jumped. After any other instruction, the program continues with the next instruction. Continuing (or jumping) off either end of the program terminates it. For example: set a 1 add a 2 mul a a mod a 5 snd a set a 0 rcv a jgz a -1 set a 1 jgz a -2 The first four instructions set a to 1, add 2 to it, square it, and then set it to itself modulo 5, resulting in a value of 4. Then, a sound with frequency 4 (the value of a) is played. After that, a is set to 0, causing the subsequent rcv and jgz instructions to both be skipped (rcv because a is 0, and jgz because a is not greater than 0). Finally, a is set to 1, causing the next jgz instruction to activate, jumping back two instructions to another jump, which jumps again to the rcv, which ultimately triggers the recover operation. At the time the recover operation is executed, the frequency of the last sound played is 4. What is the value of the recovered frequency (the value of the most recently played sound) the first time a rcv instruction is executed with a non-zero value? --- Part Two --- As you congratulate yourself for a job well done, you notice that the documentation has been on the back of the tablet this entire time. While you actually got most of the instructions correct, there are a few key differences. This assembly code isn't about sound at all - it's meant to be run twice at the same time. Each running copy of the program has its own set of registers and follows the code independently - in fact, the programs don't even necessarily run at the same speed. To coordinate, they use the send (snd) and receive (rcv) instructions: snd X sends the value of X to the other program. These values wait in a queue until that program is ready to receive them. Each program has its own message queue, so a program can never receive a message it sent. rcv X receives the next value and stores it in register X. If no values are in the queue, the program waits for a value to be sent to it. Programs do not continue to the next instruction until they have received a value. Values are received in the order they are sent. Each program also has its own program ID (one 0 and the other 1); the register p should begin with this value. For example: snd 1 snd 2 snd p rcv a rcv b rcv c rcv d Both programs begin by sending three values to the other. Program 0 sends 1, 2, 0; program 1 sends 1, 2, 1. Then, each program receives a value (both 1) and stores it in a, receives another value (both 2) and stores it in b, and then each receives the program ID of the other program (program 0 receives 1; program 1 receives 0) and stores it in c. Each program now sees a different value in its own copy of register c. Finally, both programs try to rcv a fourth time, but no data is waiting for either of them, and they reach a deadlock. When this happens, both programs terminate. It should be noted that it would be equally valid for the programs to run at different speeds; for example, program 0 might have sent all three values and then stopped at the first rcv before program 1 executed even its first instruction. Once both of your programs have terminated (regardless of what caused them to do so), how many times did program 1 send a value? """ def read(): with open('inputs/day18.txt') as fd: return fd.readlines() def parse(lines): l = [] for line in lines: (inst, *params) = line.strip().split() l.append((inst, params)) return l test_input = 'set a 1\nadd a 2\nmul a a\nmod a 5\nsnd a\nset a 0\nrcv a\njgz a -1\nset a 1\njgz a -2'.splitlines() test_input2 = 'snd 1\nsnd 2\nsnd p\nrcv a\nrcv b\nrcv c\nrcv d'.splitlines() class Reg(dict): def __missing__(self, key): try: v = int(key) except ValueError: v = 0 self[key] = 0 return v class Register: def __init__(self): self.reg = reg() self.INSTRUCTIONS = {'snd': self.send, 'set': self.set, 'add': self.add, 'mul': self.mul, 'mod': self.mod, 'rcv': self.recover, 'jgz': self.jump} self.last_played = None self.recovered = None self.instructions = None self.pos = 0 def send(self, reg): self.last_played = self.reg[reg] def set(self, reg, val): self.reg[reg] = self.reg[val] def add(self, reg, val): self.reg[reg] += self.reg[val] def mul(self, reg1, reg2): self.reg[reg1] *= self.reg[reg2] def mod(self, reg, val): self.reg[reg] = self.reg[reg] % self.reg[val] def recover(self, reg): if self.reg[reg] != 0: return self.last_played def jump(self, reg, val): if self.reg[reg] > 0: self.pos += self.reg[val] - 1 def operate(self, instructions): self.instructions = instructions self.pos = 0 while True: (inst, params) = self.instructions[self.pos] r = self.INSTRUCTIONS[inst](*params) if r is not None: return r self.pos += 1 if self.pos < 0 or self.pos >= len(self.instructions): break return self.last_played def test1(): r = register() assert 4 == r.operate(parse(test_input)) def part1(): r = register() print(r.operate(parse(read()))) class Register2(Register): def __init__(self, read, write, id, instructions): self.read_queue = read self.write_queue = write self.sends = 0 self.blocked = False super().__init__() self.reg['p'] = id self.instructions = instructions self.ended = False self.waiting = False self.pos = 0 def send(self, reg): self.write_queue.append(self.reg[reg]) self.sends += 1 def recover(self, reg): self.reg[reg] = self.read_queue.pop(0) def operate(self): """Return True if it is ended or blocked""" if self.ended: return True (inst, params) = self.instructions[self.pos] if inst == 'rcv' and len(self.read_queue) == 0: return True self.INSTRUCTIONS[inst](*params) self.pos += 1 if self.pos < 0 or self.pos >= len(self.instructions): self.ended = True return False def dual(input): d1 = [] d2 = [] r0 = register2(d1, d2, 0, input) r1 = register2(d2, d1, 1, input) while True: if r0.operate() and r1.operate(): return r1.sends def test2(): assert 3 == dual(parse(test_input2)) def part2(): print(dual(parse(read()))) if __name__ == '__main__': part2()
def do_stuff(fn, lhs, rhs): return fn(lhs, rhs) def add(lhs, rhs): return lhs + rhs def multiply(lhs, rhs): return lhs * rhs def exponent(lhs, rhs): return lhs ** rhs print(do_stuff(add, 2, 3)) print(do_stuff(multiply, 2, 3)) print(do_stuff(exponent, 2, 3))
def do_stuff(fn, lhs, rhs): return fn(lhs, rhs) def add(lhs, rhs): return lhs + rhs def multiply(lhs, rhs): return lhs * rhs def exponent(lhs, rhs): return lhs ** rhs print(do_stuff(add, 2, 3)) print(do_stuff(multiply, 2, 3)) print(do_stuff(exponent, 2, 3))
# A tuple operates like a list but it's initial values can't be modified # Tuples are declared using the () # Use case examples of using Tuple - Dates of the week, Months of the Year, Hours of the clock # we can create a tuple like this... monthsOfTheYear = ("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec") # Prints all the items in the tuple print(monthsOfTheYear) # prints an item in the tuple print(monthsOfTheYear[0]) print(monthsOfTheYear[:3]) # If we try to run the code below it will error # This is because we are change a value in the tuple, which is not allowed! # monthsOfTheYear[0] = "January" # Other operations we can do with tuples # find an item in the tuple myTuple = ('Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun') print(len(myTuple)) print(sorted(myTuple)) names = ['John', 'Lamin', 'Vicky', 'Jasmine'] print(names * 3)
months_of_the_year = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec') print(monthsOfTheYear) print(monthsOfTheYear[0]) print(monthsOfTheYear[:3]) my_tuple = ('Mon', 'Tue', 'Wed', 'Thurs', 'Fri', 'Sat', 'Sun') print(len(myTuple)) print(sorted(myTuple)) names = ['John', 'Lamin', 'Vicky', 'Jasmine'] print(names * 3)
# class Solution: # def lengthOfLIS(self, nums): # """ # :type nums: List[int] # :rtype: int # """ # O(n^2) complexity # if not nums: # return 0 # n = len(nums) # aux = [1] * n # for i in range(n): # for j in range(i): # if (nums[j] < nums[i] and aux[i] < aux[j] + 1): # aux[i] = aux[j] + 1 # return max(aux) class Solution: def lengthOfLIS(self, nums): ''' O(nlogn) Binary Search+Greedy ''' def binarySearch(arr, target): ''' find the position of this num ''' low = 0 high = len(arr) while (low < high): mid = (low + high) // 2 if arr[mid] == target: return mid if arr[mid] < target: low = mid+1 else: high = mid if low == len(arr): return low-1 return low if not nums: return 0 sequence = [nums[0]] for num in nums: if num < sequence[0]: sequence[0] = num elif num > sequence[-1]: sequence.append(num) else: sequence[binarySearch(sequence, num)] = num return len(sequence)
class Solution: def length_of_lis(self, nums): """ O(nlogn) Binary Search+Greedy """ def binary_search(arr, target): """ find the position of this num """ low = 0 high = len(arr) while low < high: mid = (low + high) // 2 if arr[mid] == target: return mid if arr[mid] < target: low = mid + 1 else: high = mid if low == len(arr): return low - 1 return low if not nums: return 0 sequence = [nums[0]] for num in nums: if num < sequence[0]: sequence[0] = num elif num > sequence[-1]: sequence.append(num) else: sequence[binary_search(sequence, num)] = num return len(sequence)
def solve(array): even = [] odd = [] for i in range(len(array)): if array[i] % 2 == 0: even.append(i) else: odd.append(i) if even: return f"1\n{even[-1] + 1}" if len(odd) > 1: return f"2\n{odd[-1] + 1} {odd[-2] + 1}" else: return "-1" def main(): t = int(input()) for _ in range(t): __ = int(input()) array = [int(x) for x in input().split(' ')] print(solve(array)) main()
def solve(array): even = [] odd = [] for i in range(len(array)): if array[i] % 2 == 0: even.append(i) else: odd.append(i) if even: return f'1\n{even[-1] + 1}' if len(odd) > 1: return f'2\n{odd[-1] + 1} {odd[-2] + 1}' else: return '-1' def main(): t = int(input()) for _ in range(t): __ = int(input()) array = [int(x) for x in input().split(' ')] print(solve(array)) main()
# These constants can be set by the external UI-layer process, don't change them manually is_ui_process = False execution_id = '' task_id = '' executable_name = 'insomniac' do_location_permission_dialog_checks = True # no need in these checks if location permission is denied beforehand def callback(profile_name): pass hardban_detected_callback = callback softban_detected_callback = callback def is_insomniac(): return execution_id == ''
is_ui_process = False execution_id = '' task_id = '' executable_name = 'insomniac' do_location_permission_dialog_checks = True def callback(profile_name): pass hardban_detected_callback = callback softban_detected_callback = callback def is_insomniac(): return execution_id == ''
defaults = ''' const vec4 light = vec4(4.0, 3.0, 10.0, 0.0); const vec4 eye = vec4(4.0, 3.0, 2.0, 0.0); const mat4 mvp = mat4( -0.8147971034049988, -0.7172931432723999, -0.7429299354553223, -0.7427813410758972, 1.0863960981369019, -0.5379698276519775, -0.5571974515914917, -0.5570859909057617, 0.0, 2.2415409088134766, -0.37146496772766113, -0.3713906705379486, 0.0, 0.0, 5.186222076416016, 5.385164737701416 ); '''
defaults = '\n const vec4 light = vec4(4.0, 3.0, 10.0, 0.0);\n const vec4 eye = vec4(4.0, 3.0, 2.0, 0.0);\n const mat4 mvp = mat4(\n -0.8147971034049988, -0.7172931432723999, -0.7429299354553223, -0.7427813410758972,\n 1.0863960981369019, -0.5379698276519775, -0.5571974515914917, -0.5570859909057617,\n 0.0, 2.2415409088134766, -0.37146496772766113, -0.3713906705379486,\n 0.0, 0.0, 5.186222076416016, 5.385164737701416\n );\n'
class OutOfService(Exception): def __init__(self,Note:str=""): pass class InternalError(Exception): def __init__(self,Note:str=""): pass class NothingFoundError(Exception): def __init__(self,Note:str=""): pass class DummyError(Exception): def __init__(self,Note:str=""): pass
class Outofservice(Exception): def __init__(self, Note: str=''): pass class Internalerror(Exception): def __init__(self, Note: str=''): pass class Nothingfounderror(Exception): def __init__(self, Note: str=''): pass class Dummyerror(Exception): def __init__(self, Note: str=''): pass
"""Cayley 2020, Problem 20""" def is_divisible(n, d): return (n % d) == 0 def solutions(): a = range(1, 101) b = range(101, 206) return [(m, n) for m in a for n in b if is_divisible(3**m + 7**n, 10)] s = solutions() a = len(s) print(f'Answer = {a}')
"""Cayley 2020, Problem 20""" def is_divisible(n, d): return n % d == 0 def solutions(): a = range(1, 101) b = range(101, 206) return [(m, n) for m in a for n in b if is_divisible(3 ** m + 7 ** n, 10)] s = solutions() a = len(s) print(f'Answer = {a}')
a = [1, 4, 5, 7, 19, 24] b = [4, 6, 7, 18, 24, 134] i = 0 j = 0 ans = [] while i < len(a) and j < len(b): if a[i] == b[j]: ans.append(a[i]) i += 1 j += 1 elif a[i] < b[j]: i += 1 else: j += 1 print(*ans)
a = [1, 4, 5, 7, 19, 24] b = [4, 6, 7, 18, 24, 134] i = 0 j = 0 ans = [] while i < len(a) and j < len(b): if a[i] == b[j]: ans.append(a[i]) i += 1 j += 1 elif a[i] < b[j]: i += 1 else: j += 1 print(*ans)
class Node: def __init__(self, value): self.value = value self.next = None class Queue(object): def __init__(self, size): self.queue = [] self.size = size def enqueue(self, value): '''This function adds an value to the rear end of the queue ''' if(self.isFull() != True): self.queue.insert(0, value) else: print('Queue is Full!') def dequeue(self): ''' This function removes an item from the front end of the queue ''' if(self.isEmpty() != True): return self.queue.pop() else: print('Queue is Empty!') def peek(self): ''' This function helps to see the first element at the fron end of the queue ''' if(self.isEmpty() != True): return self.queue[-1] else: print('Queue is Empty!') def isEmpty(self): ''' This function checks if the queue is empty ''' return self.queue == [] def isFull(self): ''' This function checks if the queue is full ''' return len(self.queue) == self.size def __str__(self): myString = ' '.join(str(i) for i in self.queue) return myString if __name__ == '__main__': myQueue = Queue(10) myQueue.enqueue(4) myQueue.enqueue(5) myQueue.enqueue(6) print(myQueue) myQueue.enqueue(1) myQueue.enqueue(2) myQueue.enqueue(3) print(myQueue) myQueue.dequeue() print(myQueue)
class Node: def __init__(self, value): self.value = value self.next = None class Queue(object): def __init__(self, size): self.queue = [] self.size = size def enqueue(self, value): """This function adds an value to the rear end of the queue """ if self.isFull() != True: self.queue.insert(0, value) else: print('Queue is Full!') def dequeue(self): """ This function removes an item from the front end of the queue """ if self.isEmpty() != True: return self.queue.pop() else: print('Queue is Empty!') def peek(self): """ This function helps to see the first element at the fron end of the queue """ if self.isEmpty() != True: return self.queue[-1] else: print('Queue is Empty!') def is_empty(self): """ This function checks if the queue is empty """ return self.queue == [] def is_full(self): """ This function checks if the queue is full """ return len(self.queue) == self.size def __str__(self): my_string = ' '.join((str(i) for i in self.queue)) return myString if __name__ == '__main__': my_queue = queue(10) myQueue.enqueue(4) myQueue.enqueue(5) myQueue.enqueue(6) print(myQueue) myQueue.enqueue(1) myQueue.enqueue(2) myQueue.enqueue(3) print(myQueue) myQueue.dequeue() print(myQueue)
bill_board = list(map(int, input().split())) tarp = list(map(int, input().split())) xOverlap = max(min(bill_board[2], tarp[2]) - max(bill_board[0], tarp[0]), 0) yOverlap = max(min(bill_board[3], tarp[3]) - max(bill_board[1], tarp[1]), 0) if xOverlap == 0 or yOverlap == 0: print((bill_board[2] - bill_board[0]) * (bill_board[3] - bill_board[1])) exit() if xOverlap >= bill_board[2] - bill_board[0] and yOverlap >= bill_board[3] - bill_board[1]: print(0) exit() if xOverlap < bill_board[2] - bill_board[0] and yOverlap < bill_board[3] - bill_board[1]: print((bill_board[2] - bill_board[0])*(bill_board[3]-bill_board[1])) elif xOverlap >= bill_board[2] - bill_board[0] and yOverlap < bill_board[3] - bill_board[1]: print(xOverlap*(bill_board[3]-bill_board[1] - yOverlap)) elif yOverlap >= bill_board[3] - bill_board[1] and xOverlap < bill_board[2] - bill_board[0]: print(yOverlap*(bill_board[2] - bill_board[0] - xOverlap)) else: print((bill_board[2] - bill_board[0]) * (bill_board[3] - bill_board[1]))
bill_board = list(map(int, input().split())) tarp = list(map(int, input().split())) x_overlap = max(min(bill_board[2], tarp[2]) - max(bill_board[0], tarp[0]), 0) y_overlap = max(min(bill_board[3], tarp[3]) - max(bill_board[1], tarp[1]), 0) if xOverlap == 0 or yOverlap == 0: print((bill_board[2] - bill_board[0]) * (bill_board[3] - bill_board[1])) exit() if xOverlap >= bill_board[2] - bill_board[0] and yOverlap >= bill_board[3] - bill_board[1]: print(0) exit() if xOverlap < bill_board[2] - bill_board[0] and yOverlap < bill_board[3] - bill_board[1]: print((bill_board[2] - bill_board[0]) * (bill_board[3] - bill_board[1])) elif xOverlap >= bill_board[2] - bill_board[0] and yOverlap < bill_board[3] - bill_board[1]: print(xOverlap * (bill_board[3] - bill_board[1] - yOverlap)) elif yOverlap >= bill_board[3] - bill_board[1] and xOverlap < bill_board[2] - bill_board[0]: print(yOverlap * (bill_board[2] - bill_board[0] - xOverlap)) else: print((bill_board[2] - bill_board[0]) * (bill_board[3] - bill_board[1]))
""" --- Day 21: RPG Simulator 20XX --- Little Henry Case got a new video game for Christmas. It's an RPG, and he's stuck on a boss. He needs to know what equipment to buy at the shop. He hands you the controller. In this game, the player (you) and the enemy (the boss) take turns attacking. The player always goes first. Each attack reduces the opponent's hit points by at least 1. The first character at or below 0 hit points loses. Damage dealt by an attacker each turn is equal to the attacker's damage score minus the defender's armor score. An attacker always does at least 1 damage. So, if the attacker has a damage score of 8, and the defender has an armor score of 3, the defender loses 5 hit points. If the defender had an armor score of 300, the defender would still lose 1 hit point. Your damage score and armor score both start at zero. They can be increased by buying items in exchange for gold. You start with no items and have as much gold as you need. Your total damage or armor is equal to the sum of those stats from all of your items. You have 100 hit points. Here is what the item shop is selling: Weapons: Cost Damage Armor Dagger 8 4 0 Shortsword 10 5 0 Warhammer 25 6 0 Longsword 40 7 0 Greataxe 74 8 0 Armor: Cost Damage Armor Leather 13 0 1 Chainmail 31 0 2 Splintmail 53 0 3 Bandedmail 75 0 4 Platemail 102 0 5 Rings: Cost Damage Armor Damage +1 25 1 0 Damage +2 50 2 0 Damage +3 100 3 0 Defense +1 20 0 1 Defense +2 40 0 2 Defense +3 80 0 3 You must buy exactly one weapon; no dual-wielding. Armor is optional, but you can't use more than one. You can buy 0-2 rings (at most one for each hand). You must use any items you buy. The shop only has one of each item, so you can't buy, for example, two rings of Damage +3. For example, suppose you have 8 hit points, 5 damage, and 5 armor, and that the boss has 12 hit points, 7 damage, and 2 armor: The player deals 5-2 = 3 damage; the boss goes down to 9 hit points. The boss deals 7-5 = 2 damage; the player goes down to 6 hit points. The player deals 5-2 = 3 damage; the boss goes down to 6 hit points. The boss deals 7-5 = 2 damage; the player goes down to 4 hit points. The player deals 5-2 = 3 damage; the boss goes down to 3 hit points. The boss deals 7-5 = 2 damage; the player goes down to 2 hit points. The player deals 5-2 = 3 damage; the boss goes down to 0 hit points. In this scenario, the player wins! (Barely.) You have 100 hit points. The boss's actual stats are in your puzzle input. What is the least amount of gold you can spend and still win the fight? Your puzzle answer was 121. --- Part Two --- Turns out the shopkeeper is working with the boss, and can persuade you to buy whatever items he wants. The other rules still apply, and he still only has one of each item. What is the most amount of gold you can spend and still lose the fight? Your puzzle answer was 201. """ class Character: def __init__(self, hit_points, damage, armor, inventory_cost=0): self.hit_points = hit_points self.damage = damage self.armor = armor self.inventory_cost = inventory_cost def attack(self, other_character): damage = self.damage - other_character.armor other_character.hit_points -= damage if damage >= 1 else 1 return self.is_alive and other_character.is_alive @property def is_alive(self): return self.hit_points > 0 def encounter(character1, character2): both_live = character1.attack(character2) if both_live: both_live = character2.attack(character1) if not both_live: return character1 if character1.is_alive else character2 class Inventory: def __init__(self, cost, damage, armor): self.cost = cost self.damage = damage self.armor = armor weapons = [ Inventory(cost, damage, 0) for cost, damage in [ (8, 4), (10, 5), (25, 6), (40, 7), (74, 8) ] ] armors = [ Inventory(cost, 0, armor) for cost, armor in [ (0, 0), (13, 1), (31, 2), (53, 3), (75, 4), (102, 5) ] ] rings = [ Inventory(cost, damage, armor) for cost, damage, armor in [ (0, 0, 0), (0, 0, 0), (25, 1, 0), (50, 2, 0), (100, 3, 0), (20, 0, 1), (40, 0, 2), (80, 0, 3) ] ] def character_variant(hit_points): for weapon in weapons: for armor in armors: for left_hand_ring in rings: for right_hand_ring in [ring for ring in rings if ring != left_hand_ring]: equipment = [weapon, armor, left_hand_ring, right_hand_ring] yield Character( hit_points=hit_points, damage=sum(e.damage for e in equipment), armor=sum(e.armor for e in equipment), inventory_cost=sum(e.cost for e in equipment)) def simulate_battle(character1, character2): winner = None while winner is None: winner = encounter(character1, character2) return winner def find_winners(boss_stats, is_player_winner=True): for player in character_variant(100): boss = Character(**boss_stats) winner = simulate_battle(player, boss) expected_winner = player if is_player_winner else boss if winner == expected_winner: yield player def find_cheapest_winning_inventory(victors): return min(victor.inventory_cost for victor in victors) def find_most_expensive_losing_inventory(losers): return max(loser.inventory_cost for loser in losers) if __name__ == "__main__": boss_stats = { "hit_points": 103, "damage": 9, "armor": 2 } player_victors = find_winners(boss_stats, is_player_winner=True) player_losers = find_winners(boss_stats, is_player_winner=False) print("Cheapest inventory: {}".format(find_cheapest_winning_inventory(player_victors))) print("Most expensive losing inventory: {}".format(find_most_expensive_losing_inventory(player_losers)))
""" --- Day 21: RPG Simulator 20XX --- Little Henry Case got a new video game for Christmas. It's an RPG, and he's stuck on a boss. He needs to know what equipment to buy at the shop. He hands you the controller. In this game, the player (you) and the enemy (the boss) take turns attacking. The player always goes first. Each attack reduces the opponent's hit points by at least 1. The first character at or below 0 hit points loses. Damage dealt by an attacker each turn is equal to the attacker's damage score minus the defender's armor score. An attacker always does at least 1 damage. So, if the attacker has a damage score of 8, and the defender has an armor score of 3, the defender loses 5 hit points. If the defender had an armor score of 300, the defender would still lose 1 hit point. Your damage score and armor score both start at zero. They can be increased by buying items in exchange for gold. You start with no items and have as much gold as you need. Your total damage or armor is equal to the sum of those stats from all of your items. You have 100 hit points. Here is what the item shop is selling: Weapons: Cost Damage Armor Dagger 8 4 0 Shortsword 10 5 0 Warhammer 25 6 0 Longsword 40 7 0 Greataxe 74 8 0 Armor: Cost Damage Armor Leather 13 0 1 Chainmail 31 0 2 Splintmail 53 0 3 Bandedmail 75 0 4 Platemail 102 0 5 Rings: Cost Damage Armor Damage +1 25 1 0 Damage +2 50 2 0 Damage +3 100 3 0 Defense +1 20 0 1 Defense +2 40 0 2 Defense +3 80 0 3 You must buy exactly one weapon; no dual-wielding. Armor is optional, but you can't use more than one. You can buy 0-2 rings (at most one for each hand). You must use any items you buy. The shop only has one of each item, so you can't buy, for example, two rings of Damage +3. For example, suppose you have 8 hit points, 5 damage, and 5 armor, and that the boss has 12 hit points, 7 damage, and 2 armor: The player deals 5-2 = 3 damage; the boss goes down to 9 hit points. The boss deals 7-5 = 2 damage; the player goes down to 6 hit points. The player deals 5-2 = 3 damage; the boss goes down to 6 hit points. The boss deals 7-5 = 2 damage; the player goes down to 4 hit points. The player deals 5-2 = 3 damage; the boss goes down to 3 hit points. The boss deals 7-5 = 2 damage; the player goes down to 2 hit points. The player deals 5-2 = 3 damage; the boss goes down to 0 hit points. In this scenario, the player wins! (Barely.) You have 100 hit points. The boss's actual stats are in your puzzle input. What is the least amount of gold you can spend and still win the fight? Your puzzle answer was 121. --- Part Two --- Turns out the shopkeeper is working with the boss, and can persuade you to buy whatever items he wants. The other rules still apply, and he still only has one of each item. What is the most amount of gold you can spend and still lose the fight? Your puzzle answer was 201. """ class Character: def __init__(self, hit_points, damage, armor, inventory_cost=0): self.hit_points = hit_points self.damage = damage self.armor = armor self.inventory_cost = inventory_cost def attack(self, other_character): damage = self.damage - other_character.armor other_character.hit_points -= damage if damage >= 1 else 1 return self.is_alive and other_character.is_alive @property def is_alive(self): return self.hit_points > 0 def encounter(character1, character2): both_live = character1.attack(character2) if both_live: both_live = character2.attack(character1) if not both_live: return character1 if character1.is_alive else character2 class Inventory: def __init__(self, cost, damage, armor): self.cost = cost self.damage = damage self.armor = armor weapons = [inventory(cost, damage, 0) for (cost, damage) in [(8, 4), (10, 5), (25, 6), (40, 7), (74, 8)]] armors = [inventory(cost, 0, armor) for (cost, armor) in [(0, 0), (13, 1), (31, 2), (53, 3), (75, 4), (102, 5)]] rings = [inventory(cost, damage, armor) for (cost, damage, armor) in [(0, 0, 0), (0, 0, 0), (25, 1, 0), (50, 2, 0), (100, 3, 0), (20, 0, 1), (40, 0, 2), (80, 0, 3)]] def character_variant(hit_points): for weapon in weapons: for armor in armors: for left_hand_ring in rings: for right_hand_ring in [ring for ring in rings if ring != left_hand_ring]: equipment = [weapon, armor, left_hand_ring, right_hand_ring] yield character(hit_points=hit_points, damage=sum((e.damage for e in equipment)), armor=sum((e.armor for e in equipment)), inventory_cost=sum((e.cost for e in equipment))) def simulate_battle(character1, character2): winner = None while winner is None: winner = encounter(character1, character2) return winner def find_winners(boss_stats, is_player_winner=True): for player in character_variant(100): boss = character(**boss_stats) winner = simulate_battle(player, boss) expected_winner = player if is_player_winner else boss if winner == expected_winner: yield player def find_cheapest_winning_inventory(victors): return min((victor.inventory_cost for victor in victors)) def find_most_expensive_losing_inventory(losers): return max((loser.inventory_cost for loser in losers)) if __name__ == '__main__': boss_stats = {'hit_points': 103, 'damage': 9, 'armor': 2} player_victors = find_winners(boss_stats, is_player_winner=True) player_losers = find_winners(boss_stats, is_player_winner=False) print('Cheapest inventory: {}'.format(find_cheapest_winning_inventory(player_victors))) print('Most expensive losing inventory: {}'.format(find_most_expensive_losing_inventory(player_losers)))
''' Edges in a block diagram computational graph. The edges themselves don't have direction, but the ports that they attach to may. ''' class WireConnection: pass class NamedConnection(WireConnection): def __init__(self, target_uid: int, target_port: str): self.target_uid = target_uid self.target_port = target_port def __str__(self): return f'NamedConnection(id={self.target_uid}, port={self.target_port})' class IdentConnection(WireConnection): def __init__(self, target_uid: int): self.target_uid = target_uid def __str__(self): return f'IdentConnection(id={self.target_uid})' class Wire: ''' Wires in TIA's S7 XML format can have more than two terminals, but we always decompose them into a series of two terminal blocks. ''' def __init__(self, a: WireConnection, b: WireConnection): self.a = a self.b = b
""" Edges in a block diagram computational graph. The edges themselves don't have direction, but the ports that they attach to may. """ class Wireconnection: pass class Namedconnection(WireConnection): def __init__(self, target_uid: int, target_port: str): self.target_uid = target_uid self.target_port = target_port def __str__(self): return f'NamedConnection(id={self.target_uid}, port={self.target_port})' class Identconnection(WireConnection): def __init__(self, target_uid: int): self.target_uid = target_uid def __str__(self): return f'IdentConnection(id={self.target_uid})' class Wire: """ Wires in TIA's S7 XML format can have more than two terminals, but we always decompose them into a series of two terminal blocks. """ def __init__(self, a: WireConnection, b: WireConnection): self.a = a self.b = b
RADIO_ENABLED = ":white_check_mark: **Radio enabled**" RADIO_DISABLED = ":x: **Radio disabled**" SKIPPED = ":fast_forward: **Skipped** :thumbsup:" NO_MATCH = ":x: **No matches**" SEARCHING = ":trumpet: **Searching** :mag_right:" PAUSE = "**Paused** :pause_button:" STOP = "**Stopped** :stop_button:" LOOP_ENABLED = "**Loop enabled**" LOOP_DISABLED = "**Loop disabled**" RESUME = "**Resumed**" SHUFFLE = "**Playlist shuffled**" CONNECT_TO_CHANNEL = ":x: **Please connect to a voice channel**" WRONG_CHANNEL = ":x: **You need to be in the same voice channel as HalvaBot to use this command**" CURRENT = "**Now playing** :notes:" NO_CURRENT = "**No current songs**" START_PLAYING = "**Playing** :notes: `{song_name}` - Now!" ENQUEUE = "`{song_name}` - **added to queue!**"
radio_enabled = ':white_check_mark: **Radio enabled**' radio_disabled = ':x: **Radio disabled**' skipped = ':fast_forward: **Skipped** :thumbsup:' no_match = ':x: **No matches**' searching = ':trumpet: **Searching** :mag_right:' pause = '**Paused** :pause_button:' stop = '**Stopped** :stop_button:' loop_enabled = '**Loop enabled**' loop_disabled = '**Loop disabled**' resume = '**Resumed**' shuffle = '**Playlist shuffled**' connect_to_channel = ':x: **Please connect to a voice channel**' wrong_channel = ':x: **You need to be in the same voice channel as HalvaBot to use this command**' current = '**Now playing** :notes:' no_current = '**No current songs**' start_playing = '**Playing** :notes: `{song_name}` - Now!' enqueue = '`{song_name}` - **added to queue!**'
def leiaInt(msg): while True: try: n = int(input(msg)) except (ValueError, TypeError): print('Erro: Por favor, digite um numero valido') continue except (KeyboardInterrupt): print('Entrada interromepida pelo usuario') return 0 else: return n def leiaFloat(msg): while True: try: n = float(input(msg)) except (ValueError, TypeError): print('Erro: Por favor, digite um numero valido') continue except (KeyboardInterrupt): print('Entrada interromepida pelo usuario') return 0 else: return n num1 = leiaInt('digite um numero inteiro: ') num2 = leiaFloat('digite um numero real: ') print(num1, num2 )
def leia_int(msg): while True: try: n = int(input(msg)) except (ValueError, TypeError): print('Erro: Por favor, digite um numero valido') continue except KeyboardInterrupt: print('Entrada interromepida pelo usuario') return 0 else: return n def leia_float(msg): while True: try: n = float(input(msg)) except (ValueError, TypeError): print('Erro: Por favor, digite um numero valido') continue except KeyboardInterrupt: print('Entrada interromepida pelo usuario') return 0 else: return n num1 = leia_int('digite um numero inteiro: ') num2 = leia_float('digite um numero real: ') print(num1, num2)
#leia um numero inteiro e #imprima a soma do sucessor de seu triplo com #o antecessor de seu dobro num=int(input("Informe um numero: ")) valor=((num*3)+1)+((num*2)-1) print(f"A soma do sucessor de seu triplo com o antecessor de seu dobro eh {valor}")
num = int(input('Informe um numero: ')) valor = num * 3 + 1 + (num * 2 - 1) print(f'A soma do sucessor de seu triplo com o antecessor de seu dobro eh {valor}')
""" [Weekly #22] Machine Learning https://www.reddit.com/r/dailyprogrammer/comments/3206mk/weekly_22_machine_learning/ # [](#WeeklyIcon) Asimov would be proud! [Machine learning](http://en.wikipedia.org/wiki/Machine_learning) is a diverse field spanning from optimization and data classification, to computer vision and pattern recognition. Modern algorithms for detecting spam email use machine learning to react to developing types of spam and spot them quicker than people could! Techniques include evolutionary programming and genetic algorithms, and models such as [artificial neural networks](http://en.wikipedia.org/wiki/Artificial_neural_network). Do you work in any of these fields, or study them in academics? Do you know something about them that's interesting, or have any cool resources or videos to share? Show them to the world! Libraries like [OpenCV](http://en.wikipedia.org/wiki/OpenCV) (available [here](http://opencv.org/)) use machine learning to some extent, in order to adapt to new situations. The United Kingdom makes extensive use of [automatic number plate recognition](http://en.wikipedia.org/wiki/Police-enforced_ANPR_in_the_UK) on speed cameras, which is a subset of optical character recognition that needs to work in high speeds and poor visibility. Of course, there's also /r/MachineLearning if you want to check out even more. They have a [simple questions thread](http://www.reddit.com/r/MachineLearning/comments/2xopnm/mondays_simple_questions_thread_20150302/) if you want some reading material! *This post was inspired by [this challenge submission](http://www.reddit.com/r/dailyprogrammer_ideas/comments/31wpzp/intermediate_hello_world_genetic_or_evolutionary/). Check out /r/DailyProgrammer_Ideas to submit your own challenges to the subreddit!* ### IRC We have an [IRC channel on Freenode](http://www.reddit.com/r/dailyprogrammer/comments/2dtqr7/), at **#reddit-dailyprogrammer**. Join the channel and lurk with us! ### Previously... The previous weekly thread was [**Recap and Updates**](http://www.reddit.com/r/dailyprogrammer/comments/2sx7nn/). """ def main(): pass if __name__ == "__main__": main()
""" [Weekly #22] Machine Learning https://www.reddit.com/r/dailyprogrammer/comments/3206mk/weekly_22_machine_learning/ # [](#WeeklyIcon) Asimov would be proud! [Machine learning](http://en.wikipedia.org/wiki/Machine_learning) is a diverse field spanning from optimization and data classification, to computer vision and pattern recognition. Modern algorithms for detecting spam email use machine learning to react to developing types of spam and spot them quicker than people could! Techniques include evolutionary programming and genetic algorithms, and models such as [artificial neural networks](http://en.wikipedia.org/wiki/Artificial_neural_network). Do you work in any of these fields, or study them in academics? Do you know something about them that's interesting, or have any cool resources or videos to share? Show them to the world! Libraries like [OpenCV](http://en.wikipedia.org/wiki/OpenCV) (available [here](http://opencv.org/)) use machine learning to some extent, in order to adapt to new situations. The United Kingdom makes extensive use of [automatic number plate recognition](http://en.wikipedia.org/wiki/Police-enforced_ANPR_in_the_UK) on speed cameras, which is a subset of optical character recognition that needs to work in high speeds and poor visibility. Of course, there's also /r/MachineLearning if you want to check out even more. They have a [simple questions thread](http://www.reddit.com/r/MachineLearning/comments/2xopnm/mondays_simple_questions_thread_20150302/) if you want some reading material! *This post was inspired by [this challenge submission](http://www.reddit.com/r/dailyprogrammer_ideas/comments/31wpzp/intermediate_hello_world_genetic_or_evolutionary/). Check out /r/DailyProgrammer_Ideas to submit your own challenges to the subreddit!* ### IRC We have an [IRC channel on Freenode](http://www.reddit.com/r/dailyprogrammer/comments/2dtqr7/), at **#reddit-dailyprogrammer**. Join the channel and lurk with us! ### Previously... The previous weekly thread was [**Recap and Updates**](http://www.reddit.com/r/dailyprogrammer/comments/2sx7nn/). """ def main(): pass if __name__ == '__main__': main()
input = open('input.txt', 'r').read().split("\n") depths = list(map(lambda s: int(s), input)) increases = 0; for i in range(1, len(depths)): if depths[i-2] + depths[i-1] + depths[i] > depths[i-3] + depths[i-2] + depths[i-1]: increases += 1 print(increases)
input = open('input.txt', 'r').read().split('\n') depths = list(map(lambda s: int(s), input)) increases = 0 for i in range(1, len(depths)): if depths[i - 2] + depths[i - 1] + depths[i] > depths[i - 3] + depths[i - 2] + depths[i - 1]: increases += 1 print(increases)
#!/usr/bin/env python # # Copyright 2019 DFKI GmbH. # # Permission is hereby granted, free of charge, to any person obtaining a # copy of this software and associated documentation files (the # "Software"), to deal in the Software without restriction, including # without limitation the rights to use, copy, modify, merge, publish, # distribute, sublicense, and/or sell copies of the Software, and to permit # persons to whom the Software is furnished to do so, subject to the # following conditions: # # The above copyright notice and this permission notice shall be included # in all copies or substantial portions of the Software. # # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS # OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF # MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN # NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, # DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR # OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE # USE OR OTHER DEALINGS IN THE SOFTWARE. class HeightMapInterface(object): def __init__(self, image, width, depth, scale, height_scale, pixel_is_tuple=False): self.height_map_image = image self.scale = scale self.height_scale = height_scale self.width = width self.depth = depth self.x_offset = 0 self.z_offset = 0 self.is_tuple = pixel_is_tuple def to_relative_coordinates(self, center_x, center_z, x, z): """ get position relative to upper left """ relative_x = x - center_x relative_z = z - center_z relative_x /= self.scale[0] relative_z /= self.scale[1] relative_x += self.width / 2 relative_z += self.depth / 2 # scale by width and depth to range of 1 relative_x /= self.width relative_z /= self.depth return relative_x, relative_z def get_height_from_relative_coordinates(self, relative_x, relative_z): if relative_x < 0 or relative_x > 1.0 or relative_z < 0 or relative_z > 1.0: print("Coordinates outside of the range") return 0 # scale by image width and height to image range ix = relative_x * self.height_map_image.size[0] iy = relative_z * self.height_map_image.size[1] p = self.height_map_image.getpixel((ix, iy)) if self.is_tuple: p = p[0] return (p / 255) * self.height_scale def get_height(self, x, z): rel_x, rel_z = self.to_relative_coordinates(self.x_offset, self.z_offset, x, z) y = self.get_height_from_relative_coordinates(rel_x, rel_z) #print("get height", x, z,":", y) return y
class Heightmapinterface(object): def __init__(self, image, width, depth, scale, height_scale, pixel_is_tuple=False): self.height_map_image = image self.scale = scale self.height_scale = height_scale self.width = width self.depth = depth self.x_offset = 0 self.z_offset = 0 self.is_tuple = pixel_is_tuple def to_relative_coordinates(self, center_x, center_z, x, z): """ get position relative to upper left """ relative_x = x - center_x relative_z = z - center_z relative_x /= self.scale[0] relative_z /= self.scale[1] relative_x += self.width / 2 relative_z += self.depth / 2 relative_x /= self.width relative_z /= self.depth return (relative_x, relative_z) def get_height_from_relative_coordinates(self, relative_x, relative_z): if relative_x < 0 or relative_x > 1.0 or relative_z < 0 or (relative_z > 1.0): print('Coordinates outside of the range') return 0 ix = relative_x * self.height_map_image.size[0] iy = relative_z * self.height_map_image.size[1] p = self.height_map_image.getpixel((ix, iy)) if self.is_tuple: p = p[0] return p / 255 * self.height_scale def get_height(self, x, z): (rel_x, rel_z) = self.to_relative_coordinates(self.x_offset, self.z_offset, x, z) y = self.get_height_from_relative_coordinates(rel_x, rel_z) return y
class NasmPackage (Package): def __init__ (self): Package.__init__ (self, 'nasm', '2.10.07', sources = [ 'http://www.nasm.us/pub/nasm/releasebuilds/2.10.07/nasm-%{version}.tar.xz' ]) NasmPackage ()
class Nasmpackage(Package): def __init__(self): Package.__init__(self, 'nasm', '2.10.07', sources=['http://www.nasm.us/pub/nasm/releasebuilds/2.10.07/nasm-%{version}.tar.xz']) nasm_package()
''' Description: Given the root of a binary search tree with distinct values, modify it so that every node has a new value equal to the sum of the values of the original tree that are greater than or equal to node.val. As a reminder, a binary search tree is a tree that satisfies these constraints: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] Note: The number of nodes in the tree is between 1 and 100. Each node will have value between 0 and 100. The given tree is a binary search tree. ''' # Definition for a binary tree node. class TreeNode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def reversed_inorder_traversal( self, node: TreeNode): if not node: # empty node or empty tree return else: # DFS to next level yield from self.reversed_inorder_traversal( node.right ) yield node yield from self.reversed_inorder_traversal( node.left ) def bstToGst(self, root: TreeNode) -> TreeNode: accumulation_sum = 0 for node in self.reversed_inorder_traversal(root): accumulation_sum += node.val node.val = accumulation_sum return root # n : number of nodes in binary tree ## Time Complexity: O( n ) # # The overhead in time is the cost of reversed in-order DFS traversal, which is of O( n ). ## Space Complexity: O( 1 ) # # The overhead in space is the looping index and iterator, which is of O( n ) def print_inorder( node: TreeNode): if node: print_inorder( node.left ) print(f'{node.val} ', end = '') print_inorder( node.right ) return def test_bench(): node_0 = TreeNode( 0 ) node_1 = TreeNode( 1 ) node_2 = TreeNode( 2 ) node_3 = TreeNode( 3 ) node_4 = TreeNode( 4 ) node_5 = TreeNode( 5 ) node_6 = TreeNode( 6 ) node_7 = TreeNode( 7 ) node_8 = TreeNode( 8 ) root = node_4 root.left = node_1 root.right = node_6 node_1.left = node_0 node_1.right = node_2 node_6.left = node_5 node_6.right = node_7 node_2.right = node_3 node_7.right = node_8 # before: # expected output: ''' 0 1 2 3 4 5 6 7 8 ''' print_inorder( root ) Solution().bstToGst( root ) print("\n") # after: # expected output: ''' 36 36 35 33 30 26 21 15 8 ''' print_inorder( root ) return if __name__ == '__main__': test_bench()
""" Description: Given the root of a binary search tree with distinct values, modify it so that every node has a new value equal to the sum of the values of the original tree that are greater than or equal to node.val. As a reminder, a binary search tree is a tree that satisfies these constraints: The left subtree of a node contains only nodes with keys less than the node's key. The right subtree of a node contains only nodes with keys greater than the node's key. Both the left and right subtrees must also be binary search trees. Example 1: Input: [4,1,6,0,2,5,7,null,null,null,3,null,null,null,8] Output: [30,36,21,36,35,26,15,null,null,null,33,null,null,null,8] Note: The number of nodes in the tree is between 1 and 100. Each node will have value between 0 and 100. The given tree is a binary search tree. """ class Treenode: def __init__(self, x): self.val = x self.left = None self.right = None class Solution: def reversed_inorder_traversal(self, node: TreeNode): if not node: return else: yield from self.reversed_inorder_traversal(node.right) yield node yield from self.reversed_inorder_traversal(node.left) def bst_to_gst(self, root: TreeNode) -> TreeNode: accumulation_sum = 0 for node in self.reversed_inorder_traversal(root): accumulation_sum += node.val node.val = accumulation_sum return root def print_inorder(node: TreeNode): if node: print_inorder(node.left) print(f'{node.val} ', end='') print_inorder(node.right) return def test_bench(): node_0 = tree_node(0) node_1 = tree_node(1) node_2 = tree_node(2) node_3 = tree_node(3) node_4 = tree_node(4) node_5 = tree_node(5) node_6 = tree_node(6) node_7 = tree_node(7) node_8 = tree_node(8) root = node_4 root.left = node_1 root.right = node_6 node_1.left = node_0 node_1.right = node_2 node_6.left = node_5 node_6.right = node_7 node_2.right = node_3 node_7.right = node_8 '\n 0 1 2 3 4 5 6 7 8\n ' print_inorder(root) solution().bstToGst(root) print('\n') '\n 36 36 35 33 30 26 21 15 8\n ' print_inorder(root) return if __name__ == '__main__': test_bench()
number_of_drugs = 5 max_id = 1<<5 string_length = len("{0:#b}".format(max_id-1)) -2 EC50_for_0 = 0.75 EC50_for_1 = 1.3 f = lambda x: EC50_for_0 if x=='0' else EC50_for_1 print("[\n", end="") for x in range(0,max_id): gene_string = ("{0:0"+str(string_length)+"b}").format(x) ec50 = list(map(f, list(gene_string))) print(ec50, end="") if(x != max_id-1) : print(",") else: print("") print("]")
number_of_drugs = 5 max_id = 1 << 5 string_length = len('{0:#b}'.format(max_id - 1)) - 2 ec50_for_0 = 0.75 ec50_for_1 = 1.3 f = lambda x: EC50_for_0 if x == '0' else EC50_for_1 print('[\n', end='') for x in range(0, max_id): gene_string = ('{0:0' + str(string_length) + 'b}').format(x) ec50 = list(map(f, list(gene_string))) print(ec50, end='') if x != max_id - 1: print(',') else: print('') print(']')
input1='389125467' input2='496138527' lowest=1 highest=1000000 class Node: def __init__(self, val, next_node=None): self.val=val self.next=next_node cups=list(input2) cups=list(map(int,cups)) lookup_table={} prev=None # form linked list from the end node to beginning node for i in range(len(cups)-1,-1,-1): new=Node(cups[i]) new.next=prev lookup_table[cups[i]]=new # direct reference to the node that has the cup value prev=new for i in range(highest,9,-1): new=Node(i) new.next=prev lookup_table[i]=new prev=new lookup_table[cups[-1]].next=lookup_table[10] current=lookup_table[cups[0]] for _ in range(10000000): a=current.next b=a.next c=b.next current.next=c.next removed={current.val,a.val,b.val,c.val} destination=current.val while destination in removed: destination-=1 if destination==0: destination=highest destination_reference=lookup_table[destination] destination_old_next=destination_reference.next destination_reference.next=a c.next=destination_old_next current=current.next maincup=lookup_table[1] a=maincup.next b=a.next print(a.val*b.val)
input1 = '389125467' input2 = '496138527' lowest = 1 highest = 1000000 class Node: def __init__(self, val, next_node=None): self.val = val self.next = next_node cups = list(input2) cups = list(map(int, cups)) lookup_table = {} prev = None for i in range(len(cups) - 1, -1, -1): new = node(cups[i]) new.next = prev lookup_table[cups[i]] = new prev = new for i in range(highest, 9, -1): new = node(i) new.next = prev lookup_table[i] = new prev = new lookup_table[cups[-1]].next = lookup_table[10] current = lookup_table[cups[0]] for _ in range(10000000): a = current.next b = a.next c = b.next current.next = c.next removed = {current.val, a.val, b.val, c.val} destination = current.val while destination in removed: destination -= 1 if destination == 0: destination = highest destination_reference = lookup_table[destination] destination_old_next = destination_reference.next destination_reference.next = a c.next = destination_old_next current = current.next maincup = lookup_table[1] a = maincup.next b = a.next print(a.val * b.val)
def counting_sort(arr): k = max(arr) count = [0] * k + [0] for x in arr: count[x] += 1 for i in range(1, len(count)): count[i] = count[i] + count[i-1] output = [0] * len(arr) for x in arr: output[count[x]-1] = x yield output, count[x]-1 count[x] -= 1 yield output, count[x] #print(counting_sort([1,4,2,3,4,5]))
def counting_sort(arr): k = max(arr) count = [0] * k + [0] for x in arr: count[x] += 1 for i in range(1, len(count)): count[i] = count[i] + count[i - 1] output = [0] * len(arr) for x in arr: output[count[x] - 1] = x yield (output, count[x] - 1) count[x] -= 1 yield (output, count[x])
number = int(input()) if 100 <= number <= 200 or number == 0: pass else: print('invalid')
number = int(input()) if 100 <= number <= 200 or number == 0: pass else: print('invalid')
def nth(test, items): if test > 0: test -= 1 else: test = 0 for i, v in enumerate(items): if i == test: return v
def nth(test, items): if test > 0: test -= 1 else: test = 0 for (i, v) in enumerate(items): if i == test: return v
# Combinations class Solution: def combine(self, n, k): ans = [] def helper(choices, start, count, ans): if count == k: # cloning the list here ans.append(list(choices)) return for i in range(start, n + 1): choices[count] = i helper(choices, i + 1, count + 1, ans) helper([None] * k, 1, 0, ans) return ans if __name__ == "__main__": sol = Solution() n = 1 k = 1 print(sol.combine(n, k))
class Solution: def combine(self, n, k): ans = [] def helper(choices, start, count, ans): if count == k: ans.append(list(choices)) return for i in range(start, n + 1): choices[count] = i helper(choices, i + 1, count + 1, ans) helper([None] * k, 1, 0, ans) return ans if __name__ == '__main__': sol = solution() n = 1 k = 1 print(sol.combine(n, k))
class PyTime: def printTime(self,input): time_in_string = str(input) length = len(time_in_string) if length == 3: hour,minute1,minute2 = time_in_string hours = "0" + hour minutes = minute1 + minute2 converted_time = self.calculateTime(hours,minutes) elif length == 4: hour1,hour2,minute1,minute2 = time_in_string hours = hour1 + hour2 minutes = minute1 + minute2 converted_time = self.calculateTime(hours,minutes) elif time_in_string=="000" or time_in_string=="0000": hour1,hour2,minute1,minute2 = time_in_string hours = hour1 + hour2 minutes = minute1 + minute2 converted_time = self.calculateTime(hours,minutes) else: return "Invalid Format" return converted_time def calculateTime(self,hours,minutes): hours_in_int = int(hours) minutes_in_int = int(minutes) if hours_in_int >= 1 and hours_in_int < 12: converted_time = hours + ":" + minutes + " AM" elif hours_in_int >= 12 and hours_in_int < 24: converted_time = hours + ":" + minutes + " PM" elif hours == "00": hours = "12" converted_time = hours + ":" + minutes + " AM" return converted_time
class Pytime: def print_time(self, input): time_in_string = str(input) length = len(time_in_string) if length == 3: (hour, minute1, minute2) = time_in_string hours = '0' + hour minutes = minute1 + minute2 converted_time = self.calculateTime(hours, minutes) elif length == 4: (hour1, hour2, minute1, minute2) = time_in_string hours = hour1 + hour2 minutes = minute1 + minute2 converted_time = self.calculateTime(hours, minutes) elif time_in_string == '000' or time_in_string == '0000': (hour1, hour2, minute1, minute2) = time_in_string hours = hour1 + hour2 minutes = minute1 + minute2 converted_time = self.calculateTime(hours, minutes) else: return 'Invalid Format' return converted_time def calculate_time(self, hours, minutes): hours_in_int = int(hours) minutes_in_int = int(minutes) if hours_in_int >= 1 and hours_in_int < 12: converted_time = hours + ':' + minutes + ' AM' elif hours_in_int >= 12 and hours_in_int < 24: converted_time = hours + ':' + minutes + ' PM' elif hours == '00': hours = '12' converted_time = hours + ':' + minutes + ' AM' return converted_time
# create sets names = {'anonymous','tazri','farha'}; extra_name = {'tazri','farha','troy'}; name_list = {'solus','xenon','neon'}; name_tuple = ('helium','hydrogen'); print("names : ",names); # add focasa in names print("add 'focasa' than set : "); names.add("focasa"); print(names); # update method print("\n\nadd extra_name in set with update method : "); names.update(extra_name); print(names); # update set with list print("\nadd name_list in set with update method : "); names.update(name_list); print(names); # update set with tuple print("\nadd name_tuple in set with update method : "); names.update(name_tuple); print(names);
names = {'anonymous', 'tazri', 'farha'} extra_name = {'tazri', 'farha', 'troy'} name_list = {'solus', 'xenon', 'neon'} name_tuple = ('helium', 'hydrogen') print('names : ', names) print("add 'focasa' than set : ") names.add('focasa') print(names) print('\n\nadd extra_name in set with update method : ') names.update(extra_name) print(names) print('\nadd name_list in set with update method : ') names.update(name_list) print(names) print('\nadd name_tuple in set with update method : ') names.update(name_tuple) print(names)
#! /usr/bin/python3.6 def create_spa_workbench(document): """ :param document: :return: workbench com object """ return document.GetWorkbench("SPAWorkbench")
def create_spa_workbench(document): """ :param document: :return: workbench com object """ return document.GetWorkbench('SPAWorkbench')
user = int(input("ENTER NUMBER OF STUDENTS IN CLASS : ")) i = 1 marks = [] absent = [] # mark = marks.copy() print("FOR ABSENT STUDENTS TYPE -1 AS MARKS") for j in range(user): student = int(input("ENTER MARKS OF STUDENT {} : ".format(i))) if student == -1: absent.append(i) else: marks.append(student) i += 1 def avg(): mrk = 0 for mark in marks: mrk += mark avg = mrk/(user-len(absent)) print("AVERAGE SCORE OF THE CLASS IS {}".format(avg)) def hmax_hmin(): hmax = 0 hmin = 100 for high in marks: if high > hmax: hmax = high for min in marks: if min < hmin: hmin = min print("HIGHEST SCORE OF THE CLASS IS {}".format(hmax)) print("--------------------------") print("LOWEST SCORE OF THE CLASS IS {}".format(hmin)) print("--------------------------") # print("--------------------------") # print("--------------------------") def abs_nt(): if len(absent) > 1: print("{} STUDENTS WERE ABSENT FOR THE TEST".format(len(absent))) elif len(absent) >= 1: print("{} STUDENT WAS ABSENT FOR THE TEST".format(len(absent))) else: print("ALL STUDENTS WERE PRESENT FOR THE TEST") print("--------------------------") def freq(): frq = 0 frmax = 0 for ele in marks: if marks.count(ele) > frq: frq = marks.count(ele) frmax = ele print("{} IS THE SCORE WITH HIGHEST OCCURING FREQUENCY {}".format(frmax, frq)) ######################################## while(1): print("FOR AVG TYPE 1") print("FOR MAX_MARKS AND MIN_MARKS TYPE 2") print("FOR FREQUENCY TYPE 3") print("FOR NUMBER OF ABSENT STUDENT TYPE 4") choise=int(input()) if choise==1: print("--------------------------") avg() print("--------------------------") elif choise==2: print("--------------------------") hmax_hmin() print("--------------------------") elif choise==3: print("--------------------------") freq() print("--------------------------") elif choise==4: print("--------------------------") abs_nt() print("--------------------------") else: print("--------------------------") print("TYPE RIGHT CHOICE") print("--------------------------") break
user = int(input('ENTER NUMBER OF STUDENTS IN CLASS : ')) i = 1 marks = [] absent = [] print('FOR ABSENT STUDENTS TYPE -1 AS MARKS') for j in range(user): student = int(input('ENTER MARKS OF STUDENT {} : '.format(i))) if student == -1: absent.append(i) else: marks.append(student) i += 1 def avg(): mrk = 0 for mark in marks: mrk += mark avg = mrk / (user - len(absent)) print('AVERAGE SCORE OF THE CLASS IS {}'.format(avg)) def hmax_hmin(): hmax = 0 hmin = 100 for high in marks: if high > hmax: hmax = high for min in marks: if min < hmin: hmin = min print('HIGHEST SCORE OF THE CLASS IS {}'.format(hmax)) print('--------------------------') print('LOWEST SCORE OF THE CLASS IS {}'.format(hmin)) print('--------------------------') def abs_nt(): if len(absent) > 1: print('{} STUDENTS WERE ABSENT FOR THE TEST'.format(len(absent))) elif len(absent) >= 1: print('{} STUDENT WAS ABSENT FOR THE TEST'.format(len(absent))) else: print('ALL STUDENTS WERE PRESENT FOR THE TEST') print('--------------------------') def freq(): frq = 0 frmax = 0 for ele in marks: if marks.count(ele) > frq: frq = marks.count(ele) frmax = ele print('{} IS THE SCORE WITH HIGHEST OCCURING FREQUENCY {}'.format(frmax, frq)) while 1: print('FOR AVG TYPE 1') print('FOR MAX_MARKS AND MIN_MARKS TYPE 2') print('FOR FREQUENCY TYPE 3') print('FOR NUMBER OF ABSENT STUDENT TYPE 4') choise = int(input()) if choise == 1: print('--------------------------') avg() print('--------------------------') elif choise == 2: print('--------------------------') hmax_hmin() print('--------------------------') elif choise == 3: print('--------------------------') freq() print('--------------------------') elif choise == 4: print('--------------------------') abs_nt() print('--------------------------') else: print('--------------------------') print('TYPE RIGHT CHOICE') print('--------------------------') break
def sum_func(num1,num2 =30,num3=40): return num1 + num2 + num3 print(sum_func(10)) print(sum_func(10,20)) print(sum_func(10,20,30))
def sum_func(num1, num2=30, num3=40): return num1 + num2 + num3 print(sum_func(10)) print(sum_func(10, 20)) print(sum_func(10, 20, 30))
#!/usr/bin/env python # -*- config : utf-8 -*- 'help' class Report(object): """ You can wirte the report has created into a html file. """ def __init__(self, headtitle, content): self.headtitle = 'Bat''s' + headtitle self.content = content def replace(self): self.content = self.content.replace('\n', '<br>') self.content = self.content.replace('###', '') self.content = self.content.replace('[', '<h3>') self.content = self.content.replace(']', '</h3>') def create(self): self.replace() self.content = '<h1>' + self.headtitle + ' Report</h1>' + self.content with open('./' + self.headtitle + '.html', 'w') as f: f.write(self.content) class ScanReport(Report): """ For scan """ def __init__(self, headtitle, content): pass
"""help""" class Report(object): """ You can wirte the report has created into a html file. """ def __init__(self, headtitle, content): self.headtitle = 'Bats' + headtitle self.content = content def replace(self): self.content = self.content.replace('\n', '<br>') self.content = self.content.replace('###', '') self.content = self.content.replace('[', '<h3>') self.content = self.content.replace(']', '</h3>') def create(self): self.replace() self.content = '<h1>' + self.headtitle + ' Report</h1>' + self.content with open('./' + self.headtitle + '.html', 'w') as f: f.write(self.content) class Scanreport(Report): """ For scan """ def __init__(self, headtitle, content): pass
def variableName(name): str_name = [i for i in str(name)] non_acc_chars = [ " ", ">", "<", ":", "-", "|", ".", ",", "!", "[", "]", "'", "/", "@", "#", "&", "%", "?", "*", ] if str_name[0] in str([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]): return False for j in range(len(str_name)): if str_name[j] in non_acc_chars: return False return True
def variable_name(name): str_name = [i for i in str(name)] non_acc_chars = [' ', '>', '<', ':', '-', '|', '.', ',', '!', '[', ']', "'", '/', '@', '#', '&', '%', '?', '*'] if str_name[0] in str([0, 1, 2, 3, 4, 5, 6, 7, 8, 9]): return False for j in range(len(str_name)): if str_name[j] in non_acc_chars: return False return True
class Vector2d( object, ISerializable, IEquatable[Vector2d], IComparable[Vector2d], IComparable, IEpsilonComparable[Vector2d], ): """ Represents the two components of a vector in two-dimensional space, using System.Double-precision floating point numbers. Vector2d(x: float,y: float) """ def CompareTo(self, other): """ CompareTo(self: Vector2d,other: Vector2d) -> int Compares this Rhino.Geometry.Vector2d with another Rhino.Geometry.Vector2d. Components evaluation priority is first X,then Y. other: The other Rhino.Geometry.Vector2d to use in comparison. Returns: 0: if this is identical to other-1: if this.X < other.X-1: if this.X == other.X and this.Y < other.Y+1: otherwise. """ pass def EpsilonEquals(self, other, epsilon): """ EpsilonEquals(self: Vector2d,other: Vector2d,epsilon: float) -> bool Check that all values in other are within epsilon of the values in this """ pass def Equals(self, *__args): """ Equals(self: Vector2d,vector: Vector2d) -> bool Determines whether the specified vector has the same value as the present vector. vector: The specified vector. Returns: true if vector has the same components as this; otherwise false. Equals(self: Vector2d,obj: object) -> bool Determines whether the specified System.Object is a Vector2d and has the same value as the present vector. obj: The specified object. Returns: true if obj is Vector2d and has the same components as this; otherwise false. """ pass def GetHashCode(self): """ GetHashCode(self: Vector2d) -> int Provides a hashing value for the present vector. Returns: A non-unique number based on vector components. """ pass def ToString(self): """ ToString(self: Vector2d) -> str Constructs a string representation of the current vector. Returns: A string in the form X,Y. """ pass def Unitize(self): """ Unitize(self: Vector2d) -> bool Unitizes the vector in place. A unit vector has length 1 unit. An invalid or zero length vector cannot be unitized. Returns: true on success or false on failure. """ pass def __eq__(self, *args): """ x.__eq__(y) <==> x==y """ pass def __ge__(self, *args): pass def __gt__(self, *args): pass def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __le__(self, *args): pass def __lt__(self, *args): pass @staticmethod def __new__(self, x, y): """ __new__[Vector2d]() -> Vector2d __new__(cls: type,x: float,y: float) """ pass def __ne__(self, *args): pass def __reduce_ex__(self, *args): pass def __repr__(self, *args): """ __repr__(self: object) -> str """ pass def __str__(self, *args): pass IsValid = property(lambda self: object(), lambda self, v: None, lambda self: None) """Gets a value indicating whether this vector is valid. A valid vector must be formed of valid component values for x,y and z. Get: IsValid(self: Vector2d) -> bool """ Length = property(lambda self: object(), lambda self, v: None, lambda self: None) """Computes the length (or magnitude,or size) of this vector. This is an application of Pythagoras' theorem. Get: Length(self: Vector2d) -> float """ X = property(lambda self: object(), lambda self, v: None, lambda self: None) """Gets or sets the X (first) component of this vector. Get: X(self: Vector2d) -> float Set: X(self: Vector2d)=value """ Y = property(lambda self: object(), lambda self, v: None, lambda self: None) """Gets or sets the Y (second) component of this vector. Get: Y(self: Vector2d) -> float Set: Y(self: Vector2d)=value """ Unset = None Zero = None
class Vector2D(object, ISerializable, IEquatable[Vector2d], IComparable[Vector2d], IComparable, IEpsilonComparable[Vector2d]): """ Represents the two components of a vector in two-dimensional space, using System.Double-precision floating point numbers. Vector2d(x: float,y: float) """ def compare_to(self, other): """ CompareTo(self: Vector2d,other: Vector2d) -> int Compares this Rhino.Geometry.Vector2d with another Rhino.Geometry.Vector2d. Components evaluation priority is first X,then Y. other: The other Rhino.Geometry.Vector2d to use in comparison. Returns: 0: if this is identical to other-1: if this.X < other.X-1: if this.X == other.X and this.Y < other.Y+1: otherwise. """ pass def epsilon_equals(self, other, epsilon): """ EpsilonEquals(self: Vector2d,other: Vector2d,epsilon: float) -> bool Check that all values in other are within epsilon of the values in this """ pass def equals(self, *__args): """ Equals(self: Vector2d,vector: Vector2d) -> bool Determines whether the specified vector has the same value as the present vector. vector: The specified vector. Returns: true if vector has the same components as this; otherwise false. Equals(self: Vector2d,obj: object) -> bool Determines whether the specified System.Object is a Vector2d and has the same value as the present vector. obj: The specified object. Returns: true if obj is Vector2d and has the same components as this; otherwise false. """ pass def get_hash_code(self): """ GetHashCode(self: Vector2d) -> int Provides a hashing value for the present vector. Returns: A non-unique number based on vector components. """ pass def to_string(self): """ ToString(self: Vector2d) -> str Constructs a string representation of the current vector. Returns: A string in the form X,Y. """ pass def unitize(self): """ Unitize(self: Vector2d) -> bool Unitizes the vector in place. A unit vector has length 1 unit. An invalid or zero length vector cannot be unitized. Returns: true on success or false on failure. """ pass def __eq__(self, *args): """ x.__eq__(y) <==> x==y """ pass def __ge__(self, *args): pass def __gt__(self, *args): pass def __init__(self, *args): """ x.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signaturex.__init__(...) initializes x; see x.__class__.__doc__ for signature """ pass def __le__(self, *args): pass def __lt__(self, *args): pass @staticmethod def __new__(self, x, y): """ __new__[Vector2d]() -> Vector2d __new__(cls: type,x: float,y: float) """ pass def __ne__(self, *args): pass def __reduce_ex__(self, *args): pass def __repr__(self, *args): """ __repr__(self: object) -> str """ pass def __str__(self, *args): pass is_valid = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets a value indicating whether this vector is valid. \n\n A valid vector must be formed of valid component values for x,y and z.\n\n\n\nGet: IsValid(self: Vector2d) -> bool\n\n\n\n' length = property(lambda self: object(), lambda self, v: None, lambda self: None) "Computes the length (or magnitude,or size) of this vector.\n\n This is an application of Pythagoras' theorem.\n\n\n\nGet: Length(self: Vector2d) -> float\n\n\n\n" x = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets the X (first) component of this vector.\n\n\n\nGet: X(self: Vector2d) -> float\n\n\n\nSet: X(self: Vector2d)=value\n\n' y = property(lambda self: object(), lambda self, v: None, lambda self: None) 'Gets or sets the Y (second) component of this vector.\n\n\n\nGet: Y(self: Vector2d) -> float\n\n\n\nSet: Y(self: Vector2d)=value\n\n' unset = None zero = None
def palindrome(num): return str(num) == str(num)[::-1] # Bots are software programs that combine requests # top Returns a reference to the top most element of the stack def largest(bot, top): z = 0 for i in range(top, bot, -1): for j in range(top, bot, -1): if palindrome(i * j): if i*j > z: z = i*j return z print(largest(100, 999))
def palindrome(num): return str(num) == str(num)[::-1] def largest(bot, top): z = 0 for i in range(top, bot, -1): for j in range(top, bot, -1): if palindrome(i * j): if i * j > z: z = i * j return z print(largest(100, 999))
# # Copyright (c) 2020 Xilinx, Inc. All rights reserved. # SPDX-License-Identifier: MIT # plnx_package_boot = True # Generate Package Boot Images
plnx_package_boot = True
# # PySNMP MIB module AGG-TRAP-MIB (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/AGG-TRAP-MIB # Produced by pysmi-0.3.4 at Wed May 1 11:15:43 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) # devName, mateHost, unknownDeviceTrapContents, pepName, oldFile, reason, result, matePort, file, sbProducerPort, port, snName, host, myHost, minutes, newFile, sbProducerHost, myPort = mibBuilder.importSymbols("AGGREGATED-EXT-MIB", "devName", "mateHost", "unknownDeviceTrapContents", "pepName", "oldFile", "reason", "result", "matePort", "file", "sbProducerPort", "port", "snName", "host", "myHost", "minutes", "newFile", "sbProducerHost", "myPort") ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ValueSizeConstraint, ValueRangeConstraint, ConstraintsIntersection, ConstraintsUnion = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ValueSizeConstraint", "ValueRangeConstraint", "ConstraintsIntersection", "ConstraintsUnion") NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance") snmpModules, ObjectName, Counter32, IpAddress, Integer32, TimeTicks, ModuleIdentity, Unsigned32, Gauge32, NotificationType, enterprises, Counter64, Bits, ObjectIdentity, MibScalar, MibTable, MibTableRow, MibTableColumn, MibIdentifier, iso = mibBuilder.importSymbols("SNMPv2-SMI", "snmpModules", "ObjectName", "Counter32", "IpAddress", "Integer32", "TimeTicks", "ModuleIdentity", "Unsigned32", "Gauge32", "NotificationType", "enterprises", "Counter64", "Bits", "ObjectIdentity", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "MibIdentifier", "iso") RowStatus, TruthValue, TestAndIncr, DisplayString, TimeStamp, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "RowStatus", "TruthValue", "TestAndIncr", "DisplayString", "TimeStamp", "TextualConvention") lucent = MibIdentifier((1, 3, 6, 1, 4, 1, 1751)) products = MibIdentifier((1, 3, 6, 1, 4, 1, 1751, 1)) mantraDevice = MibIdentifier((1, 3, 6, 1, 4, 1, 1751, 1, 1198)) mantraTraps = ModuleIdentity((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0)) if mibBuilder.loadTexts: mantraTraps.setLastUpdated('240701') if mibBuilder.loadTexts: mantraTraps.setOrganization('Lucent Technologies') if mibBuilder.loadTexts: mantraTraps.setContactInfo('') if mibBuilder.loadTexts: mantraTraps.setDescription('The MIB module for entities implementing the xxxx protocol.') unParsedEvent = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 5)).setObjects(("AGGREGATED-EXT-MIB", "unknownDeviceTrapContents")) if mibBuilder.loadTexts: unParsedEvent.setStatus('current') if mibBuilder.loadTexts: unParsedEvent.setDescription('An event is sent up as unParsedEvent, if there is an error in formatting, and event construction does not succeed. The variables are: 1) unknownDeviceTrapContents - a string representing the event text as the pep received it. Severity: MAJOR') styxProducerConnect = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 6)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "host"), ("AGGREGATED-EXT-MIB", "port"), ("AGGREGATED-EXT-MIB", "file")) if mibBuilder.loadTexts: styxProducerConnect.setStatus('current') if mibBuilder.loadTexts: styxProducerConnect.setDescription('Indicates that the pep was sucessfully able to connect to the source of events specified in its config. The variables are: 1) pepName - this is the name of the PEP who is raising the event 2) devName - this is the logical name of the device this pep is connected to 3-4) host:port - these two identify the device that was mounted by the pep 5) file - this is the file name used internally start-up event, mainly. Severity: INFO') styxProducerUnReadable = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 7)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "host"), ("AGGREGATED-EXT-MIB", "port"), ("AGGREGATED-EXT-MIB", "file")) if mibBuilder.loadTexts: styxProducerUnReadable.setStatus('current') if mibBuilder.loadTexts: styxProducerUnReadable.setDescription("Indicates that the pep's connection exists to the device, but the file named in the trap is not readable. The variables are: 1) pepName - this is the name of the PEP who is raising the event 2) devName - this is the logical name of the device this pep is connected to 3-4) host:port - these two identify the device that was mounted by the pep 5) file - this is the file name used internally Severity: MAJOR") styxProducerDisconnect = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 8)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "host"), ("AGGREGATED-EXT-MIB", "port"), ("AGGREGATED-EXT-MIB", "file")) if mibBuilder.loadTexts: styxProducerDisconnect.setStatus('current') if mibBuilder.loadTexts: styxProducerDisconnect.setDescription("Indicates that the pep's connection to the source of events was severed. This could either be because device process died, or because there is a network outage. The variables are: 1) pepName - this is the name of the PEP who is raising the event 2) devName - this is the logical name of the device this pep is connected to 3-4) host:port - these two identify the device that was mounted by the pep 5) file - this is the file name used internally Severity: MAJOR") styxProducerUnReachable = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 9)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "host"), ("AGGREGATED-EXT-MIB", "port"), ("AGGREGATED-EXT-MIB", "file"), ("AGGREGATED-EXT-MIB", "minutes")) if mibBuilder.loadTexts: styxProducerUnReachable.setStatus('current') if mibBuilder.loadTexts: styxProducerUnReachable.setDescription("Indicates that the pep's connection to the device has not been up for some time now, indicated in minutes. The variables are: 1) pepName - this is the name of the PEP who is raising the event 2) devName - this is the logical name of the device this pep is connected to 3-4) host, port - these two identify the device that was mounted by the pep 5) file - this is the file name used internally minutes - the time in minutes for which the connection to the device has not been up. Severity: MAJOR") logFileChanged = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 10)).setObjects(("AGGREGATED-EXT-MIB", "oldFile"), ("AGGREGATED-EXT-MIB", "newFile"), ("AGGREGATED-EXT-MIB", "result"), ("AGGREGATED-EXT-MIB", "reason")) if mibBuilder.loadTexts: logFileChanged.setStatus('current') if mibBuilder.loadTexts: logFileChanged.setDescription("Indicates that a log-file-change attempt is successful or failure. The variables are: 1) oldFile - this is the name of the old file which was to be changed. 2) newFile - this is the new log file name 3) result - this indicates 'success' or failure of logFileChange attempt. 4) reason - this describes the reason when log file change has failed. Severity: INFO") styxFTMateConnect = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 11)).setObjects(("AGGREGATED-EXT-MIB", "snName"), ("AGGREGATED-EXT-MIB", "myHost"), ("AGGREGATED-EXT-MIB", "myPort"), ("AGGREGATED-EXT-MIB", "mateHost"), ("AGGREGATED-EXT-MIB", "matePort")) if mibBuilder.loadTexts: styxFTMateConnect.setStatus('current') if mibBuilder.loadTexts: styxFTMateConnect.setDescription('Indicates that this ServiceNode was sucessfully able to connect to its redundant mate. This event is usually raised by the Backup mate who is responsible for monitoring its respective Primary. The variables are: 1) snName - this is the name of the ServiceNode who is raising the event. 2-3) myHost:myPort - these identify the host and port of the ServiceNode raising the event. 4-5) mateHost:matePort - these identify the host and port of the mate to which this ServiceNode connected. Severity: INFO') styxFTMateDisconnect = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 12)).setObjects(("AGGREGATED-EXT-MIB", "snName"), ("AGGREGATED-EXT-MIB", "myHost"), ("AGGREGATED-EXT-MIB", "myPort"), ("AGGREGATED-EXT-MIB", "mateHost"), ("AGGREGATED-EXT-MIB", "matePort")) if mibBuilder.loadTexts: styxFTMateDisconnect.setStatus('current') if mibBuilder.loadTexts: styxFTMateDisconnect.setDescription('Indicates that this ServiceNode has lost connection to its redundant mate due to either process or host failure. This event is usually raised by the Backup mate who is monitoring its respective Primary. Connection will be established upon recovery of the mate. The variables are: 1) snName - this is the name of the ServiceNode who is raising the event 2-3) myHost:myPort - these identify the host and port of the ServiceNode raising the event. 4-5) mateHost:matePort - these identify the host and port of the mate to which this ServiceNode lost connection. Severity: MAJOR') sBProducerUnreachable = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 13)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "sbProducerHost"), ("AGGREGATED-EXT-MIB", "sbProducerPort")) if mibBuilder.loadTexts: sBProducerUnreachable.setStatus('current') if mibBuilder.loadTexts: sBProducerUnreachable.setDescription('Indicates that this Socket Based Producer is not reachable by the Policy Enforcement Point. The variables are: 1) pepName - this is the name of the Policy Enforcement Point (PEP) who is raising the event 2) devName: Device which is unreachable 3) sbProducerHost: Host where the Socket Based event producer is on. 4) sbProducerPort: Port where the Socket Based event producer is running on. Severity: MAJOR') sBProducerConnected = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 14)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "sbProducerHost"), ("AGGREGATED-EXT-MIB", "sbProducerPort")) if mibBuilder.loadTexts: sBProducerConnected.setStatus('current') if mibBuilder.loadTexts: sBProducerConnected.setDescription('Indicates that this Socket Based Producer has connected to the Policy Enforcement Point (PEP). The variables are: 1) pepName - this is the name of the Policy Enforcement Point (PEP) who is raising the event 2) devName: Device which is unreachable 3) sbProducerHost: Host where the Socket Based event producer is on. 4) sbProducerPort: Port where the Socket Based event producer is running on. Severity: MAJOR') sBProducerRegistered = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 15)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "sbProducerHost"), ("AGGREGATED-EXT-MIB", "sbProducerPort")) if mibBuilder.loadTexts: sBProducerRegistered.setStatus('current') if mibBuilder.loadTexts: sBProducerRegistered.setDescription('Indicates that this Socket Based Producer has registered with the Policy Enforcement Point (PEP). The variables are: 1) pepName - this is the name of the Policy Enforcement Point (PEP) who is raising the event 2) devName: Device which is unreachable 3) sbProducerHost: Host where the Socket Based event producer is on. 4) sbProducerPort: Port where the Socket Based event producer is running on. Severity: INFO') sBProducerDisconnected = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 16)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "sbProducerHost"), ("AGGREGATED-EXT-MIB", "sbProducerPort")) if mibBuilder.loadTexts: sBProducerDisconnected.setStatus('current') if mibBuilder.loadTexts: sBProducerDisconnected.setDescription('Indicates that this Socket Based Producer has disconnected from the Policy Enforcement Point (PEP). The variables are: 1) pepName - this is the name of the Policy Enforcement Point (PEP) who is raising the event 2) devName: Device which is unreachable 3) sbProducerHost: Host where the Socket Based event producer is on. 4) sbProducerPort: Port where the Socket Based event producer is running on. Severity: INFO') sBProducerCannotRegister = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 17)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "sbProducerHost"), ("AGGREGATED-EXT-MIB", "sbProducerPort")) if mibBuilder.loadTexts: sBProducerCannotRegister.setStatus('current') if mibBuilder.loadTexts: sBProducerCannotRegister.setDescription('Indicates that this Socket Based Producer cannot register to the Policy Enforcement Point (PEP). The variables are: 1) pepName - this is the name of the Policy Enforcement Point (PEP) who is raising the event 2) devName: Device which is unreachable 3) sbProducerHost: Host where the Socket Based event producer is on. 4) sbProducerPort: Port where the Socket Based event producer is running on. Severity: INFO') sBProducerCannotDisconnect = NotificationType((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 18)).setObjects(("AGGREGATED-EXT-MIB", "pepName"), ("AGGREGATED-EXT-MIB", "devName"), ("AGGREGATED-EXT-MIB", "sbProducerHost"), ("AGGREGATED-EXT-MIB", "sbProducerPort")) if mibBuilder.loadTexts: sBProducerCannotDisconnect.setStatus('current') if mibBuilder.loadTexts: sBProducerCannotDisconnect.setDescription('Indicates that this Socket Based Producer cannot disconenct from the Policy Enforcement Point (PEP). The variables are: 1) pepName - this is the name of the Policy Enforcement Point (PEP) who is raising the event 2) devName: Device which is unreachable 3) sbProducerHost: Host where the Socket Based event producer is on. 4) sbProducerPort: Port where the Socket Based event producer is running on. Severity: INFO') mibBuilder.exportSymbols("AGG-TRAP-MIB", sBProducerUnreachable=sBProducerUnreachable, sBProducerRegistered=sBProducerRegistered, PYSNMP_MODULE_ID=mantraTraps, sBProducerDisconnected=sBProducerDisconnected, products=products, styxProducerConnect=styxProducerConnect, mantraTraps=mantraTraps, styxFTMateDisconnect=styxFTMateDisconnect, sBProducerCannotDisconnect=sBProducerCannotDisconnect, styxProducerUnReachable=styxProducerUnReachable, sBProducerCannotRegister=sBProducerCannotRegister, unParsedEvent=unParsedEvent, styxFTMateConnect=styxFTMateConnect, sBProducerConnected=sBProducerConnected, logFileChanged=logFileChanged, lucent=lucent, styxProducerDisconnect=styxProducerDisconnect, mantraDevice=mantraDevice, styxProducerUnReadable=styxProducerUnReadable)
(dev_name, mate_host, unknown_device_trap_contents, pep_name, old_file, reason, result, mate_port, file, sb_producer_port, port, sn_name, host, my_host, minutes, new_file, sb_producer_host, my_port) = mibBuilder.importSymbols('AGGREGATED-EXT-MIB', 'devName', 'mateHost', 'unknownDeviceTrapContents', 'pepName', 'oldFile', 'reason', 'result', 'matePort', 'file', 'sbProducerPort', 'port', 'snName', 'host', 'myHost', 'minutes', 'newFile', 'sbProducerHost', 'myPort') (object_identifier, octet_string, integer) = mibBuilder.importSymbols('ASN1', 'ObjectIdentifier', 'OctetString', 'Integer') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, value_size_constraint, value_range_constraint, constraints_intersection, constraints_union) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ValueSizeConstraint', 'ValueRangeConstraint', 'ConstraintsIntersection', 'ConstraintsUnion') (notification_group, module_compliance) = mibBuilder.importSymbols('SNMPv2-CONF', 'NotificationGroup', 'ModuleCompliance') (snmp_modules, object_name, counter32, ip_address, integer32, time_ticks, module_identity, unsigned32, gauge32, notification_type, enterprises, counter64, bits, object_identity, mib_scalar, mib_table, mib_table_row, mib_table_column, mib_identifier, iso) = mibBuilder.importSymbols('SNMPv2-SMI', 'snmpModules', 'ObjectName', 'Counter32', 'IpAddress', 'Integer32', 'TimeTicks', 'ModuleIdentity', 'Unsigned32', 'Gauge32', 'NotificationType', 'enterprises', 'Counter64', 'Bits', 'ObjectIdentity', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'MibIdentifier', 'iso') (row_status, truth_value, test_and_incr, display_string, time_stamp, textual_convention) = mibBuilder.importSymbols('SNMPv2-TC', 'RowStatus', 'TruthValue', 'TestAndIncr', 'DisplayString', 'TimeStamp', 'TextualConvention') lucent = mib_identifier((1, 3, 6, 1, 4, 1, 1751)) products = mib_identifier((1, 3, 6, 1, 4, 1, 1751, 1)) mantra_device = mib_identifier((1, 3, 6, 1, 4, 1, 1751, 1, 1198)) mantra_traps = module_identity((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0)) if mibBuilder.loadTexts: mantraTraps.setLastUpdated('240701') if mibBuilder.loadTexts: mantraTraps.setOrganization('Lucent Technologies') if mibBuilder.loadTexts: mantraTraps.setContactInfo('') if mibBuilder.loadTexts: mantraTraps.setDescription('The MIB module for entities implementing the xxxx protocol.') un_parsed_event = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 5)).setObjects(('AGGREGATED-EXT-MIB', 'unknownDeviceTrapContents')) if mibBuilder.loadTexts: unParsedEvent.setStatus('current') if mibBuilder.loadTexts: unParsedEvent.setDescription('An event is sent up as unParsedEvent, if there is an error in formatting, and event construction does not succeed. The variables are: 1) unknownDeviceTrapContents - a string representing the event text as the pep received it. Severity: MAJOR') styx_producer_connect = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 6)).setObjects(('AGGREGATED-EXT-MIB', 'pepName'), ('AGGREGATED-EXT-MIB', 'devName'), ('AGGREGATED-EXT-MIB', 'host'), ('AGGREGATED-EXT-MIB', 'port'), ('AGGREGATED-EXT-MIB', 'file')) if mibBuilder.loadTexts: styxProducerConnect.setStatus('current') if mibBuilder.loadTexts: styxProducerConnect.setDescription('Indicates that the pep was sucessfully able to connect to the source of events specified in its config. The variables are: 1) pepName - this is the name of the PEP who is raising the event 2) devName - this is the logical name of the device this pep is connected to 3-4) host:port - these two identify the device that was mounted by the pep 5) file - this is the file name used internally start-up event, mainly. Severity: INFO') styx_producer_un_readable = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 7)).setObjects(('AGGREGATED-EXT-MIB', 'pepName'), ('AGGREGATED-EXT-MIB', 'devName'), ('AGGREGATED-EXT-MIB', 'host'), ('AGGREGATED-EXT-MIB', 'port'), ('AGGREGATED-EXT-MIB', 'file')) if mibBuilder.loadTexts: styxProducerUnReadable.setStatus('current') if mibBuilder.loadTexts: styxProducerUnReadable.setDescription("Indicates that the pep's connection exists to the device, but the file named in the trap is not readable. The variables are: 1) pepName - this is the name of the PEP who is raising the event 2) devName - this is the logical name of the device this pep is connected to 3-4) host:port - these two identify the device that was mounted by the pep 5) file - this is the file name used internally Severity: MAJOR") styx_producer_disconnect = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 8)).setObjects(('AGGREGATED-EXT-MIB', 'pepName'), ('AGGREGATED-EXT-MIB', 'devName'), ('AGGREGATED-EXT-MIB', 'host'), ('AGGREGATED-EXT-MIB', 'port'), ('AGGREGATED-EXT-MIB', 'file')) if mibBuilder.loadTexts: styxProducerDisconnect.setStatus('current') if mibBuilder.loadTexts: styxProducerDisconnect.setDescription("Indicates that the pep's connection to the source of events was severed. This could either be because device process died, or because there is a network outage. The variables are: 1) pepName - this is the name of the PEP who is raising the event 2) devName - this is the logical name of the device this pep is connected to 3-4) host:port - these two identify the device that was mounted by the pep 5) file - this is the file name used internally Severity: MAJOR") styx_producer_un_reachable = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 9)).setObjects(('AGGREGATED-EXT-MIB', 'pepName'), ('AGGREGATED-EXT-MIB', 'devName'), ('AGGREGATED-EXT-MIB', 'host'), ('AGGREGATED-EXT-MIB', 'port'), ('AGGREGATED-EXT-MIB', 'file'), ('AGGREGATED-EXT-MIB', 'minutes')) if mibBuilder.loadTexts: styxProducerUnReachable.setStatus('current') if mibBuilder.loadTexts: styxProducerUnReachable.setDescription("Indicates that the pep's connection to the device has not been up for some time now, indicated in minutes. The variables are: 1) pepName - this is the name of the PEP who is raising the event 2) devName - this is the logical name of the device this pep is connected to 3-4) host, port - these two identify the device that was mounted by the pep 5) file - this is the file name used internally minutes - the time in minutes for which the connection to the device has not been up. Severity: MAJOR") log_file_changed = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 10)).setObjects(('AGGREGATED-EXT-MIB', 'oldFile'), ('AGGREGATED-EXT-MIB', 'newFile'), ('AGGREGATED-EXT-MIB', 'result'), ('AGGREGATED-EXT-MIB', 'reason')) if mibBuilder.loadTexts: logFileChanged.setStatus('current') if mibBuilder.loadTexts: logFileChanged.setDescription("Indicates that a log-file-change attempt is successful or failure. The variables are: 1) oldFile - this is the name of the old file which was to be changed. 2) newFile - this is the new log file name 3) result - this indicates 'success' or failure of logFileChange attempt. 4) reason - this describes the reason when log file change has failed. Severity: INFO") styx_ft_mate_connect = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 11)).setObjects(('AGGREGATED-EXT-MIB', 'snName'), ('AGGREGATED-EXT-MIB', 'myHost'), ('AGGREGATED-EXT-MIB', 'myPort'), ('AGGREGATED-EXT-MIB', 'mateHost'), ('AGGREGATED-EXT-MIB', 'matePort')) if mibBuilder.loadTexts: styxFTMateConnect.setStatus('current') if mibBuilder.loadTexts: styxFTMateConnect.setDescription('Indicates that this ServiceNode was sucessfully able to connect to its redundant mate. This event is usually raised by the Backup mate who is responsible for monitoring its respective Primary. The variables are: 1) snName - this is the name of the ServiceNode who is raising the event. 2-3) myHost:myPort - these identify the host and port of the ServiceNode raising the event. 4-5) mateHost:matePort - these identify the host and port of the mate to which this ServiceNode connected. Severity: INFO') styx_ft_mate_disconnect = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 12)).setObjects(('AGGREGATED-EXT-MIB', 'snName'), ('AGGREGATED-EXT-MIB', 'myHost'), ('AGGREGATED-EXT-MIB', 'myPort'), ('AGGREGATED-EXT-MIB', 'mateHost'), ('AGGREGATED-EXT-MIB', 'matePort')) if mibBuilder.loadTexts: styxFTMateDisconnect.setStatus('current') if mibBuilder.loadTexts: styxFTMateDisconnect.setDescription('Indicates that this ServiceNode has lost connection to its redundant mate due to either process or host failure. This event is usually raised by the Backup mate who is monitoring its respective Primary. Connection will be established upon recovery of the mate. The variables are: 1) snName - this is the name of the ServiceNode who is raising the event 2-3) myHost:myPort - these identify the host and port of the ServiceNode raising the event. 4-5) mateHost:matePort - these identify the host and port of the mate to which this ServiceNode lost connection. Severity: MAJOR') s_b_producer_unreachable = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 13)).setObjects(('AGGREGATED-EXT-MIB', 'pepName'), ('AGGREGATED-EXT-MIB', 'devName'), ('AGGREGATED-EXT-MIB', 'sbProducerHost'), ('AGGREGATED-EXT-MIB', 'sbProducerPort')) if mibBuilder.loadTexts: sBProducerUnreachable.setStatus('current') if mibBuilder.loadTexts: sBProducerUnreachable.setDescription('Indicates that this Socket Based Producer is not reachable by the Policy Enforcement Point. The variables are: 1) pepName - this is the name of the Policy Enforcement Point (PEP) who is raising the event 2) devName: Device which is unreachable 3) sbProducerHost: Host where the Socket Based event producer is on. 4) sbProducerPort: Port where the Socket Based event producer is running on. Severity: MAJOR') s_b_producer_connected = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 14)).setObjects(('AGGREGATED-EXT-MIB', 'pepName'), ('AGGREGATED-EXT-MIB', 'devName'), ('AGGREGATED-EXT-MIB', 'sbProducerHost'), ('AGGREGATED-EXT-MIB', 'sbProducerPort')) if mibBuilder.loadTexts: sBProducerConnected.setStatus('current') if mibBuilder.loadTexts: sBProducerConnected.setDescription('Indicates that this Socket Based Producer has connected to the Policy Enforcement Point (PEP). The variables are: 1) pepName - this is the name of the Policy Enforcement Point (PEP) who is raising the event 2) devName: Device which is unreachable 3) sbProducerHost: Host where the Socket Based event producer is on. 4) sbProducerPort: Port where the Socket Based event producer is running on. Severity: MAJOR') s_b_producer_registered = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 15)).setObjects(('AGGREGATED-EXT-MIB', 'pepName'), ('AGGREGATED-EXT-MIB', 'devName'), ('AGGREGATED-EXT-MIB', 'sbProducerHost'), ('AGGREGATED-EXT-MIB', 'sbProducerPort')) if mibBuilder.loadTexts: sBProducerRegistered.setStatus('current') if mibBuilder.loadTexts: sBProducerRegistered.setDescription('Indicates that this Socket Based Producer has registered with the Policy Enforcement Point (PEP). The variables are: 1) pepName - this is the name of the Policy Enforcement Point (PEP) who is raising the event 2) devName: Device which is unreachable 3) sbProducerHost: Host where the Socket Based event producer is on. 4) sbProducerPort: Port where the Socket Based event producer is running on. Severity: INFO') s_b_producer_disconnected = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 16)).setObjects(('AGGREGATED-EXT-MIB', 'pepName'), ('AGGREGATED-EXT-MIB', 'devName'), ('AGGREGATED-EXT-MIB', 'sbProducerHost'), ('AGGREGATED-EXT-MIB', 'sbProducerPort')) if mibBuilder.loadTexts: sBProducerDisconnected.setStatus('current') if mibBuilder.loadTexts: sBProducerDisconnected.setDescription('Indicates that this Socket Based Producer has disconnected from the Policy Enforcement Point (PEP). The variables are: 1) pepName - this is the name of the Policy Enforcement Point (PEP) who is raising the event 2) devName: Device which is unreachable 3) sbProducerHost: Host where the Socket Based event producer is on. 4) sbProducerPort: Port where the Socket Based event producer is running on. Severity: INFO') s_b_producer_cannot_register = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 17)).setObjects(('AGGREGATED-EXT-MIB', 'pepName'), ('AGGREGATED-EXT-MIB', 'devName'), ('AGGREGATED-EXT-MIB', 'sbProducerHost'), ('AGGREGATED-EXT-MIB', 'sbProducerPort')) if mibBuilder.loadTexts: sBProducerCannotRegister.setStatus('current') if mibBuilder.loadTexts: sBProducerCannotRegister.setDescription('Indicates that this Socket Based Producer cannot register to the Policy Enforcement Point (PEP). The variables are: 1) pepName - this is the name of the Policy Enforcement Point (PEP) who is raising the event 2) devName: Device which is unreachable 3) sbProducerHost: Host where the Socket Based event producer is on. 4) sbProducerPort: Port where the Socket Based event producer is running on. Severity: INFO') s_b_producer_cannot_disconnect = notification_type((1, 3, 6, 1, 4, 1, 1751, 1, 1198, 0, 18)).setObjects(('AGGREGATED-EXT-MIB', 'pepName'), ('AGGREGATED-EXT-MIB', 'devName'), ('AGGREGATED-EXT-MIB', 'sbProducerHost'), ('AGGREGATED-EXT-MIB', 'sbProducerPort')) if mibBuilder.loadTexts: sBProducerCannotDisconnect.setStatus('current') if mibBuilder.loadTexts: sBProducerCannotDisconnect.setDescription('Indicates that this Socket Based Producer cannot disconenct from the Policy Enforcement Point (PEP). The variables are: 1) pepName - this is the name of the Policy Enforcement Point (PEP) who is raising the event 2) devName: Device which is unreachable 3) sbProducerHost: Host where the Socket Based event producer is on. 4) sbProducerPort: Port where the Socket Based event producer is running on. Severity: INFO') mibBuilder.exportSymbols('AGG-TRAP-MIB', sBProducerUnreachable=sBProducerUnreachable, sBProducerRegistered=sBProducerRegistered, PYSNMP_MODULE_ID=mantraTraps, sBProducerDisconnected=sBProducerDisconnected, products=products, styxProducerConnect=styxProducerConnect, mantraTraps=mantraTraps, styxFTMateDisconnect=styxFTMateDisconnect, sBProducerCannotDisconnect=sBProducerCannotDisconnect, styxProducerUnReachable=styxProducerUnReachable, sBProducerCannotRegister=sBProducerCannotRegister, unParsedEvent=unParsedEvent, styxFTMateConnect=styxFTMateConnect, sBProducerConnected=sBProducerConnected, logFileChanged=logFileChanged, lucent=lucent, styxProducerDisconnect=styxProducerDisconnect, mantraDevice=mantraDevice, styxProducerUnReadable=styxProducerUnReadable)
nums = [int(input()) for _ in range(int(input()))] nums_count = [nums.count(a) for a in nums] min_count, max_count - min(nums_count), max(nums_count) min_num, max_num = 0, 0 a, b = 0, 0 for i in range(len(nums)): if nums_count[i] > b: max_num = nums[i] elif nums_count[i] == b: if nums[i] > max_num: max_num = numx[i]
nums = [int(input()) for _ in range(int(input()))] nums_count = [nums.count(a) for a in nums] (min_count, max_count - min(nums_count), max(nums_count)) (min_num, max_num) = (0, 0) (a, b) = (0, 0) for i in range(len(nums)): if nums_count[i] > b: max_num = nums[i] elif nums_count[i] == b: if nums[i] > max_num: max_num = numx[i]
# File: phishtank_consts.py # # Copyright (c) 2016-2021 Splunk Inc. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software distributed under # the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, # either express or implied. See the License for the specific language governing permissions # and limitations under the License. PHISHTANK_DOMAIN = 'http://www.phishtank.com' PHISHTANK_API_DOMAIN = 'https://checkurl.phishtank.com/checkurl/' PHISHTANK_APP_KEY = 'app_key' PHISHTANK_MSG_QUERY_URL = 'Querying URL: {query_url}' PHISHTANK_MSG_CONNECTING = 'Polling Phishtank site ...' PHISHTANK_SERVICE_SUCC_MSG = 'Phishtank Service successfully executed.' PHISHTANK_SUCC_CONNECTIVITY_TEST = 'Connectivity test passed' PHISHTANK_ERR_CONNECTIVITY_TEST = 'Connectivity test failed' PHISHTANK_MSG_GOT_RESP = 'Got response from Phishtank' PHISHTANK_NO_RESPONSE = 'Server did not return a response \ for the object queried' PHISHTANK_SERVER_CONNECTION_ERROR = 'Server connection error' PHISHTANK_MSG_CHECK_CONNECTIVITY = 'Please check your network connectivity' PHISHTANK_SERVER_RETURNED_ERROR_CODE = 'Server returned error code: {code}' PHISHTANK_ERR_MSG_OBJECT_QUERIED = "Phishtank response didn't \ send expected response" PHISHTANK_ERR_MSG_ACTION_PARAM = 'Mandatory action parameter missing' PHISHTANK_SERVER_ERROR_RATE_LIMIT = 'Query is being rate limited. \ Server returned 509'
phishtank_domain = 'http://www.phishtank.com' phishtank_api_domain = 'https://checkurl.phishtank.com/checkurl/' phishtank_app_key = 'app_key' phishtank_msg_query_url = 'Querying URL: {query_url}' phishtank_msg_connecting = 'Polling Phishtank site ...' phishtank_service_succ_msg = 'Phishtank Service successfully executed.' phishtank_succ_connectivity_test = 'Connectivity test passed' phishtank_err_connectivity_test = 'Connectivity test failed' phishtank_msg_got_resp = 'Got response from Phishtank' phishtank_no_response = 'Server did not return a response for the object queried' phishtank_server_connection_error = 'Server connection error' phishtank_msg_check_connectivity = 'Please check your network connectivity' phishtank_server_returned_error_code = 'Server returned error code: {code}' phishtank_err_msg_object_queried = "Phishtank response didn't send expected response" phishtank_err_msg_action_param = 'Mandatory action parameter missing' phishtank_server_error_rate_limit = 'Query is being rate limited. Server returned 509'
# -*- coding: utf-8 -*- { 'name': 'Events', 'category': 'Website/Website', 'sequence': 166, 'summary': 'Publish events, sell tickets', 'website': 'https://www.odoo.com/page/events', 'description': "", 'depends': ['website', 'website_partner', 'website_mail', 'event'], 'data': [ 'data/event_data.xml', 'views/res_config_settings_views.xml', 'views/event_snippets.xml', 'views/event_templates.xml', 'views/event_views.xml', 'security/ir.model.access.csv', 'security/event_security.xml', ], 'demo': [ 'data/event_demo.xml' ], 'application': True, 'license': 'LGPL-3', }
{'name': 'Events', 'category': 'Website/Website', 'sequence': 166, 'summary': 'Publish events, sell tickets', 'website': 'https://www.odoo.com/page/events', 'description': '', 'depends': ['website', 'website_partner', 'website_mail', 'event'], 'data': ['data/event_data.xml', 'views/res_config_settings_views.xml', 'views/event_snippets.xml', 'views/event_templates.xml', 'views/event_views.xml', 'security/ir.model.access.csv', 'security/event_security.xml'], 'demo': ['data/event_demo.xml'], 'application': True, 'license': 'LGPL-3'}
Ds = [1, 1.2, 1.5, 2, 4] file_name = "f.csv" f = open(file_name, 'r') for depth in Ds: print('\n\n DEALING WITH ALL D = ', depth-1) DATA['below_depth'] = (depth - 1) * HEIGHT for angle in range(2,90,1): if angle %5 ==0: continue if angle >= 50 and angle <=60: continue f.close() f = open(file_name, 'a') update_data(new_slope=angle, radius_step=0.1, steps_number=400) DATA['below_depth'] = (depth - 1) * HEIGHT mySlope = generate_failures(DATA['h'], DATA['slope_angle'], DATA['steps_number'], DATA['left_right'], DATA['radius_range'], below_level=DATA['below_depth'], density=DATA['density'], plot=False) iter_data = [depth, SLOPE, mySlope.stability_number, mySlope.radius, mySlope.circle_cg[0], mySlope.circle_cg[1], mySlope.type, mySlope.compound] f.write(write_list(iter_data)) f.close() for angle in range(10,90,5): plt.clf() update_data(new_slope=angle) mySlope = generate_failures(DATA['h'], DATA['slope_angle'], DATA['steps_number'], DATA['left_right'], DATA['radius_range'], below_level=DATA['below_depth'], density=DATA['density']) plt.gca().set_aspect('equal', adjustable='box') plt.xlim(-10,70) plt.ylim(-1*DATA['below_depth']-1,50) plt.savefig('plots/' + str(angle) + '.png')
ds = [1, 1.2, 1.5, 2, 4] file_name = 'f.csv' f = open(file_name, 'r') for depth in Ds: print('\n\n DEALING WITH ALL D = ', depth - 1) DATA['below_depth'] = (depth - 1) * HEIGHT for angle in range(2, 90, 1): if angle % 5 == 0: continue if angle >= 50 and angle <= 60: continue f.close() f = open(file_name, 'a') update_data(new_slope=angle, radius_step=0.1, steps_number=400) DATA['below_depth'] = (depth - 1) * HEIGHT my_slope = generate_failures(DATA['h'], DATA['slope_angle'], DATA['steps_number'], DATA['left_right'], DATA['radius_range'], below_level=DATA['below_depth'], density=DATA['density'], plot=False) iter_data = [depth, SLOPE, mySlope.stability_number, mySlope.radius, mySlope.circle_cg[0], mySlope.circle_cg[1], mySlope.type, mySlope.compound] f.write(write_list(iter_data)) f.close() for angle in range(10, 90, 5): plt.clf() update_data(new_slope=angle) my_slope = generate_failures(DATA['h'], DATA['slope_angle'], DATA['steps_number'], DATA['left_right'], DATA['radius_range'], below_level=DATA['below_depth'], density=DATA['density']) plt.gca().set_aspect('equal', adjustable='box') plt.xlim(-10, 70) plt.ylim(-1 * DATA['below_depth'] - 1, 50) plt.savefig('plots/' + str(angle) + '.png')
class Db(): def __init__(self, section, host, wiki): self.section = section self.host = host self.wiki = wiki
class Db: def __init__(self, section, host, wiki): self.section = section self.host = host self.wiki = wiki
"""Classes for handling geometry. Geometric objects (see :class:`GeometricObject`) are usually used in :class:`~ihm.restraint.GeometricRestraint` objects. """ class Center(object): """Define the center of a geometric object in Cartesian space. :param float x: x coordinate :param float y: y coordinate :param float z: z coordinate """ def __init__(self, x, y, z): self.x, self.y, self.z = x, y, z class Transformation(object): """Rotation and translation applied to an object. Transformation objects are typically used in subclasses of :class:`GeometricObject`, or by :class:`ihm.dataset.TransformedDataset`. :param rot_matrix: Rotation matrix (as a 3x3 array of floats) that places the object in its final position. :param tr_vector: Translation vector (as a 3-element float list) that places the object in its final position. """ def __init__(self, rot_matrix, tr_vector): self.rot_matrix, self.tr_vector = rot_matrix, tr_vector """Return the identity transformation. :return: A new identity Transformation. :rtype: :class:`Transformation` """ @classmethod def identity(cls): return cls([[1., 0., 0.], [0., 1., 0.], [0., 0., 1.]], [0.,0.,0.]) class GeometricObject(object): """A generic geometric object. See also :class:`Sphere`, :class:`Torus`, :class:`Axis`, :class:`Plane`. Geometric objects are typically assigned to one or more :class:`~ihm.restraint.GeometricRestraint` objects. :param str name: A short user-provided name. :param str description: A brief description of the object. """ type = 'other' def __init__(self, name=None, description=None): self.name, self.description = name, description class Sphere(GeometricObject): """A sphere in Cartesian space. :param center: Coordinates of the center of the sphere. :type center: :class:`Center` :param radius: Radius of the sphere. :param transformation: Rotation and translation that moves the sphere from the original center to its final location, if any. :type transformation: :class:`Transformation` :param str name: A short user-provided name. :param str description: A brief description of the object. """ type = 'sphere' def __init__(self, center, radius, transformation=None, name=None, description=None): super(Sphere, self).__init__(name, description) self.center, self.transformation = center, transformation self.radius = radius class Torus(GeometricObject): """A torus in Cartesian space. :param center: Coordinates of the center of the torus. :type center: :class:`Center` :param major_radius: The major radius - the distance from the center of the tube to the center of the torus. :param minor_radius: The minor radius - the radius of the tube. :param transformation: Rotation and translation that moves the torus (which by default lies in the xy plane) from the original center to its final location, if any. :type transformation: :class:`Transformation` :param str name: A short user-provided name. :param str description: A brief description of the object. """ type = 'torus' def __init__(self, center, major_radius, minor_radius, transformation=None, name=None, description=None): super(Torus, self).__init__(name, description) self.center, self.transformation = center, transformation self.major_radius, self.minor_radius = major_radius, minor_radius class HalfTorus(GeometricObject): """A section of a :class:`Torus`. This is defined as a surface over part of the torus with a given thickness, and is often used to represent a membrane. :param thickness: The thickness of the surface. :param inner: True if the surface is the 'inner' half of the torus (i.e. closer to the center), False for the outer surface, or None for some other section (described in `description`). See :class:`Torus` for a description of the other parameters. """ type = 'half-torus' def __init__(self, center, major_radius, minor_radius, thickness, transformation=None, inner=None, name=None, description=None): super(HalfTorus, self).__init__(name, description) self.center, self.transformation = center, transformation self.major_radius, self.minor_radius = major_radius, minor_radius self.thickness, self.inner = thickness, inner class Axis(GeometricObject): """One of the three Cartesian axes - see :class:`XAxis`, :class:`YAxis`, :class:`ZAxis`. :param transformation: Rotation and translation that moves the axis from the original Cartesian axis to its final location, if any. :type transformation: :class:`Transformation` :param str name: A short user-provided name. :param str description: A brief description of the object. """ type = 'axis' def __init__(self, transformation=None, name=None, description=None): super(Axis, self).__init__(name, description) self.transformation = transformation class XAxis(Axis): """The x Cartesian axis. See :class:`GeometricObject` for a description of the parameters. """ axis_type = 'x-axis' class YAxis(Axis): """The y Cartesian axis. See :class:`GeometricObject` for a description of the parameters. """ axis_type = 'y-axis' class ZAxis(Axis): """The z Cartesian axis. See :class:`GeometricObject` for a description of the parameters. """ axis_type = 'z-axis' class Plane(GeometricObject): """A plane in Cartesian space - see :class:`XYPlane`, :class:`YZPlane`, :class:`XZPlane`. :param transformation: Rotation and translation that moves the plane from the original position to its final location, if any. :type transformation: :class:`Transformation` :param str name: A short user-provided name. :param str description: A brief description of the object. """ type = 'plane' def __init__(self, transformation=None, name=None, description=None): super(Plane, self).__init__(name, description) self.transformation = transformation class XYPlane(Plane): """The xy plane in Cartesian space. See :class:`GeometricObject` for a description of the parameters. """ plane_type = 'xy-plane' class YZPlane(Plane): """The yz plane in Cartesian space. See :class:`GeometricObject` for a description of the parameters. """ plane_type = 'yz-plane' class XZPlane(Plane): """The xz plane in Cartesian space. See :class:`GeometricObject` for a description of the parameters. """ plane_type = 'xz-plane'
"""Classes for handling geometry. Geometric objects (see :class:`GeometricObject`) are usually used in :class:`~ihm.restraint.GeometricRestraint` objects. """ class Center(object): """Define the center of a geometric object in Cartesian space. :param float x: x coordinate :param float y: y coordinate :param float z: z coordinate """ def __init__(self, x, y, z): (self.x, self.y, self.z) = (x, y, z) class Transformation(object): """Rotation and translation applied to an object. Transformation objects are typically used in subclasses of :class:`GeometricObject`, or by :class:`ihm.dataset.TransformedDataset`. :param rot_matrix: Rotation matrix (as a 3x3 array of floats) that places the object in its final position. :param tr_vector: Translation vector (as a 3-element float list) that places the object in its final position. """ def __init__(self, rot_matrix, tr_vector): (self.rot_matrix, self.tr_vector) = (rot_matrix, tr_vector) 'Return the identity transformation.\n\n :return: A new identity Transformation.\n :rtype: :class:`Transformation`\n ' @classmethod def identity(cls): return cls([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]], [0.0, 0.0, 0.0]) class Geometricobject(object): """A generic geometric object. See also :class:`Sphere`, :class:`Torus`, :class:`Axis`, :class:`Plane`. Geometric objects are typically assigned to one or more :class:`~ihm.restraint.GeometricRestraint` objects. :param str name: A short user-provided name. :param str description: A brief description of the object. """ type = 'other' def __init__(self, name=None, description=None): (self.name, self.description) = (name, description) class Sphere(GeometricObject): """A sphere in Cartesian space. :param center: Coordinates of the center of the sphere. :type center: :class:`Center` :param radius: Radius of the sphere. :param transformation: Rotation and translation that moves the sphere from the original center to its final location, if any. :type transformation: :class:`Transformation` :param str name: A short user-provided name. :param str description: A brief description of the object. """ type = 'sphere' def __init__(self, center, radius, transformation=None, name=None, description=None): super(Sphere, self).__init__(name, description) (self.center, self.transformation) = (center, transformation) self.radius = radius class Torus(GeometricObject): """A torus in Cartesian space. :param center: Coordinates of the center of the torus. :type center: :class:`Center` :param major_radius: The major radius - the distance from the center of the tube to the center of the torus. :param minor_radius: The minor radius - the radius of the tube. :param transformation: Rotation and translation that moves the torus (which by default lies in the xy plane) from the original center to its final location, if any. :type transformation: :class:`Transformation` :param str name: A short user-provided name. :param str description: A brief description of the object. """ type = 'torus' def __init__(self, center, major_radius, minor_radius, transformation=None, name=None, description=None): super(Torus, self).__init__(name, description) (self.center, self.transformation) = (center, transformation) (self.major_radius, self.minor_radius) = (major_radius, minor_radius) class Halftorus(GeometricObject): """A section of a :class:`Torus`. This is defined as a surface over part of the torus with a given thickness, and is often used to represent a membrane. :param thickness: The thickness of the surface. :param inner: True if the surface is the 'inner' half of the torus (i.e. closer to the center), False for the outer surface, or None for some other section (described in `description`). See :class:`Torus` for a description of the other parameters. """ type = 'half-torus' def __init__(self, center, major_radius, minor_radius, thickness, transformation=None, inner=None, name=None, description=None): super(HalfTorus, self).__init__(name, description) (self.center, self.transformation) = (center, transformation) (self.major_radius, self.minor_radius) = (major_radius, minor_radius) (self.thickness, self.inner) = (thickness, inner) class Axis(GeometricObject): """One of the three Cartesian axes - see :class:`XAxis`, :class:`YAxis`, :class:`ZAxis`. :param transformation: Rotation and translation that moves the axis from the original Cartesian axis to its final location, if any. :type transformation: :class:`Transformation` :param str name: A short user-provided name. :param str description: A brief description of the object. """ type = 'axis' def __init__(self, transformation=None, name=None, description=None): super(Axis, self).__init__(name, description) self.transformation = transformation class Xaxis(Axis): """The x Cartesian axis. See :class:`GeometricObject` for a description of the parameters. """ axis_type = 'x-axis' class Yaxis(Axis): """The y Cartesian axis. See :class:`GeometricObject` for a description of the parameters. """ axis_type = 'y-axis' class Zaxis(Axis): """The z Cartesian axis. See :class:`GeometricObject` for a description of the parameters. """ axis_type = 'z-axis' class Plane(GeometricObject): """A plane in Cartesian space - see :class:`XYPlane`, :class:`YZPlane`, :class:`XZPlane`. :param transformation: Rotation and translation that moves the plane from the original position to its final location, if any. :type transformation: :class:`Transformation` :param str name: A short user-provided name. :param str description: A brief description of the object. """ type = 'plane' def __init__(self, transformation=None, name=None, description=None): super(Plane, self).__init__(name, description) self.transformation = transformation class Xyplane(Plane): """The xy plane in Cartesian space. See :class:`GeometricObject` for a description of the parameters. """ plane_type = 'xy-plane' class Yzplane(Plane): """The yz plane in Cartesian space. See :class:`GeometricObject` for a description of the parameters. """ plane_type = 'yz-plane' class Xzplane(Plane): """The xz plane in Cartesian space. See :class:`GeometricObject` for a description of the parameters. """ plane_type = 'xz-plane'
# a dp method class Solution: def longestPalindrome(self, s: str) -> str: size = len(s) if size < 2: return s dp = [[False for _ in range(size)] for _ in range(size)] maxLen = 1 start = 0 for i in range(size): dp[i][i] = True for j in range(1, size): for i in range(0, j): if s[i] == s[j]: if j - i <= 2: dp[i][j] = True else: dp[i][j] = dp[i + 1][j - 1] if dp[i][j]: curLen = j - i + 1 if curLen > maxLen: maxLen = curLen start = i return s[start : start + maxLen]
class Solution: def longest_palindrome(self, s: str) -> str: size = len(s) if size < 2: return s dp = [[False for _ in range(size)] for _ in range(size)] max_len = 1 start = 0 for i in range(size): dp[i][i] = True for j in range(1, size): for i in range(0, j): if s[i] == s[j]: if j - i <= 2: dp[i][j] = True else: dp[i][j] = dp[i + 1][j - 1] if dp[i][j]: cur_len = j - i + 1 if curLen > maxLen: max_len = curLen start = i return s[start:start + maxLen]
""" Use the Eratoshenes Algorithm to generate first 1229 prime numbers. """ max = 10000 smax = 100 # sqrt(10000) lst = [] # number list, all True (is prime) at first for i in range(max + 1): # initialization lst.append(True) for i in range(2, smax + 1): # Eratoshenes Algorithm sieve = 2 * i while sieve <= max: lst[sieve] = False sieve += i for i in range(2, max + 1): # output in a line if lst[i] == True: print(i, end=',')
""" Use the Eratoshenes Algorithm to generate first 1229 prime numbers. """ max = 10000 smax = 100 lst = [] for i in range(max + 1): lst.append(True) for i in range(2, smax + 1): sieve = 2 * i while sieve <= max: lst[sieve] = False sieve += i for i in range(2, max + 1): if lst[i] == True: print(i, end=',')
#Votes Voter0 = int(input("Vote:")) Voter1 = int(input("Vote:")) Voter2 = int(input("Vote:")) #Count def count_votes(): #Accounts voter0_account = 0 voter1_account = 0 voter2_account = 0 #Total total = Voter0 + Voter1 + Voter2 #Return if total > 1: voter2_account =+ 1 print(voter2_account) else: print(voter2_account) count_votes()
voter0 = int(input('Vote:')) voter1 = int(input('Vote:')) voter2 = int(input('Vote:')) def count_votes(): voter0_account = 0 voter1_account = 0 voter2_account = 0 total = Voter0 + Voter1 + Voter2 if total > 1: voter2_account = +1 print(voter2_account) else: print(voter2_account) count_votes()
otra_coordenada=(0, 1) new=otra_coordenada.x print(new)
otra_coordenada = (0, 1) new = otra_coordenada.x print(new)
#!/usr/bin/env python # coding: utf-8 # Given two arrays, write a function to compute their intersection. # # Example 1: # # Input: nums1 = [1,2,2,1], nums2 = [2,2] # Output: [2] # Example 2: # # Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4] # Output: [9,4] # In[1]: def intersection(nums1, nums2): return list(set(nums1) & set(nums2)) print(intersection([4,9,5],[9,4,9,8,4])) # In[2]: def intersection(nums1, nums2): stack =[] for i in nums1: if i not in stack and i in nums2: stack.append(i) return stack print(intersection([4,9,5],[9,4,9,8,4])) # In[ ]:
def intersection(nums1, nums2): return list(set(nums1) & set(nums2)) print(intersection([4, 9, 5], [9, 4, 9, 8, 4])) def intersection(nums1, nums2): stack = [] for i in nums1: if i not in stack and i in nums2: stack.append(i) return stack print(intersection([4, 9, 5], [9, 4, 9, 8, 4]))
s = 0 for c in range(0, 6): n = int(input('Digite numero inteiro: ')) if n%2==0: s += n print(f'A soma dos valores par e {s}')
s = 0 for c in range(0, 6): n = int(input('Digite numero inteiro: ')) if n % 2 == 0: s += n print(f'A soma dos valores par e {s}')
#stringCaps.py msg = "john nash" print(msg) # ALL CAPS msg_upper = msg.upper() print(msg_upper) # First Letter Of Each Word Capitalized msg_title = msg.title() print(msg_title)
msg = 'john nash' print(msg) msg_upper = msg.upper() print(msg_upper) msg_title = msg.title() print(msg_title)
def create_500M_file(name): native.genrule( name = name + "_target", outs = [name], output_to_bindir = 1, cmd = "truncate -s 500M $@", )
def create_500_m_file(name): native.genrule(name=name + '_target', outs=[name], output_to_bindir=1, cmd='truncate -s 500M $@')
hotels = pois[pois['fclass']=='hotel'] citylondon = boroughs.loc[boroughs['name'] == 'City of London', 'geometry'].squeeze() cityhotels = hotels[hotels.within(citylondon)] [fig,ax] = plt.subplots(1, figsize=(12, 8)) base = boroughs.plot(color='lightblue', edgecolor='black',ax=ax); cityhotels.plot(ax=ax, marker='o', color='red', markersize=8); ax.axis('off');
hotels = pois[pois['fclass'] == 'hotel'] citylondon = boroughs.loc[boroughs['name'] == 'City of London', 'geometry'].squeeze() cityhotels = hotels[hotels.within(citylondon)] [fig, ax] = plt.subplots(1, figsize=(12, 8)) base = boroughs.plot(color='lightblue', edgecolor='black', ax=ax) cityhotels.plot(ax=ax, marker='o', color='red', markersize=8) ax.axis('off')