content
stringlengths
7
1.05M
fixed_cases
stringlengths
1
1.28M
#!/usr/bin/env python3 names = ['Alice', 'Bob', 'John'] for name in names: print(name)
names = ['Alice', 'Bob', 'John'] for name in names: print(name)
''' Exception classes for cr-vision library ''' # Definitive guide to Python exceptions https://julien.danjou.info/python-exceptions-guide/ class CRVError(Exception): '''Base exception class''' class InvalidNumDimensionsError(CRVError): '''Invalid number of dimensions error''' class InvalidNumChannelsError(CRVError): ''' Invalid number of channels error''' def __init__(self, expected_channels, actual_channels): message = 'Invalid number of channels. Expected: {}, Actual: {}'.format( expected_channels, actual_channels) super().__init__(message) class NotU8C1Error(CRVError): '''Image is not grayscale 8 bit unsigned''' class NotU8C3Error(CRVError): '''Image is not 8 bit unsigned 3 channel color image''' class UnsupportedImageFormatError(CRVError): """Unsupported image format""" def check_ndim(actual_ndim, expected_min_ndim=None, expected_max_ndim=None): ''' Checks if the number of dimensions is correct''' message = None if expected_min_ndim is not None and expected_max_ndim is not None: if expected_min_ndim == expected_max_ndim: if actual_ndim != expected_min_ndim: message = 'Invalid number of dimensions. Expected: {}, Actual: {}'.format( expected_min_ndim, actual_ndim) else: if actual_ndim < expected_min_ndim or actual_ndim > expected_max_ndim: message = 'Invalid dimensions. Expected between: {}-{}, Actual: {}'.format( expected_min_ndim, expected_max_ndim, actual_ndim) elif expected_min_ndim is not None: if actual_ndim < expected_min_ndim: message = 'Expected Minimum: {}, Actual: {}'.format( expected_min_ndim, actual_ndim) elif expected_max_ndim is not None: if actual_ndim > expected_max_ndim: message = 'Expected Maximum: {}, Actual: {}'.format( expected_max_ndim, actual_ndim) if message is not None: raise InvalidNumDimensionsError(message) def check_nchannels(expected_channels, actual_channels): '''Checks if number of channels is correct''' if actual_channels != expected_channels: raise InvalidNumChannelsError(expected_channels, actual_channels) def check_u8c1(image): '''Checks that the image is an unsigned 8 bit image with one channel''' if image.dtype != 'uint8': raise NotU8C1Error('The image data type is not unsigned 8 bit') if image.ndim == 1: raise NotU8C1Error('It is a vector. Expected an image.') elif image.ndim == 2: # all good pass elif image.ndim == 3: if image.shape[2] != 1: raise NotU8C1Error('Image has more than one channels') else: raise NotU8C1Error('Invalid dimensions') def check_u8c3(image): '''Chcecks that the image is an unsigned 8 bit image with 3 channels''' if image.dtype != 'uint8': raise NotU8C3Error('The image data type is not unsigned 8 bit') if image.ndim != 3: raise NotU8C3Error('Image must have 3 dimensions') if image.shape[2] != 3: raise NotU8C3Error('Image must have 3 channels') def error_unsupported_image_format(format=None): """Raises UnsupportedImageFormatError exception""" if format is None: raise UnsupportedImageFormatError("Unsupported image format") message = "Unsupported image format: {}".format(format) raise UnsupportedImageFormatError(message)
""" Exception classes for cr-vision library """ class Crverror(Exception): """Base exception class""" class Invalidnumdimensionserror(CRVError): """Invalid number of dimensions error""" class Invalidnumchannelserror(CRVError): """ Invalid number of channels error""" def __init__(self, expected_channels, actual_channels): message = 'Invalid number of channels. Expected: {}, Actual: {}'.format(expected_channels, actual_channels) super().__init__(message) class Notu8C1Error(CRVError): """Image is not grayscale 8 bit unsigned""" class Notu8C3Error(CRVError): """Image is not 8 bit unsigned 3 channel color image""" class Unsupportedimageformaterror(CRVError): """Unsupported image format""" def check_ndim(actual_ndim, expected_min_ndim=None, expected_max_ndim=None): """ Checks if the number of dimensions is correct""" message = None if expected_min_ndim is not None and expected_max_ndim is not None: if expected_min_ndim == expected_max_ndim: if actual_ndim != expected_min_ndim: message = 'Invalid number of dimensions. Expected: {}, Actual: {}'.format(expected_min_ndim, actual_ndim) elif actual_ndim < expected_min_ndim or actual_ndim > expected_max_ndim: message = 'Invalid dimensions. Expected between: {}-{}, Actual: {}'.format(expected_min_ndim, expected_max_ndim, actual_ndim) elif expected_min_ndim is not None: if actual_ndim < expected_min_ndim: message = 'Expected Minimum: {}, Actual: {}'.format(expected_min_ndim, actual_ndim) elif expected_max_ndim is not None: if actual_ndim > expected_max_ndim: message = 'Expected Maximum: {}, Actual: {}'.format(expected_max_ndim, actual_ndim) if message is not None: raise invalid_num_dimensions_error(message) def check_nchannels(expected_channels, actual_channels): """Checks if number of channels is correct""" if actual_channels != expected_channels: raise invalid_num_channels_error(expected_channels, actual_channels) def check_u8c1(image): """Checks that the image is an unsigned 8 bit image with one channel""" if image.dtype != 'uint8': raise not_u8_c1_error('The image data type is not unsigned 8 bit') if image.ndim == 1: raise not_u8_c1_error('It is a vector. Expected an image.') elif image.ndim == 2: pass elif image.ndim == 3: if image.shape[2] != 1: raise not_u8_c1_error('Image has more than one channels') else: raise not_u8_c1_error('Invalid dimensions') def check_u8c3(image): """Chcecks that the image is an unsigned 8 bit image with 3 channels""" if image.dtype != 'uint8': raise not_u8_c3_error('The image data type is not unsigned 8 bit') if image.ndim != 3: raise not_u8_c3_error('Image must have 3 dimensions') if image.shape[2] != 3: raise not_u8_c3_error('Image must have 3 channels') def error_unsupported_image_format(format=None): """Raises UnsupportedImageFormatError exception""" if format is None: raise unsupported_image_format_error('Unsupported image format') message = 'Unsupported image format: {}'.format(format) raise unsupported_image_format_error(message)
# pylint: disable=too-many-instance-attributes # number of attributes is reasonable in this case class Skills: def __init__(self): self.acrobatics = Skill() self.animal_handling = Skill() self.arcana = Skill() self.athletics = Skill() self.deception = Skill() self.history = Skill() self.insight = Skill() self.intimidation = Skill() self.investigation = Skill() self.medicine = Skill() self.nature = Skill() self.perception = Skill() self.performance = Skill() self.persuasion = Skill() self.religion = Skill() self.sleight_of_hand = Skill() self.stealth = Skill() self.survival = Skill() class Skill: def __init__(self): self._proficient = False self._modifier = 0 @property def proficient(self): return self._proficient @proficient.setter def proficient(self, proficient): self._proficient = proficient @property def modifier(self): return self._modifier @modifier.setter def modifier(self, modifier): self._modifier = modifier
class Skills: def __init__(self): self.acrobatics = skill() self.animal_handling = skill() self.arcana = skill() self.athletics = skill() self.deception = skill() self.history = skill() self.insight = skill() self.intimidation = skill() self.investigation = skill() self.medicine = skill() self.nature = skill() self.perception = skill() self.performance = skill() self.persuasion = skill() self.religion = skill() self.sleight_of_hand = skill() self.stealth = skill() self.survival = skill() class Skill: def __init__(self): self._proficient = False self._modifier = 0 @property def proficient(self): return self._proficient @proficient.setter def proficient(self, proficient): self._proficient = proficient @property def modifier(self): return self._modifier @modifier.setter def modifier(self, modifier): self._modifier = modifier
class TestResult: def __init__(self, test_case) -> None: self.__test_case = test_case self.__failed = False self.__reason = None def record_failure(self, reason: str): self.__reason = reason self.__failed = True def test_case(self) -> str: return type(self.__test_case).__name__ def test_name(self) -> str: return self.__test_case.name() def failed(self) -> bool: return self.__failed def reason(self) -> str: return self.__reason class IReport: def record_test_result(self, test_result: TestResult): raise NotImplementedError def test_results(self) -> dict[str, list]: raise NotImplementedError def run_count(self) -> int: raise NotImplementedError def failure_count(self) -> int: raise NotImplementedError class IFormatter: @classmethod def format(cls, test_report: IReport) -> any: raise NotImplementedError
class Testresult: def __init__(self, test_case) -> None: self.__test_case = test_case self.__failed = False self.__reason = None def record_failure(self, reason: str): self.__reason = reason self.__failed = True def test_case(self) -> str: return type(self.__test_case).__name__ def test_name(self) -> str: return self.__test_case.name() def failed(self) -> bool: return self.__failed def reason(self) -> str: return self.__reason class Ireport: def record_test_result(self, test_result: TestResult): raise NotImplementedError def test_results(self) -> dict[str, list]: raise NotImplementedError def run_count(self) -> int: raise NotImplementedError def failure_count(self) -> int: raise NotImplementedError class Iformatter: @classmethod def format(cls, test_report: IReport) -> any: raise NotImplementedError
# -*- coding: utf-8 -*- def get_tokens(line): """tokenize a line""" return line.split() def read_metro_map_file(filename): """read ressources from a metro map input file""" sections = ('[Vertices]', '[Edges]') vertices = dict(); edges = list(); line_number = 0 section = None with open(filename, "r") as input_file: for line in input_file: line_number += 1 tokens = get_tokens(line) if len(tokens) > 0: if tokens[0][:1] == '[': # section keyword, check that it ends with a ']' if tokens[0][-1:] == ']': section = tokens[0] if section in sections: pass else: print("ERROR invalid section name at line {} : {}".format(line_number, line)) else: # in section line if section is None: print("WARNING lines before any section at line {} : {}".format(line_number, line)) elif section == '[Vertices]': # remove leading zeros key = tokens[0].lstrip("0") if key == '': key = '0' if key in vertices: print("ERROR duplicated key at line {} : {}".format(line_number, line)) else: vertices[key] = ' '.join(tokens[1:]) elif section == '[Edges]': duration = float(tokens[2]) edges.append((tokens[0], tokens[1], duration)) else: # kind of section not handled pass # sanity check for source, destination, duration in edges: if source not in vertices: print("ERROR source is not a vertice {} -> {} : {}".format(source, destination, duration)) if destination not in vertices: print("ERROR destination is not a vertice {} -> {} : {}".format(source, destination, duration)) if duration <= 0: print("ERROR invalid duration {} -> {} : {}".format(source, destination, duration)) resources = dict() resources["vertices"] = vertices resources["edges"] = edges return resources
def get_tokens(line): """tokenize a line""" return line.split() def read_metro_map_file(filename): """read ressources from a metro map input file""" sections = ('[Vertices]', '[Edges]') vertices = dict() edges = list() line_number = 0 section = None with open(filename, 'r') as input_file: for line in input_file: line_number += 1 tokens = get_tokens(line) if len(tokens) > 0: if tokens[0][:1] == '[': if tokens[0][-1:] == ']': section = tokens[0] if section in sections: pass else: print('ERROR invalid section name at line {} : {}'.format(line_number, line)) elif section is None: print('WARNING lines before any section at line {} : {}'.format(line_number, line)) elif section == '[Vertices]': key = tokens[0].lstrip('0') if key == '': key = '0' if key in vertices: print('ERROR duplicated key at line {} : {}'.format(line_number, line)) else: vertices[key] = ' '.join(tokens[1:]) elif section == '[Edges]': duration = float(tokens[2]) edges.append((tokens[0], tokens[1], duration)) else: pass for (source, destination, duration) in edges: if source not in vertices: print('ERROR source is not a vertice {} -> {} : {}'.format(source, destination, duration)) if destination not in vertices: print('ERROR destination is not a vertice {} -> {} : {}'.format(source, destination, duration)) if duration <= 0: print('ERROR invalid duration {} -> {} : {}'.format(source, destination, duration)) resources = dict() resources['vertices'] = vertices resources['edges'] = edges return resources
#!/usr/bin/python #-*-coding:utf-8-*- '''This packge contains the UCT algorithem of the UAV searching. The algorithem conform to the standard OperateInterface defined in the PlatForm class.''' __all__ = ['UCTControl', 'UCTSearchTree', 'UCTTreeNode']
"""This packge contains the UCT algorithem of the UAV searching. The algorithem conform to the standard OperateInterface defined in the PlatForm class.""" __all__ = ['UCTControl', 'UCTSearchTree', 'UCTTreeNode']
# --- Starting python tests --- #Funct def functione(x,y): return x*y # call print(format(functione(2,3)))
def functione(x, y): return x * y print(format(functione(2, 3)))
# # CLASS MEHTODS # class Employee: # company ="camel" # salary = 100 # location = "mumbai" # def ChangeSalary(self, sal): # self.__class__.salary = sal # # THE EASY METHOD FOR THE ABOVE STATEMENT AND FOR THE CLASS ATTRIBUTE IS # @classmethod # def ChangeSalary(cls, sal): # cls.salary = sal # e = Employee() # print("this is e.salary obj of employee************",e.salary) # print("this is of employee**********", Employee.salary) # e.ChangeSalary(455) # print("this is the e .salary obj after using e.changeSalary method so this is an instance*************", e.salary) # print("This is the same Employee that hasnt been changed even after we use e.chanegSalary************", Employee.salary) # PROPERTY DECORATOR class Employee: company = "Bharat Gas" salary =4500 salaryBonus= 500 # totalSalary = 5000 # ALSO CALLED AS GETTER METHOD @property def totalSalary(self): return self.salary +self.salaryBonus @totalSalary.setter def totalSalary(self, val): self.salaryBonus = val - self.salary e= Employee() print(e.totalSalary) e.totalSalary = 4900 print(e.totalSalary) print(e.salary) print(e.salaryBonus)
class Employee: company = 'Bharat Gas' salary = 4500 salary_bonus = 500 @property def total_salary(self): return self.salary + self.salaryBonus @totalSalary.setter def total_salary(self, val): self.salaryBonus = val - self.salary e = employee() print(e.totalSalary) e.totalSalary = 4900 print(e.totalSalary) print(e.salary) print(e.salaryBonus)
#!/usr/bin/env python3 # -*- coding: utf-8 -*- def bubble_sort(arr): for n in range(len(arr)-1, 0, -1): for k in range(n): if r[k] > r[k+1]: tmp = r[k] r[k] = r[k+1] r[k+1] = tmp if __name__ == '__main__': r = [5, 4, 2, 3, 1] bubble_sort(r) print(r)
def bubble_sort(arr): for n in range(len(arr) - 1, 0, -1): for k in range(n): if r[k] > r[k + 1]: tmp = r[k] r[k] = r[k + 1] r[k + 1] = tmp if __name__ == '__main__': r = [5, 4, 2, 3, 1] bubble_sort(r) print(r)
# Let's say you have a dictionary matchinhg your friends' names # with their favorite flowers: fav_flowers = {'Alex': 'field flowers', 'Kate': 'daffodil', 'Eva': 'artichoke flower', 'Daniel': 'tulip'} # Your new friend Alice likes orchid the most: add this info to the # fav_flowers dict and print the dict. # NB: Do not redefine the dictionary itself, just add the new # element to the existing one. fav_flowers['Alice'] = 'orchid' print(fav_flowers)
fav_flowers = {'Alex': 'field flowers', 'Kate': 'daffodil', 'Eva': 'artichoke flower', 'Daniel': 'tulip'} fav_flowers['Alice'] = 'orchid' print(fav_flowers)
num1 = float(input("Enter 1st number: ")) op = input("Enter operator: ") num2 = float(input("Enter 2nd number: ")) if op == "+": val = num1 + num2 elif op == "-": val = num1 - num2 elif op == "*" or op == "x": val = num1 * num2 elif op == "/": val = num1 / num2 print(val)
num1 = float(input('Enter 1st number: ')) op = input('Enter operator: ') num2 = float(input('Enter 2nd number: ')) if op == '+': val = num1 + num2 elif op == '-': val = num1 - num2 elif op == '*' or op == 'x': val = num1 * num2 elif op == '/': val = num1 / num2 print(val)
def count_substring(string, sub_string): times = 0 length = len(sub_string) for letter in range(0, len(string)): if string[letter:letter+length] == sub_string: times += 1 return times
def count_substring(string, sub_string): times = 0 length = len(sub_string) for letter in range(0, len(string)): if string[letter:letter + length] == sub_string: times += 1 return times
#!/usr/bin/pthon3 # Time complexity: O(N) def solution(A): count = {} size_A = len(A) leader = None for i, a in enumerate(A): count[a] = count.get(a, 0) + 1 if count[a] > size_A // 2: leader = a equi_leader = 0 before = 0 for i in range(size_A): if A[i] == leader: before += 1 if (before > (i + 1) // 2) and ((count[leader] - before) > (size_A - i - 1) // 2): equi_leader += 1 return equi_leader
def solution(A): count = {} size_a = len(A) leader = None for (i, a) in enumerate(A): count[a] = count.get(a, 0) + 1 if count[a] > size_A // 2: leader = a equi_leader = 0 before = 0 for i in range(size_A): if A[i] == leader: before += 1 if before > (i + 1) // 2 and count[leader] - before > (size_A - i - 1) // 2: equi_leader += 1 return equi_leader
class Solution: def isHappy(self, n): """ :type n: int :rtype: bool """ tried = set() while n not in tried and n != 1: tried.add(n) n2 = 0 while n > 0: n2, n = n2 + (n % 10) ** 2, n // 10 n = n2 return n == 1 if __name__ == "__main__": print(Solution().isHappy(19))
class Solution: def is_happy(self, n): """ :type n: int :rtype: bool """ tried = set() while n not in tried and n != 1: tried.add(n) n2 = 0 while n > 0: (n2, n) = (n2 + (n % 10) ** 2, n // 10) n = n2 return n == 1 if __name__ == '__main__': print(solution().isHappy(19))
n1 = int(input('digite um valor >>')) n2 = int(input('digite outro vaor >>')) n3 = int(input('digite outro valor >>')) #menor menor = n1 if n2 < n1 and n2 < n3: menor = n2 if n3 < n1 and n3 < n2: menor = n3 #maior maior = n1 if n2 > n1 and n2 > n3: maior = n2 if n3 > n1 and n3 > n2: maior = n3 print('o maior numero e {}'.format(maior)) print('o menor numero e {}'.format(menor))
n1 = int(input('digite um valor >>')) n2 = int(input('digite outro vaor >>')) n3 = int(input('digite outro valor >>')) menor = n1 if n2 < n1 and n2 < n3: menor = n2 if n3 < n1 and n3 < n2: menor = n3 maior = n1 if n2 > n1 and n2 > n3: maior = n2 if n3 > n1 and n3 > n2: maior = n3 print('o maior numero e {}'.format(maior)) print('o menor numero e {}'.format(menor))
def fahrenheit_to_celsius(deg_F): """Convert degrees Fahrenheit to Celsius.""" return (5 / 9) * (deg_F - 32) def celsius_to_fahrenheit(deg_C): """Convert degrees Celsius to Fahrenheit.""" return (9 / 5) * deg_C + 32 def celsius_to_kelvin(deg_C): """Convert degree Celsius to Kelvin.""" return deg_C + 273.15 def fahrenheit_to_kelvin(deg_F): """Convert degree Fahrenheit to Kelvin.""" deg_C = fahrenheit_to_celsius(deg_F) return celsius_to_kelvin(deg_C)
def fahrenheit_to_celsius(deg_F): """Convert degrees Fahrenheit to Celsius.""" return 5 / 9 * (deg_F - 32) def celsius_to_fahrenheit(deg_C): """Convert degrees Celsius to Fahrenheit.""" return 9 / 5 * deg_C + 32 def celsius_to_kelvin(deg_C): """Convert degree Celsius to Kelvin.""" return deg_C + 273.15 def fahrenheit_to_kelvin(deg_F): """Convert degree Fahrenheit to Kelvin.""" deg_c = fahrenheit_to_celsius(deg_F) return celsius_to_kelvin(deg_C)
class TypeFactory(object): def __init__(self, client): self.client = client def create(self, transport_type, *args, **kwargs): klass = self.classes[transport_type] cls = klass(*args, **kwargs) cls._client = self.client return cls
class Typefactory(object): def __init__(self, client): self.client = client def create(self, transport_type, *args, **kwargs): klass = self.classes[transport_type] cls = klass(*args, **kwargs) cls._client = self.client return cls
# Copyright 2020-present Kensho Technologies, LLC. """Tools for constructing high-performance query interpreters over arbitrary schemas. While GraphQL compiler's database querying capabilities are sufficient for many use cases, there are many types of data querying for which the compilation-based approach is unsuitable. A few examples: - data accessible via a simple API instead of a rich query language, - data represented as a set of files and directories on a local disk, - data produced on-demand by running a machine learning model over some inputs. The data in each of these cases can be described by a valid schema, and users could write well-defined and legal queries against that schema. However, the execution of such queries cannot proceed by compiling them to another query language -- no such target query language exists. Instead, the queries need to be executed using an *interpreter*: a piece of code that executes queries incrementally in a series of steps, such as "fetch the value of this field" or "filter out this data point if its value is less than 5." Some parts of the interpreter (e.g. "fetch the value of this field") obviously need to be aware of the schema and the underlying data source. Other parts (e.g. "filter out this data point") are schema-agnostic -- they work in the same way regardless of the schema and data source. This library provides efficient implementations of all schema-agnostic interpreter components. All schema-aware logic is abstracted into the straightforward, four-method API of the InterpreterAdapter class, which should be subclassed to create a new interpreter over a new dataset. As a result, the development of a new interpreter looks like this: - Construct the schema of the data your new interpreter will be querying. - Construct a subclass InterpreterAdapter class -- let's call it MyCustomAdapter. - Add long-lived interpreter state such as API keys, connection pools, etc. as instance attributes of the MyCustomAdapter class. - Implement the four simple functions that form the InterpreterAdapter API. - Construct an instance of MyCustomAdapter and pass it to the schema-agnostic portion of the interpreter implemented in this library, such as the interpret_ir() function. - You now have a way to execute queries over your schema! Then, profit! For more information, consult the documentation of the items exported below. """
"""Tools for constructing high-performance query interpreters over arbitrary schemas. While GraphQL compiler's database querying capabilities are sufficient for many use cases, there are many types of data querying for which the compilation-based approach is unsuitable. A few examples: - data accessible via a simple API instead of a rich query language, - data represented as a set of files and directories on a local disk, - data produced on-demand by running a machine learning model over some inputs. The data in each of these cases can be described by a valid schema, and users could write well-defined and legal queries against that schema. However, the execution of such queries cannot proceed by compiling them to another query language -- no such target query language exists. Instead, the queries need to be executed using an *interpreter*: a piece of code that executes queries incrementally in a series of steps, such as "fetch the value of this field" or "filter out this data point if its value is less than 5." Some parts of the interpreter (e.g. "fetch the value of this field") obviously need to be aware of the schema and the underlying data source. Other parts (e.g. "filter out this data point") are schema-agnostic -- they work in the same way regardless of the schema and data source. This library provides efficient implementations of all schema-agnostic interpreter components. All schema-aware logic is abstracted into the straightforward, four-method API of the InterpreterAdapter class, which should be subclassed to create a new interpreter over a new dataset. As a result, the development of a new interpreter looks like this: - Construct the schema of the data your new interpreter will be querying. - Construct a subclass InterpreterAdapter class -- let's call it MyCustomAdapter. - Add long-lived interpreter state such as API keys, connection pools, etc. as instance attributes of the MyCustomAdapter class. - Implement the four simple functions that form the InterpreterAdapter API. - Construct an instance of MyCustomAdapter and pass it to the schema-agnostic portion of the interpreter implemented in this library, such as the interpret_ir() function. - You now have a way to execute queries over your schema! Then, profit! For more information, consult the documentation of the items exported below. """
length = float(input("Enter the length of a side of the cube: ")) total_surface_area = 6 * length ** 2 volume = 3 * length ** 2 print("The surface area of the cube is", total_surface_area) print("The volume of the cube is", volume) close = input("Press X to exit") # The above code keeps the program open for the user to see the outcome of the problem.
length = float(input('Enter the length of a side of the cube: ')) total_surface_area = 6 * length ** 2 volume = 3 * length ** 2 print('The surface area of the cube is', total_surface_area) print('The volume of the cube is', volume) close = input('Press X to exit')
#========================================================================================= class Task(): """Task is a part of Itinerary """ def __init__(self, aName, aDuration, aMachine): self.name = aName self.duration = aDuration self.machine = aMachine self.taskChanged = False def exportToDict(self): """Serialize information about Task into dictionary""" exData = {} exData['taskName'] = self.name exData['taskMachine'] = self.machine.exportToDict() exData['taskDuration'] = self.duration return exData
class Task: """Task is a part of Itinerary """ def __init__(self, aName, aDuration, aMachine): self.name = aName self.duration = aDuration self.machine = aMachine self.taskChanged = False def export_to_dict(self): """Serialize information about Task into dictionary""" ex_data = {} exData['taskName'] = self.name exData['taskMachine'] = self.machine.exportToDict() exData['taskDuration'] = self.duration return exData
""" lec 4, tuple and dictionary """ my_tuple='a','b','c','d','e' print(my_tuple) my_2nd_tuple=('a','b','c','d','e') print(my_2nd_tuple) test='a' print(type(test)) #not a tuple bc no comma Test='a', print(type(Test)) print(my_tuple[1]) print(my_tuple[-1]) print(my_tuple[1:3]) print(my_tuple[1:]) print(my_tuple[:3]) my_car={ 'color':'red', 'maker':'toyota', 'year':2015 } print(my_car['year']) print(my_car.get('year')) my_car['model']='corolla' print(my_car) my_car['year']=2020 print(my_car) print(len(my_car)) print('color'in my_car) print('mile' in my_car)
""" lec 4, tuple and dictionary """ my_tuple = ('a', 'b', 'c', 'd', 'e') print(my_tuple) my_2nd_tuple = ('a', 'b', 'c', 'd', 'e') print(my_2nd_tuple) test = 'a' print(type(test)) test = ('a',) print(type(Test)) print(my_tuple[1]) print(my_tuple[-1]) print(my_tuple[1:3]) print(my_tuple[1:]) print(my_tuple[:3]) my_car = {'color': 'red', 'maker': 'toyota', 'year': 2015} print(my_car['year']) print(my_car.get('year')) my_car['model'] = 'corolla' print(my_car) my_car['year'] = 2020 print(my_car) print(len(my_car)) print('color' in my_car) print('mile' in my_car)
def generate(): class Spam: count = 1 def method(self): print(count) return Spam() generate().method()
def generate(): class Spam: count = 1 def method(self): print(count) return spam() generate().method()
def add(a, b): """Adds a and b.""" return a + b if __name__ == '__main__': assert add(2, 5) == 7, '2 and 5 are not 7' assert add(-2, 5) == 3, '-2 and 5 are not 3' print('This executes only if I am main!')
def add(a, b): """Adds a and b.""" return a + b if __name__ == '__main__': assert add(2, 5) == 7, '2 and 5 are not 7' assert add(-2, 5) == 3, '-2 and 5 are not 3' print('This executes only if I am main!')
# Title : Generators in python # Author : Kiran raj R. # Date : 31:10:2020 def printNum(): num = 0 while True: yield num num += 1 result = printNum() print(next(result)) print(next(result)) print(next(result)) result = (num for num in range(10000)) print(result) print(next(result)) print(next(result)) print(next(result))
def print_num(): num = 0 while True: yield num num += 1 result = print_num() print(next(result)) print(next(result)) print(next(result)) result = (num for num in range(10000)) print(result) print(next(result)) print(next(result)) print(next(result))
""" Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. """ class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ if numRows==0: return [] if numRows==1: return [[1]] if numRows==2: return [[1], [1,1]] result = [[1],[1,1]] for row in range(3,numRows+1): new_row = [] for col in range(row): if col==0: new_row.append(1) elif col==row-1: new_row.append(1) else: new_row.append(result[row-2][col-1]+result[row-2][col]) result.append(new_row) return result if __name__ == "__main__": s = Solution() print(s.generate(1))
""" Given a non-negative integer numRows, generate the first numRows of Pascal's triangle. """ class Solution(object): def generate(self, numRows): """ :type numRows: int :rtype: List[List[int]] """ if numRows == 0: return [] if numRows == 1: return [[1]] if numRows == 2: return [[1], [1, 1]] result = [[1], [1, 1]] for row in range(3, numRows + 1): new_row = [] for col in range(row): if col == 0: new_row.append(1) elif col == row - 1: new_row.append(1) else: new_row.append(result[row - 2][col - 1] + result[row - 2][col]) result.append(new_row) return result if __name__ == '__main__': s = solution() print(s.generate(1))
def funcion(nums,n): print(nums) res = [] for i in range(len(nums)): suma = 0 aux = [] suma += nums[i] for j in range(i+1,len(nums)): print(i,j) if suma + nums[j] == n: aux.append(nums[i]) aux.append(nums[j]) res.append(aux) else: pass return res def main(): print(funcion([1,2,3,4,5,6,7,-1],6)) main()
def funcion(nums, n): print(nums) res = [] for i in range(len(nums)): suma = 0 aux = [] suma += nums[i] for j in range(i + 1, len(nums)): print(i, j) if suma + nums[j] == n: aux.append(nums[i]) aux.append(nums[j]) res.append(aux) else: pass return res def main(): print(funcion([1, 2, 3, 4, 5, 6, 7, -1], 6)) main()
class Solution: def findRadius(self, houses, heaters): """ :type houses: List[int] :type heaters: List[int] :rtype: int """ houses.sort() heaters.sort() radius = 0 i = 0 for house in houses: while i < len(heaters) and heaters[i] < house: i += 1 if i == 0: radius = max(radius, heaters[i] - house) elif i == len(heaters): return max(radius, houses[-1] - heaters[-1]) else: radius = max(radius, min(heaters[i]-house, house-heaters[i-1])) return radius """ Winter is coming! Your first job during the contest is to design a standard heater with fixed warm radius to warm all the houses. Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of heaters so that all houses could be covered by those heaters. So, your input will be the positions of houses and heaters seperately, and your expected output will be the minimum radius standard of heaters. Note: Numbers of houses and heaters you are given are non-negative and will not exceed 25000. Positions of houses and heaters you are given are non-negative and will not exceed 10^9. As long as a house is in the heaters' warm radius range, it can be warmed. All the heaters follow your radius standard and the warm radius will the same. Example 1: Input: [1,2,3],[2] Output: 1 Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then all the houses can be warmed. """
class Solution: def find_radius(self, houses, heaters): """ :type houses: List[int] :type heaters: List[int] :rtype: int """ houses.sort() heaters.sort() radius = 0 i = 0 for house in houses: while i < len(heaters) and heaters[i] < house: i += 1 if i == 0: radius = max(radius, heaters[i] - house) elif i == len(heaters): return max(radius, houses[-1] - heaters[-1]) else: radius = max(radius, min(heaters[i] - house, house - heaters[i - 1])) return radius "\n Winter is coming! Your first job during the contest is to design a standard heater with fixed warm\n radius to warm all the houses.\n\n Now, you are given positions of houses and heaters on a horizontal line, find out minimum radius of\n heaters so that all houses could be covered by those heaters.\n\n So, your input will be the positions of houses and heaters seperately, and your expected output will\n be the minimum radius standard of heaters.\n\n Note:\n Numbers of houses and heaters you are given are non-negative and will not exceed 25000.\n Positions of houses and heaters you are given are non-negative and will not exceed 10^9.\n As long as a house is in the heaters' warm radius range, it can be warmed.\n All the heaters follow your radius standard and the warm radius will the same.\n Example 1:\n Input: [1,2,3],[2]\n Output: 1\n Explanation: The only heater was placed in the position 2, and if we use the radius 1 standard, then\n all the houses can be warmed.\n\n "
""" A list of the custom settings used on the site. Many of the external libraries have their own settings, see library documentation for details. """ VAVS_EMAIL_FROM = 'address shown in reply-to field of emails' VAVS_EMAIL_TO = 'list of staff addresses to send reports to' VAVS_EMAIL_SURVEYS = 'address to send surveys to' VAVS_ROOT = 'path to root directory of site' VAVS_DOWNLOAD_DIR = 'path to download directory' VAVS_THUMBNAILS_DIR = 'path tothumbnail directory' VAVS_THUMBNAILS_SIZE = 'size of thumbnails as tuple: (width, height)' FBDATA_LIKES_LIMIT = 'maximum number of likes to show in listings' FBDATA_INITIAL_PERIOD = 'number of days to backdate data collection to' FBDATA_MIN_PERIOD = 'minimum duration, as timedelta, between updates'
""" A list of the custom settings used on the site. Many of the external libraries have their own settings, see library documentation for details. """ vavs_email_from = 'address shown in reply-to field of emails' vavs_email_to = 'list of staff addresses to send reports to' vavs_email_surveys = 'address to send surveys to' vavs_root = 'path to root directory of site' vavs_download_dir = 'path to download directory' vavs_thumbnails_dir = 'path tothumbnail directory' vavs_thumbnails_size = 'size of thumbnails as tuple: (width, height)' fbdata_likes_limit = 'maximum number of likes to show in listings' fbdata_initial_period = 'number of days to backdate data collection to' fbdata_min_period = 'minimum duration, as timedelta, between updates'
class TestHLD: # edges = [ # (0, 1), # (0, 6), # (0, 10), # (1, 2), # (1, 5), # (2, 3), # (2, 4), # (6, 7), # (7, 8), # (7, 9), # (10, 11), # ] # root = 0 # get_lca = lca_hld(edges, root) # print(get_lca(3, 5)) ...
class Testhld: ...
input = """ ok:- #count{V:b(V)}=X, not p(X). b(1). p(2). """ output = """ ok:- #count{V:b(V)}=X, not p(X). b(1). p(2). """
input = '\nok:- #count{V:b(V)}=X, not p(X).\n\nb(1).\np(2).\n' output = '\nok:- #count{V:b(V)}=X, not p(X).\n\nb(1).\np(2).\n'
# # PySNMP MIB module OVERLAND-NEXTGEN (http://snmplabs.com/pysmi) # ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/OVERLAND-NEXTGEN # Produced by pysmi-0.3.4 at Wed May 1 14:35:46 2019 # On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4 # Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15) # Integer, OctetString, ObjectIdentifier = mibBuilder.importSymbols("ASN1", "Integer", "OctetString", "ObjectIdentifier") NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues") SingleValueConstraint, ConstraintsUnion, ValueRangeConstraint, ValueSizeConstraint, ConstraintsIntersection = mibBuilder.importSymbols("ASN1-REFINEMENT", "SingleValueConstraint", "ConstraintsUnion", "ValueRangeConstraint", "ValueSizeConstraint", "ConstraintsIntersection") ObjectGroup, ModuleCompliance, NotificationGroup = mibBuilder.importSymbols("SNMPv2-CONF", "ObjectGroup", "ModuleCompliance", "NotificationGroup") MibScalar, MibTable, MibTableRow, MibTableColumn, Integer32, ObjectIdentity, ModuleIdentity, NotificationType, iso, Gauge32, IpAddress, Bits, MibIdentifier, TimeTicks, Counter64, Counter32, Unsigned32 = mibBuilder.importSymbols("SNMPv2-SMI", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "Integer32", "ObjectIdentity", "ModuleIdentity", "NotificationType", "iso", "Gauge32", "IpAddress", "Bits", "MibIdentifier", "TimeTicks", "Counter64", "Counter32", "Unsigned32") TextualConvention, DisplayString = mibBuilder.importSymbols("SNMPv2-TC", "TextualConvention", "DisplayString") overlandGlobalRegModule = ModuleIdentity((1, 3, 6, 1, 4, 1, 3351, 1, 1, 1, 1)) if mibBuilder.loadTexts: overlandGlobalRegModule.setLastUpdated('9807090845Z') if mibBuilder.loadTexts: overlandGlobalRegModule.setOrganization('Overland Data, Inc.') if mibBuilder.loadTexts: overlandGlobalRegModule.setContactInfo('Robert Kingsley email: bkingsley@overlanddata.com') if mibBuilder.loadTexts: overlandGlobalRegModule.setDescription('The Overland Data central registration module.') overlandRoot = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1)) overlandReg = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 1)) overlandGeneric = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 2)) overlandProducts = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 3)) overlandCaps = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 4)) overlandReqs = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 5)) overlandExpr = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 6)) overlandModules = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 1, 1)) overlandNextGen = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2)) overlandNextGenActions = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 1)) overlandNextGenStatistics = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 2)) overlandNextGenState = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3)) overlandNextGenComponents = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 4)) overlandNextGenAttributes = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5)) overlandNextGenEvents = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6)) overlandNextGenGroups = MibIdentifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 7)) overlandLoopback = MibScalar((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 1, 1), DisplayString().subtype(subtypeSpec=ValueSizeConstraint(1, 32))).setMaxAccess("readwrite") if mibBuilder.loadTexts: overlandLoopback.setStatus('current') if mibBuilder.loadTexts: overlandLoopback.setDescription('Sends or retrieves a loopback string to the target.') overlandActionGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 7, 1)).setObjects(("OVERLAND-NEXTGEN", "overlandLoopback")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): overlandActionGroup = overlandActionGroup.setStatus('current') if mibBuilder.loadTexts: overlandActionGroup.setDescription('Current library status which may be queried.') driveStatusTable = MibTable((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1), ) if mibBuilder.loadTexts: driveStatusTable.setStatus('current') if mibBuilder.loadTexts: driveStatusTable.setDescription('Table containing various drive status.') driveStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1), ).setIndexNames((0, "OVERLAND-NEXTGEN", "dstIndex")) if mibBuilder.loadTexts: driveStatusEntry.setStatus('current') if mibBuilder.loadTexts: driveStatusEntry.setDescription('A row in the drive status table.') dstRowValid = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: dstRowValid.setStatus('current') if mibBuilder.loadTexts: dstRowValid.setDescription('Provides an INVALID indication if no drives are installed or if the drive type is unknown; otherwise, an indication of the drive type is provided.') dstIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 32))).setMaxAccess("readonly") if mibBuilder.loadTexts: dstIndex.setStatus('current') if mibBuilder.loadTexts: dstIndex.setDescription('Index to drive status fields.') dstState = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3, 4))).clone(namedValues=NamedValues(("initializedNoError", 0), ("initializedWithError", 1), ("notInitialized", 2), ("notInstalled", 3), ("notInserted", 4)))).setMaxAccess("readonly") if mibBuilder.loadTexts: dstState.setStatus('current') if mibBuilder.loadTexts: dstState.setDescription('Current state of the drive.') dstMotion = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: dstMotion.setStatus('current') if mibBuilder.loadTexts: dstMotion.setDescription('ASCII msg describing current drive tape motion.') dstCodeRevDrive = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dstCodeRevDrive.setStatus('current') if mibBuilder.loadTexts: dstCodeRevDrive.setDescription('Revision number of the drive code.') dstCodeRevController = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: dstCodeRevController.setStatus('current') if mibBuilder.loadTexts: dstCodeRevController.setDescription('Revision number of the drive controller code.') dstScsiId = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 7), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 15))).setMaxAccess("readonly") if mibBuilder.loadTexts: dstScsiId.setStatus('current') if mibBuilder.loadTexts: dstScsiId.setDescription('SCSI Id number of drive.') dstSerialNum = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 8), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: dstSerialNum.setStatus('current') if mibBuilder.loadTexts: dstSerialNum.setDescription('Serial number of this drive.') dstCleanRequested = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 9), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("cleanNotNeeded", 0), ("cleanNeeded", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: dstCleanRequested.setStatus('current') if mibBuilder.loadTexts: dstCleanRequested.setDescription('The drive heads needs to be cleaned with a cleaning cartridge.') libraryStatusTable = MibTable((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2), ) if mibBuilder.loadTexts: libraryStatusTable.setStatus('current') if mibBuilder.loadTexts: libraryStatusTable.setDescription('Table containing fault code, severity and ACSII error messages displayed on front panel of library.') libraryStatusEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1), ).setIndexNames((0, "OVERLAND-NEXTGEN", "lstIndex")) if mibBuilder.loadTexts: libraryStatusEntry.setStatus('current') if mibBuilder.loadTexts: libraryStatusEntry.setDescription('A row in the library status table.') lstIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1))).setMaxAccess("readonly") if mibBuilder.loadTexts: lstIndex.setStatus('current') if mibBuilder.loadTexts: lstIndex.setDescription('Index to table of library status.') lstConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("standalone", 0), ("multimodule", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: lstConfig.setStatus('current') if mibBuilder.loadTexts: lstConfig.setDescription('Indicates if library is standalone or multi-module.') lstScsiId = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 15))).setMaxAccess("readonly") if mibBuilder.loadTexts: lstScsiId.setStatus('current') if mibBuilder.loadTexts: lstScsiId.setDescription('Indicates library SCSI bus ID.') lstStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: lstStatus.setStatus('current') if mibBuilder.loadTexts: lstStatus.setDescription('Indication of current library status.') lstChangerStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1, 5), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: lstChangerStatus.setStatus('current') if mibBuilder.loadTexts: lstChangerStatus.setDescription('Bit-mapped indication of current changer status: bit 0 - cartridge map valid bit 1 - initializing bit 2 - door open bit 3 - front panel mode bit 4 - door closed bit 5 - browser mode bit 6 - master busy') lstLibraryState = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1, 6), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2))).clone(namedValues=NamedValues(("initializing", 0), ("online", 1), ("offline", 2)))).setMaxAccess("readonly") if mibBuilder.loadTexts: lstLibraryState.setStatus('current') if mibBuilder.loadTexts: lstLibraryState.setDescription('Indication of current library state.') errorTable = MibTable((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3), ) if mibBuilder.loadTexts: errorTable.setStatus('current') if mibBuilder.loadTexts: errorTable.setDescription('Table containing fault code, severity and ACSII error messages displayed on front panel of library.') errorEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3, 1), ).setIndexNames((0, "OVERLAND-NEXTGEN", "errIndex")) if mibBuilder.loadTexts: errorEntry.setStatus('current') if mibBuilder.loadTexts: errorEntry.setDescription('A row in the error info table.') errIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3, 1, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(1, 1))).setMaxAccess("readonly") if mibBuilder.loadTexts: errIndex.setStatus('current') if mibBuilder.loadTexts: errIndex.setDescription('Index to table of library error information.') errCode = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3, 1, 2), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: errCode.setStatus('current') if mibBuilder.loadTexts: errCode.setDescription('Hex code unique to the reported error.') errSeverity = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("informational", 0), ("mild", 1), ("hard", 2), ("severe", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: errSeverity.setStatus('current') if mibBuilder.loadTexts: errSeverity.setDescription('Indication of how serious the reported error is: 0 = informational error, not very severe 1 = mild error, operator intervention not necessary 2 = hard error, may be corrected remotely 3 = very severe, power cycle required to clear') errMsg = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: errMsg.setStatus('current') if mibBuilder.loadTexts: errMsg.setDescription('ASCII message naming the current error.') errActionMsg = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3, 1, 5), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: errActionMsg.setStatus('current') if mibBuilder.loadTexts: errActionMsg.setDescription('ASCII message providing additional information about current error and possibly some suggestions for correcting it.') overlandStateGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 7, 3)).setObjects(("OVERLAND-NEXTGEN", "errIndex"), ("OVERLAND-NEXTGEN", "errCode"), ("OVERLAND-NEXTGEN", "errSeverity"), ("OVERLAND-NEXTGEN", "errMsg"), ("OVERLAND-NEXTGEN", "errActionMsg"), ("OVERLAND-NEXTGEN", "dstRowValid"), ("OVERLAND-NEXTGEN", "dstIndex"), ("OVERLAND-NEXTGEN", "dstState"), ("OVERLAND-NEXTGEN", "dstMotion"), ("OVERLAND-NEXTGEN", "dstCodeRevDrive"), ("OVERLAND-NEXTGEN", "dstCodeRevController"), ("OVERLAND-NEXTGEN", "dstScsiId"), ("OVERLAND-NEXTGEN", "dstSerialNum"), ("OVERLAND-NEXTGEN", "dstCleanRequested"), ("OVERLAND-NEXTGEN", "lstIndex"), ("OVERLAND-NEXTGEN", "lstConfig"), ("OVERLAND-NEXTGEN", "lstScsiId"), ("OVERLAND-NEXTGEN", "lstStatus"), ("OVERLAND-NEXTGEN", "lstChangerStatus"), ("OVERLAND-NEXTGEN", "lstLibraryState")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): overlandStateGroup = overlandStateGroup.setStatus('current') if mibBuilder.loadTexts: overlandStateGroup.setDescription('Current library states which may be queried.') numModules = MibScalar((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 1), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 256))).setMaxAccess("readonly") if mibBuilder.loadTexts: numModules.setStatus('current') if mibBuilder.loadTexts: numModules.setDescription('Reads the total number of modules available in the attached library.') numBins = MibScalar((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 2), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 256))).setMaxAccess("readonly") if mibBuilder.loadTexts: numBins.setStatus('current') if mibBuilder.loadTexts: numBins.setDescription('Reads the total number of cartridge storage slots available in the attached library.') numDrives = MibScalar((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 3), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 128))).setMaxAccess("readonly") if mibBuilder.loadTexts: numDrives.setStatus('current') if mibBuilder.loadTexts: numDrives.setDescription('Reads the total number of drives available in the attached library.') numMailSlots = MibScalar((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 4), Integer32().subtype(subtypeSpec=ValueRangeConstraint(0, 15))).setMaxAccess("readonly") if mibBuilder.loadTexts: numMailSlots.setStatus('current') if mibBuilder.loadTexts: numMailSlots.setDescription('Returns the total number of mail slots available in the attached library.') moduleGeometryTable = MibTable((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5), ) if mibBuilder.loadTexts: moduleGeometryTable.setStatus('current') if mibBuilder.loadTexts: moduleGeometryTable.setDescription('Table containing library module geometry.') moduleGeometryEntry = MibTableRow((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1), ).setIndexNames((0, "OVERLAND-NEXTGEN", "modIndex")) if mibBuilder.loadTexts: moduleGeometryEntry.setStatus('current') if mibBuilder.loadTexts: moduleGeometryEntry.setDescription('A row in the library module geometry table.') modDesc = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 1), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: modDesc.setStatus('current') if mibBuilder.loadTexts: modDesc.setDescription('If library geometry is valid, an ASCII message desribing the module.') modIndex = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 2), Integer32().subtype(subtypeSpec=ConstraintsUnion(ValueRangeConstraint(0, 7), ValueRangeConstraint(8, 8), ))).setMaxAccess("readonly") if mibBuilder.loadTexts: modIndex.setStatus('current') if mibBuilder.loadTexts: modIndex.setDescription('Index to table of library module geometry: 8 = Master or Standalone module 0-7 = Slave Module') modAttached = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 3), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1))).clone(namedValues=NamedValues(("isNotAttached", 0), ("isAttached", 1)))).setMaxAccess("readonly") if mibBuilder.loadTexts: modAttached.setStatus('current') if mibBuilder.loadTexts: modAttached.setDescription('Indication of whether or not module is attached.') modStatus = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 4), DisplayString()).setMaxAccess("readonly") if mibBuilder.loadTexts: modStatus.setStatus('current') if mibBuilder.loadTexts: modStatus.setDescription('ASCII message desribing the current status of the module.') modConfig = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 5), Integer32().subtype(subtypeSpec=ConstraintsUnion(SingleValueConstraint(0, 1, 2, 3))).clone(namedValues=NamedValues(("unknown", 0), ("lightning", 1), ("thunder", 2), ("invalid", 3)))).setMaxAccess("readonly") if mibBuilder.loadTexts: modConfig.setStatus('current') if mibBuilder.loadTexts: modConfig.setDescription("Indication of this module's type.") modFwRev = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 6), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: modFwRev.setStatus('current') if mibBuilder.loadTexts: modFwRev.setDescription("Indication of this module's firmware revision level.") modNumBins = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 7), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: modNumBins.setStatus('current') if mibBuilder.loadTexts: modNumBins.setDescription('Indication of the number of bins within this module.') modNumDrives = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 8), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: modNumDrives.setStatus('current') if mibBuilder.loadTexts: modNumDrives.setDescription('Indication of the number of drives within this module.') modNumMailSlots = MibTableColumn((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 9), Integer32()).setMaxAccess("readonly") if mibBuilder.loadTexts: modNumMailSlots.setStatus('current') if mibBuilder.loadTexts: modNumMailSlots.setDescription('Indication of the number of mailslots within this module.') overlandAttributesGroup = ObjectGroup((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 7, 4)).setObjects(("OVERLAND-NEXTGEN", "numModules"), ("OVERLAND-NEXTGEN", "numBins"), ("OVERLAND-NEXTGEN", "numDrives"), ("OVERLAND-NEXTGEN", "numMailSlots"), ("OVERLAND-NEXTGEN", "modDesc"), ("OVERLAND-NEXTGEN", "modIndex"), ("OVERLAND-NEXTGEN", "modAttached"), ("OVERLAND-NEXTGEN", "modStatus"), ("OVERLAND-NEXTGEN", "modConfig"), ("OVERLAND-NEXTGEN", "modFwRev"), ("OVERLAND-NEXTGEN", "modNumBins"), ("OVERLAND-NEXTGEN", "modNumDrives"), ("OVERLAND-NEXTGEN", "modNumMailSlots")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): overlandAttributesGroup = overlandAttributesGroup.setStatus('current') if mibBuilder.loadTexts: overlandAttributesGroup.setDescription('Current library info which may be queried.') eventDoorOpen = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 1)) if mibBuilder.loadTexts: eventDoorOpen.setStatus('current') if mibBuilder.loadTexts: eventDoorOpen.setDescription('A library door has been opened.') eventMailSlotAccessed = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 2)) if mibBuilder.loadTexts: eventMailSlotAccessed.setStatus('current') if mibBuilder.loadTexts: eventMailSlotAccessed.setDescription('A mail slot is being accessed.') eventHardFault = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 3)) if mibBuilder.loadTexts: eventHardFault.setStatus('current') if mibBuilder.loadTexts: eventHardFault.setDescription('The library has posted a hard fault.') eventSlaveFailed = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 4)) if mibBuilder.loadTexts: eventSlaveFailed.setStatus('current') if mibBuilder.loadTexts: eventSlaveFailed.setDescription('A slave module has faulted.') eventPowerSupplyFailed = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 5)) if mibBuilder.loadTexts: eventPowerSupplyFailed.setStatus('current') if mibBuilder.loadTexts: eventPowerSupplyFailed.setDescription('One of the redundant power supplies has failed.') eventRequestDriveClean = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 6)) if mibBuilder.loadTexts: eventRequestDriveClean.setStatus('current') if mibBuilder.loadTexts: eventRequestDriveClean.setDescription('One of the library tape drives has requested a cleaning cycle to ensure continued data reliability.') eventFanStalled = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 7)) if mibBuilder.loadTexts: eventFanStalled.setStatus('current') if mibBuilder.loadTexts: eventFanStalled.setDescription('A tape drive fan has stalled.') eventDriveError = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 8)) if mibBuilder.loadTexts: eventDriveError.setStatus('current') if mibBuilder.loadTexts: eventDriveError.setDescription('A tape drive error has occurred.') eventDriveRemoved = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 9)) if mibBuilder.loadTexts: eventDriveRemoved.setStatus('current') if mibBuilder.loadTexts: eventDriveRemoved.setDescription('A tape drive has been removed from the library.') eventSlaveRemoved = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 10)) if mibBuilder.loadTexts: eventSlaveRemoved.setStatus('current') if mibBuilder.loadTexts: eventSlaveRemoved.setDescription('A slave module has been removed from the library.') eventFailedOver = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 11)) if mibBuilder.loadTexts: eventFailedOver.setStatus('current') if mibBuilder.loadTexts: eventFailedOver.setDescription('The library is failed over to the Secondary Master.') eventLoaderRetriesExcessive = NotificationType((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 12)) if mibBuilder.loadTexts: eventLoaderRetriesExcessive.setStatus('current') if mibBuilder.loadTexts: eventLoaderRetriesExcessive.setDescription('The library has detected excessive loader retries.') overlandNotificationGroup = NotificationGroup((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 7, 7)).setObjects(("OVERLAND-NEXTGEN", "eventDoorOpen"), ("OVERLAND-NEXTGEN", "eventMailSlotAccessed"), ("OVERLAND-NEXTGEN", "eventHardFault"), ("OVERLAND-NEXTGEN", "eventSlaveFailed"), ("OVERLAND-NEXTGEN", "eventPowerSupplyFailed"), ("OVERLAND-NEXTGEN", "eventRequestDriveClean"), ("OVERLAND-NEXTGEN", "eventFanStalled"), ("OVERLAND-NEXTGEN", "eventDriveError"), ("OVERLAND-NEXTGEN", "eventDriveRemoved"), ("OVERLAND-NEXTGEN", "eventSlaveRemoved"), ("OVERLAND-NEXTGEN", "eventFailedOver"), ("OVERLAND-NEXTGEN", "eventLoaderRetriesExcessive")) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): overlandNotificationGroup = overlandNotificationGroup.setStatus('current') if mibBuilder.loadTexts: overlandNotificationGroup.setDescription('Trap events returned by the browser.') mibBuilder.exportSymbols("OVERLAND-NEXTGEN", modIndex=modIndex, eventSlaveFailed=eventSlaveFailed, driveStatusEntry=driveStatusEntry, dstState=dstState, eventRequestDriveClean=eventRequestDriveClean, modDesc=modDesc, modNumMailSlots=modNumMailSlots, overlandNotificationGroup=overlandNotificationGroup, eventMailSlotAccessed=eventMailSlotAccessed, overlandAttributesGroup=overlandAttributesGroup, dstCleanRequested=dstCleanRequested, overlandProducts=overlandProducts, dstIndex=dstIndex, overlandReqs=overlandReqs, dstCodeRevDrive=dstCodeRevDrive, moduleGeometryTable=moduleGeometryTable, dstScsiId=dstScsiId, numMailSlots=numMailSlots, dstMotion=dstMotion, overlandNextGenEvents=overlandNextGenEvents, overlandNextGenComponents=overlandNextGenComponents, lstScsiId=lstScsiId, overlandActionGroup=overlandActionGroup, overlandLoopback=overlandLoopback, overlandCaps=overlandCaps, lstIndex=lstIndex, errorTable=errorTable, modConfig=modConfig, lstChangerStatus=lstChangerStatus, numDrives=numDrives, errActionMsg=errActionMsg, overlandGeneric=overlandGeneric, errMsg=errMsg, overlandNextGenState=overlandNextGenState, lstConfig=lstConfig, modStatus=modStatus, eventPowerSupplyFailed=eventPowerSupplyFailed, overlandGlobalRegModule=overlandGlobalRegModule, errSeverity=errSeverity, driveStatusTable=driveStatusTable, overlandStateGroup=overlandStateGroup, errIndex=errIndex, moduleGeometryEntry=moduleGeometryEntry, modFwRev=modFwRev, eventFanStalled=eventFanStalled, errCode=errCode, eventDriveError=eventDriveError, eventDoorOpen=eventDoorOpen, dstRowValid=dstRowValid, eventSlaveRemoved=eventSlaveRemoved, eventFailedOver=eventFailedOver, numModules=numModules, overlandReg=overlandReg, lstLibraryState=lstLibraryState, modNumBins=modNumBins, overlandNextGen=overlandNextGen, libraryStatusTable=libraryStatusTable, overlandNextGenAttributes=overlandNextGenAttributes, numBins=numBins, overlandExpr=overlandExpr, dstCodeRevController=dstCodeRevController, dstSerialNum=dstSerialNum, libraryStatusEntry=libraryStatusEntry, errorEntry=errorEntry, modNumDrives=modNumDrives, overlandRoot=overlandRoot, eventLoaderRetriesExcessive=eventLoaderRetriesExcessive, overlandModules=overlandModules, eventDriveRemoved=eventDriveRemoved, PYSNMP_MODULE_ID=overlandGlobalRegModule, overlandNextGenStatistics=overlandNextGenStatistics, lstStatus=lstStatus, modAttached=modAttached, eventHardFault=eventHardFault, overlandNextGenActions=overlandNextGenActions, overlandNextGenGroups=overlandNextGenGroups)
(integer, octet_string, object_identifier) = mibBuilder.importSymbols('ASN1', 'Integer', 'OctetString', 'ObjectIdentifier') (named_values,) = mibBuilder.importSymbols('ASN1-ENUMERATION', 'NamedValues') (single_value_constraint, constraints_union, value_range_constraint, value_size_constraint, constraints_intersection) = mibBuilder.importSymbols('ASN1-REFINEMENT', 'SingleValueConstraint', 'ConstraintsUnion', 'ValueRangeConstraint', 'ValueSizeConstraint', 'ConstraintsIntersection') (object_group, module_compliance, notification_group) = mibBuilder.importSymbols('SNMPv2-CONF', 'ObjectGroup', 'ModuleCompliance', 'NotificationGroup') (mib_scalar, mib_table, mib_table_row, mib_table_column, integer32, object_identity, module_identity, notification_type, iso, gauge32, ip_address, bits, mib_identifier, time_ticks, counter64, counter32, unsigned32) = mibBuilder.importSymbols('SNMPv2-SMI', 'MibScalar', 'MibTable', 'MibTableRow', 'MibTableColumn', 'Integer32', 'ObjectIdentity', 'ModuleIdentity', 'NotificationType', 'iso', 'Gauge32', 'IpAddress', 'Bits', 'MibIdentifier', 'TimeTicks', 'Counter64', 'Counter32', 'Unsigned32') (textual_convention, display_string) = mibBuilder.importSymbols('SNMPv2-TC', 'TextualConvention', 'DisplayString') overland_global_reg_module = module_identity((1, 3, 6, 1, 4, 1, 3351, 1, 1, 1, 1)) if mibBuilder.loadTexts: overlandGlobalRegModule.setLastUpdated('9807090845Z') if mibBuilder.loadTexts: overlandGlobalRegModule.setOrganization('Overland Data, Inc.') if mibBuilder.loadTexts: overlandGlobalRegModule.setContactInfo('Robert Kingsley email: bkingsley@overlanddata.com') if mibBuilder.loadTexts: overlandGlobalRegModule.setDescription('The Overland Data central registration module.') overland_root = mib_identifier((1, 3, 6, 1, 4, 1, 3351, 1)) overland_reg = mib_identifier((1, 3, 6, 1, 4, 1, 3351, 1, 1)) overland_generic = mib_identifier((1, 3, 6, 1, 4, 1, 3351, 1, 2)) overland_products = mib_identifier((1, 3, 6, 1, 4, 1, 3351, 1, 3)) overland_caps = mib_identifier((1, 3, 6, 1, 4, 1, 3351, 1, 4)) overland_reqs = mib_identifier((1, 3, 6, 1, 4, 1, 3351, 1, 5)) overland_expr = mib_identifier((1, 3, 6, 1, 4, 1, 3351, 1, 6)) overland_modules = mib_identifier((1, 3, 6, 1, 4, 1, 3351, 1, 1, 1)) overland_next_gen = mib_identifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2)) overland_next_gen_actions = mib_identifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 1)) overland_next_gen_statistics = mib_identifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 2)) overland_next_gen_state = mib_identifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3)) overland_next_gen_components = mib_identifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 4)) overland_next_gen_attributes = mib_identifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5)) overland_next_gen_events = mib_identifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6)) overland_next_gen_groups = mib_identifier((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 7)) overland_loopback = mib_scalar((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 1, 1), display_string().subtype(subtypeSpec=value_size_constraint(1, 32))).setMaxAccess('readwrite') if mibBuilder.loadTexts: overlandLoopback.setStatus('current') if mibBuilder.loadTexts: overlandLoopback.setDescription('Sends or retrieves a loopback string to the target.') overland_action_group = object_group((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 7, 1)).setObjects(('OVERLAND-NEXTGEN', 'overlandLoopback')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): overland_action_group = overlandActionGroup.setStatus('current') if mibBuilder.loadTexts: overlandActionGroup.setDescription('Current library status which may be queried.') drive_status_table = mib_table((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1)) if mibBuilder.loadTexts: driveStatusTable.setStatus('current') if mibBuilder.loadTexts: driveStatusTable.setDescription('Table containing various drive status.') drive_status_entry = mib_table_row((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1)).setIndexNames((0, 'OVERLAND-NEXTGEN', 'dstIndex')) if mibBuilder.loadTexts: driveStatusEntry.setStatus('current') if mibBuilder.loadTexts: driveStatusEntry.setDescription('A row in the drive status table.') dst_row_valid = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 1), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: dstRowValid.setStatus('current') if mibBuilder.loadTexts: dstRowValid.setDescription('Provides an INVALID indication if no drives are installed or if the drive type is unknown; otherwise, an indication of the drive type is provided.') dst_index = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 2), integer32().subtype(subtypeSpec=value_range_constraint(1, 32))).setMaxAccess('readonly') if mibBuilder.loadTexts: dstIndex.setStatus('current') if mibBuilder.loadTexts: dstIndex.setDescription('Index to drive status fields.') dst_state = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3, 4))).clone(namedValues=named_values(('initializedNoError', 0), ('initializedWithError', 1), ('notInitialized', 2), ('notInstalled', 3), ('notInserted', 4)))).setMaxAccess('readonly') if mibBuilder.loadTexts: dstState.setStatus('current') if mibBuilder.loadTexts: dstState.setDescription('Current state of the drive.') dst_motion = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 4), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: dstMotion.setStatus('current') if mibBuilder.loadTexts: dstMotion.setDescription('ASCII msg describing current drive tape motion.') dst_code_rev_drive = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 5), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dstCodeRevDrive.setStatus('current') if mibBuilder.loadTexts: dstCodeRevDrive.setDescription('Revision number of the drive code.') dst_code_rev_controller = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 6), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: dstCodeRevController.setStatus('current') if mibBuilder.loadTexts: dstCodeRevController.setDescription('Revision number of the drive controller code.') dst_scsi_id = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 7), integer32().subtype(subtypeSpec=value_range_constraint(0, 15))).setMaxAccess('readonly') if mibBuilder.loadTexts: dstScsiId.setStatus('current') if mibBuilder.loadTexts: dstScsiId.setDescription('SCSI Id number of drive.') dst_serial_num = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 8), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: dstSerialNum.setStatus('current') if mibBuilder.loadTexts: dstSerialNum.setDescription('Serial number of this drive.') dst_clean_requested = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 1, 1, 9), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('cleanNotNeeded', 0), ('cleanNeeded', 1)))).setMaxAccess('readonly') if mibBuilder.loadTexts: dstCleanRequested.setStatus('current') if mibBuilder.loadTexts: dstCleanRequested.setDescription('The drive heads needs to be cleaned with a cleaning cartridge.') library_status_table = mib_table((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2)) if mibBuilder.loadTexts: libraryStatusTable.setStatus('current') if mibBuilder.loadTexts: libraryStatusTable.setDescription('Table containing fault code, severity and ACSII error messages displayed on front panel of library.') library_status_entry = mib_table_row((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1)).setIndexNames((0, 'OVERLAND-NEXTGEN', 'lstIndex')) if mibBuilder.loadTexts: libraryStatusEntry.setStatus('current') if mibBuilder.loadTexts: libraryStatusEntry.setDescription('A row in the library status table.') lst_index = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 1))).setMaxAccess('readonly') if mibBuilder.loadTexts: lstIndex.setStatus('current') if mibBuilder.loadTexts: lstIndex.setDescription('Index to table of library status.') lst_config = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1, 2), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('standalone', 0), ('multimodule', 1)))).setMaxAccess('readonly') if mibBuilder.loadTexts: lstConfig.setStatus('current') if mibBuilder.loadTexts: lstConfig.setDescription('Indicates if library is standalone or multi-module.') lst_scsi_id = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1, 3), integer32().subtype(subtypeSpec=value_range_constraint(0, 15))).setMaxAccess('readonly') if mibBuilder.loadTexts: lstScsiId.setStatus('current') if mibBuilder.loadTexts: lstScsiId.setDescription('Indicates library SCSI bus ID.') lst_status = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1, 4), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: lstStatus.setStatus('current') if mibBuilder.loadTexts: lstStatus.setDescription('Indication of current library status.') lst_changer_status = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1, 5), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: lstChangerStatus.setStatus('current') if mibBuilder.loadTexts: lstChangerStatus.setDescription('Bit-mapped indication of current changer status: bit 0 - cartridge map valid bit 1 - initializing bit 2 - door open bit 3 - front panel mode bit 4 - door closed bit 5 - browser mode bit 6 - master busy') lst_library_state = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 2, 1, 6), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2))).clone(namedValues=named_values(('initializing', 0), ('online', 1), ('offline', 2)))).setMaxAccess('readonly') if mibBuilder.loadTexts: lstLibraryState.setStatus('current') if mibBuilder.loadTexts: lstLibraryState.setDescription('Indication of current library state.') error_table = mib_table((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3)) if mibBuilder.loadTexts: errorTable.setStatus('current') if mibBuilder.loadTexts: errorTable.setDescription('Table containing fault code, severity and ACSII error messages displayed on front panel of library.') error_entry = mib_table_row((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3, 1)).setIndexNames((0, 'OVERLAND-NEXTGEN', 'errIndex')) if mibBuilder.loadTexts: errorEntry.setStatus('current') if mibBuilder.loadTexts: errorEntry.setDescription('A row in the error info table.') err_index = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3, 1, 1), integer32().subtype(subtypeSpec=value_range_constraint(1, 1))).setMaxAccess('readonly') if mibBuilder.loadTexts: errIndex.setStatus('current') if mibBuilder.loadTexts: errIndex.setDescription('Index to table of library error information.') err_code = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3, 1, 2), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: errCode.setStatus('current') if mibBuilder.loadTexts: errCode.setDescription('Hex code unique to the reported error.') err_severity = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3))).clone(namedValues=named_values(('informational', 0), ('mild', 1), ('hard', 2), ('severe', 3)))).setMaxAccess('readonly') if mibBuilder.loadTexts: errSeverity.setStatus('current') if mibBuilder.loadTexts: errSeverity.setDescription('Indication of how serious the reported error is: 0 = informational error, not very severe 1 = mild error, operator intervention not necessary 2 = hard error, may be corrected remotely 3 = very severe, power cycle required to clear') err_msg = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3, 1, 4), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: errMsg.setStatus('current') if mibBuilder.loadTexts: errMsg.setDescription('ASCII message naming the current error.') err_action_msg = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 3, 3, 1, 5), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: errActionMsg.setStatus('current') if mibBuilder.loadTexts: errActionMsg.setDescription('ASCII message providing additional information about current error and possibly some suggestions for correcting it.') overland_state_group = object_group((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 7, 3)).setObjects(('OVERLAND-NEXTGEN', 'errIndex'), ('OVERLAND-NEXTGEN', 'errCode'), ('OVERLAND-NEXTGEN', 'errSeverity'), ('OVERLAND-NEXTGEN', 'errMsg'), ('OVERLAND-NEXTGEN', 'errActionMsg'), ('OVERLAND-NEXTGEN', 'dstRowValid'), ('OVERLAND-NEXTGEN', 'dstIndex'), ('OVERLAND-NEXTGEN', 'dstState'), ('OVERLAND-NEXTGEN', 'dstMotion'), ('OVERLAND-NEXTGEN', 'dstCodeRevDrive'), ('OVERLAND-NEXTGEN', 'dstCodeRevController'), ('OVERLAND-NEXTGEN', 'dstScsiId'), ('OVERLAND-NEXTGEN', 'dstSerialNum'), ('OVERLAND-NEXTGEN', 'dstCleanRequested'), ('OVERLAND-NEXTGEN', 'lstIndex'), ('OVERLAND-NEXTGEN', 'lstConfig'), ('OVERLAND-NEXTGEN', 'lstScsiId'), ('OVERLAND-NEXTGEN', 'lstStatus'), ('OVERLAND-NEXTGEN', 'lstChangerStatus'), ('OVERLAND-NEXTGEN', 'lstLibraryState')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): overland_state_group = overlandStateGroup.setStatus('current') if mibBuilder.loadTexts: overlandStateGroup.setDescription('Current library states which may be queried.') num_modules = mib_scalar((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 1), integer32().subtype(subtypeSpec=value_range_constraint(0, 256))).setMaxAccess('readonly') if mibBuilder.loadTexts: numModules.setStatus('current') if mibBuilder.loadTexts: numModules.setDescription('Reads the total number of modules available in the attached library.') num_bins = mib_scalar((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 2), integer32().subtype(subtypeSpec=value_range_constraint(0, 256))).setMaxAccess('readonly') if mibBuilder.loadTexts: numBins.setStatus('current') if mibBuilder.loadTexts: numBins.setDescription('Reads the total number of cartridge storage slots available in the attached library.') num_drives = mib_scalar((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 3), integer32().subtype(subtypeSpec=value_range_constraint(0, 128))).setMaxAccess('readonly') if mibBuilder.loadTexts: numDrives.setStatus('current') if mibBuilder.loadTexts: numDrives.setDescription('Reads the total number of drives available in the attached library.') num_mail_slots = mib_scalar((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 4), integer32().subtype(subtypeSpec=value_range_constraint(0, 15))).setMaxAccess('readonly') if mibBuilder.loadTexts: numMailSlots.setStatus('current') if mibBuilder.loadTexts: numMailSlots.setDescription('Returns the total number of mail slots available in the attached library.') module_geometry_table = mib_table((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5)) if mibBuilder.loadTexts: moduleGeometryTable.setStatus('current') if mibBuilder.loadTexts: moduleGeometryTable.setDescription('Table containing library module geometry.') module_geometry_entry = mib_table_row((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1)).setIndexNames((0, 'OVERLAND-NEXTGEN', 'modIndex')) if mibBuilder.loadTexts: moduleGeometryEntry.setStatus('current') if mibBuilder.loadTexts: moduleGeometryEntry.setDescription('A row in the library module geometry table.') mod_desc = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 1), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: modDesc.setStatus('current') if mibBuilder.loadTexts: modDesc.setDescription('If library geometry is valid, an ASCII message desribing the module.') mod_index = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 2), integer32().subtype(subtypeSpec=constraints_union(value_range_constraint(0, 7), value_range_constraint(8, 8)))).setMaxAccess('readonly') if mibBuilder.loadTexts: modIndex.setStatus('current') if mibBuilder.loadTexts: modIndex.setDescription('Index to table of library module geometry: 8 = Master or Standalone module 0-7 = Slave Module') mod_attached = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 3), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1))).clone(namedValues=named_values(('isNotAttached', 0), ('isAttached', 1)))).setMaxAccess('readonly') if mibBuilder.loadTexts: modAttached.setStatus('current') if mibBuilder.loadTexts: modAttached.setDescription('Indication of whether or not module is attached.') mod_status = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 4), display_string()).setMaxAccess('readonly') if mibBuilder.loadTexts: modStatus.setStatus('current') if mibBuilder.loadTexts: modStatus.setDescription('ASCII message desribing the current status of the module.') mod_config = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 5), integer32().subtype(subtypeSpec=constraints_union(single_value_constraint(0, 1, 2, 3))).clone(namedValues=named_values(('unknown', 0), ('lightning', 1), ('thunder', 2), ('invalid', 3)))).setMaxAccess('readonly') if mibBuilder.loadTexts: modConfig.setStatus('current') if mibBuilder.loadTexts: modConfig.setDescription("Indication of this module's type.") mod_fw_rev = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 6), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: modFwRev.setStatus('current') if mibBuilder.loadTexts: modFwRev.setDescription("Indication of this module's firmware revision level.") mod_num_bins = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 7), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: modNumBins.setStatus('current') if mibBuilder.loadTexts: modNumBins.setDescription('Indication of the number of bins within this module.') mod_num_drives = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 8), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: modNumDrives.setStatus('current') if mibBuilder.loadTexts: modNumDrives.setDescription('Indication of the number of drives within this module.') mod_num_mail_slots = mib_table_column((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 5, 5, 1, 9), integer32()).setMaxAccess('readonly') if mibBuilder.loadTexts: modNumMailSlots.setStatus('current') if mibBuilder.loadTexts: modNumMailSlots.setDescription('Indication of the number of mailslots within this module.') overland_attributes_group = object_group((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 7, 4)).setObjects(('OVERLAND-NEXTGEN', 'numModules'), ('OVERLAND-NEXTGEN', 'numBins'), ('OVERLAND-NEXTGEN', 'numDrives'), ('OVERLAND-NEXTGEN', 'numMailSlots'), ('OVERLAND-NEXTGEN', 'modDesc'), ('OVERLAND-NEXTGEN', 'modIndex'), ('OVERLAND-NEXTGEN', 'modAttached'), ('OVERLAND-NEXTGEN', 'modStatus'), ('OVERLAND-NEXTGEN', 'modConfig'), ('OVERLAND-NEXTGEN', 'modFwRev'), ('OVERLAND-NEXTGEN', 'modNumBins'), ('OVERLAND-NEXTGEN', 'modNumDrives'), ('OVERLAND-NEXTGEN', 'modNumMailSlots')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): overland_attributes_group = overlandAttributesGroup.setStatus('current') if mibBuilder.loadTexts: overlandAttributesGroup.setDescription('Current library info which may be queried.') event_door_open = notification_type((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 1)) if mibBuilder.loadTexts: eventDoorOpen.setStatus('current') if mibBuilder.loadTexts: eventDoorOpen.setDescription('A library door has been opened.') event_mail_slot_accessed = notification_type((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 2)) if mibBuilder.loadTexts: eventMailSlotAccessed.setStatus('current') if mibBuilder.loadTexts: eventMailSlotAccessed.setDescription('A mail slot is being accessed.') event_hard_fault = notification_type((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 3)) if mibBuilder.loadTexts: eventHardFault.setStatus('current') if mibBuilder.loadTexts: eventHardFault.setDescription('The library has posted a hard fault.') event_slave_failed = notification_type((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 4)) if mibBuilder.loadTexts: eventSlaveFailed.setStatus('current') if mibBuilder.loadTexts: eventSlaveFailed.setDescription('A slave module has faulted.') event_power_supply_failed = notification_type((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 5)) if mibBuilder.loadTexts: eventPowerSupplyFailed.setStatus('current') if mibBuilder.loadTexts: eventPowerSupplyFailed.setDescription('One of the redundant power supplies has failed.') event_request_drive_clean = notification_type((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 6)) if mibBuilder.loadTexts: eventRequestDriveClean.setStatus('current') if mibBuilder.loadTexts: eventRequestDriveClean.setDescription('One of the library tape drives has requested a cleaning cycle to ensure continued data reliability.') event_fan_stalled = notification_type((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 7)) if mibBuilder.loadTexts: eventFanStalled.setStatus('current') if mibBuilder.loadTexts: eventFanStalled.setDescription('A tape drive fan has stalled.') event_drive_error = notification_type((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 8)) if mibBuilder.loadTexts: eventDriveError.setStatus('current') if mibBuilder.loadTexts: eventDriveError.setDescription('A tape drive error has occurred.') event_drive_removed = notification_type((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 9)) if mibBuilder.loadTexts: eventDriveRemoved.setStatus('current') if mibBuilder.loadTexts: eventDriveRemoved.setDescription('A tape drive has been removed from the library.') event_slave_removed = notification_type((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 10)) if mibBuilder.loadTexts: eventSlaveRemoved.setStatus('current') if mibBuilder.loadTexts: eventSlaveRemoved.setDescription('A slave module has been removed from the library.') event_failed_over = notification_type((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 11)) if mibBuilder.loadTexts: eventFailedOver.setStatus('current') if mibBuilder.loadTexts: eventFailedOver.setDescription('The library is failed over to the Secondary Master.') event_loader_retries_excessive = notification_type((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 6, 12)) if mibBuilder.loadTexts: eventLoaderRetriesExcessive.setStatus('current') if mibBuilder.loadTexts: eventLoaderRetriesExcessive.setDescription('The library has detected excessive loader retries.') overland_notification_group = notification_group((1, 3, 6, 1, 4, 1, 3351, 1, 3, 2, 7, 7)).setObjects(('OVERLAND-NEXTGEN', 'eventDoorOpen'), ('OVERLAND-NEXTGEN', 'eventMailSlotAccessed'), ('OVERLAND-NEXTGEN', 'eventHardFault'), ('OVERLAND-NEXTGEN', 'eventSlaveFailed'), ('OVERLAND-NEXTGEN', 'eventPowerSupplyFailed'), ('OVERLAND-NEXTGEN', 'eventRequestDriveClean'), ('OVERLAND-NEXTGEN', 'eventFanStalled'), ('OVERLAND-NEXTGEN', 'eventDriveError'), ('OVERLAND-NEXTGEN', 'eventDriveRemoved'), ('OVERLAND-NEXTGEN', 'eventSlaveRemoved'), ('OVERLAND-NEXTGEN', 'eventFailedOver'), ('OVERLAND-NEXTGEN', 'eventLoaderRetriesExcessive')) if getattr(mibBuilder, 'version', (0, 0, 0)) > (4, 4, 0): overland_notification_group = overlandNotificationGroup.setStatus('current') if mibBuilder.loadTexts: overlandNotificationGroup.setDescription('Trap events returned by the browser.') mibBuilder.exportSymbols('OVERLAND-NEXTGEN', modIndex=modIndex, eventSlaveFailed=eventSlaveFailed, driveStatusEntry=driveStatusEntry, dstState=dstState, eventRequestDriveClean=eventRequestDriveClean, modDesc=modDesc, modNumMailSlots=modNumMailSlots, overlandNotificationGroup=overlandNotificationGroup, eventMailSlotAccessed=eventMailSlotAccessed, overlandAttributesGroup=overlandAttributesGroup, dstCleanRequested=dstCleanRequested, overlandProducts=overlandProducts, dstIndex=dstIndex, overlandReqs=overlandReqs, dstCodeRevDrive=dstCodeRevDrive, moduleGeometryTable=moduleGeometryTable, dstScsiId=dstScsiId, numMailSlots=numMailSlots, dstMotion=dstMotion, overlandNextGenEvents=overlandNextGenEvents, overlandNextGenComponents=overlandNextGenComponents, lstScsiId=lstScsiId, overlandActionGroup=overlandActionGroup, overlandLoopback=overlandLoopback, overlandCaps=overlandCaps, lstIndex=lstIndex, errorTable=errorTable, modConfig=modConfig, lstChangerStatus=lstChangerStatus, numDrives=numDrives, errActionMsg=errActionMsg, overlandGeneric=overlandGeneric, errMsg=errMsg, overlandNextGenState=overlandNextGenState, lstConfig=lstConfig, modStatus=modStatus, eventPowerSupplyFailed=eventPowerSupplyFailed, overlandGlobalRegModule=overlandGlobalRegModule, errSeverity=errSeverity, driveStatusTable=driveStatusTable, overlandStateGroup=overlandStateGroup, errIndex=errIndex, moduleGeometryEntry=moduleGeometryEntry, modFwRev=modFwRev, eventFanStalled=eventFanStalled, errCode=errCode, eventDriveError=eventDriveError, eventDoorOpen=eventDoorOpen, dstRowValid=dstRowValid, eventSlaveRemoved=eventSlaveRemoved, eventFailedOver=eventFailedOver, numModules=numModules, overlandReg=overlandReg, lstLibraryState=lstLibraryState, modNumBins=modNumBins, overlandNextGen=overlandNextGen, libraryStatusTable=libraryStatusTable, overlandNextGenAttributes=overlandNextGenAttributes, numBins=numBins, overlandExpr=overlandExpr, dstCodeRevController=dstCodeRevController, dstSerialNum=dstSerialNum, libraryStatusEntry=libraryStatusEntry, errorEntry=errorEntry, modNumDrives=modNumDrives, overlandRoot=overlandRoot, eventLoaderRetriesExcessive=eventLoaderRetriesExcessive, overlandModules=overlandModules, eventDriveRemoved=eventDriveRemoved, PYSNMP_MODULE_ID=overlandGlobalRegModule, overlandNextGenStatistics=overlandNextGenStatistics, lstStatus=lstStatus, modAttached=modAttached, eventHardFault=eventHardFault, overlandNextGenActions=overlandNextGenActions, overlandNextGenGroups=overlandNextGenGroups)
class Solution(object): def XXX(self, x): """ :type x: int :rtype: int """ if x==0: return 0 x = (x//abs(x)) * int(str(abs(x))[::-1]) if -2 ** 31 < x < 2 ** 31 - 1: return x return 0
class Solution(object): def xxx(self, x): """ :type x: int :rtype: int """ if x == 0: return 0 x = x // abs(x) * int(str(abs(x))[::-1]) if -2 ** 31 < x < 2 ** 31 - 1: return x return 0
class Solution: def diStringMatch(self, S: str): l = 0 r = len(S) ret = [] for i in S: if i == "I": ret.append(l) l += 1 else: ret.append(r) r -= 1 ret.append(r) return ret slu = Solution() print(slu.diStringMatch("III"))
class Solution: def di_string_match(self, S: str): l = 0 r = len(S) ret = [] for i in S: if i == 'I': ret.append(l) l += 1 else: ret.append(r) r -= 1 ret.append(r) return ret slu = solution() print(slu.diStringMatch('III'))
#CONSIDER: composable authorizations class Authorization(object): ''' Base authorization class, defaults to full authorization ''' #CONSIDER: how is this notified about filtering, ids, etc def __init__(self, identity, endpoint): self.identity = identity self.endpoint = endpoint def process_queryset(self, queryset): return queryset def is_authorized(self): return True class AuthorizationMixin(object): def make_authorization(self, identity, endpoint): return Authorization(identity, endpoint) def get_identity(self): #TODO delegate return self.request.user def is_authenticated(self): return self.authorization.is_authorized() def handle(self, endpoint, *args, **kwargs): self.identity = self.get_identity() self.authorization = self.make_authorization(self.identity, endpoint) return super(AuthorizationMixin, self).handle(endpoint, *args, **kwargs) class DjangoModelAuthorization(Authorization): ''' Your basic django core permission based authorization ''' def __init__(self, identity, model, endpoint): super(DjangoModelAuthorization, self).__init__(identity, endpoint) self.model = model def is_authorized(self): #print("auth identity:", self.identity) if self.identity.is_superuser: return True #TODO proper lookup of label? if self.endpoint == 'list': return True #TODO in django fashion, you have list if you have add, change, or delete return self.identity.has_perm perm_name = self.model._meta.app_label + '.' if self.endpoint == 'create': perm_name += 'add' elif self.endpoint == 'update': perm_name += 'change' else: #TODO delete_list? update_list? others? perm_name += self.endpoint perm_name += '_' + self.model.__name__ return self.identity.has_perm(perm_name) class ModelAuthorizationMixin(AuthorizationMixin): def make_authorization(self, identity, endpoint): return DjangoModelAuthorization(identity, self.model, endpoint)
class Authorization(object): """ Base authorization class, defaults to full authorization """ def __init__(self, identity, endpoint): self.identity = identity self.endpoint = endpoint def process_queryset(self, queryset): return queryset def is_authorized(self): return True class Authorizationmixin(object): def make_authorization(self, identity, endpoint): return authorization(identity, endpoint) def get_identity(self): return self.request.user def is_authenticated(self): return self.authorization.is_authorized() def handle(self, endpoint, *args, **kwargs): self.identity = self.get_identity() self.authorization = self.make_authorization(self.identity, endpoint) return super(AuthorizationMixin, self).handle(endpoint, *args, **kwargs) class Djangomodelauthorization(Authorization): """ Your basic django core permission based authorization """ def __init__(self, identity, model, endpoint): super(DjangoModelAuthorization, self).__init__(identity, endpoint) self.model = model def is_authorized(self): if self.identity.is_superuser: return True if self.endpoint == 'list': return True return self.identity.has_perm perm_name = self.model._meta.app_label + '.' if self.endpoint == 'create': perm_name += 'add' elif self.endpoint == 'update': perm_name += 'change' else: perm_name += self.endpoint perm_name += '_' + self.model.__name__ return self.identity.has_perm(perm_name) class Modelauthorizationmixin(AuthorizationMixin): def make_authorization(self, identity, endpoint): return django_model_authorization(identity, self.model, endpoint)
# Len of signature in write signed packet SIGNATURE_LEN = 12 # Attribute Protocol Opcodes OP_ERROR = 0x01 OP_MTU_REQ = 0x02 OP_MTU_RESP = 0x03 OP_FIND_INFO_REQ = 0x04 OP_FIND_INFO_RESP = 0x05 OP_FIND_BY_TYPE_REQ = 0x06 OP_FIND_BY_TYPE_RESP= 0x07 OP_READ_BY_TYPE_REQ = 0x08 OP_READ_BY_TYPE_RESP = 0x09 OP_READ_REQ = 0x0A OP_READ_RESP = 0x0B OP_READ_BLOB_REQ = 0x0C OP_READ_BLOB_RESP = 0x0D OP_READ_MULTI_REQ = 0x0E OP_READ_MULTI_RESP = 0x0F OP_READ_BY_GROUP_REQ = 0x10 OP_READ_BY_GROUP_RESP = 0x11 OP_WRITE_REQ = 0x12 OP_WRITE_RESP = 0x13 OP_WRITE_CMD = 0x52 OP_PREP_WRITE_REQ = 0x16 OP_PREP_WRITE_RESP = 0x17 OP_EXEC_WRITE_REQ = 0x18 OP_EXEC_WRITE_RESP = 0x19 OP_HANDLE_NOTIFY = 0x1B OP_HANDLE_IND = 0x1D OP_HANDLE_CNF = 0x1E OP_SIGNED_WRITE_CMD = 0xD2 __STRING_TO_OPCODE = { "ERROR" : 0x01, "MTU_REQ" : 0x02, "MTU_RESP" : 0x03, "FIND_INFO_REQ" : 0x04, "FIND_INFO_RESP" : 0x05, "FIND_BY_TYPE_REQ" : 0x06, "FIND_BY_TYPE_RESP" : 0x07, "READ_BY_TYPE_REQ" : 0x08, "READ_BY_TYPE_RESP" : 0x09, "READ_REQ" : 0x0A, "READ_RESP" : 0x0B, "READ_BLOB_REQ" : 0x0C, "READ_BLOB_RESP" : 0x0D, "READ_MULTI_REQ" : 0x0E, "READ_MULTI_RESP" : 0x0F, "READ_BY_GROUP_REQ" : 0x10, "READ_BY_GROUP_RESP" : 0x11, "WRITE_REQ" : 0x12, "WRITE_RESP" : 0x13, "WRITE_CMD" : 0x52, "PREP_WRITE_REQ" : 0x16, "PREP_WRITE_RESP" : 0x17, "EXEC_WRITE_REQ" : 0x18, "EXEC_WRITE_RESP" : 0x19, "HANDLE_NOTIFY" : 0x1B, "HANDLE_IND" : 0x1D, "HANDLE_CNF" : 0x1E, "SIGNED_WRITE_CMD" : 0xD2, } __OPCODE_TO_STRING = { v: k for k, v in __STRING_TO_OPCODE.items() } def opcodeLookup(opcode): return __OPCODE_TO_STRING[opcode] if opcode in __OPCODE_TO_STRING \ else "unknown" __OP_COMMAND = frozenset((OP_WRITE_CMD, OP_SIGNED_WRITE_CMD)) def isCommand(opcode): return opcode in __OP_COMMAND __OP_REQUEST = frozenset(( OP_MTU_REQ, OP_FIND_INFO_REQ, OP_FIND_BY_TYPE_REQ, OP_READ_BY_TYPE_REQ, OP_READ_REQ, OP_READ_BLOB_REQ, OP_READ_MULTI_REQ, OP_READ_BY_GROUP_REQ, OP_WRITE_REQ, OP_PREP_WRITE_REQ, OP_EXEC_WRITE_REQ, )) def isRequest(opcode): return opcode in __OP_REQUEST __OP_RESPONSE = frozenset(( OP_MTU_RESP, OP_FIND_INFO_RESP, OP_FIND_BY_TYPE_RESP, OP_READ_BY_TYPE_RESP, OP_READ_RESP, OP_READ_BLOB_RESP, OP_READ_MULTI_RESP, OP_READ_BY_GROUP_RESP, OP_WRITE_RESP, OP_PREP_WRITE_RESP, OP_EXEC_WRITE_RESP, )) def isResponse(opcode): return opcode in __OP_RESPONSE # Error codes for Error response PDU ECODE_INVALID_HANDLE = 0x01 ECODE_READ_NOT_PERM = 0x02 ECODE_WRITE_NOT_PERM = 0x03 ECODE_INVALID_PDU = 0x04 ECODE_AUTHENTICATION = 0x05 ECODE_REQ_NOT_SUPP = 0x06 ECODE_INVALID_OFFSET = 0x07 ECODE_AUTHORIZATION = 0x08 ECODE_PREP_QUEUE_FULL = 0x09 ECODE_ATTR_NOT_FOUND = 0x0A ECODE_ATTR_NOT_LONG = 0x0B ECODE_INSUFF_ENCR_KEY_SIZE = 0x0C ECODE_INVAL_ATTR_VALUE_LEN = 0x0D ECODE_UNLIKELY = 0x0E ECODE_INSUFF_ENC = 0x0F ECODE_UNSUPP_GRP_TYPE = 0x10 ECODE_INSUFF_RESOURCES = 0x11 # Application error ECODE_IO = 0x80 ECODE_TIMEOUT = 0x81 ECODE_ABORTED = 0x82 __STRING_TO_ECODE = { "INVALID_HANDLE" : 0x01, "READ_NOT_PERM" : 0x02, "WRITE_NOT_PERM" : 0x03, "INVALID_PDU" : 0x04, "AUTHENTICATION" : 0x05, "REQ_NOT_SUPP" : 0x06, "INVALID_OFFSET" : 0x07, "AUTHORIZATION" : 0x08, "PREP_QUEUE_FULL" : 0x09, "ATTR_NOT_FOUND" : 0x0A, "ATTR_NOT_LONG" : 0x0B, "INSUFF_ENCR_KEY_SIZE" : 0x0C, "INVAL_ATTR_VALUE_LEN" : 0x0D, "UNLIKELY" : 0x0E, "INSUFF_ENC" : 0x0F, "UNSUPP_GRP_TYPE" : 0x10, "INSUFF_RESOURCES" : 0x11, "IO" : 0x80, "TIMEOUT" : 0x81, "ABORTED" : 0x82, } __ECODE_TO_STRING = { v: k for k, v in __STRING_TO_ECODE.items() } def ecodeLookup(ecode): return __ECODE_TO_STRING[ecode] if ecode in __ECODE_TO_STRING else "unknown" MAX_VALUE_LEN = 512 DEFAULT_L2CAP_MTU = 48 DEFAULT_LE_MTU = 23 CID = 4 PSM = 31 # Flags for Execute Write Request Operation CANCEL_ALL_PREP_WRITES = 0x00 WRITE_ALL_PREP_WRITES = 0x01 # Find Information Response Formats FIND_INFO_RESP_FMT_16BIT = 0x01 FIND_INFO_RESP_FMT_128BIT = 0x02
signature_len = 12 op_error = 1 op_mtu_req = 2 op_mtu_resp = 3 op_find_info_req = 4 op_find_info_resp = 5 op_find_by_type_req = 6 op_find_by_type_resp = 7 op_read_by_type_req = 8 op_read_by_type_resp = 9 op_read_req = 10 op_read_resp = 11 op_read_blob_req = 12 op_read_blob_resp = 13 op_read_multi_req = 14 op_read_multi_resp = 15 op_read_by_group_req = 16 op_read_by_group_resp = 17 op_write_req = 18 op_write_resp = 19 op_write_cmd = 82 op_prep_write_req = 22 op_prep_write_resp = 23 op_exec_write_req = 24 op_exec_write_resp = 25 op_handle_notify = 27 op_handle_ind = 29 op_handle_cnf = 30 op_signed_write_cmd = 210 __string_to_opcode = {'ERROR': 1, 'MTU_REQ': 2, 'MTU_RESP': 3, 'FIND_INFO_REQ': 4, 'FIND_INFO_RESP': 5, 'FIND_BY_TYPE_REQ': 6, 'FIND_BY_TYPE_RESP': 7, 'READ_BY_TYPE_REQ': 8, 'READ_BY_TYPE_RESP': 9, 'READ_REQ': 10, 'READ_RESP': 11, 'READ_BLOB_REQ': 12, 'READ_BLOB_RESP': 13, 'READ_MULTI_REQ': 14, 'READ_MULTI_RESP': 15, 'READ_BY_GROUP_REQ': 16, 'READ_BY_GROUP_RESP': 17, 'WRITE_REQ': 18, 'WRITE_RESP': 19, 'WRITE_CMD': 82, 'PREP_WRITE_REQ': 22, 'PREP_WRITE_RESP': 23, 'EXEC_WRITE_REQ': 24, 'EXEC_WRITE_RESP': 25, 'HANDLE_NOTIFY': 27, 'HANDLE_IND': 29, 'HANDLE_CNF': 30, 'SIGNED_WRITE_CMD': 210} __opcode_to_string = {v: k for (k, v) in __STRING_TO_OPCODE.items()} def opcode_lookup(opcode): return __OPCODE_TO_STRING[opcode] if opcode in __OPCODE_TO_STRING else 'unknown' __op_command = frozenset((OP_WRITE_CMD, OP_SIGNED_WRITE_CMD)) def is_command(opcode): return opcode in __OP_COMMAND __op_request = frozenset((OP_MTU_REQ, OP_FIND_INFO_REQ, OP_FIND_BY_TYPE_REQ, OP_READ_BY_TYPE_REQ, OP_READ_REQ, OP_READ_BLOB_REQ, OP_READ_MULTI_REQ, OP_READ_BY_GROUP_REQ, OP_WRITE_REQ, OP_PREP_WRITE_REQ, OP_EXEC_WRITE_REQ)) def is_request(opcode): return opcode in __OP_REQUEST __op_response = frozenset((OP_MTU_RESP, OP_FIND_INFO_RESP, OP_FIND_BY_TYPE_RESP, OP_READ_BY_TYPE_RESP, OP_READ_RESP, OP_READ_BLOB_RESP, OP_READ_MULTI_RESP, OP_READ_BY_GROUP_RESP, OP_WRITE_RESP, OP_PREP_WRITE_RESP, OP_EXEC_WRITE_RESP)) def is_response(opcode): return opcode in __OP_RESPONSE ecode_invalid_handle = 1 ecode_read_not_perm = 2 ecode_write_not_perm = 3 ecode_invalid_pdu = 4 ecode_authentication = 5 ecode_req_not_supp = 6 ecode_invalid_offset = 7 ecode_authorization = 8 ecode_prep_queue_full = 9 ecode_attr_not_found = 10 ecode_attr_not_long = 11 ecode_insuff_encr_key_size = 12 ecode_inval_attr_value_len = 13 ecode_unlikely = 14 ecode_insuff_enc = 15 ecode_unsupp_grp_type = 16 ecode_insuff_resources = 17 ecode_io = 128 ecode_timeout = 129 ecode_aborted = 130 __string_to_ecode = {'INVALID_HANDLE': 1, 'READ_NOT_PERM': 2, 'WRITE_NOT_PERM': 3, 'INVALID_PDU': 4, 'AUTHENTICATION': 5, 'REQ_NOT_SUPP': 6, 'INVALID_OFFSET': 7, 'AUTHORIZATION': 8, 'PREP_QUEUE_FULL': 9, 'ATTR_NOT_FOUND': 10, 'ATTR_NOT_LONG': 11, 'INSUFF_ENCR_KEY_SIZE': 12, 'INVAL_ATTR_VALUE_LEN': 13, 'UNLIKELY': 14, 'INSUFF_ENC': 15, 'UNSUPP_GRP_TYPE': 16, 'INSUFF_RESOURCES': 17, 'IO': 128, 'TIMEOUT': 129, 'ABORTED': 130} __ecode_to_string = {v: k for (k, v) in __STRING_TO_ECODE.items()} def ecode_lookup(ecode): return __ECODE_TO_STRING[ecode] if ecode in __ECODE_TO_STRING else 'unknown' max_value_len = 512 default_l2_cap_mtu = 48 default_le_mtu = 23 cid = 4 psm = 31 cancel_all_prep_writes = 0 write_all_prep_writes = 1 find_info_resp_fmt_16_bit = 1 find_info_resp_fmt_128_bit = 2
''' Description: ------------ When objects are instantiated, the object itself is passed into the self parameter. The Object is passed into the self parameter so that the object can keep hold of its own data. ''' print(__doc__) print('-'*25) class State(object): def __init__(self): global x x=self.field = 5.0 def add(self, x): self.field += x def mul(self, x): self.field *= x def div(self, x): self.field /= x def sub(self, x): self.field -= x n=int(input('Enter a valued: ')) s = State() print(f"\nAfter intializing the varaiable, the value of variable is: {s.field}") s.add(n) # Self is implicitly passed. print(f"\nAddition of the initalized variable {x} with {n} is: {s.field}") s.mul(n) # Self is implicitly passed. print(f"\nMultiplication of the initalized variable {x} with {n} is: {s.field}") s.div(n) # Self is implicitly passed. print(f"\nSubtraction of the initalized variable {x} with {n} is: {s.field}") s.sub(n) # Self is implicitly passed. print(f"\nDivision of the initalized variable {x} with {n} is: {s.field}")
""" Description: ------------ When objects are instantiated, the object itself is passed into the self parameter. The Object is passed into the self parameter so that the object can keep hold of its own data. """ print(__doc__) print('-' * 25) class State(object): def __init__(self): global x x = self.field = 5.0 def add(self, x): self.field += x def mul(self, x): self.field *= x def div(self, x): self.field /= x def sub(self, x): self.field -= x n = int(input('Enter a valued: ')) s = state() print(f'\nAfter intializing the varaiable, the value of variable is: {s.field}') s.add(n) print(f'\nAddition of the initalized variable {x} with {n} is: {s.field}') s.mul(n) print(f'\nMultiplication of the initalized variable {x} with {n} is: {s.field}') s.div(n) print(f'\nSubtraction of the initalized variable {x} with {n} is: {s.field}') s.sub(n) print(f'\nDivision of the initalized variable {x} with {n} is: {s.field}')
# # @lc app=leetcode id=611 lang=python3 # # [611] Valid Triangle Number # # https://leetcode.com/problems/valid-triangle-number/description/ # # algorithms # Medium (49.73%) # Likes: 1857 # Dislikes: 129 # Total Accepted: 109.5K # Total Submissions: 222.7K # Testcase Example: '[2,2,3,4]' # # Given an integer array nums, return the number of triplets chosen from the # array that can make triangles if we take them as side lengths of a # triangle. # # # Example 1: # # # Input: nums = [2,2,3,4] # Output: 3 # Explanation: Valid combinations are: # 2,3,4 (using the first 2) # 2,3,4 (using the second 2) # 2,2,3 # # # Example 2: # # # Input: nums = [4,2,3,4] # Output: 4 # # # # Constraints: # # # 1 <= nums.length <= 1000 # 0 <= nums[i] <= 1000 # # # # @lc code=start class Solution: def triangleNumber(self, nums: List[int]) -> int: if not nums or len(nums) <= 2: return 0 nums.sort() count = 0 for i in range(len(nums) - 1, 1, -1): delta = self.two_sum_greater(nums, 0, i - 1, nums[i]) count += delta return count def two_sum_greater(self, nums, start, end, target): delta = 0 while start <= end: if nums[start] + nums[end] > target: delta += end - start end -= 1 else: start += 1 return delta # solve using DFS, print out all possible combination def triangleNumber_DFS(self, nums: List[int]) -> int: if not nums or len(nums) < 3: return 0 self.ret = 0 self.tmp = [] self.used = [False for _ in range(len(nums))] nums.sort() self._dfs(nums, 0, []) # print(self.tmp) return self.ret def _dfs(self, nums, start, curr): if len(curr) > 3: return if len(curr) == 3: if curr[0] + curr[1] > curr[2]: self.ret += 1 self.tmp.append(curr[:]) return for i in range(start, len(nums)): self.used[i] = True curr.append(nums[i]) self._dfs(nums, i + 1, curr) curr.pop() self.used[i] = False # @lc code=end
class Solution: def triangle_number(self, nums: List[int]) -> int: if not nums or len(nums) <= 2: return 0 nums.sort() count = 0 for i in range(len(nums) - 1, 1, -1): delta = self.two_sum_greater(nums, 0, i - 1, nums[i]) count += delta return count def two_sum_greater(self, nums, start, end, target): delta = 0 while start <= end: if nums[start] + nums[end] > target: delta += end - start end -= 1 else: start += 1 return delta def triangle_number_dfs(self, nums: List[int]) -> int: if not nums or len(nums) < 3: return 0 self.ret = 0 self.tmp = [] self.used = [False for _ in range(len(nums))] nums.sort() self._dfs(nums, 0, []) return self.ret def _dfs(self, nums, start, curr): if len(curr) > 3: return if len(curr) == 3: if curr[0] + curr[1] > curr[2]: self.ret += 1 self.tmp.append(curr[:]) return for i in range(start, len(nums)): self.used[i] = True curr.append(nums[i]) self._dfs(nums, i + 1, curr) curr.pop() self.used[i] = False
""" Objects dealing with EBUS boundaries for plotting, statistics, etc. Functions --------- - `visual_bounds` : lat/lon bounds for close-up shots of our regions. - `latitude_bounds` : lat bounds for statistical analysis To do ----- - `full_scope_bounds` : regions pulled from Chavez paper for lat/lon to show full system for validation """ def visual_bounds(EBC, std_lon=False): """ Returns the latitude and longitude bounds for plotting a decently large swatch of the EBC. Parameters ---------- EBC : str Identifier for the EBC. 'CalCS': California Current 'HumCS': Humboldt Current 'CanCS': Canary Current 'BenCS': Benguela Current std_lon : boolean (optional) Set to True if you desire -180 to 180 longitude. Returns ------- lon1 : int; minimum lon boundary lon2 : int; maximum lon boundary lat1 : int; minimum lat boundary lat2 : int; maximum lat boundary Examples -------- import esmtools.ebus as ebus x1,x2,y1,y2 = ebus.visual_bounds('CalCS') """ if EBC == 'CalCS': lat1 = 32 lat2 = 45 lon1 = -135 lon2 = -115 elif EBC == 'HumCS': lat1 = -20 lat2 = 0 lon1 = -85 lon2 = -70 elif EBC == 'CanCS': lat1 = 15 lat2 = 35 lon1 = -25 lon2 = -5 elif EBC == 'BenCS': lat1 = -30 lat2 = -15 lon1 = 5 lon2 = 20 else: raise ValueError('\n' + 'Must select from the following EBUS strings:' \ + '\n' + 'CalCS' + '\n' + 'CanCS' + '\n' + 'BenCS' + \ '\n' + 'HumCS') if (std_lon == False) & (EBC != 'BenCS'): lon1 = lon1 + 360 lon2 = lon2 + 360 return lon1,lon2,lat1,lat2 def latitude_bounds(EBC): """ Returns the standard 10 degrees of latitude to be analyzed for each system. For the CalCS, HumCS, and BenCS, this comes from the Chavez 2009 EBUS Comparison paper. For the CanCS, this comes from the Aristegui 2009 CanCS paper. These bounds are used in the EBUS CO2 Flux comparison study to standardize latitude. Parameters ---------- EBC : str Identifier for the boundary current. 'CalCS' : California Current 'HumCS' : Humboldt Current 'CanCS' : Canary Current 'BenCS' : Benguela Current Returns ------- lat1 : int Minimum latitude bound. lat2 : int Maximum latitude bound. Examples -------- import esmtools.ebus as eb y1,y2 = eb.boundaries.latitude_bounds('HumCS') """ if EBC == 'CalCS': lat1 = 34 lat2 = 44 elif EBC == 'HumCS': lat1 = -16 lat2 = -6 elif EBC == 'CanCS': lat1 = 21 lat2 = 31 elif EBC == 'BenCS': lat1 = -28 lat2 = -18 else: raise ValueError('\n' + 'Must select from the following EBUS strings:' + '\n' + 'CalCS' + '\n' + 'CanCS' + '\n' + 'BenCS' + '\n' + 'HumCS') return lat1, lat2
""" Objects dealing with EBUS boundaries for plotting, statistics, etc. Functions --------- - `visual_bounds` : lat/lon bounds for close-up shots of our regions. - `latitude_bounds` : lat bounds for statistical analysis To do ----- - `full_scope_bounds` : regions pulled from Chavez paper for lat/lon to show full system for validation """ def visual_bounds(EBC, std_lon=False): """ Returns the latitude and longitude bounds for plotting a decently large swatch of the EBC. Parameters ---------- EBC : str Identifier for the EBC. 'CalCS': California Current 'HumCS': Humboldt Current 'CanCS': Canary Current 'BenCS': Benguela Current std_lon : boolean (optional) Set to True if you desire -180 to 180 longitude. Returns ------- lon1 : int; minimum lon boundary lon2 : int; maximum lon boundary lat1 : int; minimum lat boundary lat2 : int; maximum lat boundary Examples -------- import esmtools.ebus as ebus x1,x2,y1,y2 = ebus.visual_bounds('CalCS') """ if EBC == 'CalCS': lat1 = 32 lat2 = 45 lon1 = -135 lon2 = -115 elif EBC == 'HumCS': lat1 = -20 lat2 = 0 lon1 = -85 lon2 = -70 elif EBC == 'CanCS': lat1 = 15 lat2 = 35 lon1 = -25 lon2 = -5 elif EBC == 'BenCS': lat1 = -30 lat2 = -15 lon1 = 5 lon2 = 20 else: raise value_error('\n' + 'Must select from the following EBUS strings:' + '\n' + 'CalCS' + '\n' + 'CanCS' + '\n' + 'BenCS' + '\n' + 'HumCS') if (std_lon == False) & (EBC != 'BenCS'): lon1 = lon1 + 360 lon2 = lon2 + 360 return (lon1, lon2, lat1, lat2) def latitude_bounds(EBC): """ Returns the standard 10 degrees of latitude to be analyzed for each system. For the CalCS, HumCS, and BenCS, this comes from the Chavez 2009 EBUS Comparison paper. For the CanCS, this comes from the Aristegui 2009 CanCS paper. These bounds are used in the EBUS CO2 Flux comparison study to standardize latitude. Parameters ---------- EBC : str Identifier for the boundary current. 'CalCS' : California Current 'HumCS' : Humboldt Current 'CanCS' : Canary Current 'BenCS' : Benguela Current Returns ------- lat1 : int Minimum latitude bound. lat2 : int Maximum latitude bound. Examples -------- import esmtools.ebus as eb y1,y2 = eb.boundaries.latitude_bounds('HumCS') """ if EBC == 'CalCS': lat1 = 34 lat2 = 44 elif EBC == 'HumCS': lat1 = -16 lat2 = -6 elif EBC == 'CanCS': lat1 = 21 lat2 = 31 elif EBC == 'BenCS': lat1 = -28 lat2 = -18 else: raise value_error('\n' + 'Must select from the following EBUS strings:' + '\n' + 'CalCS' + '\n' + 'CanCS' + '\n' + 'BenCS' + '\n' + 'HumCS') return (lat1, lat2)
# Computers are fast, so we can implement a brute-force search to directly solve the problem. def compute(): PERIMETER = 1000 for a in range(1, PERIMETER + 1): for b in range(a + 1, PERIMETER + 1): c = PERIMETER - a - b if a * a + b * b == c * c: # It is now implied that b < c, because we have a > 0 return str(a * b * c) if __name__ == "__main__": print(compute())
def compute(): perimeter = 1000 for a in range(1, PERIMETER + 1): for b in range(a + 1, PERIMETER + 1): c = PERIMETER - a - b if a * a + b * b == c * c: return str(a * b * c) if __name__ == '__main__': print(compute())
{ "targets": [ { "target_name": "yolo", "sources": [ "src/yolo.cc" ] } ] }
{'targets': [{'target_name': 'yolo', 'sources': ['src/yolo.cc']}]}
class Docs(object): def __init__(self, conn): self.client = conn.client def size(self): r = self.client.get('/docs/size') return int(r.text) def add(self, name, content): self.client.post('/docs', files={'upload': (name, content)}) def clear(self): self.client.delete('/docs') def get(self, name, stream=False, chunk_size=10240): with self.client.get('/docs/{}'.format(name), stream=stream) as r: yield r.iter_content( chunk_size=chunk_size) if stream else r.content def delete(self, name): self.client.delete('/docs/{}'.format(name))
class Docs(object): def __init__(self, conn): self.client = conn.client def size(self): r = self.client.get('/docs/size') return int(r.text) def add(self, name, content): self.client.post('/docs', files={'upload': (name, content)}) def clear(self): self.client.delete('/docs') def get(self, name, stream=False, chunk_size=10240): with self.client.get('/docs/{}'.format(name), stream=stream) as r: yield (r.iter_content(chunk_size=chunk_size) if stream else r.content) def delete(self, name): self.client.delete('/docs/{}'.format(name))
class SlowDisjointSet: def __init__(self, N): self.N = N self._bubbles = [] for i in range(N): self._bubbles.append({i}) self._operations = 0 self._calls = 0 def _find_i(self, i): """ Find the index of the bubble that holds a particular value in the list of bubbles Parameters ---------- i: int Element we're looking for Returns ------- Index of the bubble containing i """ index = -1 k = 0 while k < len(self._bubbles) and index == -1: for item in self._bubbles[k]: self._operations += 1 if item == i: index = k break k += 1 return index def find(self, i, j): """ Return true if i and j are in the same component, or false otherwise Parameters ---------- i: int Index of first element j: int Index of second element """ self._calls += 1 id_i = self._find_i(i) id_j = self._find_i(j) if id_i == id_j: return True else: return False def union(self, i, j): """ Merge the two sets containing i and j, or do nothing if they're in the same set Parameters ---------- i: int Index of first element j: int Index of second element """ self._calls += 1 idx_i = self._find_i(i) idx_j = self._find_i(j) if idx_i != idx_j: # Merge lists # Decide that bubble containing j will be absorbed into # bubble containing i self._operations += len(self._bubbles[idx_i]) + len(self._bubbles[idx_j]) self._bubbles[idx_i] |= self._bubbles[idx_j] # Remove the old bubble containing j self._bubbles = self._bubbles[0:idx_j] + self._bubbles[idx_j+1::]
class Slowdisjointset: def __init__(self, N): self.N = N self._bubbles = [] for i in range(N): self._bubbles.append({i}) self._operations = 0 self._calls = 0 def _find_i(self, i): """ Find the index of the bubble that holds a particular value in the list of bubbles Parameters ---------- i: int Element we're looking for Returns ------- Index of the bubble containing i """ index = -1 k = 0 while k < len(self._bubbles) and index == -1: for item in self._bubbles[k]: self._operations += 1 if item == i: index = k break k += 1 return index def find(self, i, j): """ Return true if i and j are in the same component, or false otherwise Parameters ---------- i: int Index of first element j: int Index of second element """ self._calls += 1 id_i = self._find_i(i) id_j = self._find_i(j) if id_i == id_j: return True else: return False def union(self, i, j): """ Merge the two sets containing i and j, or do nothing if they're in the same set Parameters ---------- i: int Index of first element j: int Index of second element """ self._calls += 1 idx_i = self._find_i(i) idx_j = self._find_i(j) if idx_i != idx_j: self._operations += len(self._bubbles[idx_i]) + len(self._bubbles[idx_j]) self._bubbles[idx_i] |= self._bubbles[idx_j] self._bubbles = self._bubbles[0:idx_j] + self._bubbles[idx_j + 1:]
#!/bin/env python3 option = input("[E]ncryption, [D]ecryption, or [Q]uit -- ") def key_generation(a, b, a1, b1): M = a * b - 1 e = a1 * M + a d = b1 * M + b n = (e * d - 1) / M return int(e), int(d), int(n) def encryption(a, b, a1, b1): e, d, n = key_generation(a, b, a1, b1) print("You may publish your public key (n,e) = (", n, ", ", e, ")") print("and keep your private key (n,d) = (",n, ", ", d, ") secret.") plaintext = input("Plaintext - ") cipher = [] for i in range(len(plaintext)): cipher.append(str((ord(plaintext[i]) * e) % n)) ciphertext = " ".join(cipher) print(ciphertext) def decryption(): private = input("Your private key (n, d), separated by a space or comma -- ").replace(",", " ") n, d = list(map(int, private.split(" "))) ciphertext = input("Ciphertext (integers separated by spaces) -- ") cipher = list(map(int, ciphertext.split(" "))) plain = [] for i in range(len(cipher)): plain.append(str((cipher[i] * d) % n)) print(" ".join(plain)) plaintext = "" for i in range(len(plain)): plaintext += chr(int(plain[i])) print("Plaintext - ", plaintext) def main(): if option.upper() == "E": ints = input("Input 4 integers a, b, a', b' -- ") a, b, a1, b1 = list(map(int, ints.split(" "))) encryption(a, b, a1, b1) elif option.upper() == "D": decryption() else: return if __name__ == "__main__": main()
option = input('[E]ncryption, [D]ecryption, or [Q]uit -- ') def key_generation(a, b, a1, b1): m = a * b - 1 e = a1 * M + a d = b1 * M + b n = (e * d - 1) / M return (int(e), int(d), int(n)) def encryption(a, b, a1, b1): (e, d, n) = key_generation(a, b, a1, b1) print('You may publish your public key (n,e) = (', n, ', ', e, ')') print('and keep your private key (n,d) = (', n, ', ', d, ') secret.') plaintext = input('Plaintext - ') cipher = [] for i in range(len(plaintext)): cipher.append(str(ord(plaintext[i]) * e % n)) ciphertext = ' '.join(cipher) print(ciphertext) def decryption(): private = input('Your private key (n, d), separated by a space or comma -- ').replace(',', ' ') (n, d) = list(map(int, private.split(' '))) ciphertext = input('Ciphertext (integers separated by spaces) -- ') cipher = list(map(int, ciphertext.split(' '))) plain = [] for i in range(len(cipher)): plain.append(str(cipher[i] * d % n)) print(' '.join(plain)) plaintext = '' for i in range(len(plain)): plaintext += chr(int(plain[i])) print('Plaintext - ', plaintext) def main(): if option.upper() == 'E': ints = input("Input 4 integers a, b, a', b' -- ") (a, b, a1, b1) = list(map(int, ints.split(' '))) encryption(a, b, a1, b1) elif option.upper() == 'D': decryption() else: return if __name__ == '__main__': main()
#!/usr/bin/env python # coding: utf-8 # # Seldon Kafka Integration Example with CIFAR10 Model # # In this example we will run SeldonDeployments for a CIFAR10 Tensorflow model which take their inputs from a Kafka topic and push their outputs to a Kafka topic. We will experiment with both REST and gRPC Seldon graphs. For REST we will load our input topic with Tensorflow JSON requests and for gRPC we will load Tensorflow PredictRequest protoBuffers. # ## Requirements # # * [Install gsutil](https://cloud.google.com/storage/docs/gsutil_install) # # In[ ]: get_ipython().system('pip install -r requirements.txt') # ## Setup Kafka # Install Strimzi on cluster # In[ ]: get_ipython().system('helm repo add strimzi https://strimzi.io/charts/') # In[ ]: get_ipython().system('helm install my-release strimzi/strimzi-kafka-operator') # Set the following to whether you are running a local Kind cluster or a cloud based cluster. # In[ ]: clusterType = "kind" # clusterType="cloud" # In[ ]: if clusterType == "kind": get_ipython().system('kubectl apply -f cluster-kind.yaml') else: get_ipython().system('kubectl apply -f cluster-cloud.yaml') # Get broker endpoint. # In[ ]: if clusterType == "kind": res = get_ipython().getoutput("kubectl get service my-cluster-kafka-external-bootstrap -n default -o=jsonpath='{.spec.ports[0].nodePort}'") port = res[0] get_ipython().run_line_magic('env', 'BROKER=172.17.0.2:$port') else: res = get_ipython().getoutput("kubectl get service my-cluster-kafka-external-bootstrap -o=jsonpath='{.status.loadBalancer.ingress[0].hostname}'") if len(res) == 1: hostname = res[0] get_ipython().run_line_magic('env', 'BROKER=$h:9094') else: res = get_ipython().getoutput("kubectl get service my-cluster-kafka-external-bootstrap -o=jsonpath='{.status.loadBalancer.ingress[0].ip}'") ip = res[0] get_ipython().run_line_magic('env', 'BROKER=$ip:9094') # In[ ]: get_ipython().run_cell_magic('writefile', 'topics.yaml', 'apiVersion: kafka.strimzi.io/v1beta1\nkind: KafkaTopic\nmetadata:\n name: cifar10-rest-input\n labels:\n strimzi.io/cluster: "my-cluster"\nspec:\n partitions: 2\n replicas: 1\n---\napiVersion: kafka.strimzi.io/v1beta1\nkind: KafkaTopic\nmetadata:\n name: cifar10-rest-output\n labels:\n strimzi.io/cluster: "my-cluster"\nspec:\n partitions: 2\n replicas: 1\n---\napiVersion: kafka.strimzi.io/v1beta1\nkind: KafkaTopic\nmetadata:\n name: cifar10-grpc-input\n labels:\n strimzi.io/cluster: "my-cluster"\nspec:\n partitions: 2\n replicas: 1\n---\napiVersion: kafka.strimzi.io/v1beta1\nkind: KafkaTopic\nmetadata:\n name: cifar10-grpc-output\n labels:\n strimzi.io/cluster: "my-cluster"\nspec:\n partitions: 2\n replicas: 1') # In[ ]: get_ipython().system('kubectl apply -f topics.yaml') # ## Install Seldon # # * [Install Seldon](https://docs.seldon.io/projects/seldon-core/en/latest/workflow/install.html) # * [Follow our docs to intstall the Grafana analytics](https://docs.seldon.io/projects/seldon-core/en/latest/analytics/analytics.html). # ## Download Test Request Data # We have two example datasets containing 50,000 requests in tensorflow serving format for CIFAR10. One in JSON format and one as length encoded proto buffers. # In[ ]: get_ipython().system('gsutil cp gs://seldon-datasets/cifar10/requests/tensorflow/cifar10_tensorflow.json.gz cifar10_tensorflow.json.gz') get_ipython().system('gunzip cifar10_tensorflow.json.gz') get_ipython().system('gsutil cp gs://seldon-datasets/cifar10/requests/tensorflow/cifar10_tensorflow.proto cifar10_tensorflow.proto') # ## Test CIFAR10 REST Model # Upload tensorflow serving rest requests to kafka. This may take some time dependent on your network connection. # In[ ]: get_ipython().system('python ../../../util/kafka/test-client.py produce $BROKER cifar10-rest-input --file cifar10_tensorflow.json') # In[ ]: res = get_ipython().getoutput("kubectl get service my-cluster-kafka-external-bootstrap -o=jsonpath='{.spec.clusterIP}'") ip = res[0] get_ipython().run_line_magic('env', 'BROKER_CIP=$ip') # In[ ]: get_ipython().run_cell_magic('writefile', 'cifar10_rest.yaml', 'apiVersion: machinelearning.seldon.io/v1\nkind: SeldonDeployment\nmetadata:\n name: tfserving-cifar10\nspec:\n protocol: tensorflow\n transport: rest\n serverType: kafka \n predictors:\n - componentSpecs:\n - spec:\n containers:\n - args: \n - --port=8500\n - --rest_api_port=8501\n - --model_name=resnet32\n - --model_base_path=gs://seldon-models/tfserving/cifar10/resnet32\n - --enable_batching\n image: tensorflow/serving\n name: resnet32\n ports:\n - containerPort: 8501\n name: http\n svcOrchSpec:\n env:\n - name: KAFKA_BROKER\n value: BROKER_IP\n - name: KAFKA_INPUT_TOPIC\n value: cifar10-rest-input\n - name: KAFKA_OUTPUT_TOPIC\n value: cifar10-rest-output\n graph:\n name: resnet32\n type: MODEL\n endpoint:\n service_port: 8501\n name: model\n replicas: 1') # In[ ]: get_ipython().system('cat cifar10_rest.yaml | sed s/BROKER_IP/$BROKER_CIP:9094/ | kubectl apply -f -') # Looking at the metrics dashboard for Seldon you should see throughput we are getting. For a single replica on GKE with n1-standard-4 nodes we can see roughly 150 requests per second being processed. # # ![rest](tensorflow-rest-kafka.png) # In[ ]: get_ipython().system('kubectl delete -f cifar10_rest.yaml') # ## Test CIFAR10 gRPC Model # Upload tensorflow serving rest requests to kafka. This is a file of protobuffer `tenserflow.serving.PredictRequest` ([defn](https://github.com/tensorflow/serving/blob/master/tensorflow_serving/apis/predict.proto)). Each binary protobuffer is prefixed by the numbre of bytes. Out test-client python script reads them and sends to our topic. This may take some time dependent on your network connection. # In[ ]: get_ipython().system('python ../../../util/kafka/test-client.py produce $BROKER cifar10-grpc-input --file cifar10_tensorflow.proto --proto_name tensorflow.serving.PredictRequest') # In[ ]: res = get_ipython().getoutput("kubectl get service my-cluster-kafka-external-bootstrap -o=jsonpath='{.spec.clusterIP}'") ip = res[0] get_ipython().run_line_magic('env', 'BROKER_CIP=$ip') # In[ ]: get_ipython().run_cell_magic('writefile', 'cifar10_grpc.yaml', 'apiVersion: machinelearning.seldon.io/v1\nkind: SeldonDeployment\nmetadata:\n name: tfserving-cifar10\nspec:\n protocol: tensorflow\n transport: grpc\n serverType: kafka \n predictors:\n - componentSpecs:\n - spec:\n containers:\n - args: \n - --port=8500\n - --rest_api_port=8501\n - --model_name=resnet32\n - --model_base_path=gs://seldon-models/tfserving/cifar10/resnet32\n - --enable_batching \n image: tensorflow/serving\n name: resnet32\n ports:\n - containerPort: 8500\n name: http\n svcOrchSpec:\n env:\n - name: KAFKA_BROKER\n value: BROKER_IP\n - name: KAFKA_INPUT_TOPIC\n value: cifar10-grpc-input\n - name: KAFKA_OUTPUT_TOPIC\n value: cifar10-grpc-output\n graph:\n name: resnet32\n type: MODEL\n endpoint:\n service_port: 8500\n name: model\n replicas: 2') # In[ ]: get_ipython().system('cat cifar10_grpc.yaml | sed s/BROKER_IP/$BROKER_CIP:9094/ | kubectl apply -f -') # Looking at the metrics dashboard for Seldon you should see throughput we are getting. For a single replica on GKE with n1-standard-4 nodes we can see around 220 requests per second being processed. # # ![grpc](tensorflow-grpc-kafka.png) # In[ ]: get_ipython().system('kubectl delete -f cifar10_grpc.yaml') # In[ ]:
get_ipython().system('pip install -r requirements.txt') get_ipython().system('helm repo add strimzi https://strimzi.io/charts/') get_ipython().system('helm install my-release strimzi/strimzi-kafka-operator') cluster_type = 'kind' if clusterType == 'kind': get_ipython().system('kubectl apply -f cluster-kind.yaml') else: get_ipython().system('kubectl apply -f cluster-cloud.yaml') if clusterType == 'kind': res = get_ipython().getoutput("kubectl get service my-cluster-kafka-external-bootstrap -n default -o=jsonpath='{.spec.ports[0].nodePort}'") port = res[0] get_ipython().run_line_magic('env', 'BROKER=172.17.0.2:$port') else: res = get_ipython().getoutput("kubectl get service my-cluster-kafka-external-bootstrap -o=jsonpath='{.status.loadBalancer.ingress[0].hostname}'") if len(res) == 1: hostname = res[0] get_ipython().run_line_magic('env', 'BROKER=$h:9094') else: res = get_ipython().getoutput("kubectl get service my-cluster-kafka-external-bootstrap -o=jsonpath='{.status.loadBalancer.ingress[0].ip}'") ip = res[0] get_ipython().run_line_magic('env', 'BROKER=$ip:9094') get_ipython().run_cell_magic('writefile', 'topics.yaml', 'apiVersion: kafka.strimzi.io/v1beta1\nkind: KafkaTopic\nmetadata:\n name: cifar10-rest-input\n labels:\n strimzi.io/cluster: "my-cluster"\nspec:\n partitions: 2\n replicas: 1\n---\napiVersion: kafka.strimzi.io/v1beta1\nkind: KafkaTopic\nmetadata:\n name: cifar10-rest-output\n labels:\n strimzi.io/cluster: "my-cluster"\nspec:\n partitions: 2\n replicas: 1\n---\napiVersion: kafka.strimzi.io/v1beta1\nkind: KafkaTopic\nmetadata:\n name: cifar10-grpc-input\n labels:\n strimzi.io/cluster: "my-cluster"\nspec:\n partitions: 2\n replicas: 1\n---\napiVersion: kafka.strimzi.io/v1beta1\nkind: KafkaTopic\nmetadata:\n name: cifar10-grpc-output\n labels:\n strimzi.io/cluster: "my-cluster"\nspec:\n partitions: 2\n replicas: 1') get_ipython().system('kubectl apply -f topics.yaml') get_ipython().system('gsutil cp gs://seldon-datasets/cifar10/requests/tensorflow/cifar10_tensorflow.json.gz cifar10_tensorflow.json.gz') get_ipython().system('gunzip cifar10_tensorflow.json.gz') get_ipython().system('gsutil cp gs://seldon-datasets/cifar10/requests/tensorflow/cifar10_tensorflow.proto cifar10_tensorflow.proto') get_ipython().system('python ../../../util/kafka/test-client.py produce $BROKER cifar10-rest-input --file cifar10_tensorflow.json') res = get_ipython().getoutput("kubectl get service my-cluster-kafka-external-bootstrap -o=jsonpath='{.spec.clusterIP}'") ip = res[0] get_ipython().run_line_magic('env', 'BROKER_CIP=$ip') get_ipython().run_cell_magic('writefile', 'cifar10_rest.yaml', 'apiVersion: machinelearning.seldon.io/v1\nkind: SeldonDeployment\nmetadata:\n name: tfserving-cifar10\nspec:\n protocol: tensorflow\n transport: rest\n serverType: kafka \n predictors:\n - componentSpecs:\n - spec:\n containers:\n - args: \n - --port=8500\n - --rest_api_port=8501\n - --model_name=resnet32\n - --model_base_path=gs://seldon-models/tfserving/cifar10/resnet32\n - --enable_batching\n image: tensorflow/serving\n name: resnet32\n ports:\n - containerPort: 8501\n name: http\n svcOrchSpec:\n env:\n - name: KAFKA_BROKER\n value: BROKER_IP\n - name: KAFKA_INPUT_TOPIC\n value: cifar10-rest-input\n - name: KAFKA_OUTPUT_TOPIC\n value: cifar10-rest-output\n graph:\n name: resnet32\n type: MODEL\n endpoint:\n service_port: 8501\n name: model\n replicas: 1') get_ipython().system('cat cifar10_rest.yaml | sed s/BROKER_IP/$BROKER_CIP:9094/ | kubectl apply -f -') get_ipython().system('kubectl delete -f cifar10_rest.yaml') get_ipython().system('python ../../../util/kafka/test-client.py produce $BROKER cifar10-grpc-input --file cifar10_tensorflow.proto --proto_name tensorflow.serving.PredictRequest') res = get_ipython().getoutput("kubectl get service my-cluster-kafka-external-bootstrap -o=jsonpath='{.spec.clusterIP}'") ip = res[0] get_ipython().run_line_magic('env', 'BROKER_CIP=$ip') get_ipython().run_cell_magic('writefile', 'cifar10_grpc.yaml', 'apiVersion: machinelearning.seldon.io/v1\nkind: SeldonDeployment\nmetadata:\n name: tfserving-cifar10\nspec:\n protocol: tensorflow\n transport: grpc\n serverType: kafka \n predictors:\n - componentSpecs:\n - spec:\n containers:\n - args: \n - --port=8500\n - --rest_api_port=8501\n - --model_name=resnet32\n - --model_base_path=gs://seldon-models/tfserving/cifar10/resnet32\n - --enable_batching \n image: tensorflow/serving\n name: resnet32\n ports:\n - containerPort: 8500\n name: http\n svcOrchSpec:\n env:\n - name: KAFKA_BROKER\n value: BROKER_IP\n - name: KAFKA_INPUT_TOPIC\n value: cifar10-grpc-input\n - name: KAFKA_OUTPUT_TOPIC\n value: cifar10-grpc-output\n graph:\n name: resnet32\n type: MODEL\n endpoint:\n service_port: 8500\n name: model\n replicas: 2') get_ipython().system('cat cifar10_grpc.yaml | sed s/BROKER_IP/$BROKER_CIP:9094/ | kubectl apply -f -') get_ipython().system('kubectl delete -f cifar10_grpc.yaml')
# Code generated by ./release.sh. DO NOT EDIT. """Package version""" __version__ = "0.9.5-dev"
"""Package version""" __version__ = '0.9.5-dev'
# Creates the file nonsilence_phones.txt which contains # all the phonemes except sil. source = open("slp_lab2_data/lexicon.txt", 'r') phones = [] # Get all the separate phonemes from lexicon.txt. for line in source: line_phones = line.split(' ')[1:] for phone in line_phones: phone = phone.strip(' ') phone = phone.strip('\n') if phone not in phones and phone!='sil': phones.append(phone) source.close() phones.sort() # Write phonemes to the file. wf = open("data/local/dict/nonsilence_phones.txt", 'w') for x in phones: wf.write(x+'\n') wf.close()
source = open('slp_lab2_data/lexicon.txt', 'r') phones = [] for line in source: line_phones = line.split(' ')[1:] for phone in line_phones: phone = phone.strip(' ') phone = phone.strip('\n') if phone not in phones and phone != 'sil': phones.append(phone) source.close() phones.sort() wf = open('data/local/dict/nonsilence_phones.txt', 'w') for x in phones: wf.write(x + '\n') wf.close()
""" A basic doubly linked list implementation @author taylor.osmun """ class LinkedList(object): """ Internal object representing a node in the linked list @author taylor.osmun """ class _Node(object): def __init__(self, _data=None, _next=None, _prev=None): self.data = _data self.next = _next self.prev = _prev """ Construct a new linked list """ def __init__(self): self._first = None self._last = None self._size = 0 """ @return True IFF the list is empty """ def empty(self): return len(self) <= 0 """ Adds the given data to the beginning of the list @param data: The data to add """ def add_first(self, data): node = LinkedList._Node(data, _next=self._first) if self._first is None: self._first = node self._last = node else: self._first.prev = node self._first = node self._size += 1 """ Adds the given data to the end of the list @param data: The data to add """ def add_last(self, data): node = LinkedList._Node(data, _prev=self._last) if self._first is None: self._first = node self._last = node else: self._last.next = node self._last = node self._size += 1 """ Removes and returns the first element in the list @return The first element in the list @raise EmptyListException: If the list is empty when removal is attempted """ def remove_first(self): if self.empty(): raise EmptyListException() ret = self._first self._first = ret.next if self._first is not None: self._first.prev = None else: self._last = None self._size -= 1 return ret.data """ Removes and returns the last element in the list @return The last element in the list @raise EmptyListException: If the list is empty when removal is attempted """ def remove_last(self): if self.empty(): raise EmptyListException() ret = self._last self._last = ret.prev if self._last is not None: self._last.next = None else: self._first = None self._size -= 1 return ret.data def __len__(self): return self._size def __iter__(self): node = self._first while node is not None: yield node.data node = node.next def __str__(self): return '[%s]'%(','.join(map(str, self))) """ Thrown when a removal is attempted and the list is empty @author taylor.osmun """ class EmptyListException(IndexError): def __init__(self): super(EmptyListException, self).__init__()
""" A basic doubly linked list implementation @author taylor.osmun """ class Linkedlist(object): """ Internal object representing a node in the linked list @author taylor.osmun """ class _Node(object): def __init__(self, _data=None, _next=None, _prev=None): self.data = _data self.next = _next self.prev = _prev '\n Construct a new linked list\n ' def __init__(self): self._first = None self._last = None self._size = 0 '\n @return True IFF the list is empty\n ' def empty(self): return len(self) <= 0 '\n Adds the given data to the beginning of the list\n @param data: The data to add\n ' def add_first(self, data): node = LinkedList._Node(data, _next=self._first) if self._first is None: self._first = node self._last = node else: self._first.prev = node self._first = node self._size += 1 '\n Adds the given data to the end of the list\n @param data: The data to add\n ' def add_last(self, data): node = LinkedList._Node(data, _prev=self._last) if self._first is None: self._first = node self._last = node else: self._last.next = node self._last = node self._size += 1 '\n Removes and returns the first element in the list\n @return The first element in the list\n @raise EmptyListException: If the list is empty when removal is attempted\n ' def remove_first(self): if self.empty(): raise empty_list_exception() ret = self._first self._first = ret.next if self._first is not None: self._first.prev = None else: self._last = None self._size -= 1 return ret.data '\n Removes and returns the last element in the list\n @return The last element in the list\n @raise EmptyListException: If the list is empty when removal is attempted\n ' def remove_last(self): if self.empty(): raise empty_list_exception() ret = self._last self._last = ret.prev if self._last is not None: self._last.next = None else: self._first = None self._size -= 1 return ret.data def __len__(self): return self._size def __iter__(self): node = self._first while node is not None: yield node.data node = node.next def __str__(self): return '[%s]' % ','.join(map(str, self)) '\nThrown when a removal is attempted and the list is empty\n@author taylor.osmun\n' class Emptylistexception(IndexError): def __init__(self): super(EmptyListException, self).__init__()
class Computer(): def __init__(self, model, memory): self.mo = model self.me = memory c = Computer('Dell', '500gb') print(c.mo,c.me)
class Computer: def __init__(self, model, memory): self.mo = model self.me = memory c = computer('Dell', '500gb') print(c.mo, c.me)
""" add 2 number """ def add(x, y): return x + y """ substract y from x """ def substract(x, y): return y - x
""" add 2 number """ def add(x, y): return x + y ' substract y from x ' def substract(x, y): return y - x
#!/usr/bin/env python files = [ "dpx_nuke_10bits_rgb.dpx", "dpx_nuke_16bits_rgba.dpx" ] for f in files: command += rw_command (OIIO_TESTSUITE_IMAGEDIR, f) # Additionally, test for regressions for endian issues with 16 bit DPX output # (related to issue #354) command += oiio_app("oiiotool") + " src/input_rgb_mattes.tif -o output_rgb_mattes.dpx >> out.txt;" command += oiio_app("idiff") + " src/input_rgb_mattes.tif output_rgb_mattes.dpx >> out.txt;" # Test reading and writing of stereo DPX (multi-image) #command += (oiio_app("oiiotool") + "--create 80x60 3 --text:x=10 Left " # + "--caption \"view angle: left\" -d uint10 -o L.dpx >> out.txt;") #command += (oiio_app("oiiotool") + "--create 80x60 3 --text:x=10 Right " # + "--caption \"view angle: right\" -d uint10 -o R.dpx >> out.txt;") command += (oiio_app("oiiotool") + "ref/L.dpx ref/R.dpx --siappend -o stereo.dpx >> out.txt;") command += info_command("stereo.dpx", safematch=True, hash=False, extraargs="--stats") command += oiio_app("idiff") + "-a stereo.dpx ref/stereo.dpx >> out.txt;" # Test read/write of 1-channel DPX -- take a color image, make it grey, # write it as 1-channel DPX, then read it again and compare to a reference. # The reference is stored as TIFF rather than DPX just because it has # fantastically better compression. command += oiiotool(OIIO_TESTSUITE_IMAGEDIR+"/dpx_nuke_16bits_rgba.dpx" " -chsum:weight=0.333,0.333,0.333 -chnames Y -ch Y -o grey.dpx") command += info_command("grey.dpx", safematch=True) command += diff_command("grey.dpx", "ref/grey.tif")
files = ['dpx_nuke_10bits_rgb.dpx', 'dpx_nuke_16bits_rgba.dpx'] for f in files: command += rw_command(OIIO_TESTSUITE_IMAGEDIR, f) command += oiio_app('oiiotool') + ' src/input_rgb_mattes.tif -o output_rgb_mattes.dpx >> out.txt;' command += oiio_app('idiff') + ' src/input_rgb_mattes.tif output_rgb_mattes.dpx >> out.txt;' command += oiio_app('oiiotool') + 'ref/L.dpx ref/R.dpx --siappend -o stereo.dpx >> out.txt;' command += info_command('stereo.dpx', safematch=True, hash=False, extraargs='--stats') command += oiio_app('idiff') + '-a stereo.dpx ref/stereo.dpx >> out.txt;' command += oiiotool(OIIO_TESTSUITE_IMAGEDIR + '/dpx_nuke_16bits_rgba.dpx -chsum:weight=0.333,0.333,0.333 -chnames Y -ch Y -o grey.dpx') command += info_command('grey.dpx', safematch=True) command += diff_command('grey.dpx', 'ref/grey.tif')
# https://leetcode.com/problems/remove-nth-node-from-end-of-list/ # Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: # @param {ListNode} head # @param {integer} n # @return {ListNode} def removeNthFromEnd(self, head, n): def removeNthFromEnd_rec(head, n): if not head: return 0 my_pos = removeNthFromEnd_rec(head.next, n) + 1 if my_pos - 1 == n: head.next = head.next.next return my_pos pre_head = ListNode(0) pre_head.next = head first_pos = removeNthFromEnd_rec(pre_head, n) return pre_head.next
class Solution: def remove_nth_from_end(self, head, n): def remove_nth_from_end_rec(head, n): if not head: return 0 my_pos = remove_nth_from_end_rec(head.next, n) + 1 if my_pos - 1 == n: head.next = head.next.next return my_pos pre_head = list_node(0) pre_head.next = head first_pos = remove_nth_from_end_rec(pre_head, n) return pre_head.next
def validate_required_kwargs_are_not_empty(args_list, kwargs): """ This function checks whether all passed keyword arguments are present and that they have truthy values. ::args:: args_list - This is a list or tuple that contains all the arguments you want to query for. The arguments are strings seperated by comma. kwargs - A dictionary of keyword arguments you where you want to ascertain that all the keys are present and they have truthy values. """ for arg in args_list: if arg not in kwargs.keys(): raise TypeError(f"{arg} must be provided.") if not kwargs.get(arg): raise TypeError(f"{arg} cannot be empty.") return kwargs
def validate_required_kwargs_are_not_empty(args_list, kwargs): """ This function checks whether all passed keyword arguments are present and that they have truthy values. ::args:: args_list - This is a list or tuple that contains all the arguments you want to query for. The arguments are strings seperated by comma. kwargs - A dictionary of keyword arguments you where you want to ascertain that all the keys are present and they have truthy values. """ for arg in args_list: if arg not in kwargs.keys(): raise type_error(f'{arg} must be provided.') if not kwargs.get(arg): raise type_error(f'{arg} cannot be empty.') return kwargs
__author__ = 'roeiherz' """ Design a method to find the frequency of occurrences of any given word in a book. What if we were running this algorithm multiplies times. """ def create_hashmap(book): hash_map = {} words = book.split(' ') for word in words: process_word = word.lower().replace(',', '').replace(".", "") if process_word in hash_map: hash_map[process_word] += 1 else: hash_map[process_word] = 1 return hash_map def word_freq_multiplies(hash_map, word=''): """ Keep dict of occurrences for each word """ if word not in hash_map: return None return hash_map[word] def word_freq_single(book, word=''): """ O(n) to go all over the book """ words = book.split(' ') tmp = 0 for wordd in words: process_word = wordd.lower().replace(',', '').replace(".", "") if process_word == word: tmp += 1 return tmp if __name__ == '__main__': book = "hello world" hash_map = create_hashmap(book) word_freq_multiplies(hash_map, word='')
__author__ = 'roeiherz' '\nDesign a method to find the frequency of occurrences of any given word in a book. \nWhat if we were running this algorithm multiplies times.\n' def create_hashmap(book): hash_map = {} words = book.split(' ') for word in words: process_word = word.lower().replace(',', '').replace('.', '') if process_word in hash_map: hash_map[process_word] += 1 else: hash_map[process_word] = 1 return hash_map def word_freq_multiplies(hash_map, word=''): """ Keep dict of occurrences for each word """ if word not in hash_map: return None return hash_map[word] def word_freq_single(book, word=''): """ O(n) to go all over the book """ words = book.split(' ') tmp = 0 for wordd in words: process_word = wordd.lower().replace(',', '').replace('.', '') if process_word == word: tmp += 1 return tmp if __name__ == '__main__': book = 'hello world' hash_map = create_hashmap(book) word_freq_multiplies(hash_map, word='')
def get_url(): return None result = get_url().text print(result)
def get_url(): return None result = get_url().text print(result)
myStr = input("Enter a String: ") count = 0 for letter in myStr: count += 1 print (count)
my_str = input('Enter a String: ') count = 0 for letter in myStr: count += 1 print(count)
a = 1 b = 2 c = 3 def foo(): a = 1 b = 2 c = 3 foo() print('TEST SUCEEDED')
a = 1 b = 2 c = 3 def foo(): a = 1 b = 2 c = 3 foo() print('TEST SUCEEDED')
train = [[1,2],[2,3],[1,1],[2,2],[3,3],[4,2],[2,5],[5,5],[4,1],[4,4]] weights = [1,1,1] def perceptron_predict(inputs, weights): activation = weights[0] for i in range(len(inputs)-1): activation += weights[i+1] * inputs[i] return 1.0 if activation >= 0.0 else 0.0 for inputs in train: print(perceptron_predict(inputs,weights))
train = [[1, 2], [2, 3], [1, 1], [2, 2], [3, 3], [4, 2], [2, 5], [5, 5], [4, 1], [4, 4]] weights = [1, 1, 1] def perceptron_predict(inputs, weights): activation = weights[0] for i in range(len(inputs) - 1): activation += weights[i + 1] * inputs[i] return 1.0 if activation >= 0.0 else 0.0 for inputs in train: print(perceptron_predict(inputs, weights))
def msg_retry(self, buf): print("retry") return buf[1:] MESSAGES = {1: msg_retry}
def msg_retry(self, buf): print('retry') return buf[1:] messages = {1: msg_retry}
print("WELCOME!\nTHIS IS A NUMBER GUESSING QUIZ ") num = 30 num_of_guesses = 1 guess = input("ARE YOU A KID?\n") while(guess != num): guess = int(input("ENTER THE NUMBER TO GUESS\n")) if guess > num: print("NOT CORRECT") print("LOWER NUMBER PLEASE!") num_of_guesses += 1 elif guess < num: print("NOT CORRECT") print("HIGHER NUMBER PLEASE!") num_of_guesses += 1 else: print("CONGRATULATION! YOU GUESSED THE NUMBER ") print("THE NUMBER IS ", num) print(num_of_guesses, "ATTEMPTS YOU USED TO ARIVE AT THE NUMBER ")
print('WELCOME!\nTHIS IS A NUMBER GUESSING QUIZ ') num = 30 num_of_guesses = 1 guess = input('ARE YOU A KID?\n') while guess != num: guess = int(input('ENTER THE NUMBER TO GUESS\n')) if guess > num: print('NOT CORRECT') print('LOWER NUMBER PLEASE!') num_of_guesses += 1 elif guess < num: print('NOT CORRECT') print('HIGHER NUMBER PLEASE!') num_of_guesses += 1 else: print('CONGRATULATION! YOU GUESSED THE NUMBER ') print('THE NUMBER IS ', num) print(num_of_guesses, 'ATTEMPTS YOU USED TO ARIVE AT THE NUMBER ')
""" A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? ![Image](https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png) Above is a 7 x 3 grid. How many possible unique paths are there? Note: m and n will be at most 100. Example 1: Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right Example 2: Input: m = 7, n = 3 Output: 28 """ class Solution: def uniquePaths(self, m: int, n: int) -> int: def select(total, down): if down > total - down: down = total - down ret = 1 for i in range(total, total - down, -1): ret *= i for i in range(1, down + 1, 1): ret = ret // i return ret total, down = m + n - 2, n - 1 return select(total, down)
""" A robot is located at the top-left corner of a m x n grid (marked 'Start' in the diagram below). The robot can only move either down or right at any point in time. The robot is trying to reach the bottom-right corner of the grid (marked 'Finish' in the diagram below). How many possible unique paths are there? ![Image](https://assets.leetcode.com/uploads/2018/10/22/robot_maze.png) Above is a 7 x 3 grid. How many possible unique paths are there? Note: m and n will be at most 100. Example 1: Input: m = 3, n = 2 Output: 3 Explanation: From the top-left corner, there are a total of 3 ways to reach the bottom-right corner: 1. Right -> Right -> Down 2. Right -> Down -> Right 3. Down -> Right -> Right Example 2: Input: m = 7, n = 3 Output: 28 """ class Solution: def unique_paths(self, m: int, n: int) -> int: def select(total, down): if down > total - down: down = total - down ret = 1 for i in range(total, total - down, -1): ret *= i for i in range(1, down + 1, 1): ret = ret // i return ret (total, down) = (m + n - 2, n - 1) return select(total, down)
MAX_FOOD_ON_BOARD = 25 # Max food on board EAT_RATIO = 0.50 # Ammount of snake length absorbed FOOD_SPAWN_RATE = 3 # Number of turns per food spawn HUNGER_THRESHOLD = 100 # Turns of inactivity before snake starvation SNAKE_STARTING_LENGTH = 3 # Snake starting size TURNS_PER_GOLD = 20 # Turns between the spawn of each gold food GOLD_VICTORY = 5 # Gold needed to win the game TURNS_PER_WALL = 5 # Turns between the span of each random wall WALL_START_TURN = 50 # The turn at which random walls will begin to spawn HEALTH_DECAY_RATE = 1 # The amount of health you lose each turn FOOD_VALUE = 30 # You gain this much health when you eat food (Advanced mode only)
max_food_on_board = 25 eat_ratio = 0.5 food_spawn_rate = 3 hunger_threshold = 100 snake_starting_length = 3 turns_per_gold = 20 gold_victory = 5 turns_per_wall = 5 wall_start_turn = 50 health_decay_rate = 1 food_value = 30
# https://codeforces.com/problemset/problem/1399/A t = int(input()) for _ in range(t): length_a = int(input()) list_a = [int(x) for x in input().split()] list_a.sort() while True: if len(list_a) == 1: print('YES') break elif abs(list_a[0] - list_a[1]) <= 1: list_a.pop(0) else: print('NO') break
t = int(input()) for _ in range(t): length_a = int(input()) list_a = [int(x) for x in input().split()] list_a.sort() while True: if len(list_a) == 1: print('YES') break elif abs(list_a[0] - list_a[1]) <= 1: list_a.pop(0) else: print('NO') break
sentence = input().split() latin = "" for word in sentence: latin += word[1:] + word[0]+"ay " print(latin,end="")
sentence = input().split() latin = '' for word in sentence: latin += word[1:] + word[0] + 'ay ' print(latin, end='')
modulename = "Help" creator = "YtnomSnrub" sd_structure = {}
modulename = 'Help' creator = 'YtnomSnrub' sd_structure = {}
class DeBracketifyMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): cleaned = request.GET.copy() for key in cleaned: if key.endswith('[]'): val = cleaned.pop(key) cleaned_key = key.replace('[]', '') cleaned.setlist(cleaned_key, val) request.GET = cleaned return self.get_response(request)
class Debracketifymiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): cleaned = request.GET.copy() for key in cleaned: if key.endswith('[]'): val = cleaned.pop(key) cleaned_key = key.replace('[]', '') cleaned.setlist(cleaned_key, val) request.GET = cleaned return self.get_response(request)
def trace_wire(wire_dirs): last_pos = [0, 0] grid_dict = {} length = 0 for direction in wire_dirs: way = direction[0] amount = int(direction[1:]) if way == 'R': for x in range(1,amount+1): grid_pos = '{}_{}'.format(last_pos[0]+x, last_pos[1]) length += 1 if grid_pos not in grid_dict: grid_dict[grid_pos] = length last_pos[0] += amount elif way == 'L': for x in range(1,amount+1): grid_pos = '{}_{}'.format(last_pos[0]-x, last_pos[1]) length += 1 if grid_pos not in grid_dict: grid_dict[grid_pos] = length last_pos[0] -= amount elif way == 'U': for y in range(1,amount+1): grid_pos = '{}_{}'.format(last_pos[0], last_pos[1]+y) length += 1 if grid_pos not in grid_dict: grid_dict[grid_pos] = length last_pos[1] += amount elif way == 'D': for y in range(1,amount+1): grid_pos = '{}_{}'.format(last_pos[0], last_pos[1]-y) length += 1 if grid_pos not in grid_dict: grid_dict[grid_pos] = length last_pos[1] -= amount return grid_dict def main(): with open('input.txt', 'r') as f: first, second = f.read().split('\n') first_grid = trace_wire(first.split(',')) second_grid = trace_wire(second.split(',')) intersection_grid = set(first_grid.keys()) & set(second_grid.keys()) # print(intersection_grid) part_1 = min([abs(int(i.split('_')[0])) + abs(int(i.split('_')[1])) for i in intersection_grid]) part_2 = min([second_grid[i] + first_grid[i] for i in intersection_grid]) print(part_1, part_2) if __name__ == '__main__': main()
def trace_wire(wire_dirs): last_pos = [0, 0] grid_dict = {} length = 0 for direction in wire_dirs: way = direction[0] amount = int(direction[1:]) if way == 'R': for x in range(1, amount + 1): grid_pos = '{}_{}'.format(last_pos[0] + x, last_pos[1]) length += 1 if grid_pos not in grid_dict: grid_dict[grid_pos] = length last_pos[0] += amount elif way == 'L': for x in range(1, amount + 1): grid_pos = '{}_{}'.format(last_pos[0] - x, last_pos[1]) length += 1 if grid_pos not in grid_dict: grid_dict[grid_pos] = length last_pos[0] -= amount elif way == 'U': for y in range(1, amount + 1): grid_pos = '{}_{}'.format(last_pos[0], last_pos[1] + y) length += 1 if grid_pos not in grid_dict: grid_dict[grid_pos] = length last_pos[1] += amount elif way == 'D': for y in range(1, amount + 1): grid_pos = '{}_{}'.format(last_pos[0], last_pos[1] - y) length += 1 if grid_pos not in grid_dict: grid_dict[grid_pos] = length last_pos[1] -= amount return grid_dict def main(): with open('input.txt', 'r') as f: (first, second) = f.read().split('\n') first_grid = trace_wire(first.split(',')) second_grid = trace_wire(second.split(',')) intersection_grid = set(first_grid.keys()) & set(second_grid.keys()) part_1 = min([abs(int(i.split('_')[0])) + abs(int(i.split('_')[1])) for i in intersection_grid]) part_2 = min([second_grid[i] + first_grid[i] for i in intersection_grid]) print(part_1, part_2) if __name__ == '__main__': main()
#Linear Seach Algorithm def linearSearch(data, number): found = False for index in range(0, len(data)): if (data[index] == number): found = True break if found: print("Element is present in the array", index) else: print("Element is not present in the array.")
def linear_search(data, number): found = False for index in range(0, len(data)): if data[index] == number: found = True break if found: print('Element is present in the array', index) else: print('Element is not present in the array.')
i = 1 # valor inicial de I j = aux = 7 # valor inicial de J while i < 10: # equanto for menor que 10: for x in range(3): # loop: mostra as linhas consecutivas print('I={} J={}' .format(i,j)) # mostra os valores j -= 1 # diminui 1 no J (7,6,5) i += 2 # altera I aux += 2 # altera a aux j = aux # novo J = aux
i = 1 j = aux = 7 while i < 10: for x in range(3): print('I={} J={}'.format(i, j)) j -= 1 i += 2 aux += 2 j = aux
IOSXE_TEST = { "host": "172.18.0.11", "username": "vrnetlab", "password": "VR-netlab9", "device_type": "cisco_xe", "test_commands": ["show run", "show version"], } NXOS_TEST = { "host": "172.18.0.12", "username": "vrnetlab", "password": "VR-netlab9", "device_type": "cisco_nxos", "test_commands": ["show run", "show version"], } IOSXR_TEST = { "host": "172.18.0.13", "username": "vrnetlab", "password": "VR-netlab9", "device_type": "cisco_iosxr", "test_commands": ["show run", "show version"], } # need to get arista_eos image in vrnetlab for testing + fix libssh2 keyboard interactive auth issue # EOS_TEST = { # "host": "172.18.0.14", # "username": "vrnetlab", # "password": "VR-netlab9", # "device_type": "arista_eos", # "test_commands": ["show run", "show version"], # } JUNOS_TEST = { "host": "172.18.0.15", "username": "vrnetlab", "password": "VR-netlab9", "device_type": "juniper_junos", "test_commands": ["show configuration", "show version"], }
iosxe_test = {'host': '172.18.0.11', 'username': 'vrnetlab', 'password': 'VR-netlab9', 'device_type': 'cisco_xe', 'test_commands': ['show run', 'show version']} nxos_test = {'host': '172.18.0.12', 'username': 'vrnetlab', 'password': 'VR-netlab9', 'device_type': 'cisco_nxos', 'test_commands': ['show run', 'show version']} iosxr_test = {'host': '172.18.0.13', 'username': 'vrnetlab', 'password': 'VR-netlab9', 'device_type': 'cisco_iosxr', 'test_commands': ['show run', 'show version']} junos_test = {'host': '172.18.0.15', 'username': 'vrnetlab', 'password': 'VR-netlab9', 'device_type': 'juniper_junos', 'test_commands': ['show configuration', 'show version']}
def rotate_left(list_f, step): for _ in range(step): list_f.append(list_f.pop(0)) list_s = list_f[:] return list_s
def rotate_left(list_f, step): for _ in range(step): list_f.append(list_f.pop(0)) list_s = list_f[:] return list_s
times = [{'writing_data': 6.627535581588745, 'ndvi_pc10': 27.36231303215027, 'loading_data': 109.62806057929993, 'ndvi_pc90': 21.421257734298706, 'ndvi_pc50': 27.33169937133789}, {'writing_data': 6.443411588668823, 'ndvi_pc10': 39.16243243217468, 'loading_data': 123.19368815422058, 'ndvi_pc90': 38.72961163520813, 'ndvi_pc50': 36.39958381652832}, {'writing_data': 6.733800649642944, 'ndvi_pc10': 32.248281955718994, 'loading_data': 56.15437984466553, 'ndvi_pc90': 31.813125610351562, 'ndvi_pc50': 35.00871157646179}, {'writing_data': 6.484926462173462, 'ndvi_pc10': 30.538794994354248, 'loading_data': 72.27108573913574, 'ndvi_pc90': 31.11927819252014, 'ndvi_pc50': 30.832648038864136}, {'writing_data': 6.359814405441284, 'ndvi_pc10': 46.55086040496826, 'loading_data': 59.67847752571106, 'ndvi_pc90': 39.096333265304565, 'ndvi_pc50': 42.16282844543457}, {'writing_data': 6.564153432846069, 'ndvi_pc10': 45.175180196762085, 'loading_data': 87.63148283958435, 'ndvi_pc90': 49.379384994506836, 'ndvi_pc50': 45.34032440185547}, {'writing_data': 6.604489326477051, 'ndvi_pc10': 32.93318557739258, 'loading_data': 78.88174366950989, 'ndvi_pc90': 31.08031392097473, 'ndvi_pc50': 29.89056134223938}, {'writing_data': 6.4211084842681885, 'ndvi_pc10': 41.337995767593384, 'loading_data': 82.0915629863739, 'ndvi_pc90': 39.3358314037323, 'ndvi_pc50': 39.409401655197144}, {'writing_data': 6.546594858169556, 'ndvi_pc10': 35.091548681259155, 'loading_data': 47.397238969802856, 'ndvi_pc90': 34.05122685432434, 'ndvi_pc50': 33.63374209403992}, {'writing_data': 6.11034631729126, 'ndvi_pc10': 43.16675114631653, 'loading_data': 63.00188064575195, 'ndvi_pc90': 40.11013221740723, 'ndvi_pc50': 40.178325176239014}, {'writing_data': 6.267251491546631, 'ndvi_pc10': 36.879666328430176, 'loading_data': 59.68582105636597, 'ndvi_pc90': 35.762709617614746, 'ndvi_pc50': 36.186012506484985}, {'writing_data': 6.086328744888306, 'ndvi_pc10': 34.747477531433105, 'loading_data': 51.13255739212036, 'ndvi_pc90': 33.50469946861267, 'ndvi_pc50': 33.493101358413696}, {'writing_data': 6.232825517654419, 'ndvi_pc10': 37.161699056625366, 'loading_data': 72.47414040565491, 'ndvi_pc90': 36.648998975753784, 'ndvi_pc50': 38.17262291908264}, {'writing_data': 6.4867870807647705, 'ndvi_pc10': 22.58499264717102, 'loading_data': 50.658077239990234, 'ndvi_pc90': 23.183380842208862, 'ndvi_pc50': 23.05723762512207}, {'writing_data': 6.315629243850708, 'ndvi_pc10': 24.482516288757324, 'loading_data': 52.54269289970398, 'ndvi_pc90': 23.933518171310425, 'ndvi_pc50': 23.647018909454346}, {'writing_data': 6.466713190078735, 'ndvi_pc10': 33.10160160064697, 'loading_data': 39.69579243659973, 'ndvi_pc90': 35.594271183013916, 'ndvi_pc50': 33.5105459690094}, {'writing_data': 6.146531581878662, 'ndvi_pc10': 41.39342451095581, 'loading_data': 82.68737983703613, 'ndvi_pc90': 40.2240526676178, 'ndvi_pc50': 42.00848603248596}, {'writing_data': 6.4085304737091064, 'ndvi_pc10': 24.061297178268433, 'loading_data': 65.79187154769897, 'ndvi_pc90': 24.270387649536133, 'ndvi_pc50': 23.630946397781372}, {'writing_data': 5.905577898025513, 'ndvi_pc10': 37.23882865905762, 'loading_data': 55.112420082092285, 'ndvi_pc90': 36.291778326034546, 'ndvi_pc50': 36.75375556945801}, {'writing_data': 6.305130481719971, 'ndvi_pc10': 35.108429193496704, 'loading_data': 56.73119306564331, 'ndvi_pc90': 35.175426959991455, 'ndvi_pc50': 35.82203245162964}, {'writing_data': 5.938111066818237, 'ndvi_pc10': 36.650582790374756, 'loading_data': 55.64810013771057, 'ndvi_pc90': 36.924052238464355, 'ndvi_pc50': 36.689247369766235}, {'writing_data': 5.939232587814331, 'ndvi_pc10': 34.53633236885071, 'loading_data': 64.5890371799469, 'ndvi_pc90': 32.73802304267883, 'ndvi_pc50': 35.01725482940674}, {'writing_data': 6.481805801391602, 'ndvi_pc10': 15.486124753952026, 'loading_data': 44.980570793151855, 'ndvi_pc90': 16.636183738708496, 'ndvi_pc50': 19.395575284957886}, {'writing_data': 6.364058494567871, 'ndvi_pc10': 34.192909955978394, 'loading_data': 41.18637776374817, 'ndvi_pc90': 33.94004559516907, 'ndvi_pc50': 32.72668814659119}, {'writing_data': 6.19329047203064, 'ndvi_pc10': 21.083044290542603, 'loading_data': 54.03144335746765, 'ndvi_pc90': 18.876606702804565, 'ndvi_pc50': 20.58382821083069}, {'writing_data': 6.390938997268677, 'ndvi_pc10': 17.885555505752563, 'loading_data': 64.85111451148987, 'ndvi_pc90': 17.912266969680786, 'ndvi_pc50': 16.847716808319092}, {'writing_data': 6.0089945793151855, 'ndvi_pc10': 37.12860655784607, 'loading_data': 80.22634196281433, 'ndvi_pc90': 36.44176435470581, 'ndvi_pc50': 37.66867637634277}, {'writing_data': 5.877416372299194, 'ndvi_pc10': 37.55026960372925, 'loading_data': 67.21783351898193, 'ndvi_pc90': 34.27371907234192, 'ndvi_pc50': 33.92675566673279}, {'writing_data': 6.228186845779419, 'ndvi_pc10': 31.5383403301239, 'loading_data': 61.13664984703064, 'ndvi_pc90': 30.51774287223816, 'ndvi_pc50': 30.585197687149048}, {'writing_data': 6.655982971191406, 'ndvi_pc10': 10.241628408432007, 'loading_data': 41.03610324859619, 'ndvi_pc90': 8.946972131729126, 'ndvi_pc50': 10.193110942840576}, {'writing_data': 6.053949356079102, 'ndvi_pc10': 34.719430446624756, 'loading_data': 69.46687150001526, 'ndvi_pc90': 31.912947416305542, 'ndvi_pc50': 34.160250186920166}, {'writing_data': 5.863107919692993, 'ndvi_pc10': 35.627281665802, 'loading_data': 58.374780893325806, 'ndvi_pc90': 35.16462683677673, 'ndvi_pc50': 35.169331073760986}, {'writing_data': 6.245217323303223, 'ndvi_pc10': 26.947230339050293, 'loading_data': 37.8329381942749, 'ndvi_pc90': 28.4262912273407, 'ndvi_pc50': 26.491452932357788}, {'writing_data': 6.1906843185424805, 'ndvi_pc10': 10.243769407272339, 'loading_data': 47.66607213020325, 'ndvi_pc90': 10.901005268096924, 'ndvi_pc50': 9.574926376342773}, {'writing_data': 6.27140212059021, 'ndvi_pc10': 9.982360601425171, 'loading_data': 52.55823802947998, 'ndvi_pc90': 9.319277286529541, 'ndvi_pc50': 9.227921962738037}, {'writing_data': 6.332434177398682, 'ndvi_pc10': 4.836212396621704, 'loading_data': 32.75589728355408, 'ndvi_pc90': 5.307963848114014, 'ndvi_pc50': 4.731549501419067}, {'writing_data': 6.2034995555877686, 'ndvi_pc10': 36.06976509094238, 'loading_data': 81.16117906570435, 'ndvi_pc90': 35.752469539642334, 'ndvi_pc50': 37.97353792190552}, {'writing_data': 6.317094087600708, 'ndvi_pc10': 6.397157907485962, 'loading_data': 32.58416557312012, 'ndvi_pc90': 7.095927000045776, 'ndvi_pc50': 6.454242944717407}, {'writing_data': 6.197620153427124, 'ndvi_pc10': 11.273391008377075, 'loading_data': 38.74477291107178, 'ndvi_pc90': 10.42611837387085, 'ndvi_pc50': 11.03548288345337}, {'writing_data': 6.481883764266968, 'ndvi_pc10': 3.8671746253967285, 'loading_data': 26.47277569770813, 'ndvi_pc90': 3.9668197631835938, 'ndvi_pc50': 3.716965675354004}, {'writing_data': 6.128786563873291, 'ndvi_pc10': 16.900771617889404, 'loading_data': 45.50841689109802, 'ndvi_pc90': 19.169956922531128, 'ndvi_pc50': 16.847289562225342}, {'writing_data': 6.797720909118652, 'ndvi_pc10': 4.179133892059326, 'loading_data': 24.04671049118042, 'ndvi_pc90': 4.420083284378052, 'ndvi_pc50': 4.485124349594116}, {'writing_data': 6.50871467590332, 'ndvi_pc10': 5.876180410385132, 'loading_data': 35.49396777153015, 'ndvi_pc90': 5.70380973815918, 'ndvi_pc50': 5.584086894989014}, {'writing_data': 6.459113836288452, 'ndvi_pc10': 4.990781784057617, 'loading_data': 42.639532804489136, 'ndvi_pc90': 4.918926239013672, 'ndvi_pc50': 4.503567218780518}]
times = [{'writing_data': 6.627535581588745, 'ndvi_pc10': 27.36231303215027, 'loading_data': 109.62806057929993, 'ndvi_pc90': 21.421257734298706, 'ndvi_pc50': 27.33169937133789}, {'writing_data': 6.443411588668823, 'ndvi_pc10': 39.16243243217468, 'loading_data': 123.19368815422058, 'ndvi_pc90': 38.72961163520813, 'ndvi_pc50': 36.39958381652832}, {'writing_data': 6.733800649642944, 'ndvi_pc10': 32.248281955718994, 'loading_data': 56.15437984466553, 'ndvi_pc90': 31.813125610351562, 'ndvi_pc50': 35.00871157646179}, {'writing_data': 6.484926462173462, 'ndvi_pc10': 30.538794994354248, 'loading_data': 72.27108573913574, 'ndvi_pc90': 31.11927819252014, 'ndvi_pc50': 30.832648038864136}, {'writing_data': 6.359814405441284, 'ndvi_pc10': 46.55086040496826, 'loading_data': 59.67847752571106, 'ndvi_pc90': 39.096333265304565, 'ndvi_pc50': 42.16282844543457}, {'writing_data': 6.564153432846069, 'ndvi_pc10': 45.175180196762085, 'loading_data': 87.63148283958435, 'ndvi_pc90': 49.379384994506836, 'ndvi_pc50': 45.34032440185547}, {'writing_data': 6.604489326477051, 'ndvi_pc10': 32.93318557739258, 'loading_data': 78.88174366950989, 'ndvi_pc90': 31.08031392097473, 'ndvi_pc50': 29.89056134223938}, {'writing_data': 6.4211084842681885, 'ndvi_pc10': 41.337995767593384, 'loading_data': 82.0915629863739, 'ndvi_pc90': 39.3358314037323, 'ndvi_pc50': 39.409401655197144}, {'writing_data': 6.546594858169556, 'ndvi_pc10': 35.091548681259155, 'loading_data': 47.397238969802856, 'ndvi_pc90': 34.05122685432434, 'ndvi_pc50': 33.63374209403992}, {'writing_data': 6.11034631729126, 'ndvi_pc10': 43.16675114631653, 'loading_data': 63.00188064575195, 'ndvi_pc90': 40.11013221740723, 'ndvi_pc50': 40.178325176239014}, {'writing_data': 6.267251491546631, 'ndvi_pc10': 36.879666328430176, 'loading_data': 59.68582105636597, 'ndvi_pc90': 35.762709617614746, 'ndvi_pc50': 36.186012506484985}, {'writing_data': 6.086328744888306, 'ndvi_pc10': 34.747477531433105, 'loading_data': 51.13255739212036, 'ndvi_pc90': 33.50469946861267, 'ndvi_pc50': 33.493101358413696}, {'writing_data': 6.232825517654419, 'ndvi_pc10': 37.161699056625366, 'loading_data': 72.47414040565491, 'ndvi_pc90': 36.648998975753784, 'ndvi_pc50': 38.17262291908264}, {'writing_data': 6.4867870807647705, 'ndvi_pc10': 22.58499264717102, 'loading_data': 50.658077239990234, 'ndvi_pc90': 23.183380842208862, 'ndvi_pc50': 23.05723762512207}, {'writing_data': 6.315629243850708, 'ndvi_pc10': 24.482516288757324, 'loading_data': 52.54269289970398, 'ndvi_pc90': 23.933518171310425, 'ndvi_pc50': 23.647018909454346}, {'writing_data': 6.466713190078735, 'ndvi_pc10': 33.10160160064697, 'loading_data': 39.69579243659973, 'ndvi_pc90': 35.594271183013916, 'ndvi_pc50': 33.5105459690094}, {'writing_data': 6.146531581878662, 'ndvi_pc10': 41.39342451095581, 'loading_data': 82.68737983703613, 'ndvi_pc90': 40.2240526676178, 'ndvi_pc50': 42.00848603248596}, {'writing_data': 6.4085304737091064, 'ndvi_pc10': 24.061297178268433, 'loading_data': 65.79187154769897, 'ndvi_pc90': 24.270387649536133, 'ndvi_pc50': 23.630946397781372}, {'writing_data': 5.905577898025513, 'ndvi_pc10': 37.23882865905762, 'loading_data': 55.112420082092285, 'ndvi_pc90': 36.291778326034546, 'ndvi_pc50': 36.75375556945801}, {'writing_data': 6.305130481719971, 'ndvi_pc10': 35.108429193496704, 'loading_data': 56.73119306564331, 'ndvi_pc90': 35.175426959991455, 'ndvi_pc50': 35.82203245162964}, {'writing_data': 5.938111066818237, 'ndvi_pc10': 36.650582790374756, 'loading_data': 55.64810013771057, 'ndvi_pc90': 36.924052238464355, 'ndvi_pc50': 36.689247369766235}, {'writing_data': 5.939232587814331, 'ndvi_pc10': 34.53633236885071, 'loading_data': 64.5890371799469, 'ndvi_pc90': 32.73802304267883, 'ndvi_pc50': 35.01725482940674}, {'writing_data': 6.481805801391602, 'ndvi_pc10': 15.486124753952026, 'loading_data': 44.980570793151855, 'ndvi_pc90': 16.636183738708496, 'ndvi_pc50': 19.395575284957886}, {'writing_data': 6.364058494567871, 'ndvi_pc10': 34.192909955978394, 'loading_data': 41.18637776374817, 'ndvi_pc90': 33.94004559516907, 'ndvi_pc50': 32.72668814659119}, {'writing_data': 6.19329047203064, 'ndvi_pc10': 21.083044290542603, 'loading_data': 54.03144335746765, 'ndvi_pc90': 18.876606702804565, 'ndvi_pc50': 20.58382821083069}, {'writing_data': 6.390938997268677, 'ndvi_pc10': 17.885555505752563, 'loading_data': 64.85111451148987, 'ndvi_pc90': 17.912266969680786, 'ndvi_pc50': 16.847716808319092}, {'writing_data': 6.0089945793151855, 'ndvi_pc10': 37.12860655784607, 'loading_data': 80.22634196281433, 'ndvi_pc90': 36.44176435470581, 'ndvi_pc50': 37.66867637634277}, {'writing_data': 5.877416372299194, 'ndvi_pc10': 37.55026960372925, 'loading_data': 67.21783351898193, 'ndvi_pc90': 34.27371907234192, 'ndvi_pc50': 33.92675566673279}, {'writing_data': 6.228186845779419, 'ndvi_pc10': 31.5383403301239, 'loading_data': 61.13664984703064, 'ndvi_pc90': 30.51774287223816, 'ndvi_pc50': 30.585197687149048}, {'writing_data': 6.655982971191406, 'ndvi_pc10': 10.241628408432007, 'loading_data': 41.03610324859619, 'ndvi_pc90': 8.946972131729126, 'ndvi_pc50': 10.193110942840576}, {'writing_data': 6.053949356079102, 'ndvi_pc10': 34.719430446624756, 'loading_data': 69.46687150001526, 'ndvi_pc90': 31.912947416305542, 'ndvi_pc50': 34.160250186920166}, {'writing_data': 5.863107919692993, 'ndvi_pc10': 35.627281665802, 'loading_data': 58.374780893325806, 'ndvi_pc90': 35.16462683677673, 'ndvi_pc50': 35.169331073760986}, {'writing_data': 6.245217323303223, 'ndvi_pc10': 26.947230339050293, 'loading_data': 37.8329381942749, 'ndvi_pc90': 28.4262912273407, 'ndvi_pc50': 26.491452932357788}, {'writing_data': 6.1906843185424805, 'ndvi_pc10': 10.243769407272339, 'loading_data': 47.66607213020325, 'ndvi_pc90': 10.901005268096924, 'ndvi_pc50': 9.574926376342773}, {'writing_data': 6.27140212059021, 'ndvi_pc10': 9.982360601425171, 'loading_data': 52.55823802947998, 'ndvi_pc90': 9.319277286529541, 'ndvi_pc50': 9.227921962738037}, {'writing_data': 6.332434177398682, 'ndvi_pc10': 4.836212396621704, 'loading_data': 32.75589728355408, 'ndvi_pc90': 5.307963848114014, 'ndvi_pc50': 4.731549501419067}, {'writing_data': 6.2034995555877686, 'ndvi_pc10': 36.06976509094238, 'loading_data': 81.16117906570435, 'ndvi_pc90': 35.752469539642334, 'ndvi_pc50': 37.97353792190552}, {'writing_data': 6.317094087600708, 'ndvi_pc10': 6.397157907485962, 'loading_data': 32.58416557312012, 'ndvi_pc90': 7.095927000045776, 'ndvi_pc50': 6.454242944717407}, {'writing_data': 6.197620153427124, 'ndvi_pc10': 11.273391008377075, 'loading_data': 38.74477291107178, 'ndvi_pc90': 10.42611837387085, 'ndvi_pc50': 11.03548288345337}, {'writing_data': 6.481883764266968, 'ndvi_pc10': 3.8671746253967285, 'loading_data': 26.47277569770813, 'ndvi_pc90': 3.9668197631835938, 'ndvi_pc50': 3.716965675354004}, {'writing_data': 6.128786563873291, 'ndvi_pc10': 16.900771617889404, 'loading_data': 45.50841689109802, 'ndvi_pc90': 19.169956922531128, 'ndvi_pc50': 16.847289562225342}, {'writing_data': 6.797720909118652, 'ndvi_pc10': 4.179133892059326, 'loading_data': 24.04671049118042, 'ndvi_pc90': 4.420083284378052, 'ndvi_pc50': 4.485124349594116}, {'writing_data': 6.50871467590332, 'ndvi_pc10': 5.876180410385132, 'loading_data': 35.49396777153015, 'ndvi_pc90': 5.70380973815918, 'ndvi_pc50': 5.584086894989014}, {'writing_data': 6.459113836288452, 'ndvi_pc10': 4.990781784057617, 'loading_data': 42.639532804489136, 'ndvi_pc90': 4.918926239013672, 'ndvi_pc50': 4.503567218780518}]
#!/usr/bin/env python3 class InitializationException(Exception): """Raise when initialization errors occur.""" class ChallengeNotFound(Exception): """Raise when challenge not found.""" class ChallengeNotCovered(Exception): """Raise when challenge not found.""" class TestNotFound(Exception): """Raise when test not found.""" class NotEmptyDirectory(Exception): """Raise when test not found.""" class IncorrectTestNameFormat(Exception): """Raise when test name doesn't match format."""
class Initializationexception(Exception): """Raise when initialization errors occur.""" class Challengenotfound(Exception): """Raise when challenge not found.""" class Challengenotcovered(Exception): """Raise when challenge not found.""" class Testnotfound(Exception): """Raise when test not found.""" class Notemptydirectory(Exception): """Raise when test not found.""" class Incorrecttestnameformat(Exception): """Raise when test name doesn't match format."""
fname = input("Enter file name: ") fh = open(fname) total = 0.0 count = 0.0 for line in fh: if line.startswith("X-DSPAM-Confidence:"): total += float(line[line.find(":") + 1:]) count += 1 lf = total/count else: continue print('Average spam confidence: ',"{0:.12f}".format(round(lf,12)))
fname = input('Enter file name: ') fh = open(fname) total = 0.0 count = 0.0 for line in fh: if line.startswith('X-DSPAM-Confidence:'): total += float(line[line.find(':') + 1:]) count += 1 lf = total / count else: continue print('Average spam confidence: ', '{0:.12f}'.format(round(lf, 12)))
def selectmenuitem(window,object): #log("{} :not implemented yet".format(sys._getframe().f_code.co_name)) object = object.split(";") if len(object) == 2: objectHandle = getobjecthandle(window,object[0])['handle'] mousemove(window,object[0],handle=objectHandle) ldtp_extend_mouse_click_here() time.sleep(1) objectHandle = getobjecthandle(window,object[1])['handle'] mousemove(window,object[1],handle=objectHandle) ldtp_extend_mouse_click_here()
def selectmenuitem(window, object): object = object.split(';') if len(object) == 2: object_handle = getobjecthandle(window, object[0])['handle'] mousemove(window, object[0], handle=objectHandle) ldtp_extend_mouse_click_here() time.sleep(1) object_handle = getobjecthandle(window, object[1])['handle'] mousemove(window, object[1], handle=objectHandle) ldtp_extend_mouse_click_here()
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None def kAltReverse(head, k) : current = head next = None prev = None count = 0 #1) reverse first k nodes of the linked list while (current != None and count < k) : next = current.next current.next = prev prev = current current = next count = count + 1; # 2) Now head pos to the kth node. # So change next of head to (k+1)th node if(head != None): head.next = current # 3) We do not want to reverse next k # nodes. So move the current # poer to skip next k nodes count = 0 while(count < k - 1 and current != None ): current = current.next count = count + 1 # 4) Recursively call for the list # starting from current.next. And make # rest of the list as next of first node if(current != None): current.next = kAltReverse(current.next, k) # 5) prev is new head of the input list return prev class Solution: # @param A : head node of linked list # @param B : integer # @return the head node in the linked list def solve(self, A, B): return kAltReverse(A,B);
def k_alt_reverse(head, k): current = head next = None prev = None count = 0 while current != None and count < k: next = current.next current.next = prev prev = current current = next count = count + 1 if head != None: head.next = current count = 0 while count < k - 1 and current != None: current = current.next count = count + 1 if current != None: current.next = k_alt_reverse(current.next, k) return prev class Solution: def solve(self, A, B): return k_alt_reverse(A, B)
_base_ = "./FlowNet512_1.5AugCosyAAEGray_AggressiveV2_Flat_Pbr_01_ape.py" OUTPUT_DIR = "output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_AggressiveV2_Flat_lmPbr_SO/cat" DATASETS = dict(TRAIN=("lm_pbr_cat_train",), TEST=("lm_real_cat_test",)) # bbnc5 # objects cat Avg(1) # ad_2 19.26 19.26 # ad_5 62.48 62.48 # ad_10 91.52 91.52 # rete_2 78.24 78.24 # rete_5 99.60 99.60 # rete_10 100.00 100.00 # re_2 79.74 79.74 # re_5 99.60 99.60 # re_10 100.00 100.00 # te_2 97.70 97.70 # te_5 100.00 100.00 # te_10 100.00 100.00 # proj_2 83.63 83.63 # proj_5 99.10 99.10 # proj_10 100.00 100.00 # re 1.45 1.45 # te 0.01 0.01
_base_ = './FlowNet512_1.5AugCosyAAEGray_AggressiveV2_Flat_Pbr_01_ape.py' output_dir = 'output/deepim/lmPbrSO/FlowNet512_1.5AugCosyAAEGray_AggressiveV2_Flat_lmPbr_SO/cat' datasets = dict(TRAIN=('lm_pbr_cat_train',), TEST=('lm_real_cat_test',))
def main(): with open('input.txt') as f: inputs = [line.split() for line in f.readlines()] pos = (0, 0) # horiz, depth for cmd, amount in inputs: amount = int(amount) match cmd: case 'forward': pos = (pos[0] + amount, pos[1]) case 'down': pos = (pos[0], pos[1] + amount) case 'up': pos = (pos[0], pos[1] - amount) case _: print(f'invalid direction: {cmd}') print(f'final coord: {pos}') print(f'answer 1: {pos[0] * pos[1]}') pos = (0, 0, 0) # horiz, depth, aim for cmd, amount in inputs: amount = int(amount) match cmd: case 'forward': pos = (pos[0] + amount, pos[1] + pos[2] * amount, pos[2]) case 'down': pos = (pos[0], pos[1], pos[2] + amount) case 'up': pos = (pos[0], pos[1], pos[2] - amount) case _: print(f'invalid direction: {cmd}') print(f'final coord: {pos}') print(f'answer 2: {pos[0] * pos[1]}') if __name__ == '__main__': main()
def main(): with open('input.txt') as f: inputs = [line.split() for line in f.readlines()] pos = (0, 0) for (cmd, amount) in inputs: amount = int(amount) match cmd: case 'forward': pos = (pos[0] + amount, pos[1]) case 'down': pos = (pos[0], pos[1] + amount) case 'up': pos = (pos[0], pos[1] - amount) case _: print(f'invalid direction: {cmd}') print(f'final coord: {pos}') print(f'answer 1: {pos[0] * pos[1]}') pos = (0, 0, 0) for (cmd, amount) in inputs: amount = int(amount) match cmd: case 'forward': pos = (pos[0] + amount, pos[1] + pos[2] * amount, pos[2]) case 'down': pos = (pos[0], pos[1], pos[2] + amount) case 'up': pos = (pos[0], pos[1], pos[2] - amount) case _: print(f'invalid direction: {cmd}') print(f'final coord: {pos}') print(f'answer 2: {pos[0] * pos[1]}') if __name__ == '__main__': main()
# Python Lists # @IdiotInside_ print ("Creating List:") colors = ['red', 'blue', 'green'] print (colors[0]) ## red print (colors[1]) ## blue print (colors[2]) ## green print (len(colors)) ## 3 print ("Append to the List") colors.append("orange") print (colors[3]) ##orange print ("Insert to the List") colors.insert(3, "yellow") print (colors[3]) ##yellow print (colors[4]) ##orange print ("Remove from the List") print (colors[1]) ## blue colors.remove("blue") ## deletes blue and shifts elements to the left print (colors[1]) ## green print ("Sorting Ascending order using sorted") nums = [98,22,45,30] numsAsc = sorted(nums) print (numsAsc[0]) ## 22 print (numsAsc[1]) ## 30 print (numsAsc[2]) ## 45 print ("Sorting Descending order using sorted") numsDesc = sorted(nums,reverse=True) print (numsDesc[0]) ## 98 print (numsDesc[1]) ## 45 print (numsDesc[2]) ## 30
print('Creating List:') colors = ['red', 'blue', 'green'] print(colors[0]) print(colors[1]) print(colors[2]) print(len(colors)) print('Append to the List') colors.append('orange') print(colors[3]) print('Insert to the List') colors.insert(3, 'yellow') print(colors[3]) print(colors[4]) print('Remove from the List') print(colors[1]) colors.remove('blue') print(colors[1]) print('Sorting Ascending order using sorted') nums = [98, 22, 45, 30] nums_asc = sorted(nums) print(numsAsc[0]) print(numsAsc[1]) print(numsAsc[2]) print('Sorting Descending order using sorted') nums_desc = sorted(nums, reverse=True) print(numsDesc[0]) print(numsDesc[1]) print(numsDesc[2])
class Solution: def find_averages(self, k, arr): result = [] window_sum = 0 window_start = 0 for window_end in range(len(arr)): window_sum += arr[window_end] if window_end >= k - 1: result.append(window_sum / k) window_sum -= arr[window_start] window_start += 1 return result def main(): solution = Solution() print(solution.find_averages(5, [1, 3, 2, 6, -1, 4, 1, 8, 2])) if __name__ == '__main__': main()
class Solution: def find_averages(self, k, arr): result = [] window_sum = 0 window_start = 0 for window_end in range(len(arr)): window_sum += arr[window_end] if window_end >= k - 1: result.append(window_sum / k) window_sum -= arr[window_start] window_start += 1 return result def main(): solution = solution() print(solution.find_averages(5, [1, 3, 2, 6, -1, 4, 1, 8, 2])) if __name__ == '__main__': main()
# calculting factorial using recursion def Fact(n): return (n * Fact(n-1) if (n > 1) else 1.0) #main num = int(input("n = ")) print(Fact(num))
def fact(n): return n * fact(n - 1) if n > 1 else 1.0 num = int(input('n = ')) print(fact(num))
# https://www.hackerrank.com/challenges/ctci-lonely-integer def lonely_integer(a): bitArray = 0b0 for ele in a: bitArray = bitArray ^ ele # print(ele, bin(bitArray)) return int(bitArray)
def lonely_integer(a): bit_array = 0 for ele in a: bit_array = bitArray ^ ele return int(bitArray)
""" MiniAuth ~~~~~~~~ Simple program and library for local user authentication. :license: This software is released under the terms of MIT license. See LICENSE file for more details. """ __version__ = '0.2.0'
""" MiniAuth ~~~~~~~~ Simple program and library for local user authentication. :license: This software is released under the terms of MIT license. See LICENSE file for more details. """ __version__ = '0.2.0'
class StatusesHelper(object): """ An helper on statuses operations """ values = { 0: ('none','Not Moderated',), 1: ('moderated','Being Moderated',), 2: ('accepted','Accepted',), 3: ('refused','Refused',), } @classmethod def encode(_class, enc_status_name): """ Encode a status string to integer """ for status_id, status_data in _class.values.iteritems(): if enc_status_name == status_data[0]: return status_id return 0 @classmethod def reverse(_class, rev_status_id): """ Reverse a status integer to string """ assert type(rev_status_id) is int if rev_status_id in _class.values: return _class.values[rev_status_id] return None @classmethod def as_tuples(_class): """ Return the list of statuses in tuples """ return [(key, value.title()) for key, value in CONTENT_LEVELS.items()]
class Statuseshelper(object): """ An helper on statuses operations """ values = {0: ('none', 'Not Moderated'), 1: ('moderated', 'Being Moderated'), 2: ('accepted', 'Accepted'), 3: ('refused', 'Refused')} @classmethod def encode(_class, enc_status_name): """ Encode a status string to integer """ for (status_id, status_data) in _class.values.iteritems(): if enc_status_name == status_data[0]: return status_id return 0 @classmethod def reverse(_class, rev_status_id): """ Reverse a status integer to string """ assert type(rev_status_id) is int if rev_status_id in _class.values: return _class.values[rev_status_id] return None @classmethod def as_tuples(_class): """ Return the list of statuses in tuples """ return [(key, value.title()) for (key, value) in CONTENT_LEVELS.items()]
andmed = [] nimekiri = open("nimekiri.txt", encoding="UTF-8") for rida in nimekiri: f = open(rida.strip() + ".txt", encoding="UTF-8") kirje = {} for attr in f: osad = attr.strip().split(": ") kirje[osad[0]] = osad[1] f.close() andmed.append(kirje) nimekiri.close() uus_failinimi = input("Sisesta uue faili nimi: ") veerud = input("Sisesta attribuutide nimed: ") uus = open(uus_failinimi, mode="w", encoding="utf-8") uus.write(veerud + "\n") for isik in andmed: atts = [] for veerg in veerud.split(","): if veerg in isik: atts.append(isik[veerg]) else: atts.append("") uus.write(",".join(atts) + "\n") uus.close()
andmed = [] nimekiri = open('nimekiri.txt', encoding='UTF-8') for rida in nimekiri: f = open(rida.strip() + '.txt', encoding='UTF-8') kirje = {} for attr in f: osad = attr.strip().split(': ') kirje[osad[0]] = osad[1] f.close() andmed.append(kirje) nimekiri.close() uus_failinimi = input('Sisesta uue faili nimi: ') veerud = input('Sisesta attribuutide nimed: ') uus = open(uus_failinimi, mode='w', encoding='utf-8') uus.write(veerud + '\n') for isik in andmed: atts = [] for veerg in veerud.split(','): if veerg in isik: atts.append(isik[veerg]) else: atts.append('') uus.write(','.join(atts) + '\n') uus.close()
# window's attributes TITLE = 'Arkanoid.py' WIDTH = 640 HEIGHT = 400 ICON = 'images/ball.png'
title = 'Arkanoid.py' width = 640 height = 400 icon = 'images/ball.png'
elemDictInv = { 100:'TrivialElement', 101:'PolyElement', 102:'NullElement', 110:'DirichletNode', 111:'DirichletNodeLag', 112:'zeroVariable', 120:'NodalForce', 121:'NodalForceLine', 130:'setMaterialParam', 131:'setDamageParam', 132:'IncrementVariables', 133:'insertDeformation', 134:'insertDeformationGeneral', 140:'posProcElem', 141:'posProcElemOld', 142:'Cell2Point', 143:'PosProcElemNew', 150:'Viscosity', 200:'FSgen', 201:'FSgenMixedStab', 203:'FSgen_newDamage', 210:'NeumannFiniteStrain', 211:'NeumannFiniteStrainSpatial', 212:'NeumannRefTraction', 300:'damageEvolution', 400:'StressHom', 410:'TotalDisp', 4410:'TotalDisp3D', 420:'minRestrictionBC2DExact', 421:'minRestrictionRVE', 422:'enforcePeriodic2D', 423:'MRmeanVolRVE', 424:'enforcePeriodic2D_inc', 425:'enforcePeriodic2D_inc_copy', 430:'canonicalProblem', 431:'computeTangent', 432:'TangentHom', 433:'computeMinDetQ', 434:'computeMinDetQNew', 440:'DecisionBifurcation', 441:'LocDomainBC', 442:'MarkLocPoint', 443:'LocPointsBC', 500:'nonlinearFibres', 501:'nonlinearFibresDamage', 502:'nonlinearFibresDamage_localised', 503:'NonLinFibresGen', 504:'NonlinearFibresQuang', 505:'nonlinearFibresDamage_viscous', 5505:'nonlinearFibresDamage_viscous3D', 506:'torsionalSpring', 507:'networkConstraintGen_pureInc', 5507:'networkConstraintGen_pureInc3D', 508:'networkConstraintLinear', 5508:'networkConstraintLinear3D', 509:'networkConstraintGen', 5509:'networkConstraintGen3D', 510:'networkConstraint', 511:'networkConstraint_noVolume', 512:'affineBoundary', 513:'networkConstraint_delta', 514:'networkConstraint_RVEnormal_new_gen', 515:'networkConstraintTheta', 516:'affineBoundaryTheta', 517:'networkConstraint_RVEnormal', 518:'networkConstraint_RVEnormal_', 519:'networkConstraint_RVEnormal_new', 520:'computeAnisotropyTensor', 521:'computeAnisotropyTensorInv', 530:'damageEvolutionFibres', 540:'initParamFibres', 5550:'posProcFibres3D', 550:'posProcFibres', 560:'canonicalProblemFibres', 561:'tangentHomFibres', 601:'zeroVariable_arcLength', 602:'computeCoeficientsCilindrical_arcLength', 603:'incrementIncrementEstimation', 604:'chooseIncrementLambda', 605:'incrementDisplacementsArcLength', 606:'enforcePeriodic2D_arcLength', 607:'incrementBoundaryMultipliersArcLength', 608:'IncrementVariables_Conditional', 609:'IncrementVariablesArcLength', 610:'arcLengthConsistent', 611:'incrementLambda', 612:'incrementLambdaArcLength', 613:'computeCoeficientsSpherical_arcLength', 614:'PosProcElem_arcLength', 615:'zeroVariable_arcLength2', 616:'zeroVariable_arcLength_generic', 617:'computeCoeficientsArcLength_generic', 700:'arcLength_simple', 701:'zeroVariable_arcLength_simple', 702:'computeCoeficientsCilindrical_arcLength_simple', 703:'computeIncrementEstimation_simple', 704:'chooseIncrementLambda_simple', 705:'incrementDisplacementsArcLength_simple', 706:'computeCoeficientsSpherical_arcLength_simple'} elemDict = dict(zip(elemDictInv.values(),elemDictInv.keys()))
elem_dict_inv = {100: 'TrivialElement', 101: 'PolyElement', 102: 'NullElement', 110: 'DirichletNode', 111: 'DirichletNodeLag', 112: 'zeroVariable', 120: 'NodalForce', 121: 'NodalForceLine', 130: 'setMaterialParam', 131: 'setDamageParam', 132: 'IncrementVariables', 133: 'insertDeformation', 134: 'insertDeformationGeneral', 140: 'posProcElem', 141: 'posProcElemOld', 142: 'Cell2Point', 143: 'PosProcElemNew', 150: 'Viscosity', 200: 'FSgen', 201: 'FSgenMixedStab', 203: 'FSgen_newDamage', 210: 'NeumannFiniteStrain', 211: 'NeumannFiniteStrainSpatial', 212: 'NeumannRefTraction', 300: 'damageEvolution', 400: 'StressHom', 410: 'TotalDisp', 4410: 'TotalDisp3D', 420: 'minRestrictionBC2DExact', 421: 'minRestrictionRVE', 422: 'enforcePeriodic2D', 423: 'MRmeanVolRVE', 424: 'enforcePeriodic2D_inc', 425: 'enforcePeriodic2D_inc_copy', 430: 'canonicalProblem', 431: 'computeTangent', 432: 'TangentHom', 433: 'computeMinDetQ', 434: 'computeMinDetQNew', 440: 'DecisionBifurcation', 441: 'LocDomainBC', 442: 'MarkLocPoint', 443: 'LocPointsBC', 500: 'nonlinearFibres', 501: 'nonlinearFibresDamage', 502: 'nonlinearFibresDamage_localised', 503: 'NonLinFibresGen', 504: 'NonlinearFibresQuang', 505: 'nonlinearFibresDamage_viscous', 5505: 'nonlinearFibresDamage_viscous3D', 506: 'torsionalSpring', 507: 'networkConstraintGen_pureInc', 5507: 'networkConstraintGen_pureInc3D', 508: 'networkConstraintLinear', 5508: 'networkConstraintLinear3D', 509: 'networkConstraintGen', 5509: 'networkConstraintGen3D', 510: 'networkConstraint', 511: 'networkConstraint_noVolume', 512: 'affineBoundary', 513: 'networkConstraint_delta', 514: 'networkConstraint_RVEnormal_new_gen', 515: 'networkConstraintTheta', 516: 'affineBoundaryTheta', 517: 'networkConstraint_RVEnormal', 518: 'networkConstraint_RVEnormal_', 519: 'networkConstraint_RVEnormal_new', 520: 'computeAnisotropyTensor', 521: 'computeAnisotropyTensorInv', 530: 'damageEvolutionFibres', 540: 'initParamFibres', 5550: 'posProcFibres3D', 550: 'posProcFibres', 560: 'canonicalProblemFibres', 561: 'tangentHomFibres', 601: 'zeroVariable_arcLength', 602: 'computeCoeficientsCilindrical_arcLength', 603: 'incrementIncrementEstimation', 604: 'chooseIncrementLambda', 605: 'incrementDisplacementsArcLength', 606: 'enforcePeriodic2D_arcLength', 607: 'incrementBoundaryMultipliersArcLength', 608: 'IncrementVariables_Conditional', 609: 'IncrementVariablesArcLength', 610: 'arcLengthConsistent', 611: 'incrementLambda', 612: 'incrementLambdaArcLength', 613: 'computeCoeficientsSpherical_arcLength', 614: 'PosProcElem_arcLength', 615: 'zeroVariable_arcLength2', 616: 'zeroVariable_arcLength_generic', 617: 'computeCoeficientsArcLength_generic', 700: 'arcLength_simple', 701: 'zeroVariable_arcLength_simple', 702: 'computeCoeficientsCilindrical_arcLength_simple', 703: 'computeIncrementEstimation_simple', 704: 'chooseIncrementLambda_simple', 705: 'incrementDisplacementsArcLength_simple', 706: 'computeCoeficientsSpherical_arcLength_simple'} elem_dict = dict(zip(elemDictInv.values(), elemDictInv.keys()))
""" Problem: Find the number of 1s in the binary representation of a number. For example: num_ones(2) = 1 --> since "10" is the binary representation of the number "2". num_ones(5) = 2 --> since "101" is the binary representation of the number "5" etc. """ # num = 2 num = 5 # num = 11 print(bin(num)) # Approach 1 (using Python's "bin" function): one_sum = 0 bin_rep = bin(num)[2:] for i in bin_rep: one_sum += int(i) print(one_sum) # Approach to whithout "bin" function # Use &: and, and >>: shift operators one_sum = 0 while num: one_sum += num & 1 num >>= 1 print(one_sum)
""" Problem: Find the number of 1s in the binary representation of a number. For example: num_ones(2) = 1 --> since "10" is the binary representation of the number "2". num_ones(5) = 2 --> since "101" is the binary representation of the number "5" etc. """ num = 5 print(bin(num)) one_sum = 0 bin_rep = bin(num)[2:] for i in bin_rep: one_sum += int(i) print(one_sum) one_sum = 0 while num: one_sum += num & 1 num >>= 1 print(one_sum)
"""Handler class. All handlers must inherit from it.""" class Handler: def __init__(self, alert: str): self.broker = None self.alert = alert def alert_on(self): """Will be run when alert pops up.""" pass def alert_off(self): """Will be run when alert disappears.""" pass def alert_ongoing(self): """Will be run every second when the alert is up.""" pass
"""Handler class. All handlers must inherit from it.""" class Handler: def __init__(self, alert: str): self.broker = None self.alert = alert def alert_on(self): """Will be run when alert pops up.""" pass def alert_off(self): """Will be run when alert disappears.""" pass def alert_ongoing(self): """Will be run every second when the alert is up.""" pass
tupla = ('python', 'estudar', 'linguagem', 'curso', 'viajar', 'cinema', 'pipoca', 'futuro', 'programador', 'mercado') for c in tupla: print(f'\nNa palavra {c} temos as vogais:', end=' ') for vogais in c: if vogais.lower() in 'aeiou': print(vogais, end=' ')
tupla = ('python', 'estudar', 'linguagem', 'curso', 'viajar', 'cinema', 'pipoca', 'futuro', 'programador', 'mercado') for c in tupla: print(f'\nNa palavra {c} temos as vogais:', end=' ') for vogais in c: if vogais.lower() in 'aeiou': print(vogais, end=' ')
# Funcion de evaluacion de calidad de codigo. Devuelve un entero con un numero que representa la calidad. Cuanto mas cercano a 0 esten los valores, mayor sera la calidad. def evaluateCode(listOfRefactors): # Good code -> Close to 0 # Bad code -> Far from 0 codeQuality = 0 for refactor in listOfRefactors: codeQuality = refactor['nPriority'] + codeQuality return codeQuality
def evaluate_code(listOfRefactors): code_quality = 0 for refactor in listOfRefactors: code_quality = refactor['nPriority'] + codeQuality return codeQuality
DIRECTIONS = { "U": (0, 1), "D": (0, -1), "L": (-1, 0), "R": (1, 0) } def wire_to_point_set(wire): s = set() d = dict() x, y, steps = 0, 0, 0 for w in wire: dx, dy = DIRECTIONS[w[0]] dist = int(w[1:]) for _ in range(dist): x += dx y += dy s.add((x, y)) steps += 1 if (x, y) not in d: d[(x, y)] = steps return s, d if __name__ == "__main__": with open('3.txt') as f: wires = [line.strip().split(',') for line in f.readlines()] w1, w2 = wires s1, d1 = wire_to_point_set(w1) s2, d2 = wire_to_point_set(w2) intersections = s1 & s2 p1_intersections = [(abs(x) + abs(y), (x, y)) for (x, y) in intersections] p1_intersections.sort() print("Part 1: {}".format(p1_intersections[0][0])) p2_intersections = [(d1[p] + d2[p], p) for p in intersections] p2_intersections.sort() print("Part 2: {}".format(p2_intersections[0][0]))
directions = {'U': (0, 1), 'D': (0, -1), 'L': (-1, 0), 'R': (1, 0)} def wire_to_point_set(wire): s = set() d = dict() (x, y, steps) = (0, 0, 0) for w in wire: (dx, dy) = DIRECTIONS[w[0]] dist = int(w[1:]) for _ in range(dist): x += dx y += dy s.add((x, y)) steps += 1 if (x, y) not in d: d[x, y] = steps return (s, d) if __name__ == '__main__': with open('3.txt') as f: wires = [line.strip().split(',') for line in f.readlines()] (w1, w2) = wires (s1, d1) = wire_to_point_set(w1) (s2, d2) = wire_to_point_set(w2) intersections = s1 & s2 p1_intersections = [(abs(x) + abs(y), (x, y)) for (x, y) in intersections] p1_intersections.sort() print('Part 1: {}'.format(p1_intersections[0][0])) p2_intersections = [(d1[p] + d2[p], p) for p in intersections] p2_intersections.sort() print('Part 2: {}'.format(p2_intersections[0][0]))
def main(): print("Welcome To play Ground") # Invocation if __name__ == "__main__": main() myInt = 5 myFloat = 13.2 myString = "Hello" myBool = True myList = [0, 1, "Two", 3.4, 78, 89, 45, 67] myTuple = (0, 1, 2) myDict = {"one": 1, "Two": 2} # Random print Statements print(myDict) print(myTuple) print(myInt) print(myList) print(myFloat) print(myString) # Slicing in list print(myList) print(myList[2:5]) print(myList[::-1]) print(myList[:5]) print(myList[5]) # Dicts Accessing via keys print(myDict["Two"]) # Error : Variables of Different Types can't be Combined print("String" + str(123)) # Global vs Local Variables def some(): myString = "inside function" print(myString) def addition(arg1, arg2): # for default args we can use like => function(arg1, arg2=x) : result = 1 for i in range(arg2): result = result * arg1 return result def multiArg(*args): # we can have multiple args with multi, but it should always atLast result = 0 for x in args: result = result + x return result def conditionals(): x, y = 10, 100 result = "x is greater" if x > y else "y is greater" value = "three" match value: case "one": result = 1 case "two": result = 2 case "three" | "four": result = (3, 4) case _: result = -1 print(result) print("---------") x = 0 while x < 5: print(x) x = x + 1 print("---------") days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"] for day in days: print(day) print("---------") for x in range(5, 10): # if x == 7: # break if x % 2 == 0: continue print(x) print("---------") for i, d in enumerate(days): print(i, d) print("---------") some() print("============") print(myString) print("============") print(some()) print("============") print(addition(2, 10)) print("============") print(multiArg(2, 3, 4, 5, 6, 4)) print("============") conditionals() print("============")
def main(): print('Welcome To play Ground') if __name__ == '__main__': main() my_int = 5 my_float = 13.2 my_string = 'Hello' my_bool = True my_list = [0, 1, 'Two', 3.4, 78, 89, 45, 67] my_tuple = (0, 1, 2) my_dict = {'one': 1, 'Two': 2} print(myDict) print(myTuple) print(myInt) print(myList) print(myFloat) print(myString) print(myList) print(myList[2:5]) print(myList[::-1]) print(myList[:5]) print(myList[5]) print(myDict['Two']) print('String' + str(123)) def some(): my_string = 'inside function' print(myString) def addition(arg1, arg2): result = 1 for i in range(arg2): result = result * arg1 return result def multi_arg(*args): result = 0 for x in args: result = result + x return result def conditionals(): (x, y) = (10, 100) result = 'x is greater' if x > y else 'y is greater' value = 'three' match value: case 'one': result = 1 case 'two': result = 2 case 'three' | 'four': result = (3, 4) case _: result = -1 print(result) print('---------') x = 0 while x < 5: print(x) x = x + 1 print('---------') days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'] for day in days: print(day) print('---------') for x in range(5, 10): if x % 2 == 0: continue print(x) print('---------') for (i, d) in enumerate(days): print(i, d) print('---------') some() print('============') print(myString) print('============') print(some()) print('============') print(addition(2, 10)) print('============') print(multi_arg(2, 3, 4, 5, 6, 4)) print('============') conditionals() print('============')
expected_output = { "version": 3, "interfaces": { "GigabitEthernet1/0/9": { "interface": "GigabitEthernet1/0/9", "max_start": 3, "pae": "supplicant", "credentials": "switch4", "supplicant": {"eap": {"profile": "EAP-METH"}}, "timeout": {"held_period": 60, "start_period": 30, "auth_period": 30}, } }, "system_auth_control": True, }
expected_output = {'version': 3, 'interfaces': {'GigabitEthernet1/0/9': {'interface': 'GigabitEthernet1/0/9', 'max_start': 3, 'pae': 'supplicant', 'credentials': 'switch4', 'supplicant': {'eap': {'profile': 'EAP-METH'}}, 'timeout': {'held_period': 60, 'start_period': 30, 'auth_period': 30}}}, 'system_auth_control': True}
def isintersect(a,b): for i in a: for j in b: if i==j: return True return False class RopChain(object): def __init__(self): self.chains = [] self.dump_str = None self.payload = b"" self.base_addr = 0 self.next_call = None self.is_noreturn = False def merge_ropchain(self, ropchain): assert not self.is_noreturn, "can't merge ropchain, this chain is no-return" assert isinstance(ropchain, RopChain), "not RopChain instance" if self.next_call: self.append(self.next_call) for chain in ropchain.chains: self.append(chain) self.next_call = ropchain.next_call def __add__(self, ropchain): self.merge_ropchain(ropchain) return self def set_next_call(self, addr, type_val=0, comment=""): chain = Chain() chain.set_chain_values([ChainItem(addr, type_val, comment)]) self.next_call = chain def set_base_addr(self, addr): self.base_addr = addr def insert(self, idx, chain): self.chains.insert(idx, chain) def append(self, chain): self.chains.append(chain) def insert_chain(self, chain): intersect = False if isintersect(chain.written_regs, set(self.get_solved_regs())): intersect = True if intersect and len(self.chains) > 0: for i in range(len(self.chains)-1, -1, -1): solved_before = set(self.get_solved_regs(0,i+1)) written_before = set(self.get_written_regs(0, i+1)) if isintersect(chain.solved_regs, self.chains[i].written_regs) and not isintersect(solved_before, chain.written_regs): self.insert(i+1, chain) break if i == 0: regs_used_after = set(self.get_written_regs()) depends_regs_after = set(self.get_depends_regs()) if not isintersect(chain.solved_regs, regs_used_after) and not isintersect(chain.written_regs, depends_regs_after): self.insert(0, chain) else: return False else: self.append(chain) return True def get_solved_regs(self, start_chain=None, end_chain=None): regs_solved = set() chains = self.chains[start_chain:end_chain] for chain in chains: regs_solved.update(chain.solved_regs) return regs_solved def get_written_regs(self, start_chain=None, end_chain=None): regs_written = set() chains = self.chains[start_chain:end_chain] for chain in chains: regs_written.update(chain.written_regs) return regs_written def get_depends_regs(self, start_chain=None, end_chain=None): regs_depends = set() chains = self.chains[start_chain:end_chain] for chain in chains: regs_depends.update(chain.depends_regs) return regs_depends def get_chains(self): chains = [] for chain in self.chains: chains.extend(chain.get_chains()) return chains def get_comment(self): comments = [] for chain in self.chains: comments.extend(chain.comment) return comments def dump(self): next_sp = 0 for chain in self.chains: next_sp = chain.dump(next_sp, self.base_addr) if self.next_call: self.next_call.dump(next_sp, self.base_addr) print("") def payload_str(self): payload = b"" for chain in self.chains: payload += chain.payload_str(self.base_addr) if self.next_call: payload += self.next_call.payload_str(self.base_addr) return payload CHAINITEM_TYPE_VALUE = 0 CHAINITEM_TYPE_ADDR = 1 class ChainItem(object): def __init__(self, value=0, idx_chain=-1, comment="", type_val=0): self.value = value self.type_val = type_val self.comment = comment self.idx_chain = idx_chain def parseFromModel(chain_value_model, comment="", type_val=0): chain_item = chain_value_model[0] alias = chain_item.getVariable().getAlias() idxchain = int(alias.replace("STACK", "")) + 1 chain_value = chain_item.getValue() return ChainItem(chain_value, idxchain, comment, type_val) def getValue(self, base_addr=0): if base_addr and self.type_val == 1: # check if value is address return self.value + base_addr return self.value class Chain(object): def __init__(self): self.written_regs = set() self.solved_regs = set() self.depends_regs = set() self.gadget = None self.chain_values = [] def set_chain_values(self, chain_values): self.chain_values = chain_values def set_solved(self, gadget, values, regs=set(), written_regs=set(), depends_regs=set()): self.solved_regs.update(regs) self.written_regs.update(gadget.written_regs) self.written_regs.update(written_regs) self.depends_regs.update(depends_regs) self.gadget = gadget depends_chain_values = [] chain_values = [ChainItem(0)]*(gadget.diff_sp//8 + 1) chain_values[0] = ChainItem(gadget.addr, 0, str(gadget), CHAINITEM_TYPE_ADDR) for chain_item in values: if isinstance(chain_item, RopChain): self.written_regs.update(chain_item.get_written_regs()) self.depends_regs.update(chain_item.get_depends_regs()) depends_chain_values += chain_item.get_chains() continue if chain_item: chain_values[chain_item.idx_chain] = chain_item self.chain_values += depends_chain_values + chain_values if gadget.end_gadget: self.written_regs.update(gadget.end_gadget.written_regs) def get_chains(self): return self.chain_values def get_written_regs(self): return self.written_regs def get_solved_regs(self): return self.solved_regs def dump(self, sp, base_addr=0): chains = self.get_chains() dump_str = "" for i in range(len(chains)): chain = chains[i] com = "" if chain.comment: com = " # {}".format(chain.comment) dump_str += "$RSP+0x{:04x} : 0x{:016x}{}\n".format(sp, chain.getValue(base_addr), com) sp += 8 print(dump_str, end="") return sp def payload_str(self, base_addr=0): chains = self.get_chains() payload = b"" for i in range(len(chains)): chain = chains[i] payload += chain.getValue(base_addr).to_bytes(8, 'little') return payload def __repr__(self): return "written_regs : {}\nsolved_regs: {}\n".format(self.written_regs, self.solved_regs) def __str__(self): return "written_regs : {}\nsolved_regs: {}\n".format(self.written_regs, self.solved_regs)
def isintersect(a, b): for i in a: for j in b: if i == j: return True return False class Ropchain(object): def __init__(self): self.chains = [] self.dump_str = None self.payload = b'' self.base_addr = 0 self.next_call = None self.is_noreturn = False def merge_ropchain(self, ropchain): assert not self.is_noreturn, "can't merge ropchain, this chain is no-return" assert isinstance(ropchain, RopChain), 'not RopChain instance' if self.next_call: self.append(self.next_call) for chain in ropchain.chains: self.append(chain) self.next_call = ropchain.next_call def __add__(self, ropchain): self.merge_ropchain(ropchain) return self def set_next_call(self, addr, type_val=0, comment=''): chain = chain() chain.set_chain_values([chain_item(addr, type_val, comment)]) self.next_call = chain def set_base_addr(self, addr): self.base_addr = addr def insert(self, idx, chain): self.chains.insert(idx, chain) def append(self, chain): self.chains.append(chain) def insert_chain(self, chain): intersect = False if isintersect(chain.written_regs, set(self.get_solved_regs())): intersect = True if intersect and len(self.chains) > 0: for i in range(len(self.chains) - 1, -1, -1): solved_before = set(self.get_solved_regs(0, i + 1)) written_before = set(self.get_written_regs(0, i + 1)) if isintersect(chain.solved_regs, self.chains[i].written_regs) and (not isintersect(solved_before, chain.written_regs)): self.insert(i + 1, chain) break if i == 0: regs_used_after = set(self.get_written_regs()) depends_regs_after = set(self.get_depends_regs()) if not isintersect(chain.solved_regs, regs_used_after) and (not isintersect(chain.written_regs, depends_regs_after)): self.insert(0, chain) else: return False else: self.append(chain) return True def get_solved_regs(self, start_chain=None, end_chain=None): regs_solved = set() chains = self.chains[start_chain:end_chain] for chain in chains: regs_solved.update(chain.solved_regs) return regs_solved def get_written_regs(self, start_chain=None, end_chain=None): regs_written = set() chains = self.chains[start_chain:end_chain] for chain in chains: regs_written.update(chain.written_regs) return regs_written def get_depends_regs(self, start_chain=None, end_chain=None): regs_depends = set() chains = self.chains[start_chain:end_chain] for chain in chains: regs_depends.update(chain.depends_regs) return regs_depends def get_chains(self): chains = [] for chain in self.chains: chains.extend(chain.get_chains()) return chains def get_comment(self): comments = [] for chain in self.chains: comments.extend(chain.comment) return comments def dump(self): next_sp = 0 for chain in self.chains: next_sp = chain.dump(next_sp, self.base_addr) if self.next_call: self.next_call.dump(next_sp, self.base_addr) print('') def payload_str(self): payload = b'' for chain in self.chains: payload += chain.payload_str(self.base_addr) if self.next_call: payload += self.next_call.payload_str(self.base_addr) return payload chainitem_type_value = 0 chainitem_type_addr = 1 class Chainitem(object): def __init__(self, value=0, idx_chain=-1, comment='', type_val=0): self.value = value self.type_val = type_val self.comment = comment self.idx_chain = idx_chain def parse_from_model(chain_value_model, comment='', type_val=0): chain_item = chain_value_model[0] alias = chain_item.getVariable().getAlias() idxchain = int(alias.replace('STACK', '')) + 1 chain_value = chain_item.getValue() return chain_item(chain_value, idxchain, comment, type_val) def get_value(self, base_addr=0): if base_addr and self.type_val == 1: return self.value + base_addr return self.value class Chain(object): def __init__(self): self.written_regs = set() self.solved_regs = set() self.depends_regs = set() self.gadget = None self.chain_values = [] def set_chain_values(self, chain_values): self.chain_values = chain_values def set_solved(self, gadget, values, regs=set(), written_regs=set(), depends_regs=set()): self.solved_regs.update(regs) self.written_regs.update(gadget.written_regs) self.written_regs.update(written_regs) self.depends_regs.update(depends_regs) self.gadget = gadget depends_chain_values = [] chain_values = [chain_item(0)] * (gadget.diff_sp // 8 + 1) chain_values[0] = chain_item(gadget.addr, 0, str(gadget), CHAINITEM_TYPE_ADDR) for chain_item in values: if isinstance(chain_item, RopChain): self.written_regs.update(chain_item.get_written_regs()) self.depends_regs.update(chain_item.get_depends_regs()) depends_chain_values += chain_item.get_chains() continue if chain_item: chain_values[chain_item.idx_chain] = chain_item self.chain_values += depends_chain_values + chain_values if gadget.end_gadget: self.written_regs.update(gadget.end_gadget.written_regs) def get_chains(self): return self.chain_values def get_written_regs(self): return self.written_regs def get_solved_regs(self): return self.solved_regs def dump(self, sp, base_addr=0): chains = self.get_chains() dump_str = '' for i in range(len(chains)): chain = chains[i] com = '' if chain.comment: com = ' # {}'.format(chain.comment) dump_str += '$RSP+0x{:04x} : 0x{:016x}{}\n'.format(sp, chain.getValue(base_addr), com) sp += 8 print(dump_str, end='') return sp def payload_str(self, base_addr=0): chains = self.get_chains() payload = b'' for i in range(len(chains)): chain = chains[i] payload += chain.getValue(base_addr).to_bytes(8, 'little') return payload def __repr__(self): return 'written_regs : {}\nsolved_regs: {}\n'.format(self.written_regs, self.solved_regs) def __str__(self): return 'written_regs : {}\nsolved_regs: {}\n'.format(self.written_regs, self.solved_regs)
def triplets_with_sum(number): triplets = [] for a in range(1, number // 3): l = a + 1 r = (number - a - 1) // 2 while l <= r: b = (l + r) // 2 c = number - a - b if a * a + b * b < c * c: l = b + 1 elif a * a + b * b > c * c: r = b - 1 else: triplets.append([a, b, c]) break return triplets
def triplets_with_sum(number): triplets = [] for a in range(1, number // 3): l = a + 1 r = (number - a - 1) // 2 while l <= r: b = (l + r) // 2 c = number - a - b if a * a + b * b < c * c: l = b + 1 elif a * a + b * b > c * c: r = b - 1 else: triplets.append([a, b, c]) break return triplets
class ChangeTextState: def __init__(self): self.prev_tail = '' self.context = None _change_text_state = None def init(): global _change_text_state _change_text_state = ChangeTextState() init() def get_state() -> ChangeTextState: global _change_text_state if _change_text_state is None: _change_text_state = ChangeTextState() return _change_text_state
class Changetextstate: def __init__(self): self.prev_tail = '' self.context = None _change_text_state = None def init(): global _change_text_state _change_text_state = change_text_state() init() def get_state() -> ChangeTextState: global _change_text_state if _change_text_state is None: _change_text_state = change_text_state() return _change_text_state
""" flask-wow ~~~~~~~~~ A simple CLI Generator to create flask app. :copyright: 2020 Cove :license: BSD 3-Clause License """ __version__ = '0.2.1' # def demo(): # # if args.cmd == 'addapp': # print(f'Will create Flask app with name "{args.name}"') # dir_name = os.path.dirname(__file__) # source_dir = os.path.join(dir_name, 'templates', 'app_tmp') # dist_dir = os.path.join(os.getcwd(), args.name) # if dist_dir_check(dist_dir): # shutil.copytree(source_dir, dist_dir, # ignore=lambda src, names: [name for name in names if name == '__pycache__']) # format_dir(dist_dir, args.name, args.name) # print(f'Create app at {dist_dir} Success!') # else: # print(f'The directory {dist_dir} was not empty, Can\'t create app.')
""" flask-wow ~~~~~~~~~ A simple CLI Generator to create flask app. :copyright: 2020 Cove :license: BSD 3-Clause License """ __version__ = '0.2.1'
Size = (512, 748) ScaleFactor = 0.33 ZoomLevel = 1.0 Orientation = -90 Mirror = True NominalPixelSize = 0.002325 filename = '' ImageWindow.Center = (680, 512) ImageWindow.ViewportCenter = (1.1904, 1.5774772727272726) ImageWindow.crosshair_color = (255, 0, 255) ImageWindow.boxsize = (0.1, 0.06) ImageWindow.box_color = (128, 128, 255) ImageWindow.show_box = False ImageWindow.Scale = [[0.062775, -0.5417249999999999], [0.9044249999999999, -0.5324249999999999]] ImageWindow.show_scale = False ImageWindow.scale_color = (255, 0, 255) ImageWindow.crosshair_size = (0.05, 0.05) ImageWindow.show_crosshair = True ImageWindow.show_profile = False ImageWindow.show_FWHM = False ImageWindow.show_center = False ImageWindow.calculate_section = False ImageWindow.profile_color = (255, 0, 255) ImageWindow.FWHM_color = (0, 0, 255) ImageWindow.center_color = (0, 0, 255) ImageWindow.ROI = [[-0.299925, -0.5905499999999999], [0.3999, 0.19529999999999997]] ImageWindow.ROI_color = (255, 255, 0) ImageWindow.show_saturated_pixels = False ImageWindow.mask_bad_pixels = False ImageWindow.saturation_threshold = 233 ImageWindow.saturated_color = (255, 0, 0) ImageWindow.linearity_correction = False ImageWindow.bad_pixel_threshold = 233 ImageWindow.bad_pixel_color = (30, 30, 30) ImageWindow.show_grid = False ImageWindow.grid_type = u'xy' ImageWindow.grid_color = (98, 98, 98) ImageWindow.grid_x_spacing = 0.1 ImageWindow.grid_x_offset = 0.0 ImageWindow.grid_y_spacing = 1.0 ImageWindow.grid_y_offset = 0.0 camera.use_multicast = False camera.IP_addr = u'id14b-prosilica1.cars.aps.anl.gov'
size = (512, 748) scale_factor = 0.33 zoom_level = 1.0 orientation = -90 mirror = True nominal_pixel_size = 0.002325 filename = '' ImageWindow.Center = (680, 512) ImageWindow.ViewportCenter = (1.1904, 1.5774772727272726) ImageWindow.crosshair_color = (255, 0, 255) ImageWindow.boxsize = (0.1, 0.06) ImageWindow.box_color = (128, 128, 255) ImageWindow.show_box = False ImageWindow.Scale = [[0.062775, -0.5417249999999999], [0.9044249999999999, -0.5324249999999999]] ImageWindow.show_scale = False ImageWindow.scale_color = (255, 0, 255) ImageWindow.crosshair_size = (0.05, 0.05) ImageWindow.show_crosshair = True ImageWindow.show_profile = False ImageWindow.show_FWHM = False ImageWindow.show_center = False ImageWindow.calculate_section = False ImageWindow.profile_color = (255, 0, 255) ImageWindow.FWHM_color = (0, 0, 255) ImageWindow.center_color = (0, 0, 255) ImageWindow.ROI = [[-0.299925, -0.5905499999999999], [0.3999, 0.19529999999999997]] ImageWindow.ROI_color = (255, 255, 0) ImageWindow.show_saturated_pixels = False ImageWindow.mask_bad_pixels = False ImageWindow.saturation_threshold = 233 ImageWindow.saturated_color = (255, 0, 0) ImageWindow.linearity_correction = False ImageWindow.bad_pixel_threshold = 233 ImageWindow.bad_pixel_color = (30, 30, 30) ImageWindow.show_grid = False ImageWindow.grid_type = u'xy' ImageWindow.grid_color = (98, 98, 98) ImageWindow.grid_x_spacing = 0.1 ImageWindow.grid_x_offset = 0.0 ImageWindow.grid_y_spacing = 1.0 ImageWindow.grid_y_offset = 0.0 camera.use_multicast = False camera.IP_addr = u'id14b-prosilica1.cars.aps.anl.gov'
"""Constants defining gameplay.""" # dimensions SCREEN_WIDTH = 1280 SCREEN_HEIGHT = 1024 PLAYER_SPRITE_HEIGHT = 20 PLAYER_SPRITE_HOVER = 100 PLAYER_SPRITE_PADDING = 20 CLOSE_CALL_POSITION = (200, 200) # display TARGET_FRAMERATE = 60 GAME_TITLE = "Dodge" SCORE_POSITION = (20, SCREEN_HEIGHT - 50) # colors SCREEN_FILL_COLOR = (0, 0, 0) PLAYER_SPRITE_COLOR = (255, 255, 255) OBSTACLE_SPRITE_COLOR = (255, 0, 0) SCORE_COLOR = (128, 128, 255) CLOSE_CALL_COLOR = (255, 160, 56) # gameplay DEFAULT_LANE_COUNT = 3 DEFAULT_OBSTACLES_PER_SECOND = 0.5 OBSTACLE_MIN_SPEED = 150 OBSTACLE_MAX_SPEED = 500 CLOSE_CALL_THRESHOLD = 10 CLOSE_CALL_POINTS = 5
"""Constants defining gameplay.""" screen_width = 1280 screen_height = 1024 player_sprite_height = 20 player_sprite_hover = 100 player_sprite_padding = 20 close_call_position = (200, 200) target_framerate = 60 game_title = 'Dodge' score_position = (20, SCREEN_HEIGHT - 50) screen_fill_color = (0, 0, 0) player_sprite_color = (255, 255, 255) obstacle_sprite_color = (255, 0, 0) score_color = (128, 128, 255) close_call_color = (255, 160, 56) default_lane_count = 3 default_obstacles_per_second = 0.5 obstacle_min_speed = 150 obstacle_max_speed = 500 close_call_threshold = 10 close_call_points = 5
#! /usr/bin/env python3 def analyse_pattern(ls) : corresponds = {2:1,7:8,4:4,3:7} dct = {corresponds[len(i)]:i for i in ls if len(i) in [2, 3, 4, 7]} for i in range(10) : s = len(ls[i]) if s == 6 : #0 6 9 if sum(ls[i][j] in dct[4] for j in range(s)) == 3 : if sum(ls[i][j] in dct[1] for j in range(s)) == 2 : dct[0] = ls[i] else : dct[6] = ls[i] else : dct[9] = ls[i] elif s == 5 : #2 3 5 if sum(ls[i][j] in dct[7] for j in range(s)) == 3 : dct[3] = ls[i] elif sum(ls[i][j] in dct[4] for j in range(s)) == 3 : dct[5] = ls[i] else : dct[2] = ls[i] return dct def get_number(dct, n) : return int([i for i in range(10) if len(n) == len(dct[i]) and all(c in dct[i] for c in n)][0]) numbers = [tuple(map(lambda x:x.split(), line.split("|"))) for line in open("input")] print(sum(sum(10**(len(signals)-i-1) * get_number(analyse_pattern(patterns), signals[i]) for i in range(len(signals))) for patterns, signals in numbers))
def analyse_pattern(ls): corresponds = {2: 1, 7: 8, 4: 4, 3: 7} dct = {corresponds[len(i)]: i for i in ls if len(i) in [2, 3, 4, 7]} for i in range(10): s = len(ls[i]) if s == 6: if sum((ls[i][j] in dct[4] for j in range(s))) == 3: if sum((ls[i][j] in dct[1] for j in range(s))) == 2: dct[0] = ls[i] else: dct[6] = ls[i] else: dct[9] = ls[i] elif s == 5: if sum((ls[i][j] in dct[7] for j in range(s))) == 3: dct[3] = ls[i] elif sum((ls[i][j] in dct[4] for j in range(s))) == 3: dct[5] = ls[i] else: dct[2] = ls[i] return dct def get_number(dct, n): return int([i for i in range(10) if len(n) == len(dct[i]) and all((c in dct[i] for c in n))][0]) numbers = [tuple(map(lambda x: x.split(), line.split('|'))) for line in open('input')] print(sum((sum((10 ** (len(signals) - i - 1) * get_number(analyse_pattern(patterns), signals[i]) for i in range(len(signals)))) for (patterns, signals) in numbers)))