Best Python code snippet using lisa_python
muppy.py
Source:muppy.py  
...124        for o in res:125            res.extend(get_referents(o, level))126    res = _remove_duplicates(res)127    return res128def _get_usage(function, *args):129    """Test if more memory is used after the function has been called.130    The function will be invoked twice and only the second measurement will be131    considered. Thus, memory used in initialisation (e.g. loading modules)132    will not be included in the result. The goal is to identify memory leaks133    caused by functions which use more and more memory.134    Any arguments next to the function will be passed on to the function135    on invocation.136    Note that this function is currently experimental, because it is not137    tested thoroughly and performs poorly.138    """139    # The usage of a function is calculated by creating one summary of all140    # objects before the function is invoked and afterwards. These summaries141    # are compared and the diff is returned.142    # This function works in a 2-steps process. Before the actual function is143    # invoked an empty dummy function is measurement to identify the overhead144    # involved in the measuring process. This overhead then is subtracted from145    # the measurement performed on the passed function. The result reflects the146    # actual usage of a function call.147    # Also, a measurement is performed twice, allowing the adjustment to148    # initializing things, e.g. modules149    res = None150    def _get_summaries(function, *args):151        """Get a 2-tuple containing one summary from before, and one summary152        from after the function has been invoked.153        """154        s_before = summary.summarize(get_objects())155        function(*args)156        s_after = summary.summarize(get_objects())157        return (s_before, s_after)158    def _get_usage(function, *args):159        """Get the usage of a function call.160        This function is to be used only internally. The 'real' get_usage161        function is a wrapper around _get_usage, but the workload is done162        here.163        """164        res = []165        # init before calling166        (s_before, s_after) = _get_summaries(function, *args)167        # ignore all objects used for the measurement168        ignore = []169        if s_before != s_after:170            ignore.append(s_before)171        for row in s_before:172            # ignore refs from summary and frame (loop)173            if len(gc.get_referrers(row)) == 2:174                ignore.append(row)175            for item in row:176                # ignore refs from summary and frame (loop)177                if len(gc.get_referrers(item)) == 2:178                    ignore.append(item)179        for o in ignore:180            s_after = summary._subtract(s_after, o)181        res = summary.get_diff(s_before, s_after)182        return summary._sweep(res)183    # calibrate; twice for initialization184    def noop():185        pass186    offset = _get_usage(noop)187    offset = _get_usage(noop)188    # perform operation twice to handle objects possibly used in189    # initialisation190    tmp = _get_usage(function, *args)191    tmp = _get_usage(function, *args)192    tmp = summary.get_diff(offset, tmp)193    tmp = summary._sweep(tmp)194    if len(tmp) != 0:195        res = tmp196    return res197def _is_containerobject(o):198    """Is the passed object a container object."""199    if type(o).__flags__ & __TPFLAGS_HAVE_GC == 0:200        return False201    else:202        return True203def _remove_duplicates(objects):204    """Remove duplicate objects.205    Inspired by http://www.peterbe.com/plog/uniqifiers-benchmark...day7.py
Source:day7.py  
...42    data = get_question_input(7)43    crab_positions = [int(p) for p in next(data).split(",")]44    _get_usage = lambda i: sum(abs(p - i) for p in crab_positions)45    ideal_position = min(crab_positions)46    ideal_usage = _get_usage(ideal_position)47    for candidate_pos in range(min(crab_positions) + 1, max(crab_positions) + 1):48        candidate_usage = _get_usage(candidate_pos)49        if candidate_usage < ideal_usage:50            ideal_position = candidate_pos51            ideal_usage = candidate_usage52    print(ideal_usage)53def part_2():54    data = get_question_input(7)55    crab_positions = [int(p) for p in next(data).split(",")]56    def _get_usage(target_pos: int):57        _num_steps = lambda p: abs(p - target_pos)58        # Usage is just the sum of the arithmetic series 1..n (steps)59        # This is calculated with the formula: (n+1)*n/260        _individual_usage = lambda p: int((_num_steps(p) + 1) * _num_steps(p) / 2)61        return sum(_individual_usage(p) for p in crab_positions)62    ideal_position = min(crab_positions)63    ideal_usage = _get_usage(ideal_position)64    for candidate_pos in range(min(crab_positions) + 1, max(crab_positions) + 1):65        candidate_usage = _get_usage(candidate_pos)66        if candidate_usage < ideal_usage:67            ideal_position = candidate_pos68            ideal_usage = candidate_usage69    print(ideal_usage)...middleware.py
Source:middleware.py  
...21    """Monitors the resource usage of a request/response cycle """22    def __init__(self):23        self.usage_start = None24    def process_request(self, _request):25        self.usage_start = self._get_usage()26    def process_response(self, _request, response):27        if self.usage_start is not None:28            diff_usage = self._diff_usages(self.usage_start)29            logger.info("Request took %0.3f (%0.3fu, %0.3fs)" % diff_usage)30        return response31    @classmethod32    def _diff_usages(cls, start, end=None):33        end = end or cls._get_usage()34        return tuple(b-a for a,b in zip(start, end))35    @staticmethod36    def _get_usage():37        utime, stime, *_ = resource.getrusage(resource.RUSAGE_THREAD)...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
