import math
import heapq
n = int(input())
a = []
distance = [[]for _ in range(n)]
for _ in range(n):
    x, y = map(float, input().split())
    a.append([x,y])
for i in range(n-1):
    for j in range(i, n):
        l = round(math.sqrt((a[i][0]-a[j][0])**2+(a[i][1]-a[j][1])**2),2)
        if i==j:
            continue
        distance[i].append([l, j])
        distance[j].append([l, i])

queue = []
heapq.heappush(queue, [0,0])

mst = 0
y = [0 for _ in range(n)]
while queue:
    l, destination = heapq.heappop(queue)
    if y[destination] == 1: continue
    mst += l
    y[destination] = 1
    for l, destination in distance[destination]:
        heapq.heappush(queue, [l, destination])
print(mst)


#   Runtime: 56 ms, faster than 96.82% of Python3 online submissions for Median of Two Sorted Arrays.
#   Memory Usage: 13.4 MB, less than 47.19% of Python3 online submissions for Median of Two Sorted Arrays.

class Solution:
    def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:
        nums = nums1 + nums2
        nums.sort()
        if len(nums) % 2:
            return nums[len(nums)//2]
        else:
            return (nums[len(nums)//2 - 1] + nums[len(nums)//2]) / 2

4. Median of Two Sorted Arrays/solution.py


def factorial(n):
    """returns n!"""
    return 1 if n < 2 else n * factorial(n-1)

def main():
    print(factorial.__doc__)
    fact = factorial
    print(fact(5))

    my_list = list(map(fact, range(11)))
    print(my_list)

if __name__=="__main__":
    main()


from django.shortcuts import render
from .models import Carousel
# Create your views here.
def index(request):
    items = Carousel.objects.all()
    context = {
        'items' : items
    }
    print('Your email :', request.session.get('user_email'))
    return render(request, 'home/index.html', context)


HELP_TOPICS = {
    1: "This is a button. You can click it.",
    2: "Welcome to my application"
}

class HelpHandler:
    def __init__(self, successor_help_handler=None, help_topic=None):
        self._successor = successor_help_handler
        self._help_topic = help_topic

    def has_help(self):
        return self._help_topic is not None

    def set_handler(self, help_handler, help_topic):
        pass

    def handle_help(self):
        if self._successor:
            return self._successor.handle_help()

class Widget(HelpHandler):
    def __init__(self, parent_widget, help_topic=None):
        self._parent = parent_widget
        super().__init__(
            successor_help_handler=self._parent, help_topic=help_topic
        )

class Button(Widget):
    def handle_help(self):
        if self.has_help():
            print('==> Button help being shown')
            print(HELP_TOPICS[self._help_topic])
        else:
            super().handle_help()

class Application(HelpHandler):
    """End of chain. Note the inheritance from HelpHandler, not widget."""
    def handle_help(self):
        if self.has_help():
            print('==> Application help being shown')
            print(HELP_TOPICS[self._help_topic])
        else:
            super().handle_help()

if __name__:
    app = Application(help_topic=2)
    button = Button(app, help_topic=1)
    Widget = Widget(app)

    button.handle_help()
    Widget.handle_help()


from math import inf

def find_station_meteor(meteors):
    # Find the meteor from which we can see the biggest number of other meteors
    # If some meteors are hidden, they will share the same direction with a visible one
    # For a given direction, we need to distinguish left and right (since from the station we can see
    # up to one meteor on each side)

    max_meteors_in_sight = 0
    best_meteor = (0, 0)
    for meteor1 in meteors:
        directions = {}
        for meteor2 in meteors:
            if meteor1 == meteor2:
                continue
            if meteor2[0] == meteor1[0]:
                direction = ("L_" if meteor2[1] > meteor1[1] else "R_") + str(inf)
            else:
                direction = (meteor2[1] - meteor1[1]) / (meteor2[0] - meteor1[0])
                direction = ("L_" if meteor2[0] < meteor1[0] else "R_") + str(direction)
            directions[direction] = 1
        if len(directions) > max_meteors_in_sight:
            max_meteors_in_sight = len(directions)
            best_meteor = meteor1

    return max_meteors_in_sight, best_meteor

def solve(meteors):
    return find_station_meteor(meteors)[0]

def parse(file_name):
    with open(file_name, "r") as f:
        meteors = []
        for (j, line) in enumerate([l.strip() for l in f.readlines()]):
            for i in range(0, len(line)):
                if line[i] == "#":
                    meteors.append((i, j))
        return meteors

if __name__ == '__main__':
    print(solve(parse("data.txt")))


"""Implicit plotting module for SymPy.

Explanation
===========

The module implements a data series called ImplicitSeries which is used by
``Plot`` class to plot implicit plots for different backends. The module,
by default, implements plotting using interval arithmetic. It switches to a
fall back algorithm if the expression cannot be plotted using interval arithmetic.
It is also possible to specify to use the fall back algorithm for all plots.

Boolean combinations of expressions cannot be plotted by the fall back
algorithm.

See Also
========

sympy.plotting.plot

References
==========

.. [1] Jeffrey Allen Tupper. Reliable Two-Dimensional Graphing Methods for
Mathematical Formulae with Two Free Variables.

.. [2] Jeffrey Allen Tupper. Graphing Equations with Generalized Interval
Arithmetic. Master's thesis. University of Toronto, 1996

"""

from .plot import BaseSeries, Plot
from .experimental_lambdify import experimental_lambdify, vectorized_lambdify
from .intervalmath import interval
from sympy.core.relational import (Equality, GreaterThan, LessThan,
                Relational, StrictLessThan, StrictGreaterThan)
from sympy import Eq, Tuple, sympify, Symbol, Dummy
from sympy.external import import_module
from sympy.logic.boolalg import BooleanFunction
from sympy.polys.polyutils import _sort_gens
from sympy.utilities.decorator import doctest_depends_on
from sympy.utilities.iterables import flatten
import warnings

class ImplicitSeries(BaseSeries):
    """ Representation for Implicit plot """
    is_implicit = True

    def __init__(self, expr, var_start_end_x, var_start_end_y,
            has_equality, use_interval_math, depth, nb_of_points,
            line_color):
        super().__init__()
        self.expr = sympify(expr)
        self.var_x = sympify(var_start_end_x[0])
        self.start_x = float(var_start_end_x[1])
        self.end_x = float(var_start_end_x[2])
        self.var_y = sympify(var_start_end_y[0])
        self.start_y = float(var_start_end_y[1])
        self.end_y = float(var_start_end_y[2])
        self.get_points = self.get_raster
        self.has_equality = has_equality  # If the expression has equality, i.e.
                                         #Eq, Greaterthan, LessThan.
        self.nb_of_points = nb_of_points
        self.use_interval_math = use_interval_math
        self.depth = 4 + depth
        self.line_color = line_color

    def __str__(self):
        return ('Implicit equation: %s for '
                '%s over %s and %s over %s') % (
                    str(self.expr),
                    str(self.var_x),
                    str((self.start_x, self.end_x)),
                    str(self.var_y),
                    str((self.start_y, self.end_y)))

    def get_raster(self):
        func = experimental_lambdify((self.var_x, self.var_y), self.expr,
                                    use_interval=True)
        xinterval = interval(self.start_x, self.end_x)
        yinterval = interval(self.start_y, self.end_y)
        try:
            func(xinterval, yinterval)
        except AttributeError:
            # XXX: AttributeError("'list' object has no attribute 'is_real'")
            # That needs fixing somehow - we shouldn't be catching
            # AttributeError here.
            if self.use_interval_math:
                warnings.warn("Adaptive meshing could not be applied to the"
                            " expression. Using uniform meshing.")
            self.use_interval_math = False

        if self.use_interval_math:
            return self._get_raster_interval(func)
        else:
            return self._get_meshes_grid()

    def _get_raster_interval(self, func):
        """ Uses interval math to adaptively mesh and obtain the plot"""
        k = self.depth
        interval_list = []
        #Create initial 32 divisions
        np = import_module('numpy')
        xsample = np.linspace(self.start_x, self.end_x, 33)
        ysample = np.linspace(self.start_y, self.end_y, 33)

        #Add a small jitter so that there are no false positives for equality.
        # Ex: y==x becomes True for x interval(1, 2) and y interval(1, 2)
        #which will draw a rectangle.
        jitterx = (np.random.rand(
            len(xsample)) * 2 - 1) * (self.end_x - self.start_x) / 2**20
        jittery = (np.random.rand(
            len(ysample)) * 2 - 1) * (self.end_y - self.start_y) / 2**20
        xsample += jitterx
        ysample += jittery

        xinter = [interval(x1, x2) for x1, x2 in zip(xsample[:-1],
                           xsample[1:])]
        yinter = [interval(y1, y2) for y1, y2 in zip(ysample[:-1],
                           ysample[1:])]
        interval_list = [[x, y] for x in xinter for y in yinter]
        plot_list = []

        #recursive call refinepixels which subdivides the intervals which are
        #neither True nor False according to the expression.
        def refine_pixels(interval_list):
            """ Evaluates the intervals and subdivides the interval if the
            expression is partially satisfied."""
            temp_interval_list = []
            plot_list = []
            for intervals in interval_list:

                #Convert the array indices to x and y values
                intervalx = intervals[0]
                intervaly = intervals[1]
                func_eval = func(intervalx, intervaly)
                #The expression is valid in the interval. Change the contour
                #array values to 1.
                if func_eval[1] is False or func_eval[0] is False:
                    pass
                elif func_eval == (True, True):
                    plot_list.append([intervalx, intervaly])
                elif func_eval[1] is None or func_eval[0] is None:
                    #Subdivide
                    avgx = intervalx.mid
                    avgy = intervaly.mid
                    a = interval(intervalx.start, avgx)
                    b = interval(avgx, intervalx.end)
                    c = interval(intervaly.start, avgy)
                    d = interval(avgy, intervaly.end)
                    temp_interval_list.append([a, c])
                    temp_interval_list.append([a, d])
                    temp_interval_list.append([b, c])
                    temp_interval_list.append([b, d])
            return temp_interval_list, plot_list

        while k >= 0 and len(interval_list):
            interval_list, plot_list_temp = refine_pixels(interval_list)
            plot_list.extend(plot_list_temp)
            k = k - 1
        #Check whether the expression represents an equality
        #If it represents an equality, then none of the intervals
        #would have satisfied the expression due to floating point
        #differences. Add all the undecided values to the plot.
        if self.has_equality:
            for intervals in interval_list:
                intervalx = intervals[0]
                intervaly = intervals[1]
                func_eval = func(intervalx, intervaly)
                if func_eval[1] and func_eval[0] is not False:
                    plot_list.append([intervalx, intervaly])
        return plot_list, 'fill'

    def _get_meshes_grid(self):
        """Generates the mesh for generating a contour.

        In the case of equality, ``contour`` function of matplotlib can
        be used. In other cases, matplotlib's ``contourf`` is used.
        """
        equal = False
        if isinstance(self.expr, Equality):
            expr = self.expr.lhs - self.expr.rhs
            equal = True

        elif isinstance(self.expr, (GreaterThan, StrictGreaterThan)):
            expr = self.expr.lhs - self.expr.rhs

        elif isinstance(self.expr, (LessThan, StrictLessThan)):
            expr = self.expr.rhs - self.expr.lhs
        else:
            raise NotImplementedError("The expression is not supported for "
                                    "plotting in uniform meshed plot.")
        np = import_module('numpy')
        xarray = np.linspace(self.start_x, self.end_x, self.nb_of_points)
        yarray = np.linspace(self.start_y, self.end_y, self.nb_of_points)
        x_grid, y_grid = np.meshgrid(xarray, yarray)

        func = vectorized_lambdify((self.var_x, self.var_y), expr)
        z_grid = func(x_grid, y_grid)
        z_grid[np.ma.where(z_grid < 0)] = -1
        z_grid[np.ma.where(z_grid > 0)] = 1
        if equal:
            return xarray, yarray, z_grid, 'contour'
        else:
            return xarray, yarray, z_grid, 'contourf'

@doctest_depends_on(modules=('matplotlib',))
def plot_implicit(expr, x_var=None, y_var=None, adaptive=True, depth=0,
                  points=300, line_color="blue", show=True, **kwargs):
    """A plot function to plot implicit equations / inequalities.

    Arguments
    =========

    - ``expr`` : The equation / inequality that is to be plotted.
    - ``x_var`` (optional) : symbol to plot on x-axis or tuple giving symbol
      and range as ``(symbol, xmin, xmax)``
    - ``y_var`` (optional) : symbol to plot on y-axis or tuple giving symbol
      and range as ``(symbol, ymin, ymax)``

    If neither ``x_var`` nor ``y_var`` are given then the free symbols in the
    expression will be assigned in the order they are sorted.

    The following keyword arguments can also be used:

    - ``adaptive`` Boolean. The default value is set to True. It has to be
        set to False if you want to use a mesh grid.

    - ``depth`` integer. The depth of recursion for adaptive mesh grid.
        Default value is 0. Takes value in the range (0, 4).

    - ``points`` integer. The number of points if adaptive mesh grid is not
        used. Default value is 300.

    - ``show`` Boolean. Default value is True. If set to False, the plot will
        not be shown. See ``Plot`` for further information.

    - ``title`` string. The title for the plot.

    - ``xlabel`` string. The label for the x-axis

    - ``ylabel`` string. The label for the y-axis

    Aesthetics options:

    - ``line_color``: float or string. Specifies the color for the plot.
        See ``Plot`` to see how to set color for the plots.
        Default value is "Blue"

    plot_implicit, by default, uses interval arithmetic to plot functions. If
    the expression cannot be plotted using interval arithmetic, it defaults to
    a generating a contour using a mesh grid of fixed number of points. By
    setting adaptive to False, you can force plot_implicit to use the mesh
    grid. The mesh grid method can be effective when adaptive plotting using
    interval arithmetic, fails to plot with small line width.

    Examples
    ========

    Plot expressions:

    .. plot::
        :context: reset
        :format: doctest
        :include-source: True

        >>> from sympy import plot_implicit, symbols, Eq, And
        >>> x, y = symbols('x y')

    Without any ranges for the symbols in the expression:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p1 = plot_implicit(Eq(x**2 + y**2, 5))

    With the range for the symbols:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p2 = plot_implicit(
        ...     Eq(x**2 + y**2, 3), (x, -3, 3), (y, -3, 3))

    With depth of recursion as argument:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p3 = plot_implicit(
        ...     Eq(x**2 + y**2, 5), (x, -4, 4), (y, -4, 4), depth = 2)

    Using mesh grid and not using adaptive meshing:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p4 = plot_implicit(
        ...     Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
        ...     adaptive=False)

    Using mesh grid without using adaptive meshing with number of points
    specified:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p5 = plot_implicit(
        ...     Eq(x**2 + y**2, 5), (x, -5, 5), (y, -2, 2),
        ...     adaptive=False, points=400)

    Plotting regions:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p6 = plot_implicit(y > x**2)

    Plotting Using boolean conjunctions:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p7 = plot_implicit(And(y > x, y > -x))

    When plotting an expression with a single variable (y - 1, for example),
    specify the x or the y variable explicitly:

    .. plot::
        :context: close-figs
        :format: doctest
        :include-source: True

        >>> p8 = plot_implicit(y - 1, y_var=y)
        >>> p9 = plot_implicit(x - 1, x_var=x)
    """
    has_equality = False  # Represents whether the expression contains an Equality,
                     #GreaterThan or LessThan

    def arg_expand(bool_expr):
        """
        Recursively expands the arguments of an Boolean Function
        """
        for arg in bool_expr.args:
            if isinstance(arg, BooleanFunction):
                arg_expand(arg)
            elif isinstance(arg, Relational):
                arg_list.append(arg)

    arg_list = []
    if isinstance(expr, BooleanFunction):
        arg_expand(expr)

    #Check whether there is an equality in the expression provided.
        if any(isinstance(e, (Equality, GreaterThan, LessThan))
               for e in arg_list):
            has_equality = True

    elif not isinstance(expr, Relational):
        expr = Eq(expr, 0)
        has_equality = True
    elif isinstance(expr, (Equality, GreaterThan, LessThan)):
        has_equality = True

    xyvar = [i for i in (x_var, y_var) if i is not None]
    free_symbols = expr.free_symbols
    range_symbols = Tuple(*flatten(xyvar)).free_symbols
    undeclared = free_symbols - range_symbols
    if len(free_symbols & range_symbols) > 2:
        raise NotImplementedError("Implicit plotting is not implemented for "
                                  "more than 2 variables")

    #Create default ranges if the range is not provided.
    default_range = Tuple(-5, 5)
    def _range_tuple(s):
        if isinstance(s, Symbol):
            return Tuple(s) + default_range
        if len(s) == 3:
            return Tuple(*s)
        raise ValueError('symbol or `(symbol, min, max)` expected but got %s' % s)

    if len(xyvar) == 0:
        xyvar = list(_sort_gens(free_symbols))
    var_start_end_x = _range_tuple(xyvar[0])
    x = var_start_end_x[0]
    if len(xyvar) != 2:
        if x in undeclared or not undeclared:
            xyvar.append(Dummy('f(%s)' % x.name))
        else:
            xyvar.append(undeclared.pop())
    var_start_end_y = _range_tuple(xyvar[1])

    #Check whether the depth is greater than 4 or less than 0.
    if depth > 4:
        depth = 4
    elif depth < 0:
        depth = 0

    series_argument = ImplicitSeries(expr, var_start_end_x, var_start_end_y,
                                    has_equality, adaptive, depth,
                                    points, line_color)

    #set the x and y limits
    kwargs['xlim'] = tuple(float(x) for x in var_start_end_x[1:])
    kwargs['ylim'] = tuple(float(y) for y in var_start_end_y[1:])
    # set the x and y labels
    kwargs.setdefault('xlabel', var_start_end_x[0].name)
    kwargs.setdefault('ylabel', var_start_end_y[0].name)
    p = Plot(series_argument, **kwargs)
    if show:
        p.show()
    return p


import logging
import json
import os
import re
from urllib.parse import urlparse

from hashlib import md5

from tf_bodypix.utils.io import download_file_to, get_default_cache_dir

LOGGER = logging.getLogger(__name__)

_DOWNLOAD_URL_PREFIX = r'https://storage.googleapis.com/tfjs-models/savedmodel/bodypix/'

class BodyPixModelPaths:
    MOBILENET_FLOAT_50_STRIDE_8 = (
        _DOWNLOAD_URL_PREFIX + 'mobilenet/float/050/model-stride8.json'
    )
    MOBILENET_FLOAT_50_STRIDE_16 = (
        _DOWNLOAD_URL_PREFIX + 'mobilenet/float/050/model-stride16.json'
    )
    MOBILENET_FLOAT_75_STRIDE_8 = (
        _DOWNLOAD_URL_PREFIX + 'mobilenet/float/075/model-stride8.json'
    )
    MOBILENET_FLOAT_75_STRIDE_16 = (
        _DOWNLOAD_URL_PREFIX + 'mobilenet/float/075/model-stride16.json'
    )
    MOBILENET_FLOAT_100_STRIDE_8 = (
        _DOWNLOAD_URL_PREFIX + 'mobilenet/float/100/model-stride8.json'
    )
    MOBILENET_FLOAT_100_STRIDE_16 = (
        _DOWNLOAD_URL_PREFIX + 'mobilenet/float/100/model-stride16.json'
    )

    RESNET50_FLOAT_STRIDE_16 = (
        _DOWNLOAD_URL_PREFIX + 'resnet50/float/model-stride16.json'
    )
    RESNET50_FLOAT_STRIDE_32 = (
        _DOWNLOAD_URL_PREFIX + 'resnet50/float/model-stride32.json'
    )

    # deprecated (shouldn't have mobilenet in the name)
    MOBILENET_RESNET50_FLOAT_STRIDE_16 = (
        _DOWNLOAD_URL_PREFIX + 'resnet50/float/model-stride16.json'
    )
    MOBILENET_RESNET50_FLOAT_STRIDE_32 = (
        _DOWNLOAD_URL_PREFIX + 'resnet50/float/model-stride32.json'
    )

_TFLITE_DOWNLOAD_URL_PREFIX = r'https://www.dropbox.com/sh/d6tqb3gfrugs7ne/'

class TensorFlowLiteBodyPixModelPaths:
    MOBILENET_FLOAT_50_STRIDE_8_FLOAT16 = (
        _TFLITE_DOWNLOAD_URL_PREFIX
        + 'AADUtMGoDO6vzOfRLP0Dg7ira/mobilenet-float-multiplier-050-stride8-float16.tflite?dl=1'
    )
    MOBILENET_FLOAT_50_STRIDE_16_FLOAT16 = (
        _TFLITE_DOWNLOAD_URL_PREFIX
        + 'AAAhnozSEO07xzgL495dW3h8a/mobilenet-float-multiplier-050-stride16-float16.tflite?dl=1'
    )

    MOBILENET_FLOAT_75_STRIDE_8_FLOAT16 = (
        _TFLITE_DOWNLOAD_URL_PREFIX
        + 'AADBYGO2xj2v9Few4qBq62wZa/mobilenet-float-multiplier-075-stride8-float16.tflite?dl=1'
    )
    MOBILENET_FLOAT_75_STRIDE_16_FLOAT16 = (
        _TFLITE_DOWNLOAD_URL_PREFIX
        + 'AAAGYNAOTTWBl9ZDhALv7rEOa/mobilenet-float-multiplier-075-stride16-float16.tflite?dl=1'
    )

    MOBILENET_FLOAT_100_STRIDE_8_FLOAT16 = (
        _TFLITE_DOWNLOAD_URL_PREFIX
        + 'AADr8zOtPZz2cWlQEvKgIbdTa/mobilenet-float-multiplier-100-stride8-float16.tflite?dl=1'
    )
    MOBILENET_FLOAT_100_STRIDE_16_FLOAT16 = (
        _TFLITE_DOWNLOAD_URL_PREFIX
        + 'AAAo-hkaCqx2pN99cCvDPcosa/mobilenet-float-multiplier-100-stride16-float16.tflite?dl=1'
    )

    RESNET50_FLOAT_STRIDE_16 = (
        _TFLITE_DOWNLOAD_URL_PREFIX
        + 'AADvvgLyPXMPOeRyRY9WQ9Mva/resnet50-float-stride16-float16.tflite?dl=1'
    )
    MOBILENET_RESNET50_FLOAT_STRIDE_32 = (
        _TFLITE_DOWNLOAD_URL_PREFIX
        + 'AADGlTuMQQeL8vm6BuOwObKTa/resnet50-float-stride32-float16.tflite?dl=1'
    )

ALL_TENSORFLOW_LITE_BODYPIX_MODEL_PATHS = [
    value
    for key, value in TensorFlowLiteBodyPixModelPaths.__dict__.items()
    if key.isupper() and isinstance(value, str)
]

class DownloadError(RuntimeError):
    pass

def download_model(model_path: str) -> str:
    if os.path.exists(model_path):
        return model_path
    parsed_model_path = urlparse(model_path)
    local_name_part = re.sub(
        r'[^a-zA-Z0-9]+',
        r'-',
        os.path.splitext(parsed_model_path.path)[0]
    )
    local_name = (
        md5(model_path.encode('utf-8')).hexdigest() + '-'
        + os.path.basename(local_name_part)
    )
    LOGGER.debug('local_name: %r', local_name)
    cache_dir = get_default_cache_dir(
        cache_subdir=os.path.join('tf-bodypix', local_name)
    )
    if parsed_model_path.path.endswith('.tflite'):
        return download_file_to(
            source_url=model_path,
            local_path=os.path.join(
                cache_dir,
                os.path.basename(parsed_model_path.path)
            ),
            skip_if_exists=True
        )
    if not parsed_model_path.path.endswith('.json'):
        raise ValueError('remote model path needs to end with .json')
    model_base_path = os.path.dirname(model_path)
    local_model_json_path = download_file_to(
        source_url=model_path,
        local_path=os.path.join(cache_dir, 'model.json'),
        skip_if_exists=True
    )
    local_model_path = os.path.dirname(local_model_json_path)
    LOGGER.debug('local_model_json_path: %r', local_model_json_path)
    try:
        with open(local_model_json_path, 'r', encoding='utf-8') as model_json_fp:
            model_json = json.load(model_json_fp)
    except UnicodeDecodeError as exc:
        LOGGER.error(
            'failed to process %r due to %r',
            local_model_json_path, exc, exc_info=True
        )
        raise DownloadError(
            'failed to process %r due to %r' % (
                local_model_json_path, exc
            )
        ) from exc
    LOGGER.debug('model_json.keys: %s', model_json.keys())
    weights_manifest = model_json['weightsManifest']
    weights_manifest_paths = sorted({
        path
        for item in weights_manifest
        for path in item.get('paths', [])
    })
    LOGGER.debug('weights_manifest_paths: %s', weights_manifest_paths)
    for weights_manifest_path in weights_manifest_paths:
        local_model_json_path = download_file_to(
            source_url=model_base_path + '/' + weights_manifest_path,
            local_path=os.path.join(cache_dir, os.path.basename(weights_manifest_path)),
            skip_if_exists=True
        )
    return local_model_path


"""
Noah Hefner
Pygame Menu System
Last Edit: 1 January 2021
"""

# Imports
import pygame
import string

# Initialize pygame
pygame.init()

# Settings
menu_manager_settings = {

    "element_colorkey" : [0, 0, 0],
    "menu_background_color" : [0, 0, 0],
    "menu_fps" : 60

}

class Action:
    """
    Holds function and argument data for buttons.

    Attributes:
        function: The function to execute.
        arguments: Arguments for the function.
        keyword_arguments: Keyword arguments for the function.
    """

    def __init__ (self, function, args, kwargs):
        """
        Instantiate an Action object.

        Arguments:
            function: The function to execute.
            *args: Arguments for the function.
            **kwargs: Keyword arguments for the function.
        """

        self.function = function
        self.arguments = args
        self.keyword_arguments = kwargs

    def execute (self):
        """
        Calls the function, passing it the args and kwargs.
        """

        self.function(*self.arguments, **self.keyword_arguments)

class ButtonPicture(pygame.sprite.Sprite):
    """
    Button object for menu manager.

    Attributes:
        image (pygame.image): Image for button.
        action (function): Function to execute when button is pressed.
        rect (pygame.image.rect): Position, height, width values for image.
        action_args (*args): Any arguments required by the action.
    """

    def __init__ (self, image, pos = [0,0]):
        """
        Instantiate a button object.

        Arguments:
            image (string): Path of image file to be used for button.
            action (function): Function to execute when button is pressed.
            action_args (*args): Any arguments required by the action.
            pos (tuple): XY position for the button.
        """

        super(ButtonPicture, self).__init__()

        self.image = pygame.image.load(image)
        self.image.set_colorkey(menu_manager_settings["element_colorkey"])
        self.rect = self.image.get_rect()
        self.rect.x = pos[0]
        self.rect.y = pos[1]
        self.actions = []

    def get_dimensions (self):
        """
        Get the width and height of the ButtonPicture.

        Returns:
            list: Width and Height of the ButtonPicture. Uses width and height
                  from self.rect.
                  Format: [width, height]
        """

        dimensions = [self.rect.width, self.rect.height]
        return dimensions

    def get_pos (self):
        """
        Get the position of this picture button element.

        Returns:
            list: XY position of the picture button.
        """

        position = [self.rect.x, self.rect.y]
        return position

    def set_pos (self, pos):
        """
        Set position of the button.

        Arguments:
            list: XY position to set the button to.
                  Format: [x, y]
        """

        self.rect.x = pos[0]
        self.rect.y = pos[1]

    def add_action (self, function, *args, **kwargs):
        """
        Adds an action to the list of actions for this button.

        Arguments:
            function: The function to execute.
            *args: Arguments for the function.
            **kwargs: Keyword arguments for the function.
        """

        new_action = Action(function, args, kwargs)
        self.actions.append(new_action)

    def execute_actions (self):
        """
        Execute function linked to this button.
        """

        for action in self.actions:

            action.execute()

    def is_clicked (self, mouse_pos):
        """
        Returns true if the mouse cursor position is on this sprite.

        Arguments:
            mouse_pos (tuple): XY position of the cursor.
        """

        # Check x axis
        within_x = mouse_pos[0] >= self.rect.x and mouse_pos[0] <= self.rect.x + self.rect.width

        # Check y axis
        within_y = mouse_pos[1] >= self.rect.y and mouse_pos[1] <= self.rect.y + self.rect.height

        # True if within x and y area
        return within_x and within_y

class ButtonText (pygame.sprite.Sprite):
    """
    Text Button object for menu manager.

    Attributes:
        image (pygame.image): Pygame image for the text button.
        action (function): Function to execute when button is pressed.
        rect (pygame.image.rect): Position, height, width values for image.
        action_args (*args): Any arguments required by the action.
    """

    def __init__ (self, text, font, pos = [0,0], color = [255, 255, 255], \
                  antialias = True, background_color = None):
        """
        Instantiate a button object.

        Arguments:
            text (string): Text to make the button from.
            font (pygame.font.SysFont): Font to render the text in.
            action (function): Function to execute when button is pressed.
            action_args (*args): Any arguments required by the action.
            pos (tuple): XY position for the button.
        """

        super(ButtonText, self).__init__()

        self.text = text
        self.font = font
        self.antialias = antialias
        self.color = color
        self.background_color = background_color

        self.image = font.render(str(text), antialias, color, background_color)
        self.image.set_colorkey(menu_manager_settings["element_colorkey"])
        self.rect = self.image.get_rect()
        self.rect.x = pos[0]
        self.rect.y = pos[1]

        self.actions = []

    def get_pos (self):
        """
        Get the position of this text button element.

        Returns:
            pos (list): XY position of the text button.
        """

        position = [self.rect.x, self.rect.y]
        return position

    def get_text(self):
        """
        Get the text of the button.

        Returns:
            self.text (String): Text of the button.
        """

        return self.text

    def set_pos (self, pos):
        """
        Set position of the text.

        Arguments:
            pos (list): XY position to set the text button to.
        """

        self.rect.x = pos[0]
        self.rect.y = pos[1]

    def set_text (self, new_text):
        """
        Changes the text of the button.

        Arguments:
            new_text (String): New text of the button.
        """

        self.text = new_text
        self.image = self.font.render(str(new_text), self.antialias, self.color, self.background_color)

    def add_action (self, function, *args, **kwargs):
        """
        Adds an action to the list of actions for this button.

        Arguments:
            function: The function to execute.
            *args: Arguments for the function.
            **kwargs: Keyword arguments for the function.
        """

        new_action = Action(function, args, kwargs)
        self.actions.append(new_action)

    def execute_actions (self):
        """
        Execute function linked to this button.
        """

        for action in self.actions:

            action.execute()

    def is_clicked (self, mouse_pos):
        """
        Returns true if the mouse cursor position is on this sprite.

        Arguments:
            mouse_pos (tuple): XY position of the cursor.
        """

        # Check x area
        within_x = mouse_pos[0] >= self.rect.x and mouse_pos[0] <= self.rect.x + self.rect.width

        # Check y area
        within_y = mouse_pos[1] >= self.rect.y and mouse_pos[1] <= self.rect.y + self.rect.height

        # True if within x and y area
        return within_x and within_y

class Picture (pygame.sprite.Sprite):
    """
    Picture object for menu manager.

    Attributes:
        image (pygame.image): Image for picture.
        rect (pygame.image.rect): Position, height, width values for picture.
    """

    def __init__ (self, image, pos = [0,0]):
        """
        Instantiate a picture object.

        Arguments:
            image (string): Path of image file to be used for picture.
            pos (tuple): XY position for the picture.
        """

        super(Picture, self).__init__()

        self.image = pygame.image.load(image)
        self.image.set_colorkey(menu_manager_settings["element_colorkey"])
        self.rect = self.image.get_rect()
        self.rect.x = pos[0]
        self.rect.y = pos[1]

    def get_pos (self):
        """
        Get the position of this picture element.

        Returns:
            pos (list): XY position of the picture.
        """

        position = [self.rect.x, self.rect.y]
        return position

    def set_pos (self, pos):
        """
        Set position of the picture.

        Arguments:
            pos (tuple): XY position to set the picture to.
        """

        self.rect.x = pos[0]
        self.rect.y = pos[1]

    def set_image (self, new_image):
        """
        Set a new picture for this instance of Picture. Preserves x and y
        position of the old picture.

        Arguments:
            new_image (String): File name of the new picture.
        """

        # Store the current position
        temp_old_pos = self.get_pos()

        # Load the new image
        self.image = pygame.image.load(new_image)
        self.image.set_colorkey(menu_manager_settings["element_colorkey"])
        self.rect = self.image.get_rect()

        # Set the x and y position using the old position
        self.rect.x = temp_old_pos[0]
        self.rect.y = temp_old_pos[1]

class Text (pygame.sprite.Sprite):
    """
    Text object for MenuManager.

    Attributes:
        text (String): Text to be rendered.
        font (pygame.font): Font used to render the text.
        pos (tuple): Position of the text.
        color (List): Color of the text.
        antialias (Boolean): Adds antialias to text.
        background_color (List): Background color of the text.
        image (pygame.image): Rendered text.
        rect (pygame.image.rect): Position, height, width values for Text.
    """

    def __init__ (self, text, font, pos = [0,0], color = [255, 255, 255], \
                  antialias = True, background_color = None):
        """
        Instantiates a new Text object.

        Arguments:
            text (String): Text to be rendered.
            font (pygame.font): Font used to render the text.
            pos (tuple): Position of the text.
            color (List): Color of the text.
            antialias (Boolean): Adds antialias to text.
            background_color (List): Background color of the text.
        """

        super(Text, self).__init__()

        self.text = text
        self.font = font
        self.pos = pos
        self.color = color
        self.antialias = antialias
        self.background_color = background_color

        self.image = font.render(str(text), antialias, color, background_color)
        self.image.set_colorkey(menu_manager_settings["element_colorkey"])
        self.rect = self.image.get_rect()
        self.rect.x = pos[0]
        self.rect.y = pos[1]

    def get_dimensions (self):
        """
        Get the width and height of the Text.

        Returns:
            list: Width and Height of the Text. Uses width and height from
                  self.rect.
                  Format: [width, height]
        """

        dimensions = [self.rect.width, self.rect.height]
        return dimensions

    def get_pos (self):
        """
        Get the position of this text element.

        Returns:
            pos (list): XY position of the text.
        """

        position = [self.rect.x, self.rect.y]
        return position

    def set_pos (self, pos):
        """
        Set position of the text.

        Arguments:
            pos (list): XY position to set the text to.
        """

        self.rect.x = pos[0]
        self.rect.y = pos[1]

class MenuManager:
    """
    Menu manager for pygame.

    Attributes:
        pages (List): List of pages in the menu manager.
        current_page (Page): Page currently being displayed.
        screen (pygame.display): Surface to blit the pages and game to.
        clock (pygame.time.Clock): Used to set/cap game FPS.
        start_page_set (Boolean): Switch that checks if start page has been set.
    """

    def __init__ (self, screen, clock):
        """
        Instantiate a MenuManager object.

        Arguments:
            screen (pygame.Surface): Surface we are blitting objects to.
            clock (pygame.time.Clock): Pygame clock.

        NOTE: For the menu manager system to work as intended, you will want to
              use the same screen and clock objects for the menu manager and
              your game.
        """

        self.pages = list()
        self.current_page = None
        self.screen = screen
        self.clock = clock
        self.start_page = None
        self.exiting = False

    def run (self):
        """
        Puts the menu loop into a function for ease of use.
        """

        while self.__update():

            self.__display()

    def add_page (self, new_page):
        """
        Adds a page to the menu manager.

        Arguments:
            new_page (Page): Page to be added to the menu manager.
        """

        self.pages.append(new_page)

    def set_start_page (self, page_id):
        """
        Set a start page for the menu manager. This function must be called
        before calling ManuManager.run() or the program will be terminated.

        Arguments:
            page_id (String/Int): ID of the desired page destination.

        NOTE: See Page class for more info on page id's.

        """

        for page in self.pages:

            if (page_id == page.id):

                self.current_page = page
                self.start_page = page
                return

        print("Invalid start page id!")
        exit()

    def navigate (self, page_id):
        """
        Sets the currently showing page using the id attribute of Page class.

        Arguments:
            page_id (String/Int): ID of the desired page destination.

        NOTE: See Page class for more info on page id's.
        """

        for page in self.pages:

            if page.id == page_id:

                self.current_page = page

                return

        print("Invalid page id, " + str(page_id) + "! Exiting.")
        exit(-1)

    def exit_menu (self):
        """
        For exiting the menu manager. Flips the exiting flag.
        """

        self.exiting = True

    def kill_program (self):
        """
        Terminates the entire program.
        """

        exit()

    def __display (self):
        """
        Blit everything from backend to the screen.
        """

        # Fill background
        self.screen.fill(menu_manager_settings["menu_background_color"])

        # Display current screen
        self.current_page.display(self.screen)
        pygame.display.flip()
        self.clock.tick(menu_manager_settings["menu_fps"])

    def __update (self):
        """
        Handles user events. Also checks if a start page has been set. This
        function will prevent the program from running if a sart page has not
        beem set.

        Returns:
            Boolean: True if program execution should continue, False otherwise.
        """

        if self.start_page == None:

            print("Start page not set!")
            self.kill_program()

        if self.exiting:

            self.exiting = False
            self.current_page = self.start_page

            return False

        for event in pygame.event.get():

            if event.type == pygame.QUIT:

                self.kill_program()

            if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:

                mouse_pos = pygame.mouse.get_pos()

                for element in self.current_page.elements:

                    if isinstance(element, ButtonPicture) or \
                       isinstance(element, ButtonText):

                        if element.is_clicked(mouse_pos):

                            element.execute_actions()

        return True

class Page:
    """
    Page object for menu manager.

    Attributes:
        id (string/int): ID for this page.
        elements (List): List of elements on the page.

    NOTE: The ID doesn't have to be a string/int, it just has to be some
          distinct identifier for this page. I just recommend using a string or
          an integer for simplicity and readability.
    """

    def __init__ (self, id):
        """
        Instantiate a page object.

        Arguments:
            id (string/int): ID for this page.
        """

        self.id = id
        self.elements = list()

    def add_element (self, new_element):
        """
        Adds an element to the page.

        Arguments:
            new_element (Button): Element to add to the page.
        """

        self.elements.append(new_element)

    def display (self, screen):
        """
        Show this screen in the window.

        Arguments:
            screen (pygame.display): Surface to blit the elements to.
        """

        for element in self.elements:

            screen.blit(element.image, [element.rect.x, element.rect.y])


from django.urls import resolve
from django.views import View
from django.db.models import Sum,Count,Max,Q
from ipl.models import *
from django.shortcuts import render,redirect
from django.contrib.auth.mixins import LoginRequiredMixin
class IplTeamView(View):
    def get_list(self):
        teams = Matches.objects.values("team1").distinct();
        match = Matches.objects.all().values('season').annotate(dsum=Max('matchid')).order_by('season')
        list = []
        for team in teams:
            if team['team1'] != 'Delhi Daredevils' and team['team1'] != "Rising Pune Supergiants" and team[
                'team1'] != "Deccan Chargers":
                list.append([team['team1']])
        for id in match:
            winner = Matches.objects.values('winner').filter(matchid=id['dsum'])[0]
            winner = winner['winner']
            for team in list:
                if (team[0] == winner):
                    team.append(id['season'])
        return list
    def get_team_by_season(self,team):
        years=[2008,2009,2010,2011,2012,2013,2014,2015,2016,2017,2018,2019]
        li=[]
        for year in years:
            played = Matches.objects.all().filter(team1=team,season=year).count() + Matches.objects.all().filter(team2=team,season=year).count()
            print(played)
            if(played==0):
                li.append([year,"~","~","~","~"])
            else:
                won = Matches.objects.all().filter(winner=team, season=year).count()
                match=[year,played,won,played-won]
                if year in [2008,2009,2010]:
                    query=Matches.objects.values('team1', 'team2', 'matchid').filter(season=year).order_by('-matchid')[0:3]
                else:
                    query = Matches.objects.values('team1', 'team2', 'matchid').filter(season=year).order_by(
                        '-matchid')[0:4]
                Teams=[]
                for i in query:
                    if(i['team1'] not in Teams):
                        Teams.append(i['team1'])
                    if(i['team2'] not in Teams):
                        Teams.append(i['team2'])
                print(Teams, year)
                winner = Matches.objects.all().filter(season=year).order_by('-matchid')[0].winner
                if(winner==team):
                    match.append("Champion")
                elif(team in Teams):
                    match.append("Play offs")
                else:
                    match.append("League Stage")
                li.append(match)
        return li

    def get(self,request,*args,**kwargs):
        username = request.user.username
        if kwargs:
            ids= {
                "1":"Sunrisers Hyderabad",
                "2":"Mumbai Indians",
                "3":"Royal Challengers Bangalore",
                "4":"Kolkata Knight Riders",
                "5":"Kings XI Punjab",
                "6":"Chennai Super Kings",
                "7":"Rajasthan Royals",
                "8":"Delhi Capitals",
                "9":"Gujarat Lions",
                "10":"Rising Pune Supergiant",
                "11":"Pune Warriors",
                "12":"Kochi Tuskers Kerala",
            }

            team=ids[str(kwargs["id1"])]
            li2 = self.get_team_by_season(team)
            print(li2)
            played= Matches.objects.all().filter(team1=team).count()+ Matches.objects.all().filter(team2=team).count()
            noresult=Matches.objects.all().filter(team1=team,winner=None).count() + Matches.objects.all().filter(team2=team,winner=None).count()
            won= Matches.objects.all().filter(winner=team).count()
            li=[["Matches Played",played],["Won",won],["Lost",played-won-noresult],["noresult",noresult]]
            batsmans=Deliviers.objects.values('batsman').filter(batting_team=team).annotate(
                dsum=(Sum('batsman_runs'))).order_by("-dsum")[:5]
            bowlers=  Deliviers.objects.values('bowler').filter(~Q(dismissal_kind='runout'),bowling_team=team).annotate(
                dsum=(Count('player_dismissed'))).order_by("-dsum")[0:5]
            return render(
                request,
                template_name="perteam.html",
                context={
                    "played":li,
                    "batsmans":batsmans,
                    "bowlers":bowlers,
                    "stats":li2,
                    "team":team,
                    "username":username
                }
            )

        list=self.get_list()
        return render(
            request,
            template_name="team.html",
            context={
                "teams": list,
                "username": username,
            }
        )


from concurrent import futures
import grpc
from nextcloud_pb2_grpc import add_NextcloudServiceServicer_to_server, NextcloudServiceServicer
from nextcloud_pb2 import FileResponse as NextcloudFileResponse, UploadFileResponse
from utils import get_file_from_nextcloud, upload_file_to_nextcloud

class NextcloudService(NextcloudServiceServicer):

    def GetFile(self, request, context):
        content = get_file_from_nextcloud(request.path)
        return NextcloudFileResponse(content=content)

    def UploadFile(self, request, context):
        status, message = upload_file_to_nextcloud(request.filename, request.content)
        return UploadFileResponse(status=status, message=message)

def serve_grpc():
    server = grpc.server(futures.ThreadPoolExecutor(max_workers=10))
    add_NextcloudServiceServicer_to_server(NextcloudService(), server)
    server.add_insecure_port('[::]:50051')
    server.start()
    server.wait_for_termination()


import logging

import slicer
from slicer.ScriptedLoadableModule import *

#
# BRAINSFitRigidRegistrationCrashIssue4139
#

class BRAINSFitRigidRegistrationCrashIssue4139(ScriptedLoadableModule):
    """Uses ScriptedLoadableModule base class, available at:
    https://github.com/Slicer/Slicer/blob/main/Base/Python/slicer/ScriptedLoadableModule.py
    """

    def __init__(self, parent):
        ScriptedLoadableModule.__init__(self, parent)
        self.parent.title = "BRAINSFit Rigid Registration vtkITKTransformConverter crash (Issue 4139)"
        self.parent.categories = ["Testing.TestCases"]
        self.parent.dependencies = []
        self.parent.contributors = ["Jean-Christophe Fillion-Robin (Kitware)"]  # replace with "Firstname Lastname (Organization)"
        self.parent.helpText = """This test has been added to check that
    Slicer does not crash in vtkITKTransformConverter after completing BRAINSFit rigid registration.

    Problem has been documented in issue #4139. Commit r24901 fixes the problem
    by updating vtkITKTransformConverter class.
    """
        self.parent.acknowledgementText = """
    This file was originally developed by Jean-Christophe Fillion-Robin, Kitware Inc.
    and was partially funded by NIH grant 1U24CA194354-01.
    """  # replace with organization, grant and thanks.

#
# BRAINSFitRigidRegistrationCrashIssue4139Widget
#

class BRAINSFitRigidRegistrationCrashIssue4139Widget(ScriptedLoadableModuleWidget):
    """Uses ScriptedLoadableModuleWidget base class, available at:
    https://github.com/Slicer/Slicer/blob/main/Base/Python/slicer/ScriptedLoadableModule.py
    """

    def setup(self):
        ScriptedLoadableModuleWidget.setup(self)

#
# BRAINSFitRigidRegistrationCrashIssue4139Logic
#

class BRAINSFitRigidRegistrationCrashIssue4139Logic(ScriptedLoadableModuleLogic):
    """This class should implement all the actual
    computation done by your module.  The interface
    should be such that other python code can import
    this class and make use of the functionality without
    requiring an instance of the Widget.
    Uses ScriptedLoadableModuleLogic base class, available at:
    https://github.com/Slicer/Slicer/blob/main/Base/Python/slicer/ScriptedLoadableModule.py
    """

    def hasImageData(self, volumeNode):
        """This is an example logic method that
        returns true if the passed in volume
        node has valid image data
        """
        if not volumeNode:
            logging.debug("hasImageData failed: no volume node")
            return False
        if volumeNode.GetImageData() is None:
            logging.debug("hasImageData failed: no image data in volume node")
            return False
        return True

class BRAINSFitRigidRegistrationCrashIssue4139Test(ScriptedLoadableModuleTest):
    """
    This is the test case for your scripted module.
    Uses ScriptedLoadableModuleTest base class, available at:
    https://github.com/Slicer/Slicer/blob/main/Base/Python/slicer/ScriptedLoadableModule.py
    """

    def setUp(self):
        """Do whatever is needed to reset the state - typically a scene clear will be enough."""
        slicer.mrmlScene.Clear(0)

    def runTest(self):
        """Run as few or as many tests as needed here."""
        self.setUp()
        self.test_BRAINSFitRigidRegistrationCrashIssue4139()

    def test_BRAINSFitRigidRegistrationCrashIssue4139(self):
        """Ideally you should have several levels of tests.  At the lowest level
        tests should exercise the functionality of the logic with different inputs
        (both valid and invalid).  At higher levels your tests should emulate the
        way the user would interact with your code and confirm that it still works
        the way you intended.
        One of the most important features of the tests is that it should alert other
        developers when their changes will have an impact on the behavior of your
        module.  For example, if a developer removes a feature that you depend on,
        your test should break so they know that the feature is needed.
        """

        self.delayDisplay("Starting the test")

        logic = BRAINSFitRigidRegistrationCrashIssue4139Logic()

        import SampleData

        fixed = SampleData.downloadSample("MRBrainTumor1")
        self.assertIsNotNone(logic.hasImageData(fixed))

        moving = SampleData.downloadSample("MRBrainTumor2")
        self.assertIsNotNone(logic.hasImageData(moving))

        self.delayDisplay("Finished with download and loading")

        outputTransform = slicer.vtkMRMLLinearTransformNode()
        slicer.mrmlScene.AddNode(outputTransform)

        outputVolume = slicer.vtkMRMLScalarVolumeNode()
        slicer.mrmlScene.AddNode(outputVolume)

        parameters = {
            "fixedVolume": fixed,
            "movingVolume": moving,
            "linearTransform": outputTransform,
            "outputVolume": outputVolume,
            "useRigid": True,
        }
        cmdLineNode = slicer.cli.runSync(slicer.modules.brainsfit, parameters=parameters)
        self.assertIsNotNone(cmdLineNode)

        # If test reach this point without crashing it is a success

        self.delayDisplay("Test passed!")


from copy import deepcopy
import os.path as osp

import torch
import torch.nn.functional as F

from hessian_eigenthings import compute_hessian_eigenthings
import matplotlib.pyplot as plt
from pytorch_lightning.callbacks.early_stopping import EarlyStopping

from groundzero.args import parse_args
from groundzero.main import main
from groundzero.resnet import ResNet

RHO = 0.05
EIGENVALS = []
SHARPNESSES = []
SMALLBATCH_SIZE = 128
LARGEBATCH_SIZE = 4096
TRAIN_ACC_STOP_THRESHOLD = 0.99

class HessianResNet(ResNet):
    def __init__(self, args, classes):
        super().__init__(args, classes)

    def validation_step(self, batch, idx):
        torch.set_grad_enabled(True)
        super().validation_step(batch, idx)

    def validation_epoch_end(self, validation_step_outputs):
        if self.train_acc1 >= TRAIN_ACC_STOP_THRESHOLD:
            # Computes maximum Hessian eigenvalue
            torch.set_grad_enabled(True)
            loss = F.cross_entropy
            loader = self.trainer.val_dataloaders[0]
            eigenval = compute_hessian_eigenthings(self.model, loader, loss, 1)[0][0]
            EIGENVALS.append(eigenval)
            print(EIGENVALS)

            # Computes worst-case sharpness viz. SAM
            params = deepcopy(list(self.model.parameters()))
            for p in self.model.parameters():
                #print(p.grad)
                epsilon = RHO * F.normalize(p.grad, dim=0)
                p = p + epsilon

            losses = []
            sam_losses = []
            for j, step in enumerate(validation_step_outputs):
                batch = (step["imgs"].cuda(), step["targets"].cuda())
                losses.append(step["loss"])
                sam_losses.append(self.step(batch, j)["loss"])
            losses = torch.as_tensor(losses)
            sam_losses = torch.as_tensor(sam_losses)
            sharpness = sam_losses.mean() - losses.mean()
            SHARPNESSES.append(sharpness)
            self.model.parameters = (p for p in params)
            print(SHARPNESSES)

def experiment(args):
    args.max_epochs = 1000
    #lrs = [0.001, 0.005, 0.01, 0.05]
    lrs = [0.05]

    callbacks = [EarlyStopping(
                    monitor="train_acc1",
                    mode="max",
                    stopping_threshold=TRAIN_ACC_STOP_THRESHOLD,
                    check_on_train_epoch_end=True,
                )]

    for lr in lrs:
        args.lr = lr
        args.batch_size = SMALLBATCH_SIZE
        main(args, HessianResNet, callbacks=callbacks)

    """
    for lr in lrs:
        args.lr = lr
        args.batch_size = LARGEBATCH_SIZE
        main(args, HessianResNet, callbacks=callbacks)

    print(EIGENVALS)
    print(SHARPNESSSES)
    """

if __name__ == "__main__":
    args = parse_args()
    experiment(args)


class DoubleSort:
    def __init__(self, list_user:list):
        self._list_user = list_user

    def return_list_sort(self) -> list:
        list_string = []
        list_numbers = []

        for item in self._list_user:
            if isinstance(item, str):
                list_string.append(item)
            else:
                list_numbers.append(item)

        list_string.sort()
        list_numbers.sort()
        return list_numbers + list_string


from django.conf.urls import url, include
from .views import *
from .views_api import *
from rest_framework.routers import DefaultRouter
from rest_framework.authtoken.views import obtain_auth_token

router = DefaultRouter()
router.register(r'smallfixes', SmallFixViewSet)
router.register(r'smallfixes/attachments', AttachmentViewSet)
router.register(r'capsules', CapsuleViewSet)
router.register(r'customer', CustomerViewSet)
router.register(r'customer-website', CustomerWebsiteViewSet)
router.register(r'user', UserViewSet)

payment_patterns = [
    url(r'^charge$', chargePaymentToken, name="stripe-payment"),
    url(r'^get-key$', getPublishableKey, name="stripe-key"),

    #url(r'^transaction$', createTransaction, name="braintree-transaction"),
]

urlpatterns = [
    url(r'^api/', include(router.urls)),
    url(r'^dashboard$', dashboard, name='dashboard'),
    url(r'^profile$', customerProfile, name='profile'),
    url(r'^fixes$', fixes, name='fixes'),
    url(r'^capsules$', capsulesView, name='capsules'),
    url(r'^$', index, name='index'),
    url(r'^attachments/add$', addFixAttachement, name='attachment-add'),
    url(r'^payment/', include(payment_patterns)),
]


import os
import pandas as pd

dataPath = "Data/Dataset_clusters/06/"
treatedDataPath= "Data/Dataset_clusters/06_norm/"

colums_numerical = ["Nedbør (1 t)", "Lufttemperatur", "Middelvind","Skydekke" ]
colums_categorical_nominal = []
colums_categorical_ordinal = [""]

files = os.listdir(dataPath)
print(files)
for file in files:
    #normalize numerical data
    df = pd.read_csv(dataPath + file, index_col=0)
    print(df.head(3))
    for column in colums_numerical:
        df[column] = (df[column] - df[column].mean()) / df[column].std()

    #store normalized dataset
    df.to_csv(treatedDataPath + file)


class Student:
    # 类属性
    native_place='湖北'#直接写在类里面的变量，称为类属性
    #初始化方法
    def __init__(self,name,age):
        self.name=name#self.name称为实体属性，进行了一个赋值的操作，将局部变量name的值赋给实体属性
        self.age=age
    # 实例方法
    def eat(self):
        print('干饭人干饭魂')#类之内定义的叫方法，类之外定义的叫函数
    #静态方法
    @staticmethod
    def method():
        print('这是一个静态方法')
    #类方法
    @classmethod
    def cm(cls):
        print('这是一个类方法')
#实际上我所声明的类也是一个类对象
#对象的创建（又称类的实例化）
print('---------------创建Student类的对象------------------')
st1=Student('李博文',21)#st1就是根据类对象创建出来的实例对象
st1.eat()#对象名.方法名
print(st1.name)
print(st1.age)
print('----------这是一条分割线----------')
Student.eat(st1)#类名.方法名(类的对象)
#27行与23行的作用是一样的，都是调用Student类之中的参数


def main(numbers):
    """
    Given a sequence of integers. Build a new sequence of the same length. Each element of a new
    sequence should be calculated as a multiplication of elements of the original sequence except
    the element with the same index.  Think about possible corner cases.
    >>> main([1, 5, 3])
    [15, 3, 5]
    >>> main([1, 2, 2, 5, 8])
    [160, 80, 80, 32, 20]
    """
    print('numbers', numbers)
    product  = 1
    for x in numbers:
        product = product * x
    print('product', product)
    result = [int(product / i) for i in numbers]
    print('result', result)
    return result
main([1, 5, 3])
main([1, 2, 2, 5, 8])


from Model.vae import conditional_vae
from Utils.data_generator import ConditionalDataGenerator
from Utils.image_sampling import create_conditional_sample_pic, print_test_pic
from config import ConfigOptions

#define hyperparameters
config = ConfigOptions()
latent_size = config.latent_size
beta = config.beta
img_dim = config.img_dim
batch_size = config.batch_size
epochs = config.epochs
data_dir = config.data_dir
out_dir = config.out_dir
normal_dims = config.normal_dims
kernal_size = config.kernal_size
model_dir = config.out_model_dir

print_test_pic(data_dir,out_dir,img_dim)

encoder, decoder, vae_model = conditional_vae(latent_size,img_dim,kernal_size,beta)

generator = ConditionalDataGenerator(dir=data_dir,dims=img_dim,batch_size=batch_size,shuffle=True)

for j in range(0,epochs):
	print("training epoch {}".format(j))
	vae_model.fit_generator(generator, epochs=1, shuffle=True)
	create_conditional_sample_pic(img_dim,j,encoder,decoder,data_dir,out_dir)
	if(config.save_model):
		encoder.save(model_dir + "ConditionalVAEEncoderDance_epoch_{}.h5".format(j))
		decoder.save(model_dir + "ConditionalVAEDecoderDance_epoch_{}.h5".format(j))
	generator.on_epoch_end()


class Solution:
    def earliestFullBloom(self, plantTime: List[int], growTime: List[int]) -> int:

        pots, length = [], len(plantTime)

        for index in range(length):

            plant = plantTime[index]
            grow = growTime[index]

            pots.append([plant, grow])

        pots = sorted(pots, key = lambda x:x[1], reverse = True)

        current_day = 0
        result = 0

        for pot in pots:

            current_plant , current_grow = pot

            current_day = current_day + current_plant

            result = max(result, current_day + current_grow)

        return result

2136. Earliest Possible Day of Full Bloom.py


import unittest
# this stuff is necessary because of how annoying it is to use relative imports. Instead
# of setting all that up just include the path to the src directory here then
# import things like normal
import sys
sys.path.append("../src")

from Parser import parse
import Checks

class TestUS21(unittest.TestCase):
    # make sure to name the class Test<US#>

    # setup gets run before tests, so I use it to parse my test file and get the
    # data structures I need
    def setUp(self):
        individuals, families = parse("../testfiles/US21_test.ged")
        self.individuals = individuals
        self.families = families

    def test_bad_role_wife(self):
        flag, output = Checks.correct_gender_for_role(
            self.individuals, self.families)
        self.assertEqual(flag, False)
        self.assertEqual(output, str(
            self.individuals[1]) + " is a wife but not a female\n")

    def test_bad_role_husband(self):
        self.individuals[0].gender = "F"
        self.individuals[1].gender = "F"
        flag, output = Checks.correct_gender_for_role(self.individuals, self.families)
        self.assertEqual(flag, False)
        self.assertEqual(output, str(self.individuals[0]) + " is a husband but not a male\n")
        # put back
        self.individuals[0].gender = "M"
        self.individuals[1].gender = "M"

    def test_both_bad_roles(self):
        self.individuals[0].gender = "F"
        flag, output = Checks.correct_gender_for_role(self.individuals, self.families)
        self.assertEqual(flag, False)
        self.assertEqual(output, str(self.individuals[0]) + " is a husband but not a male\n" + str(
            self.individuals[1]) + " is a wife but not a female\n")
        # put back
        self.individuals[0].gender = "M"

    def test_all_good_roles(self):
        self.individuals[1].gender = "F"
        flag, output = Checks.correct_gender_for_role(self.individuals, self.families)
        self.assertEqual(flag, True)
        self.assertEqual(
            output, "All families have the correct gender for their roles\n")
        self.individuals[1].gender = "M"

    def test_empty_input(self):
        flag, output = Checks.correct_gender_for_role([], [])
        self.assertEqual(flag, True)
        self.assertEqual(
            output, "All families have the correct gender for their roles\n")

if __name__ == '__main__':
    unittest.main()


import sys
import logging
import pprint

def configure_logger(name=__name__):
    """Configure logging for proper output to DataDog
    """
    logging.getLogger().handlers = []
    logger = logging.getLogger(__name__)
    logger.handlers = []
    log_handler = logging.StreamHandler()
    logger.addHandler(log_handler)
    logger.setLevel(logging.DEBUG)
    logger.propogate = False
    return logger

def check_is_subset(expected_subset:list, superset:bool) -> bool:
    return set(expected_subset).issubset(superset)


"""
    Write a function that takes in an array of words and returns the smallest
    array of characters needed to form all of the words. The characters don't need
    to be in any particular order.

    For example, the characters ["y", "r", "o", "u"] are needed to
    form the words ["your", "you", "or", "yo"].

    Note: the input words won't contain any spaces; however, they might contain
    punctuation and/or special characters.

    Example:
        words = ["this", "that", "did", "deed", "them!", "a"]

        Output:
            ["t", "t", "h", "i", "s", "a", "d", "d", "e", "e", "m", "!"]
"""
def minimumCharactersForWords(words):
    result = []
    dict = get_char_dict(words)

    for x in dict:
        for i in range(0, dict[x]):
            result.append(x)

    return result

def get_char_dict(words):
    dict = {}
    for word in words:

        dict_for_word = {}

        for c in word:
            if c in dict_for_word:
                dict_for_word[c] = dict_for_word[c] + 1
            else:
                dict_for_word[c] = 1

        for c in dict_for_word:
            if c not in dict or dict[c] < dict_for_word[c]:
                dict[c] = dict_for_word[c]

    return dict

print(minimumCharactersForWords(["this", "that", "did", "deed", "them", "they"]))


# -*- coding: utf-8 -*-

from odoo import api, fields, models, exceptions, _
from datetime import datetime, date
from odoo.exceptions import UserError, ValidationError

class CorrespondenceType(models.Model):
    _name = 'correspondence.type'
    _inherit = ['portal.mixin', 'mail.thread', 'mail.activity.mixin']
    _description = 'Correspondence Type'

    name = fields.Char(string='Correspondence Type', tracking=True)
    ttd = fields.Image(string='Signature', tracking=True, max_width=120, max_height=120)
    ttd_name = fields.Char(string='Signee', tracking=True)
    title = fields.Char(string='Title', tracking=True)

    def associated_view_correspondence(self):
        correspondence = self.env['correspondence.correspondence'].sudo().search([('type_id', '=', self.id)])
        if not correspondence:
            raise UserError("Create Correspondence with Format of Latter '%s' First!" % self.name)
        self.ensure_one()
        action_ref = self.env.ref('base.action_ui_view')
        report_name = '%s Correspondence Type' % self.id
        action_data = action_ref.read()[0]
        form_id = self.env['ir.ui.view'].search([('name', 'ilike', report_name), ('type', '=', 'qweb')])
        action_data['views'] = [(self.env.ref('base.view_view_form').id, 'form')]
        action_data['res_id'] = form_id.id
        return action_data

    @api.model
    def create(self, vals):
        result = super(CorrespondenceType, self).create(vals)
        for rec in result:
            num_id = rec.id
            self.create_ir_ui_view(num_id)
            self.create_ir_model_data(num_id)
            self.create_ir_actions_report(num_id)
            return result

    def create_ir_ui_view(self, num_id):
        view_id = self.env['ir.ui.view'].sudo().search([('name', '=', 'report_correspondence_type'), ('xml_id', '=', 'asb_master_provider_correspondence.report_correspondence_type')])
        self.env['ir.ui.view'].sudo().create({
            'name': '%s Correspondence Type' % num_id,
            'type': 'qweb',
            'key': '%s.correspondence.type' % num_id,
            'priority': 16,
            'active': True,
            'arch_updated': False,
            'mode': 'primary',
            'arch_base': view_id.arch_db,
            'arch_db': view_id.arch_db,
            'arch_prev': False,
        })

    def create_ir_model_data(self, num_id):
        name = '%s Correspondence Type' % num_id
        res_id = self.env['ir.ui.view'].sudo().search([('name', '=', name)])
        self.env['ir.model.data'].sudo().create({
            'name': '%s_Correspondence_Type' % num_id,
            'module': num_id,
            'model': 'ir.ui.view',
            'res_id': res_id.id,
        })

    def create_ir_actions_report(self, num_id):
        self.env['ir.actions.report'].sudo().create({
            'name': '%s Correspondence Type' % num_id,
            'report_type': 'qweb-pdf',
            'model': 'correspondence.correspondence',
            'report_name': '%s.correspondence.type' % num_id,
            'paperformat_id': self.env.ref('asb_master_provider_correspondence.report_correspondence_format').id
        })

    def add_correspondence(self):
        form_view = [(self.env.ref('asb_master_provider_correspondence.correspondence_form').id, 'form')]
        res = self.env['ir.actions.act_window']._for_xml_id('asb_master_provider_correspondence.correspondence_action')
        res['context'] = {'default_type_id': self.id}
        res['view_mode'] = 'form'
        res['views'] = form_view
        res['domain'] = False
        return res


#Using the max function, which is higher 5 or 23?
x = 5
y = 23
z = max(x,y)
print(z)

#Use the math function to find the square root of 74
#Option 1
import math
x = 74
y = math.sqrt(x)
print(y)

#Option 2
import math as m
x = 74
y = m.sqrt(x)
print(y)

#option 3
from math import sqrt
x = sqrt(74)
print(x)

#Use the easygui to print the message "To be or not to be" titled "What Hamlet elocuted"
#Option 1
import easygui
x = easygui.msgbox("To be or not to be", "What Hamlet elocuted")
print(x)

#Option 2
import easygui as e
e.msgbox("To be or not to be", "What Hamlet elocuted")

#Create a function that add 1 to any number you call
def spam(x):
	x += 1
	return x
print(spam(5))

#Create a function that print the integer value after dividing x by y
def bar(x,y):
	return int(x/y)
print(bar(8, 7))

def closure(a, b, funct):
	return funct(a, b)
print (closure(8, 9, min))

a_list = [1, ["a",["b","c"]], 43, "Too many cooks spoil the broth"] #Create a list
print(len(a_list))#find out how many items are in the list

print(a_list[1][1][1])#To callout "c" from a_list

a_list.append("Foul play") #add string "foul play" to the end of a_list
print(a_list)

a_list.insert(1, "Child's Play" ) #Insert "Child's Play at position 1 of a_list
print(a_list)

a_list.extend([1,2,3]) #unpack the list and add it to the end of a_list
print(a_list)

a_list.pop() #Removes the last item in the list. That would be three in this case
print(a_list)

a_list.pop(3) #Remove the item in position 3 1.e 43
print(a_list)

print(a_list[3]) #Print the third item in the list

print(a_list[2:5]) #Print from the second item to the fifth item i.e. elements in position 2, 3 and 4

print(a_list[:4]) #Print from the beginning item to the fourth item i.e. elements in position 0,1,2,3

print(a_list[1:]) #Print from the first item to the end of the list

print(a_list[-1]) #Print the last item in the list

print(a_list[::-1])  #Print the list backwards, starting from the last item to the first i.e. reverse the list

a_list.remove(2) #Remove the first '2' in the list

a_list[1] = "Sycamore roots" #Change the item in position 1 to "Sycamore roots"
print(a_list)

x = [1,4,5,68,9,45,23,67,33,34]
for items in range(len(x)):
	print(items, x[items])

y = list(range(len(x)))
print(y)

"""Write a function search_list that searches a
list of tuples pair and return the value
associated with the first element of
the pair"""

list_of_tuples = [("AAPL", 96.43), ("IONS", 38), ("GS", 158)]

def search_list(list_of_tuples, value):
	for element in list_of_tuples:
		if element[0] == value.upper():
			return element[1]
	else:
			return("The value you selected is not available")

print(search_list(list_of_tuples, "GS"))

inventory = [("widgets", 100), ("spam", 30), ("eggs", 200)]

def search_list(inventory, value):
	for elements in inventory:
		if elements[0] == value:
			return elements[1]
	else:
		return None
y =search_list(inventory, value = "spam")
print(y)
z= search_list(inventory, value = "hay")
print(z)

dictname = {"AAPL":96.43 , "IONS":38, "GS": 158, "widgets": 100, "spam": 30, "eggs": 200} #Create a dictionary
print(dictname.keys()) #print the keys of the dictionary
print(dictname.values()) #print the values of the dictionary
print(sorted(dictname.keys())) #print the keys in ascending order
print(sorted(dictname.keys(), reverse = True)) #print the keys in descending order
print(sorted(dictname.values())) #print the value in ascendinf order
print(dictname["AAPL"]) #print the vale of AAPL
print(dictname.get("IONS")) #print the value of IONS
dictname["Awarri"] = 89 #Add a new key:value pair to the dictionary
del(dictname["Awarri"]) #delete the key:value pair of Awarri
print(dictname)

import datetime as d
z= d.date(2016, 12, 24)
y = d.date(2019, 11, 21)
print(max(z,y))
print(y - z) #To check the difference between the two days
print((y-z).days) #To print the just the number of days
print(d.date.today()) #To print today's date
print(d.datetime.today()) #To print today's date and time

#To add days, minutes and seconds using the datetime library
zz = (d.datetime.today())
tt = zz+d.timedelta(days= 5)
print(zz, tt)
ww = tt +d.timedelta(minutes = 5, seconds = 10)
print(tt, ww)

#To convert  Date in string to normal date
finale = "01-Apr-03"
finale_obj = d.datetime.strptime(finale, '%d-%b-%y')
print(finale_obj)

#To convert a time string to time
ending = "2:18:24"
Hours, Minutes, Seconds = ending.split(":")
x = d.timedelta(hours = int(Hours), minutes = int(Minutes), seconds = int(Seconds))
print(x)

#To convert a date to string
today = d.datetime.today()
today_now = d.datetime.strftime(today, "%m-%d-%y %H:%M:%S")
print(today, today_now)

# To open a csv file and view its content
data_tuples = list()
with open("sample_data.csv", 'r') as sample_data:
	for line in sample_data:
		data_tuples.append(line.strip().split(" , "))
print(data_tuples[0:10])

#Getting Data Online Using the request library
import requests
response = requests.get("http://www.epicurious.com/search/Tofu+Chili") #Use requests.get to access webpage
print(type(response)) #View the type of response

#To check if our action was successful i.e. 404 means page not found. 404 means page not found
print(response.status_code)

#or
if response.status_code == 200:
	print("Success")
else:
	print("Failure")

#View and decode the content of the webpage
print(response.content.decode("utf-8"))

#Write a function that takes two items, one a url and the other, a string of words that can be found in the url
def find(url, word):
	import requests as req
	page = req.get(url)
	if page.status_code == 200:
		pagecode = page.content.decode("utf-8")
		return pagecode.find(word)
	else:
		return "Your action wasn't successful, check the url again"

print(find(url = "https://en.wikipedia.org/wiki/main_page", word = "Did you know"))

#Text conversion using JSON
import json
data_string = '[{"b": [2, 4], "c": 3.0, "a": "A"}]' #Create a string
python_data = json.loads(data_string)  #Convert to a list using json
print(python_data)

#View the data types of its contents
print(type(data_string), type(python_data))
print(type(python_data[0]), python_data[0])
print(type(python_data[0]["a"]), python_data[0]["a"])
print(type(python_data[0]["b"]), python_data[0]["b"])
print(type(python_data[0]["c"]), python_data[0]["c"])

#Reading a Json
import json
python_data = json.loads(' "Hello" ')
print(python_data)

#Converting a json to a string
datString = json.dumps(python_data)
print(type(datString), datString)

#To access a url using API Key
address="Columbia University, New York, NY"
url="https://maps.googleapis.com/maps/api/geocode/json?address=%s" % (address)  #Add your API Key to the url
response = requests.get(url).json()
print(type(response))

#XML
data_string = """
<Bookstore>
   <Book ISBN="ISBN-13:978-1599620787" Price="15.23" Weight="1.5">
      <Title>New York Deco</Title>
      <Authors>
         <Author Residence="New York City">
            <First_Name>Richard</First_Name>
            <Last_Name>Berenholtz</Last_Name>
         </Author>
      </Authors>
   </Book>
   <Book ISBN="ISBN-13:978-1579128562" Price="15.80">
      <Remark>
      Five Hundred Buildings of New York and over one million other books are available for Amazon Kindle.
      </Remark>
      <Title>Five Hundred Buildings of New York</Title>
      <Authors>
         <Author Residence="Beijing">
            <First_Name>Bill</First_Name>
            <Last_Name>Harris</Last_Name>
         </Author>
         <Author Residence="New York City">
            <First_Name>Jorg</First_Name>
            <Last_Name>Brockmann</Last_Name>
         </Author>
      </Authors>
   </Book>
</Bookstore>
"""

from lxml import etree    #Import the lxml library and use etree
root = etree.XML(data_string) #Use etree to store the XML as a variable
print(root.tag) #Print main xml tag
print(etree.tostring(root, pretty_print = True).decode("utf-8")) #View the XML file as it is

for element in root.iter(): #using an iterator, print all the element in the xml file and its tag
	print(element, element.tag)

for child in root: #View the child of the XML file and its tag
	print(child, child.tag)

for element in root.iter("Author"): #Iterate through the Author element, print the first name and last name
	print(element.find("First_Name").text, element.find("Last_Name").text)

for element in root.findall("Book/Title"): #print the title of book in the title element
	print(element.text)

for element in root.findall("Book/Authors/Author/Last_Name"):  #using findall, return the only the last name of authors
	print(element.text)

print(root.find('Book[@Weight = "1.5"]/Authors/Author/First_Name').text) # Print the first name of the Author whose book weighs exactly 1.5

#Print first and last names of all authors who live in New York City Option 1
for element in root.findall('Book/Authors/Author[@Residence="New York City"]'):
	print(element.find("First_Name").text, element.find("Last_Name").text)

#Option 2
books = root.findall("Book")
for i in range(len(books)):
    print(root.findall('Book/Authors/Author[@Residence="New York City"]/First_Name')[i].text,
          root.findall('Book/Authors/Author[@Residence="New York City"]/Last_Name')[i].text)

#Getting data from the web

#Import the necessary packages
import requests
from bs4 import BeautifulSoup

#use request to access the webpage and parse with lxml
url = "http://www.epicurious.com/search/Tofu+Chili"
response = requests.get(url)
page_soup = BeautifulSoup(response.content, "lxml")
print(page_soup.prettify())   #print the response in a nice format

print(page_soup.find('a'))      #print the first tags that contains 'a'
print(page_soup.find_all('a')) #print all  the tags that contains 'a'

print(page_soup.find("div")) #Return the first div in the url
print(type(page_soup.find("div")))

#To find the first article with article content card
print(page_soup.find('article', class_ = "article-content-card"))

#or
print(page_soup.find('article', {'class' : "article-content-card"}))

def get_recipes(keywords):
	recipe_list = list()
	import requests
	from bs4 import BeautifulSoup
	url = "https://www.epicurious.com/search" + keywords
	response = requests.get(url)
	if not response.status_code == 200:
		return recipe_list
	try:
		results_page = BeautifulSoup(response.content, 'lxml')
		recipes = results_page.find_all('article', class_ = "article-content-card")
		for recipe in recipes:
			recipe_name = recipes.find('a').get_text()
			recipe_url ="https://epicurious.com" + recipe.find('a').get("href")
		print(recipe_name, recipe_url)
	except:
		return recipe_list
	return recipe_list

print(get_recipes(keywords = "lamb chops"))

#Database Basics with Python
#pip Install pymysql first

import pymysql

#Create a connection to your database using your password
db = pymysql.connect("localhost", "root" , "NewPoint",  db= "schooldb")
cursor = db.cursor() #create a cursor

cursor.execute('SHOW tables;') #Use the execute command to run queries
print(cursor.fetchone(), "\n")  #use fetchone to return just one item

cursor.execute("SELECT * FROM student;")
print(cursor.fetchall()) #Use fetchall to return all response from the query

query = """
SELECT course.name,enrolls_in.score FROM student
INNER JOIN enrolls_in ON student.ssn = enrolls_in.ssn
INNER JOIN course ON course.number = enrolls_in.class
WHERE f_name = "JOHN";
"""
cursor.execute(query)
result = cursor.fetchall()

#iterate over the result and get items in it.
print("Course Name", "Score", sep = "\t")
for thing in result:
	print(thing[0], thing[1], sep = "\t")

#Insert a new row into the student table
query = 'INSERT INTO student VALUES ("678-33-2345","Bing","Crossby","2346789870","New York","10001");'
cursor.execute(query)

cursor.execute('SELECT * FROM student;')
print(cursor.fetchall())

db.commit() #To make the new insert permanent on the client side of the database

db.close() #TO close the connection


## Um produto custa (x) valor, o preço deste produto com pagamento a vista, tem desconto de 10% (y) valor
# e parcelado tem acrescimento 13% (XY) valor.

produto=float(input('Qual o valor do produto R$ '))
avista= produto-(produto*10/100)         #produto*0.10
parcelado= produto+(produto*13/100)      #produto*0.13
###################################
print('O valor do produto é R$ {:.2f}: \ncom pagamento avista (PIX ou Dinheiro) tem 10% de desconto e ficará R$ {:.2f},'
      ' \ne caso seja parcelado em 2x terá um reajuste de 13% e ficará R$ {:.2f}.'.format(produto,avista,parcelado))
print('-/-'*25)


'''
Problem Statement: Rotate Image

Link: https://leetcode.com/problems/rotate-image
Tags: ['Array']
Difficulty: Medium

You are given an n x n 2D matrix representing an image, rotate the image by 90 degrees (clockwise).
You have to rotate the image in-place, which means you have to modify the input 2D matrix directly. DO NOT allocate another 2D matrix and do the rotation.

Example 1:

Input: matrix = [[1,2,3],[4,5,6],[7,8,9]]
Output: [[7,4,1],[8,5,2],[9,6,3]]

Example 2:

Input: matrix = [[5,1,9,11],[2,4,8,10],[13,3,6,7],[15,14,12,16]]
Output: [[15,13,2,5],[14,3,4,1],[12,6,8,9],[16,7,10,11]]

Example 3:
Input: matrix = [[1]]
Output: [[1]]

Example 4:
Input: matrix = [[1,2],[3,4]]
Output: [[3,1],[4,2]]

Constraints:

matrix.length == n
matrix[i].length == n
1 <= n <= 20
-1000 <= matrix[i][j] <= 1000
'''

from typing import List

class Solution:
    def rotate(self, matrix: List[List[int]]) -> None:
        """
        Do not return anything, modify matrix in-place instead.
        """
        def printmat(mat):
            for row in mat:
                print(row)
            print()

        n = len(matrix)

        for i in range(0, n // 2):
            coords = [
                (i, i),
                (i, n - i - 1),
                (n - i - 1, n - i - 1),
                (n - i - 1, i)
            ]

            for j in range(i, n - i - 1):
                last_val = [
                    matrix[coords[0][0]][coords[0][1]],
                    matrix[coords[1][0]][coords[1][1]],
                    matrix[coords[2][0]][coords[2][1]],
                    matrix[coords[3][0]][coords[3][1]]
                ]

                for k in range(0, 4):
                    a2, b2 = coords[(k + 1) % 4]
                    matrix[a2][b2] = last_val[k]

                for k in range(0, 4):
                    a, b = coords[k]

                    if k == 0:
                        coords[k] = a, b + 1
                    elif k == 1:
                        coords[k] = a + 1, b
                    elif k == 2:
                        coords[k] = a, b - 1
                    else:
                        coords[k] = a - 1, b


import re
language = 'PythonC#JavaPHPC#'
# 查找后再替换
# r = re.sub('C#', 'GO', language, 0)
# 有0表示会无限匹配下去, 1表示值匹配1个
# 常规替换可以用replace

def convert(value):
    matched = value.group()
    return '!!' + matched + '!!'

# convert函数调用流程:
# 当正则表达式匹配到一个结果时,把匹配结果传给convert函数,convert返回结果用于替换.
r = re.sub('C#', convert, language)
print(r)


from sys import stdin, stdout

t=int(input())
while(t!=0):
  t-=1
  s = list(input())
  x1,y1 = map(int,input().split())
  q = int(input())
  sfreq = {}
  for i in s:
    sfreq[i] = sfreq.get(i, 0) + 1
  while(q!=0):
    q-=1
    x2,y2 = map(int,stdin.readline().split())
    t1 = x2 - x1
    t2 = y2 - y1
    count = 0
    found = 1
    if(t1 > 0):
      if(sfreq.get('R') and sfreq['R'] - t1 >= 0):
        count +=  t1
      else:
        found = 0
    elif(t1 < 0):
      if(sfreq.get('L') and sfreq['L'] + t1 >= 0):
        count -=  t1
      else:
        found = 0
    if(t2 > 0):
      if(sfreq.get('U') and sfreq['U'] - t2 >= 0):
        count +=  t2
      else:
        found = 0
    elif(t2 < 0):
      if(sfreq.get('D') and sfreq['D'] + t2 >= 0):
        count -=  t2
      else:
        found = 0
    if(found == 1):
      stdout.write("YES " + str(count) + '\n')
    else:
      stdout.write("NO" + '\n')


from django.shortcuts import render
from django.contrib.auth.decorators import login_required, user_passes_test
from restau.models import ActiveSetup, Fotos, Horario
from typing import Dict

@login_required
@user_passes_test(lambda user: user.groups.filter(
    name='acesso_restrito').exists())
def admin_home(request):

    return render(
        request,
        'restau/pages/admin_home.html',

    )

def index(request):

    galeria = Fotos.objects \
        .all() \
        .order_by('ordem') \

    active_setup = ActiveSetup.objects.get()

    horarios = Horario.objects.all()

    dict_horarios: Dict[str, int] = {
        'Segunda': 1,
        'Terça': 2,
        'Quarta': 3,
        'Quinta': 4,
        'Sexta': 5,
        'Sábado': 6,
        'Domingo': 7,
        'Feriados': 8,
    }

    horarios_ordenados = sorted(
        horarios,
        key=lambda x: dict_horarios.get(x.dia_semana, 0),  # type: ignore
    )

    return render(
        request,
        'restau/pages/index.html',
        {'active_setup': active_setup,
         'galeria': galeria,
         'horarios_ordenados': horarios_ordenados,
         },
    )


import numpy as np
import tensorflow as tf
from tensorflow.keras import Model
from tensorflow.keras.layers import Dense, Conv1D, Dropout
from tensorflow.keras.layers import Layer
from model.helper_layers import ShiftLayer, faro_shuffle, faro_shuffle_reverse, inv_sigmoid, instance_norm, gelu

n_log_images = 6

#
# This file contains the proposed neural architecture for the denoising factorization task
#

# Convolutional Shuffle Unit
class CSU(Layer):
    def __init__(self, kernel_width, residual_weight=0.9, droput_rate=0.0):
        super(CSU, self).__init__()
        self.kernel_width = kernel_width
        self.residual_weight = residual_weight
        self.drop = Dropout(droput_rate)
        self.lr_adjust = 10.

    def build(self, input_shape):
        num_units = input_shape[2]
        self.num_units = num_units
        self.middle_units = num_units * 4
        self.conv1 = Conv1D(self.middle_units, self.kernel_width, padding='same', name='conv1')
        self.dense3 = Dense(num_units, name='dense3')

        self.residual_scale_param = self.add_weight(name="residual_scale", shape=[num_units],
                                                    initializer=tf.constant_initializer(inv_sigmoid(self.residual_weight) / self.lr_adjust))
        self.rezero = self.add_weight(name="rezero", shape=[num_units], initializer=tf.zeros_initializer())

        return super().build(input_shape)

    def call(self, mem, training=False):
        mem_drop = self.drop(mem, training=training)
        mem_shuffled = faro_shuffle(mem_drop)
        mem_shuffled1 = faro_shuffle_reverse(mem_drop)

        mem_drop = tf.concat([mem_drop, mem_shuffled, mem_shuffled1], axis=-1)
        res = self.conv1(mem_drop)
        res = instance_norm(res)
        res1 = res
        res = gelu(res)
        res_middle = res
        candidate = self.dense3(res)
        if training: candidate += tf.random.normal(tf.shape(candidate), stddev=0.001, dtype=self.compute_dtype)

        residual_scale = tf.sigmoid(self.residual_scale_param * self.lr_adjust)
        output = residual_scale * mem + candidate * self.rezero

        return output, candidate, res_middle, res1

# Recurrent Convolutional Shuffle Unit
class RCSU(Model):
    def __init__(self, dropout_rate = 0.1):
        super().__init__()
        estimated_depth = 20
        residual_weight = np.exp(np.log(0.1) / estimated_depth)
        self.compute_layer = CSU(3, residual_weight, droput_rate=dropout_rate)

    def log_image(self, image, name):
        image *= tf.math.rsqrt(tf.reduce_mean(tf.square(image))+1e-6)
        tf.summary.image(name, tf.transpose(image * 0.25 + 0.5, [3, 0, 2, 1]), max_outputs=n_log_images)

    def call(self, x, training = False, log_in_tb = False):
        length = tf.shape(x)[1]
        n_bits = tf.cast(tf.round(tf.math.log(tf.cast(length, tf.float32))/tf.math.log(2.)), tf.int32)
        step_mem = tf.TensorArray(tf.float32, size=0, dynamic_size=True, clear_after_read=True)
        step_candidates = tf.TensorArray(tf.float32, size=0, dynamic_size=True, clear_after_read=True)
        gates = tf.TensorArray(tf.float32, size=0, dynamic_size=True, clear_after_read=True)
        gates1 = tf.TensorArray(tf.float32, size=0, dynamic_size=True, clear_after_read=True)
        log_in_tb = log_in_tb and training and tf.summary.experimental.get_step()%100==0
        step_mem = step_mem.write(0, tf.cast(x[0:1, :, 0:n_log_images], tf.float32))

        depth = tf.maximum(length//2, n_bits*4)
        for i in range(depth):
            x, candidate, gate, res1 = self.compute_layer(x, training = training)
            step_mem = step_mem.write(i+1, tf.cast(x[0:1, :, 0:n_log_images], tf.float32))
            step_candidates = step_candidates.write(i, tf.cast(candidate[0:1, :, 0:n_log_images], tf.float32))
            gates = gates.write(i, tf.cast(gate[0:1, :, 0:n_log_images], tf.float32))
            gates1 = gates1.write(i, tf.cast(res1[0:1, :, 0:n_log_images], tf.float32))

        mem_all = step_mem.stack()
        step_candidates = step_candidates.stack()
        gates = gates.stack()
        gates1 = gates1.stack()

        if log_in_tb:
            self.log_image(mem_all, "mem")
            self.log_image(step_candidates, "cand")
            self.log_image(gates, "res_middle1")
            tf.summary.histogram("last_mem", x[0])
            tf.summary.histogram("res_middle", gates1)
        return x


# Week 6 - Assignment 1
# Links: http://py4e-data.dr-chuck.net/comments_42.json, http://py4e-data.dr-chuck.net/comments_869371.json

import urllib.request, urllib.parse, urllib.error
import json

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter location: ')
print("Retrieving ", url)

connection = urllib.request.urlopen(url, context=ctx)
url_info   = connection.read().decode()
print("Retrieved ",len(url_info)," characters")

info = json.loads(url_info)
# print(json.dumps(info, indent=2))

count = 0
sum_  = 0
for item in info["comments"]:
    sum_  += int(item['count'])
    count += 1

print("Count: ", count)
print("Sum: ", sum_)


import numpy as np
import tensorflow as tf
from tensorflow import keras
import matplotlib.pyplot as plt

mnist = tf.keras.datasets.mnist

(_, _), (x_test, y_test) = mnist.load_data()

# we can check how many number 0, 1

# print(np.count_nonzero(y_train==0)) # 5923
# print(np.count_nonzero(y_train==1)) # 6742

# extract  0 and 1

mask_01_test = []

for i, label in enumerate(y_test):
    if label == 0 or label == 1:
        mask_01_test.append(i)

x_test = x_test[mask_01_test]
y_test = y_test[mask_01_test]

# make reverse train and test image ( reverse mean [255 - image])
x_test_re = (255 - x_test)

# concatenate org image and reversed image
x_test = np.concatenate((x_test, x_test_re),axis=0)

y_test = np.concatenate((y_test, y_test), axis=0)

# make label for multi label image classification

test_zeros = np.zeros((len(y_test)//2))
test_ones = np.ones((len(y_test)//2))
test_zeros_and_ones = np.concatenate((test_zeros, test_ones), axis=0)

test_zeros_and_ones = test_zeros_and_ones.reshape(len(test_zeros_and_ones), 1)
y_test = y_test.reshape(len(y_test), 1)

y_test = np.concatenate((y_test, test_zeros_and_ones), axis=1)

# 0 to 1
x_test =  x_test / 255.0

# data shuffle
random_test = np.array(range(len(y_test)))
np.random.shuffle(random_test)

x_test = x_test[random_test]
y_test = y_test[random_test]

x_test = x_test.reshape(len(x_test), 28, 28, 1)

# image check

# for i in range(10):
#     print(y_test[i])
#     plt.imshow(x_test[i, :, :, 0])
#     plt.colorbar()
#     plt.show()

model = keras.models.load_model("mnist_test_model.h5")
model.evaluate(x_test, y_test)