aa=input()
aa2=list(map(int,input().split()))
c=d=0
for i in range(0,len(aa2)+1):
    if(i==aa2[i]):
        c=c+1
    else:
        d=d+1
        break
if(d>=1):
    print(d)


from __future__ import annotations

import abc
from collections import ChainMap
from typing import Any, ClassVar, Optional, Type, TypeVar

import attr

from basic_notion import exc
from basic_notion.utils import set_to_dict, del_from_dict

def _get_attr_keys_for_cls(
        members: dict[str, Any],
        only_editable: bool = False,
        only_derived: bool = False,
) -> dict[str, tuple[str, ...]]:
    from basic_notion.attr import ItemAttrDescriptor

    result: dict[str, tuple[str, ...]] = dict()
    for name, prop in members.items():
        if not isinstance(prop, ItemAttrDescriptor):
            continue
        if only_editable and not prop.editable:
            continue
        if only_derived and not prop.derived:
            continue
        attr_key: tuple[str, ...]
        try:
            attr_key = prop.key
        except AttributeError:
            attr_key = (name,)
        result[name] = attr_key

    return result

class NotionItemBaseMetaclass(abc.ABCMeta):
    # abc.ABCMeta is needed here for the abc.ABC functionality

    """Metaclass that adds ``__notion_attr_keys__`` to all ``NotionItemBase`` subclasses"""

    def __new__(cls, name: str, bases: tuple[type, ...], dct: dict):
        attr_keys_name = '__notion_attr_keys__'
        editable_keys_name = '__notion_editable_keys__'
        derived_keys_name = '__notion_derived_keys__'
        base_attr_key_maps = tuple(
            getattr(base, attr_keys_name)  # type: ignore
            for base in bases if type(base) is cls
        )
        base_editable_key_maps = tuple(
            getattr(base, editable_keys_name)  # type: ignore
            for base in bases if type(base) is cls
        )
        base_derived_key_maps = tuple(
            getattr(base, derived_keys_name)  # type: ignore
            for base in bases if type(base) is cls
        )
        attr_keys = dict(ChainMap(_get_attr_keys_for_cls(dct), *base_attr_key_maps))
        editable_keys = dict(ChainMap(_get_attr_keys_for_cls(dct, only_editable=True), *base_editable_key_maps))
        derived_keys = dict(ChainMap(_get_attr_keys_for_cls(dct, only_derived=True), *base_derived_key_maps))
        # Added to __dict__
        dct[attr_keys_name] = attr_keys
        dct[editable_keys_name] = editable_keys
        dct[derived_keys_name] = derived_keys
        new_cls = super().__new__(cls, name, bases, dct)
        return new_cls

_ITEM_TV = TypeVar('_ITEM_TV', bound='NotionItemBase')

@attr.s(slots=True)
class NotionItemBase(metaclass=NotionItemBaseMetaclass):
    __notion_attr_keys__: dict[str, tuple[str, ...]] = None  # type: ignore  # defined in metaclass
    __notion_editable_keys__: dict[str, tuple[str, ...]] = None  # type: ignore  # defined in metaclass
    __notion_derived_keys__: dict[str, tuple[str, ...]] = None  # type: ignore  # defined in metaclass

    OBJECT_TYPE_KEY_STR: ClassVar[str] = ''
    OBJECT_TYPE_STR: ClassVar[str] = ''

    _data: Optional[dict[str, Any]] = attr.ib(kw_only=True, default=None)

    @classmethod
    @property
    def attr_keys(cls) -> dict[str, tuple[str, ...]]:
        return cls.__notion_attr_keys__

    @classmethod
    @property
    def editable_keys(cls) -> dict[str, tuple[str, ...]]:
        return cls.__notion_editable_keys__

    @classmethod
    @property
    def derived_keys(cls) -> dict[str, tuple[str, ...]]:
        return cls.__notion_derived_keys__

    @property
    def data(self) -> dict:
        if self._data is None:
            raise exc.ItemHasNoData(f'Object {type(self).__name__} has no data')
        return self._data

    @classmethod
    def _make_inst_attr_dict(cls, kwargs: dict[str, Any]) -> dict:
        data: dict[str, Any] = {}
        for name, key in cls.editable_keys.items():  # type: ignore
            if name not in kwargs:
                continue

            value = kwargs[name]

            # Get attr descriptor and its `set_converter` callable
            # (if it exists) to convert the value into its serializable form
            prop = getattr(cls, name)
            set_converter = prop.set_converter
            if set_converter is not None:
                value = set_converter(value)

            set_to_dict(data, key, value)

        return data

    @classmethod
    def _make_inst_dict(cls, kwargs: dict[str, Any]) -> dict:
        data = {}
        if cls.OBJECT_TYPE_KEY_STR and cls.OBJECT_TYPE_STR:
            data[cls.OBJECT_TYPE_KEY_STR] = cls.OBJECT_TYPE_STR

        data.update(cls._make_inst_attr_dict(kwargs))
        return data

    @classmethod
    def make(cls: Type[_ITEM_TV], **kwargs: Any) -> _ITEM_TV:
        """Generate instance from attributes"""
        data = cls._make_inst_dict(kwargs)
        return cls(data=data)

    def clear_derived_attrs(self) -> None:
        for name, other_key in self.attr_keys.items():
            if name in self.derived_keys:
                # Is not editable
                del_from_dict(self.data, other_key)


import matplotlib.pyplot as plt
import numpy as np
k=9.0e9
q=1.9e-19
d=1.0e1
t=np.linspace(0,2*np.pi,10000)
i=1
V=V=(3*k*q*(d**2)/(2*(i**3)))*np.cos(2*t)
plt.plot(t,V,color='black')
plt.xlabel('theta')
plt.ylabel('Potential')
plt.show()


from django.conf.urls import patterns, include, url
from django.contrib.staticfiles.urls import staticfiles_urlpatterns

from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', 'yj.views.home'),
    url(r'^api/', include('api.urls')),

    # Include an application:
    # url(r'^app_name/', include('app_name.urls', namespace="app_name")),

    url(r'^admin/', include(admin.site.urls)),
)

urlpatterns += staticfiles_urlpatterns()


from scipy.io.wavfile import read, write
import io
import matplotlib.pyplot as plt
## This may look a bit intricate/useless, considering the fact that scipy's read() and write() function already return a
## numpy ndarray, but the BytesIO "hack" may be useful in case you get the wav not through a file, but trough some websocket or
## HTTP Post request. This should obviously work with any other sound format, as long as you have the proper decoding function

with open("gn.wav", "rb") as wavfile:
    input_wav = wavfile.read()

# here, input_wav is a bytes object representing the wav object
rate, data = read(io.BytesIO(input_wav))

# data is a numpy ND array representing the audio data. Let's do some stuff with it
reversed_data = data[::-1] #reversing it
print(reversed_data.shape)

plt.plot(reversed_data)
plt.show()
#then, let's save it to a BytesIO object, which is a buffer for bytes object
bytes_wav = bytes()
byte_io = io.BytesIO(bytes_wav)
write(byte_io, rate, reversed_data)

output_wav = byte_io.read()


# Counting element
# Given an integer array, count element x such that x + 1 is also in array.If there're duplicates in array, count them separately.

#    Example 1:
#         Input: {1, 2, 3}
#         Output: 2
#            Explanation:
#             First element is 1 + 1 = 2 (2 is present in an array)
#             Second element is 2 + 1 = 3 (3 is present in an array)
#             Third element is 3 + 1 = 4 (4 is not present in an array)
#
#     Example 2:
#         Input: {1, 1, 3, 3, 5, 5, 7, 7}
#         Output: 0
#
#     Example 3:
#         Input: {1, 3, 2, 3, 5, 0}
#         Output: 3
#         Explanation:
#             1 + 1 = 2 (Exist)
#             3 + 1 = 4 (Not exist)
#             2 + 1 = 3 (Exist)
#             3 + 1 = 4 (Not exist)
#             5 + 1 = 6 (Not exist)
#             0 + 1 = 1 (Exist)
#
#     Example 4:
#       Input: {1, 1, 2, 2}
#       Output: 2

from collections import defaultdict

class Solution(object):
    def countElements(self, arr):

        number_dictionary = defaultdict(int)
        count = 0

        for num in arr:
            number_dictionary[num] += 1

        for num in number_dictionary:
            count += number_dictionary.get(num-1, 0)

        return count


# included from libs/mincostflow.py
"""
Min Cost Flow

"""

# derived: https://atcoder.jp/contests/practice2/submissions/16726003
from heapq import heappush, heappop

class MinCostFlow():
    def __init__(self, n):
        self.n = n
        self.graph = [[] for _ in range(n)]
        self.pos = []

    def add_edge(self, fr, to, cap, cost):
        #assert 0 <= fr < self.n
        #assert 0 <= to < self.n
        m = len(self.pos)
        self.pos.append((fr, len(self.graph[fr])))
        self.graph[fr].append([to, len(self.graph[to]), cap, cost])
        self.graph[to].append([fr, len(self.graph[fr]) - 1, 0, -cost])
        return m

    def get_edge(self, idx):
        #assert 0 <= idx < len(self.pos)
        to, rev, cap, cost = self.graph[self.pos[idx][0]][self.pos[idx][1]]
        _rev_to, _rev_rev, rev_cap, _rev_cost = self.graph[to][rev]
        return self.pos[idx][0], to, cap + rev_cap, rev_cap, cost

    def edges(self):
        for i in range(len(self.pos)):
            yield self.get_edge(i)

    def dual_ref(self, s, t):
        dist = [2**63 - 1] * self.n
        dist[s] = 0
        vis = [0] * self.n
        self.pv = [-1] * self.n
        self.pe = [-1] * self.n
        queue = []
        heappush(queue, (0, s))
        while queue:
            k, v = heappop(queue)
            if vis[v]:
                continue
            vis[v] = True
            if v == t:
                break
            for i in range(len(self.graph[v])):
                to, _rev, cap, cost = self.graph[v][i]
                if vis[to] or cap == 0:
                    continue
                cost += self.dual[v] - self.dual[to]
                if dist[to] - dist[v] > cost:
                    dist[to] = dist[v] + cost
                    self.pv[to] = v
                    self.pe[to] = i
                    heappush(queue, (dist[to], to))
        if not vis[t]:
            return False
        for v in range(self.n):
            if not vis[v]:
                continue
            self.dual[v] -= dist[t] - dist[v]
        return True

    def flow(self, s, t):
        return self.flow_with_limit(s, t, 2**63 - 1)

    def flow_with_limit(self, s, t, limit):
        return self.slope_with_limit(s, t, limit)[-1]

    def slope(self, s, t):
        return self.slope_with_limit(s, t, 2**63 - 1)

    def slope_with_limit(self, s, t, limit):
        #assert 0 <= s < self.n
        #assert 0 <= t < self.n
        #assert s != t
        flow = 0
        cost = 0
        prev_cost = -1
        res = [(flow, cost)]
        self.dual = [0] * self.n
        while flow < limit:
            if not self.dual_ref(s, t):
                break
            c = limit - flow
            v = t
            while v != s:
                c = min(c, self.graph[self.pv[v]][self.pe[v]][2])
                v = self.pv[v]
            v = t
            while v != s:
                _to, rev, _cap, _ = self.graph[self.pv[v]][self.pe[v]]
                self.graph[self.pv[v]][self.pe[v]][2] -= c
                self.graph[v][rev][2] += c
                v = self.pv[v]
            d = -self.dual[s]
            flow += c
            cost += c * d
            if prev_cost == d:
                res.pop()
            res.append((flow, cost))
            prev_cost = cost
        return res

# end of libs/mincostflow.py

# included from snippets/main.py

def debug(*x, msg=""):
    import sys
    print(msg, *x, file=sys.stderr)

def solve(N, M, AS, BS, RS):
    global mcf
    INF = 10 ** 5
    mcf = MinCostFlow(N + 5)
    start = N
    goal = N + 1
    round = N + 2
    for i in range(3):
        mcf.add_edge(start, round + i, M, 0)

    for i in range(3):
        for j in range(N):
            r = AS[j] * (BS[j] ** (i + 1)) % RS[i]
            mcf.add_edge(round + i, j, 1, INF - r)

    for j in range(N):
        cs = [AS[j] * (BS[j] ** (k + 1)) for k in range(3)]
        cs.append(0)
        for k in range(3):
            c = cs[k] - cs[k-1]
            mcf.add_edge(j, goal, 1, c)

    return INF * (3 * M) - mcf.flow(start, goal)[-1]

def main():
    # parse input
    N, M = map(int, input().split())
    AS = list(map(int, input().split()))
    BS = list(map(int, input().split()))
    RS = list(map(int, input().split()))
    print(solve(N, M, AS, BS, RS))

# tests
T1 = """
2 1
3 2
3 3
100000 100000 100000
"""
TEST_T1 = """
>>> as_input(T1)
>>> main()
81
"""

T2 = """
4 2
2 4 3 3
4 2 3 3
100000 100000 100000
"""
TEST_T2 = """
>>> as_input(T2)
>>> main()
210
"""

T3 = """
20 19
3 2 3 4 3 3 2 3 2 2 3 3 4 3 2 4 4 3 3 4
2 3 4 2 4 3 3 2 4 2 4 3 3 2 3 4 4 4 2 2
3 4 5
"""
TEST_T3 = """
>>> as_input(T3)
>>> main()
-1417
"""

def _test():
    import doctest
    doctest.testmod()
    g = globals()
    for k in sorted(g):
        if k.startswith("TEST_"):
            print(k)
            doctest.run_docstring_examples(g[k], g, name=k)

def as_input(s):
    "use in test, use given string as input file"
    import io
    f = io.StringIO(s.strip())
    g = globals()
    g["input"] = lambda: bytes(f.readline(), "ascii")
    g["read"] = lambda: bytes(f.read(), "ascii")

if __name__ == "__main__":
    import sys
    input = sys.stdin.buffer.readline
    read = sys.stdin.buffer.read
    sys.setrecursionlimit(10 ** 6)
    if sys.argv[-1] == "-t":
        print("testing")
        _test()
        sys.exit()
    main()
    sys.exit()

# end of snippets/main.py


"""
A script to extract IuPS addresses from an RNC CMExport file
Works with Huawei RNC CMExport

By Tubagus Rizal
2017
"""

import xml.etree.ElementTree as ET
import glob
import pdb

def getRncInfo(xmlroot):
    # get RNC info
    rnc = {}
    for rncInfo in xmlroot.findall(".//*[@className='BSC6900UMTSNE']/attr"):
        if rncInfo.attrib["name"] == "fdn":
            rnc["fdn"] = rncInfo.text

        if rncInfo.attrib["name"] == "name":
            rnc["name"] = rncInfo.text

        if rncInfo.attrib["name"] == "neID":
            rnc["neid"] = rncInfo.text
    return rnc

def getIuPSIpAddress(xmlroot):
    # get a list of IuPS interface
    iupsIpAddr = []
    for ipPath in xmlroot.findall(".//*[@className='BSC6900UMTSIPPATH']/attr"):
        if ipPath.attrib["name"] == "IPADDR":
            ipAddress = ipPath.text

        if ipPath.attrib["name"] == "ITFT" and ipPath.text == "IUPS":
            if not ipAddress in iupsIpAddr:
                iupsIpAddr.append(ipAddress)
    return iupsIpAddr

def main():
    xmlFolder = "D:\\1000-MyDocuments\\100-Projects\\098-ProximusCFT\\TAADisttributor\\3G-OSS"
    xmlFiles = [file for file in glob.glob(xmlFolder + "/**/*.xml", recursive=True)]
    for xmlFile in xmlFiles:
        tree = ET.parse(xmlFile)
        root = tree.getroot()

        #print result
        rnc = getRncInfo(root)
        for key, value in rnc.items():
            print (key, value, ",", end=" ")

        iupsIpAddr = getIuPSIpAddress(root)
        for item in iupsIpAddr:
            print ( "IuPS: ", item,  end=" ")

        print("\n")

if __name__ == "__main__":
    main()


chicken_orders = int(input())
fish_orders = int(input())
veg_orders = int(input())
delivery_fee = 2.50

chicken_meal = 10.35
fish_meal = 12.40
veg_meal = 8.15

food_price = (chicken_orders * chicken_meal) + (fish_orders * fish_meal) + (veg_orders * veg_meal)
dessert = food_price * 0.20

full_cost = food_price + dessert + delivery_fee

print(full_cost)


def ustr(value):
    """This method is similar to the builtin `str` method, except
    it will return Unicode string.

    @param value: the value to convert

    @rtype: unicode
    @return: unicode string
    """

    if isinstance(value, unicode):
        return value

    if hasattr(value, '__unicode__'):
        return unicode(value)

    if not isinstance(value, str):
        value = str(value)

    return unicode(value, 'utf-8')

__builtins__['ustr'] = ustr

# vim: ts=4 sts=4 sw=4 si et


import os, sys
import subprocess
import json
import uproot
import awkward as ak

from coffea import processor, util, hist
from coffea.nanoevents import NanoEventsFactory, NanoAODSchema
from boostedhiggs import HbbPlotProcessor

from distributed import Client
from lpcjobqueue import LPCCondorCluster

from dask.distributed import performance_report
from dask_jobqueue import HTCondorCluster, SLURMCluster

env_extra = [
    f"export PYTHONPATH=$PYTHONPATH:{os.getcwd()}",
]

cluster = LPCCondorCluster(
    transfer_input_files=["boostedhiggs"],
    ship_env=True,
    memory="8GB",
    image="coffeateam/coffea-dask:0.7.11-fastjet-3.3.4.0rc9-ga05a1f8"
)
cluster.adapt(minimum=1, maximum=50)
client = Client(cluster)

print("Waiting for at least one worker...")  # noqa
client.wait_for_workers(1)

year = sys.argv[1]

with performance_report(filename="dask-report.html"):

    # get list of input files
    infiles = subprocess.getoutput("ls infiles/"+year+"*.json").split()

    for this_file in infiles:

        if "bsm" in this_file:
            continue

        index = this_file.split("_")[1].split(".json")[0]
        print(this_file, index)

        if "qcd" in index or "higgs" in index or "data" in index or 'top' in index:
            continue

        uproot.open.defaults["xrootd_handler"] = uproot.source.xrootd.MultithreadedXRootDSource

        p = HbbPlotProcessor(year=year,jet_arbitration='ddb')
        args = {'savemetrics':True, 'schema':NanoAODSchema}

        output = processor.run_uproot_job(
            this_file,
            treename="Events",
            processor_instance=p,
            executor=processor.dask_executor,
            executor_args={
                "client": client,
                #            "skipbadfiles": args.skipbadfiles,
                "schema": processor.NanoAODSchema,
                "retries": 50,
            },
            chunksize=100000,
            #        maxchunks=args.max,
        )

        outfile = 'outfiles-plots/'+str(year)+'_dask_'+index+'.coffea'
        util.save(output, outfile)


import os
import csv
import sqlite3

DATA_DIR="data"
DATABASE="database.db"

sensors = {
    "dht22": {
        "table": "temperaturUndLuftdruck",
        "mapping": {
            "sensor_id": "SensorID",
            "timestamp": "datetime",
            "humidity": "luftwert",
            "temperature": "tempwert"
        }
    },
    "sds011": {
        "table": "feinstaubsensor",
        "mapping": {
            "sensor_id": "SensorID",
            "timestamp": "datetime",
            "P1": "p1wert",
            "P2": "p2wert"
        }
    }
}

def main():
    if not os.path.isdir(DATA_DIR):
        print("Daten wurden nicht heruntergeladen")
        return

    count = 0
    con = sqlite3.connect(DATABASE)

    for sensor, conf in sensors.items():
        table = conf["table"]
        mapping = conf["mapping"]
        mapping_count = len(mapping)

        with open("schema/{}.sql".format(table), "r") as schema:
            schema = schema.read()
            cur = con.cursor()
            try:
                cur.executescript(schema)
            except sqlite3.OperationalError:
                pass

        TABLE_PLACEHOLDERS = ", ".join(mapping.values())
        VALUE_PLACEHOLDER = ", ".join([":{}".format(key) for key in mapping.keys()])

        QUERY = """
INSERT OR IGNORE
INTO {0}({1})
VALUES ({2})
""".format(table, TABLE_PLACEHOLDERS, VALUE_PLACEHOLDER)

        for root, dirs, files in os.walk("{}/{}".format(DATA_DIR, sensor)):
            for name in files:
                if not name.endswith(".csv"):
                    continue

                full_name = "{}/{}".format(root, name)

                with open(full_name, "r") as raw_data:
                    data = csv.DictReader(raw_data, delimiter=";")
                    data = list(data)

                    cur = con.cursor()
                    cur.executemany(QUERY, data)

    con.commit()
    con.close()

if __name__ == "__main__":
    main()


""""
Для заданного набора N точек на плоскости найти прямоугольник минимальной площади,
содержащий все указанные точки.
Стороны прямоугольника не обязаны быть параллельными координатным осям
"""
# important functions: MinimumBoundingBox

from scipy.spatial import ConvexHull
from math import sqrt,atan2
import numpy as np
from math import atan2, cos, sin, pi
from collections import namedtuple
import matplotlib.pyplot as plt
from min_square import Point

def unit_vector(pt0, pt1):
    dis_0_to_1 = sqrt((pt0[0] - pt1[0])**2 + (pt0[1] - pt1[1])**2)
    return (pt1[0] - pt0[0]) / dis_0_to_1, \
           (pt1[1] - pt0[1]) / dis_0_to_1

def orthogonal_vector(vector):
    return -1 * vector[1], vector[0]

def bounding_area(index, hull):
    unit_vector_p = unit_vector(hull[index], hull[index+1])
    unit_vector_o = orthogonal_vector(unit_vector_p)

    dis_p = tuple(np.dot(unit_vector_p, pt) for pt in hull)
    dis_o = tuple(np.dot(unit_vector_o, pt) for pt in hull)

    min_p = min(dis_p)
    min_o = min(dis_o)
    len_p = max(dis_p) - min_p
    len_o = max(dis_o) - min_o

    return {'area': len_p * len_o,
            'length_parallel': len_p,
            'length_orthogonal': len_o,
            'rectangle_center': (min_p + len_p / 2, min_o + len_o / 2),
            'unit_vector': unit_vector_p,
            }

def to_xy_coordinates(unit_vector_angle, point):
    angle_orthogonal = unit_vector_angle + pi / 2
    return point[0] * cos(unit_vector_angle) + point[1] * cos(angle_orthogonal), \
           point[0] * sin(unit_vector_angle) + point[1] * sin(angle_orthogonal)

def rotate_points(center_of_rotation, angle, points):

    rot_points = []
    ang = []
    for pt in points:
        diff = tuple([pt[d] - center_of_rotation[d] for d in range(2)])
        diff_angle = atan2(diff[1], diff[0]) + angle
        ang.append(diff_angle)
        diff_length = sqrt(sum([d**2 for d in diff]))
        rot_points.append((center_of_rotation[0] + diff_length * cos(diff_angle),
                           center_of_rotation[1] + diff_length * sin(diff_angle)))

    return rot_points

def rectangle_corners(rectangle):
    corner_points = []
    for i1 in (.5, -.5):
        for i2 in (i1, -1 * i1):
            corner_points.append((rectangle['rectangle_center'][0] + i1 * rectangle['length_parallel'],
                            rectangle['rectangle_center'][1] + i2 * rectangle['length_orthogonal']))

    return rotate_points(rectangle['rectangle_center'], rectangle['unit_vector_angle'], corner_points)

BoundingBox = namedtuple('BoundingBox', ('area',
                                         'length_parallel',
                                         'length_orthogonal',
                                         'rectangle_center',
                                         'unit_vector',
                                         'unit_vector_angle',
                                         'corner_points'
                                        )
)

# use this function to find the listed properties of the minimum bounding box of a point cloud
def MinimumBoundingBox(points):
    # Requires: points to be a list or tuple of 2D points. ex: ((5, 2), (3, 4), (6, 8))
    #           needs to be more than 2 points
    # Effects:  returns a namedtuple that contains:
    #               area: area of the rectangle
    #               length_parallel: length of the side that is parallel to unit_vector
    #               length_orthogonal: length of the side that is orthogonal to unit_vector
    #               rectangle_center: coordinates of the rectangle center
    #                   (use rectangle_corners to get the corner points of the rectangle)
    #               unit_vector: direction of the length_parallel side. RADIANS
    #                   (it's orthogonal vector can be found with the orthogonal_vector function
    #               unit_vector_angle: angle of the unit vector
    #               corner_points: set that contains the corners of the rectangle

    if len(points) <= 2: raise ValueError('More than two points required.')

    hull_ordered = [points[index] for index in ConvexHull(points).vertices]
    hull_ordered.append(hull_ordered[0])
    hull_ordered = tuple(hull_ordered)

    min_rectangle = bounding_area(0, hull_ordered)
    for i in range(1, len(hull_ordered)-1):
        rectangle = bounding_area(i, hull_ordered)
        if rectangle['area'] < min_rectangle['area']:
            min_rectangle = rectangle

    min_rectangle['unit_vector_angle'] = atan2(min_rectangle['unit_vector'][1], min_rectangle['unit_vector'][0])
    min_rectangle['rectangle_center'] = to_xy_coordinates(min_rectangle['unit_vector_angle'], min_rectangle['rectangle_center'])

    # this is ugly but a quick hack and is being changed in the speedup branch
    return BoundingBox(
        area = min_rectangle['area'],
        length_parallel = min_rectangle['length_parallel'],
        length_orthogonal = min_rectangle['length_orthogonal'],
        rectangle_center = min_rectangle['rectangle_center'],
        unit_vector = min_rectangle['unit_vector'],
        unit_vector_angle = min_rectangle['unit_vector_angle'],
        corner_points = set(rectangle_corners(min_rectangle))
    )

if __name__ =='__main__':
    points = []
    for _ in range(int(input('Count points\n'))):
        # points.append(Point.create_point())  # для мануального ввода точек многогранника
        points.append(Point().get_tuple_style())
    rectangle = MinimumBoundingBox(points).corner_points
    rectangle = sorted(rectangle, key=lambda p: atan2(p[1], p[0]))
    print(rectangle)
    print([Point(p[0], p[1]).__str__('blue') for p in points])
    plt.fill(
        [p[0] for p in rectangle],
        [p[1] for p in rectangle],
        fill=False
    )
    plt.show()


import matplotlib.pyplot as plt
import seaborn as sns
from table import create_table
import pandas as pd
import streamlit as st
import plotly.tools as tls
import plotly.figure_factory as ff
import numpy as np
import plotly.express as px
from download import report_downlaoder

import os
st.image('Somaiya Header.png',width=500)
st.title('Result analysis')
st.subheader('KJ somaiya institute of engineering and IT')
st.sidebar.title('Welcome to the result analyser App')
st.sidebar.markdown(' You can Do Visual or Database analysis as you wish after filling the parameters select as required '
                    ,unsafe_allow_html=True)
Analyse_type=st.sidebar.radio('Analyser',('Visual','Database Analyser','Reports'))

filename = st.text_input('Enter a file path:','Sem4.pdf')
Semester=st.text_input("Enter the No of semester",4)
Subject_no =st.text_input("enter the number of subjects",5)
Labs_no =st.text_input("enter the number of Labs",5)

@st.cache(persist=True)
def load_data():
    theory_df,pracs_df=create_table(filename,Subject_no,Labs_no)
    return theory_df,pracs_df

cleandf=load_data()[0]
pracsdf=load_data()[1]

#pie chart
explode=[0.1,0]
colours=['lightgreen','Red']
fig=px.pie(cleandf,labels=['Pass','Fail'],names='Pass/fail',title='Passing and failing percentage')

if Analyse_type=='Visual':
    #Pie chart
    st.markdown('
Pie chart
',unsafe_allow_html=True)
    #fig=cleandf['Pass/fail'].value_counts().plot(kind='pie',labels=['pass','fail'],autopct='%1.1f%%',startangle=140,
    #                                       explode=explode,shadow=True,colors=colours,figsize=(5,5))
    st.plotly_chart(fig)

    #Bar chart
    st.markdown('
Bar charts
',unsafe_allow_html=True)
    plt.style.use('bmh')
    colors=['green','slateblue','mediumorchid','gold','darkorange','coral','yellow']
    k=1
    for i in range(int(Subject_no)):
        fig=plt.figure()
        #cleandf.iloc[:,k].plot(kind='hist',bins=3,color=colors[k])
        sns.distplot(cleandf.iloc[:,k],color=colors[k],norm_hist=True)
        plt.xlabel(f'Marks in {cleandf.columns[k]}')
        plt.ylabel('No of students')
        try:
            plotly_fig = tls.mpl_to_plotly(fig)
        except:
            subject=cleandf.columns[k]
            plotly_fig=px.histogram(cleandf,x=subject,histnorm='probability density',opacity=0.8,title=f'Marks in {cleandf.columns[k]}',color_discrete_sequence=['indianred'] )
        st.plotly_chart(plotly_fig)
        k=k+1
        if(k>int(Subject_no)):
            break

    #Bar chart Pracicals
    st.markdown('
Bar charts for practicals
',unsafe_allow_html=True)
    plt.style.use('bmh')
    colors=['green','slateblue','mediumorchid','gold','darkorange','coral','yellow']
    k=1
    for i in range(int(Subject_no)):
        fig=plt.figure()
        #cleandf.iloc[:,k].plot(kind='hist',bins=3,color=colors[k])
        sns.distplot(pracsdf.iloc[:,k],color=colors[k],norm_hist=True)
        plt.xlabel(f'Marks in {pracsdf.columns[k]}')
        plt.ylabel('No of students')
        try:
            plotly_fig = tls.mpl_to_plotly(fig)
        except:
            subject=pracsdf.columns[k]
            plotly_fig=px.histogram(pracsdf,x=subject,histnorm='probability density',opacity=0.8,title=f'Marks in {pracsdf.columns[k]}',color_discrete_sequence=['indianred'] )
        st.plotly_chart(plotly_fig)
        k=k+1
        if(k>int(Subject_no)):
            break

#Database
if Analyse_type=='Database Analyser':
    st.markdown('
Database Analysis
',
                 unsafe_allow_html=True)
    from database import create_database,query_execute
    create_database(cleandf,pracsdf,Semester)
    st.subheader(f'SQL Theory table for sem {Semester}' )
    query=st.text_input("enter a query for the sql databse",f'SELECT * FROM Sem_{Semester}_theory_results')
    #query=f'SELECT * FROM Sem_{Semester}_theory_results
    output=query_execute(query)
    st.dataframe(output)

    st.subheader(f'SQL practical table for sem {Semester}')
    query=st.text_input("enter a query for the sql databse",f'SELECT * FROM Sem_{Semester}_pracs_results')
    #query=f'SELECT * FROM Sem_{Semester}_pracs_results'
    output_pracs=query_execute(query)
    st.dataframe(output_pracs)

if Analyse_type=='Reports':
    #First class
    st.markdown('
First class students
',
                unsafe_allow_html=True)
    FC=cleandf[cleandf['CGPA']>=7.75]
    fc_students=FC.shape[0]
    st.dataframe(FC)
    st.write(f' There are {fc_students} students in first class')

    #Second class
    st.markdown('
Second class students
',
                unsafe_allow_html=True)
    SC=cleandf[(cleandf['CGPA']>=6.75) & (cleandf['CGPA']<=7.74)]
    st.dataframe(SC)
    sc_students=SC.shape[0]
    st.write(f' There are {sc_students}  students in second class')
    #pass class
    st.markdown('
pass class students
',
                unsafe_allow_html=True)
    PC=cleandf[(cleandf['CGPA']>=4.00) & (cleandf['CGPA']<=5.74)]
    st.dataframe(PC)
    pc_students=PC.shape[0]
    st.write(f' There are {pc_students}  students in pass class')

    #Top 5 scorers
    st.markdown('
Toppers
',
                unsafe_allow_html=True)
    no_students = st.number_input('Number of students ', 6)
    column = 'CGPA'
    column=st.selectbox('select an attribute',
                 tuple(cleandf.columns[1:])
    )

    bottom = False
    toppers = cleandf[column].sort_values(ascending=bottom).values
    toppers_report = cleandf[cleandf[column].isin(toppers)].sort_values(by=[column], ascending=False)
    st.dataframe(toppers_report)

    report = report_downlaoder(FC,SC,PC,toppers_report,fig)
    st.sidebar.subheader('Click On reports to generate a report and get an option to download one')
    st.sidebar.markdown(report,unsafe_allow_html=True)


from decouple import config
from logic import bet

My_Money = int(config('MY_MONEY'))
while True:
    print('you have ' + str(My_Money))
    print('do you wanna play? (yes or no)')
    a = input('')
    if a.strip() == 'no':
        print('you are out of the game')
        break
    elif a.strip() == 'yes':
        b = int(input('guess the number from 1 to 30 '))
        g = int(input('your bet '))
        My_Money -= g
        My_Money += bet(b, g)
        #cvbnjmk

    else:
        print('yes or no')


import mailchimp_marketing as MailchimpMarketing
from mailchimp_marketing.api_client import ApiClientError

def survey_monkey_distribute_daily(**kwargs):
  api_key = kwargs['api_key']
  server = kwargs['server']

  try:
    client = MailchimpMarketing.Client()
    client.set_config({
      "api_key": api_key,
      "server": server
    })
    response = client.ping.get()
    print(response)
  except ApiClientError as error:
    print(error)

  x = client.campaigns.replicate('df4d22a9b2')['id']
  client.campaigns.send(x)


# -*- coding: utf-8 -*-
import itertools
import struct

import pytest
from mock import Mock, call, patch

from nameko_grpc.errors import GrpcError
from nameko_grpc.streams import (
    STREAM_END,
    ByteBuffer,
    ReceiveStream,
    SendStream,
    StreamBase,
)

class TestByteBuffer:
    def test_peek(self):
        buffer = ByteBuffer()
        buffer.write(b"abcdefghi")

        assert buffer.peek(slice(0, 1)) == b"a"
        assert buffer.peek(slice(3, 6)) == b"def"
        assert buffer.peek(slice(-2, -1)) == b"h"

        assert buffer.read() == b"abcdefghi"

    def test_peek_all(self):
        buffer = ByteBuffer()
        buffer.write(b"abcdefghi")

        assert buffer.peek() == b"abcdefghi"
        assert buffer.read() == b"abcdefghi"

    def test_discard(self):
        buffer = ByteBuffer()
        buffer.write(b"abcdefghi")

        assert buffer.discard(3) is None
        assert buffer.read() == b"defghi"

    def test_discard_all(self):
        buffer = ByteBuffer()
        buffer.write(b"abcdefghi")

        assert buffer.discard() is None
        assert buffer.read() == b""

    def test_read(self):
        buffer = ByteBuffer()
        buffer.write(b"abcdefghi")

        assert buffer.read(3) == b"abc"
        assert buffer.read() == b"defghi"

    def test_read_all(self):
        buffer = ByteBuffer()
        buffer.write(b"abcdefghi")

        assert buffer.read() == b"abcdefghi"
        assert buffer.read() == b""

    def test_write(self):
        buffer = ByteBuffer()

        buffer.write(b"abc")
        assert buffer.peek() == b"abc"
        buffer.write(b"def")
        assert buffer.peek() == b"abcdef"

    def test_empty(self):
        buffer = ByteBuffer()

        assert buffer.empty() is True
        buffer.write(b"abc")
        assert buffer.empty() is False
        buffer.discard()
        assert buffer.empty() is True

    def test_len(self):
        buffer = ByteBuffer()

        assert len(buffer) == 0
        buffer.write(b"abc")
        assert len(buffer) == 3

class TestStreamBase:
    def test_exhausted(self):
        stream = StreamBase(1)
        stream.buffer.write(b"abc")
        assert not stream.exhausted

        stream.close()
        assert stream.closed
        assert not stream.exhausted

        stream.queue.get()
        assert stream.queue.empty()
        assert not stream.exhausted

        stream.buffer.discard()
        assert stream.buffer.empty()
        assert stream.exhausted

    def test_close(self):
        stream = StreamBase(1)
        stream.close()

        assert stream.closed
        assert stream.queue.get() == STREAM_END

    def test_close_with_error(self):
        stream = StreamBase(1)
        error = GrpcError("boom", "details")
        stream.close(error)

        assert stream.closed
        assert stream.queue.get() == error

    def test_close_with_non_error(self):
        stream = StreamBase(1)
        error = Exception("boom")

        with pytest.raises(AssertionError):
            stream.close(error)

class TestReceiveStream:
    def test_write_to_closed_stream(self):
        stream = ReceiveStream(1)

        assert stream.buffer.empty()
        stream.close()
        stream.write(b"\x00\x00\x00")
        assert stream.buffer.empty()

    def test_write_less_bytes_than_header(self):
        stream = ReceiveStream(1)
        stream.write(b"\x00\x00\x00")

        assert stream.queue.empty()
        assert stream.buffer.peek() == b"\x00\x00\x00"

    def test_write_less_bytes_than_one_message(self):
        stream = ReceiveStream(1)
        stream.write(b"\x00\x00\x00\x01\x00\xff\xff\xff")

        assert stream.queue.empty()
        assert stream.buffer.peek() == b"\x00\x00\x00\x01\x00\xff\xff\xff"

    def test_write_more_bytes_than_one_message(self):
        stream = ReceiveStream(1)
        # incompressed single byte message, followed by two more bytes of /xff
        stream.write(b"\x00\x00\x00\x00\x01\xff\xff\xff")
        # single byte message is queued
        assert stream.queue.get() == (False, b"\xff")
        # following two bytes remain in the buffer
        assert stream.buffer.peek() == b"\xff\xff"

    def test_write_multiple_messages(self):
        stream = ReceiveStream(1)
        for _ in range(10):
            stream.write(b"\x00\x00\x00\x00\x01\xff")  # 10 single byte messages

        assert stream.queue.qsize() == 10
        assert len(stream.buffer) == 0

    def test_consume_grpc_error(self):
        stream = ReceiveStream(1)
        error = GrpcError("boom", "details")
        stream.queue.put(error)

        message_type = Mock()

        with pytest.raises(GrpcError):
            next(stream.consume(message_type))

    def test_consume_end_of_stream(self):
        stream = ReceiveStream(1)
        stream.close()

        message_type = Mock()

        assert list(stream.consume(message_type)) == []

    def test_consume_uncompressed_message(self):
        stream = ReceiveStream(1)

        message_data = b"x"
        message_type = Mock()
        message = message_type()

        stream.queue.put((False, message_data))
        stream.close()  # close stream so that consume exits

        assert list(stream.consume(message_type)) == [message]
        assert message.ParseFromString.call_args_list == [call(message_data)]

    @patch("nameko_grpc.streams.decompress")
    def test_consume_compressed_message(self, decompress):
        stream = ReceiveStream(1)

        message_data = b"x"
        message_type = Mock()
        message = message_type()

        stream.queue.put((True, message_data))
        stream.close()  # close stream so that consume exits

        assert list(stream.consume(message_type)) == [message]
        assert message.ParseFromString.call_args_list == [
            call(decompress(message_data))
        ]

    @patch("nameko_grpc.streams.decompress")
    def test_consume_multiple_messages(self, decompress):
        stream = ReceiveStream(1)

        message_data = b"x"
        message_type = Mock()
        message = message_type()

        stream.queue.put((False, message_data))
        stream.queue.put((True, message_data))
        stream.close()  # close stream so that consume exits

        assert list(stream.consume(message_type)) == [message, message]
        assert message.ParseFromString.call_args_list == [
            call(message_data),
            call(decompress(message_data)),
        ]

class TestSendStream:
    def test_populate(self):
        stream = SendStream(1)
        stream.populate(range(10))

        assert stream.closed
        assert stream.queue.qsize() == 11

    def test_populate_closed_stream(self):
        stream = SendStream(1)
        stream.close()

        assert stream.closed
        stream.populate(range(10))
        assert stream.queue.qsize() == 1

class TestSendStreamHeadersToSend:
    def test_no_headers(self):
        stream = SendStream(1)

        assert len(stream.headers) == 0
        assert stream.headers_to_send(False) is False

    def test_empty_queue(self):
        stream = SendStream(1)
        stream.headers.set(("foo", "bar"))

        assert stream.queue.qsize() == 0
        assert stream.headers_to_send(True) is False
        assert stream.headers_to_send(False) == [(b"foo", b"bar")]

    def test_mark_as_sent(self):
        stream = SendStream(1)
        stream.headers.set(("foo", "bar"))

        assert stream.headers_to_send(False) == [(b"foo", b"bar")]  # marks as sent
        assert stream.headers_to_send(False) is False  # previously sent

    def test_defer_until_data(self):
        stream = SendStream(1)
        stream.headers.set(("foo", "bar"))

        assert stream.headers_to_send(True) is False  # defer until data
        stream.queue.put(Mock())

        assert stream.queue.qsize() == 1
        assert stream.headers_to_send(True) == [(b"foo", b"bar")]

class TestSendStreamTrailersToSend:
    def test_no_trailers(self):
        stream = SendStream(1)

        assert len(stream.trailers) == 0
        assert stream.trailers_to_send() is False

    def test_send_trailers(self):
        stream = SendStream(1)
        stream.trailers.set(("foo", "bar"))

        assert stream.trailers_to_send() == [(b"foo", b"bar")]

@pytest.fixture
def generate_messages():
    with patch("nameko_grpc.streams.compress") as compress:
        compress.side_effect = lambda body, _: (False, body)

        def generate(count, length):
            """Generate a series of mock messages.

            If `count` is 2 and `length` is 4, when passed to `stream.populate`,
            two messages with the following payload will be added to the stream's
            queue.

                #1. b`\x00\x00\x00\x00`
                #2. b`\x01\x01\x01\x01`
            """
            messages = []
            for index in range(count):
                message = Mock()
                message.SerializeToString.return_value = bytes([index] * length)
                messages.append(message)
            return messages

        yield generate

class TestSendStreamFlushQueueToBuffer:
    def test_empty_queue(self):
        stream = SendStream(1)
        assert stream.queue.qsize() == 0

        stream.flush_queue_to_buffer()
        assert stream.buffer.empty()

    def test_messages_on_queue(self, generate_messages):
        stream = SendStream(1)
        stream.populate(generate_messages(count=2, length=20))

        header = struct.pack("?", False) + struct.pack(">I", 20)

        stream.flush_queue_to_buffer()
        assert stream.buffer.peek() == header + b"\x00" * 20 + header + b"\x01" * 20

    def test_stream_closed(self, generate_messages):
        stream = SendStream(1)
        stream.populate(generate_messages(count=2, length=20))

        header = struct.pack("?", False) + struct.pack(">I", 20)

        stream.flush_queue_to_buffer()
        assert stream.buffer.peek() == header + b"\x00" * 20 + header + b"\x01" * 20

        stream.flush_queue_to_buffer()  # stream closed; no-op
        assert stream.buffer.peek() == header + b"\x00" * 20 + header + b"\x01" * 20

    def test_error_on_queue(self, generate_messages):
        stream = SendStream(1)

        error = GrpcError("boom", "details")
        messages = itertools.chain(generate_messages(count=2, length=20), [error])

        stream.populate(messages)

        with pytest.raises(GrpcError):
            stream.flush_queue_to_buffer()

class TestSendStreamRead:
    def test_no_data(self):
        stream = SendStream(1)

        max_bytes = 10
        chunk_size = 10

        assert stream.buffer.empty()
        assert list(stream.read(max_bytes, chunk_size)) == []

    def test_less_than_one_chunk_of_data(self):
        stream = SendStream(1)
        stream.buffer.write(b"abc")

        max_bytes = 10
        chunk_size = 5

        assert list(stream.read(max_bytes, chunk_size)) == [b"abc"]
        assert stream.buffer.empty()

    def test_more_than_one_chunk_of_data(self):
        stream = SendStream(1)
        stream.buffer.write(b"abcdefghijklm")

        max_bytes = 10
        chunk_size = 5

        assert list(stream.read(max_bytes, chunk_size)) == [b"abcde", b"fghij"]
        assert stream.buffer.peek() == b"klm"

    def test_less_than_max_bytes_of_data(self):
        stream = SendStream(1)
        stream.buffer.write(b"abcdefghijklm")

        max_bytes = 20
        chunk_size = 5

        assert list(stream.read(max_bytes, chunk_size)) == [b"abcde", b"fghij", b"klm"]
        assert stream.buffer.empty()

    def test_more_than_max_bytes_of_data(self):
        stream = SendStream(1)
        stream.buffer.write(b"abcdefghijklm")

        max_bytes = 10
        chunk_size = 5

        assert list(stream.read(max_bytes, chunk_size)) == [b"abcde", b"fghij"]
        assert stream.buffer.peek() == b"klm"

    def test_chunk_greater_than_max_bytes(self):
        stream = SendStream(1)
        stream.buffer.write(b"abcdefghijklm")

        max_bytes = 5
        chunk_size = 10

        assert list(stream.read(max_bytes, chunk_size)) == [b"abcde"]
        assert stream.buffer.peek() == b"fghijklm"

    def test_stream_closed(self):
        stream = SendStream(1)

        max_bytes = 10
        chunk_size = 5

        stream.close()
        assert list(stream.read(max_bytes, chunk_size)) == []

    def test_stream_closed_with_error(self):
        stream = SendStream(1)

        error = GrpcError("boom", "details")
        stream.close(error)

        max_bytes = 10
        chunk_size = 5

        with pytest.raises(GrpcError):
            next(stream.read(max_bytes, chunk_size))

    def test_multiple_small_messages(self, generate_messages):
        stream = SendStream(1)
        stream.populate(generate_messages(count=100, length=1))

        header = struct.pack("?", False) + struct.pack(">I", 1)
        max_bytes = 20
        chunk_size = 10

        chunks = list(stream.read(max_bytes, chunk_size))
        expected = [
            # 5 bytes header + 1 byte payload + 4 bytes of next header
            header + b"\x00" + header[:4],
            # remaining 1 byte of header + 1 byte payload
            # + 5 bytes header + 1 byte payload + 2 bytes of next header
            header[4:] + b"\x01" + header + b"\x02" + header[:2],
        ]
        assert chunks == expected

        assert sum(map(len, chunks)) == max_bytes

        # queue is emptied into buffer
        assert len(stream.buffer) == 100 * (5 + 1) - max_bytes  # 580 bytes left
        assert stream.queue.qsize() == 0

    def test_multiple_large_messages(self, generate_messages):
        stream = SendStream(1)
        stream.populate(generate_messages(count=100, length=200))

        header = struct.pack("?", False) + struct.pack(">I", 200)
        max_bytes = 50
        chunk_size = 10

        chunks = list(stream.read(max_bytes, chunk_size))
        expected = [
            header + b"\x00\x00\x00\x00\x00",  # 5 bytes header + 5 bytes payload
            b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",  # 10 bytes payload
            b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",  # 10 bytes payload
            b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",  # 10 bytes payload
            b"\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00",  # 10 bytes payload
        ]
        assert chunks == expected

        assert sum(map(len, chunks)) == max_bytes

        # queue is emptied into buffer
        assert len(stream.buffer) == 100 * (5 + 200) - max_bytes  # 20450 bytes left
        assert stream.queue.qsize() == 0

    def test_data_in_buffer_and_messages_in_queue(self, generate_messages):
        stream = SendStream(1)
        stream.buffer.write(b"\xff\xff\xff\xff\xff")
        stream.populate(generate_messages(count=10, length=10))

        header = struct.pack("?", False) + struct.pack(">I", 10)
        max_bytes = 10
        chunk_size = 10

        chunks = list(stream.read(max_bytes, chunk_size))
        expected = [b"\xff\xff\xff\xff\xff" + header]
        assert chunks == expected

        assert sum(map(len, chunks)) == max_bytes

        # queue is emptied into buffer
        assert len(stream.buffer) == 5 + 10 * (5 + 10) - max_bytes  # 145 bytes left
        assert stream.queue.qsize() == 0


#!/usr/bin/env python3
import os
import urllib

import requests

import config

def dump_stories():
    new_stories = 0
    num_stories = 0
    r = requests.get(
        "https://i.instagram.com/api/v1/feed/reels_tray/",
        cookies=config.instagram_cookies, headers=config.instagram_headers).json()
    for user in r['tray']:
        user_dir = "./stories/{0!s}-{1!s}".format(user['user']['username'], user['id'])
        if not os.path.exists(user_dir):
            os.makedirs(user_dir)

        print("[*] dumping " + user['user']['username'])
        user_stories = requests.get(
            "https://i.instagram.com/api/v1/feed/user/{0!s}/reel_media/".format(user['id']),
            cookies=config.instagram_cookies, headers=config.instagram_headers).json()

        for item in user_stories['items']:
            num_stories += 1
            if 'video_versions' in item:
                url = item['video_versions'][0]['url']
            else:
                url = item['image_versions2']['candidates'][0]['url']

            filename = url.split('/')[-1].split('?')[0]
            file_path = user_dir + '/' + filename
            if not os.path.isfile(file_path):
                new_stories += 1
                print(" +  " + filename)
                urllib.request.urlretrieve(url, file_path)
            else:
                print(" -  " + filename)

    return len(r['tray']), num_stories, new_stories

def send_notification(message):
    requests.post(
        "https://api.pushover.net/1/messages.json",
        data={"token": config.pushover_app_token,
              "user": config.pushover_user_token,
              "title": "instadump",
              "message": message})

if __name__ == "__main__":
    num_users, num_stories, new_stories = dump_stories()
    message = "{0!s} stories ({1!s} new)\n{2!s} users".format(num_stories, new_stories, num_users)
    if config.pushover_app_token and config.pushover_user_token:
        send_notification(message)
    else:
        print(message)


n=int(input())
s=input()

li=s.split(" ")
for i in range(len(li)):
    li[i]=int(li[i])
li.sort(reverse=True)

a=li[0]
li2=[]
i=0
while i<n:
    if (a%li[i]==0) and (li[i] not  in li2):
            li2.append(li[i])
            del li[i]
            i-=1
            n-=1
    i+=1

print(li[0])
print(li2[0])


import numpy as np
from my_function import smooth_curve
from my_cnet import SimpleConvNet
from mnist import load_mnist
from my_optimizer import Adam
import matplotlib.pyplot as plt
from sklearn.metrics import confusion_matrix
import seaborn as sns

(x_train,t_train),(x_test,t_test) = load_mnist(flatten=False)

network = SimpleConvNet(input_dim=(1,28,28),
                        conv_param = {'filter_num': 30, 'filter_size': 5, 'pad': 0, 'stride': 1},
                        hidden_size=100, output_size=10, weight_init_std=0.01)

"""
epoch 全覆盖次数
mini_batch_size 批处理数据数
train_size 训练数据数
iter_per_epoch 一次全覆盖批处理次数
max_iter 整个训练批处理次数
optimizer 梯度更新选择Adam算法
current_epoch 目前进行的epoch次数
"""
epoch = 20
mini_batch_size = 100
train_size = x_train.shape[0]
iter_per_epoch = max(train_size/mini_batch_size,1)
iter_per_epoch = int(iter_per_epoch)#变为整数
max_iter = epoch*iter_per_epoch
optimizer = Adam(lr = 0.001)
current_epoch = 0
"""
画图参数

"""
train_loss_list = []
train_acc_list = []
test_acc_list = []

print("开始训练请等待...")
for i in range(max_iter):
    batch_mask = np.random.choice(train_size,mini_batch_size)

    x_batch = x_train[batch_mask]
    t_batch = t_train[batch_mask]

    grads = network.gradient(x_batch,t_batch)
    grads = optimizer.update(network.params,grads)

    loss = network.loss(x_batch,t_batch)
    train_loss_list.append(loss)
    if i %iter_per_epoch==0 :
        current_epoch += 1
        #取1000个数据计算正确率(节省时间)
        x_train_simple,t_train_simple = x_train[:1000],t_train[:1000]
        x_test_sample,t_test_sample = x_test[:1000],t_test[:1000]

        train_acc = network.accuracy(x_train_simple,t_train_simple)
        test_acc = network.accuracy(x_test_sample,t_test_sample)
        if current_epoch == 20 :
            cm = confusion_matrix(t_test_sample,np.argmax(network.predict(x_test_sample), axis=1))
            cmn = cm.astype('float')/cm.sum(axis=1)[:,np.newaxis]
            cmn = np.around(cmn,decimals=2)

            plt.figure(figsize=(8, 8))
            sns.heatmap(cmn, annot=True, cmap='Blues')

            plt.ylim(0, 10)
            plt.xlabel('Predicted labels')
            plt.ylabel('True labels')

        train_acc_list.append(train_acc)
        test_acc_list.append(test_acc)
        print("=== epoch : "+str(current_epoch)+", train acc:"+str(train_acc)+",test acc:"+str(test_acc)+" ===")
# network.save_parms("params.pkl")
print("训练结束，您的损失函数值已经降低到"+str(train_loss_list[-1])+"下面开始作图")
"""
画图
"""
plt.figure("loss")
x = np.arange(len(train_loss_list))
y = np.array(smooth_curve(train_loss_list))
plt.plot(x,y)
plt.xlabel("mini_batch")
plt.ylabel("loss")

plt.figure("accuracy")
x = np.arange(len(train_acc_list))
y1 = np.array(train_acc_list)
y2 = np.array(test_acc_list)
plt.xlabel("epoch")
plt.ylabel("accuracy")
plt.plot(x,y1,label="train_accuracy")
plt.plot(x,y2,label="test_accuracy")
plt.legend()

plt.show()


# -*- coding:utf-8 -*-
#@Time : 2020/4/27 16:05
#@Author: Triomphe
#@File : vulscan.py

import importlib
import os
import sys

from PyQt5.QtCore import QObject, pyqtSignal

from vulscan.port_scan import portscan
from modules.mod_get_rootPath import get_root_path
sys.path.append(os.path.abspath(
    os.path.dirname(__file__))+'/vuldb')

#根目录
ROOT_PATH =get_root_path()

class Vulscan(QObject):
    _signal =pyqtSignal(dict)
    _signal_finish=pyqtSignal()
    script_plugin_list=[]
    open_prot_list=[]

    def __init__(self,target_ip):
        super(Vulscan, self).__init__()
        #文件位置
        self.root_path =get_root_path()
        self.target_ip =target_ip

        self.init()

    def init(self):
        file_list = os.listdir(self.root_path + '/vulscan/vuldb')
        for filename in file_list:
            try:
                if filename.endswith('.py') and filename.split('.')[1] == 'py':
                    self.script_plugin_list.append(filename.split('.')[0])
            except Exception as e:
                print("error : "+str(e))
        #给每个插件设置 声明根目录

    #开始进行扫描
    def start_scan(self):
        try:
            self.open_prot_list=portscan(self.target_ip)
        except Exception as e:
            print(e)
            self.open_prot_list=['80']

        self.poc_check()

    #漏洞验证
    def poc_check(self):
        for plugin in self.script_plugin_list:
            res=importlib.import_module(plugin)
            setattr(res,"ROOT_PATH",ROOT_PATH)
            #先使用默认端口,如果存在就不使用端口扫描的进行检测
            result_info=res.check(self.target_ip)
            if result_info!=None:
                text=res.get_plugin_info()
                text['result_info']=result_info
                self._signal.emit(text)
            else:
                #使用masscan 扫描后对所有存活端口进行扫描
                for port in self.open_prot_list:
                    result_info=res.check(self.target_ip,port=port)
                    if result_info != None and result_info !="":
                        text=res.get_plugin_info()
                        text['result_info']=result_info
                        self._signal.emit(text)
        #表示完成了.
        self._signal_finish.emit()


from __future__ import annotations

from dataclasses import dataclass
from enum import Enum
from typing import List, cast

from pants.backend.project_info import dependents
from pants.backend.project_info.dependents import Dependents, DependentsRequest
from pants.base.build_environment import get_buildroot
from pants.base.deprecated import resolve_conflicting_options
from pants.engine.addresses import Address, Addresses
from pants.engine.collection import Collection
from pants.engine.internals.graph import Owners, OwnersRequest
from pants.engine.internals.mapper import SpecsFilter
from pants.engine.rules import Get, collect_rules, rule
from pants.engine.target import UnexpandedTargets
from pants.option.option_types import EnumOption, StrOption
from pants.option.option_value_container import OptionValueContainer
from pants.option.subsystem import Subsystem
from pants.util.docutil import doc_url
from pants.util.ordered_set import FrozenOrderedSet
from pants.util.strutil import help_text
from pants.vcs.git import GitWorktree

class DependentsOption(Enum):
    NONE = "none"
    DIRECT = "direct"
    TRANSITIVE = "transitive"

@dataclass(frozen=True)
class ChangedRequest:
    sources: tuple[str, ...]
    dependents: DependentsOption

class ChangedAddresses(Collection[Address]):
    pass

@rule
async def find_changed_owners(
    request: ChangedRequest, specs_filter: SpecsFilter
) -> ChangedAddresses:
    no_dependents = request.dependents == DependentsOption.NONE
    owners = await Get(
        Owners,
        OwnersRequest(
            request.sources,
            # If `--changed-dependents` is used, we cannot eagerly filter out root targets. We
            # need to first find their dependents, and only then should we filter. See
            # https://github.com/pantsbuild/pants/issues/15544
            filter_by_global_options=no_dependents,
            # Changing a BUILD file might impact the targets it defines.
            match_if_owning_build_file_included_in_sources=True,
        ),
    )
    if no_dependents:
        return ChangedAddresses(owners)

    # See https://github.com/pantsbuild/pants/issues/15313. We filter out target generators because
    # they are not useful as aliases for their generated targets in the context of
    # `--changed-since`. Including them makes it look like all sibling targets from the same
    # target generator have also changed.
    #
    # However, we also must be careful to preserve if target generators are direct owners, which
    # happens when a generated file is deleted.
    owner_target_generators = FrozenOrderedSet(
        addr.maybe_convert_to_target_generator() for addr in owners if addr.is_generated_target
    )
    dependents = await Get(
        Dependents,
        DependentsRequest(
            owners,
            transitive=request.dependents == DependentsOption.TRANSITIVE,
            include_roots=False,
        ),
    )
    result = FrozenOrderedSet(owners) | (dependents - owner_target_generators)
    if specs_filter.is_specified:
        # Finally, we must now filter out the result to only include what matches our tags, as the
        # last step of https://github.com/pantsbuild/pants/issues/15544.
        #
        # Note that we use `UnexpandedTargets` rather than `Targets` or `FilteredTargets` so that
        # we preserve target generators.
        result_as_tgts = await Get(UnexpandedTargets, Addresses(result))
        result = FrozenOrderedSet(
            tgt.address for tgt in result_as_tgts if specs_filter.matches(tgt)
        )

    return ChangedAddresses(result)

@dataclass(frozen=True)
class ChangedOptions:
    """A wrapper for the options from the `Changed` Subsystem.

    This is necessary because parsing of these options happens before conventional subsystems are
    configured, so the normal mechanisms like `Subsystem.rules()` would not work properly.
    """

    since: str | None
    diffspec: str | None
    dependents: DependentsOption

    @classmethod
    def from_options(cls, options: OptionValueContainer) -> ChangedOptions:
        dependents = resolve_conflicting_options(
            old_option="dependees",
            new_option="dependents",
            old_scope=Changed.options_scope,
            new_scope=Changed.options_scope,
            old_container=options,
            new_container=options,
        )
        return cls(options.since, options.diffspec, dependents)

    @property
    def provided(self) -> bool:
        return bool(self.since) or bool(self.diffspec)

    def changed_files(self, git_worktree: GitWorktree) -> list[str]:
        """Determines the files changed according to SCM/workspace and options."""
        if self.diffspec:
            return cast(
                List[str], git_worktree.changes_in(self.diffspec, relative_to=get_buildroot())
            )

        changes_since = self.since or git_worktree.current_rev_identifier
        return cast(
            List[str],
            git_worktree.changed_files(
                from_commit=changes_since, include_untracked=True, relative_to=get_buildroot()
            ),
        )

class Changed(Subsystem):
    options_scope = "changed"
    help = help_text(
        f"""
        Tell Pants to detect what files and targets have changed from Git.

        See {doc_url('advanced-target-selection')}.
        """
    )

    since = StrOption(
        default=None,
        help="Calculate changes since this Git spec (commit range/SHA/ref).",
    )
    diffspec = StrOption(
        default=None,
        help="Calculate changes contained within a given Git spec (commit range/SHA/ref).",
    )
    dependents = EnumOption(
        default=DependentsOption.NONE,
        help="Include direct or transitive dependents of changed targets.",
    )
    dependees = EnumOption(
        default=DependentsOption.NONE,
        help="Include direct or transitive dependents of changed targets.",
        removal_version="2.23.0.dev0",
        removal_hint="Use --dependents instead",
    )

def rules():
    return [*collect_rules(), *dependents.rules()]


import sys
input = sys.stdin.readline

t = int(input())
order = [list(input().strip()) for i in range(t)]

for i in range(t-1):
    for j in range(len(order[i])):
        if order[i][j] != order[i+1][j]:
            order[i+1][j] = '?'

print("".join(order[-1]))


"""add unique index for modalities

Revision ID: 3cccf6a0af7d
Revises: ba3bae2b5e27
Create Date: 2018-01-05 14:28:03.194013

"""
from alembic import op
import sqlalchemy as sa

# revision identifiers, used by Alembic.
revision = '3cccf6a0af7d'
down_revision = 'ba3bae2b5e27'
branch_labels = None
depends_on = None

def upgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.create_index(op.f('ix_monday_modality_name'), 'modality', ['name'], unique=True, schema='monday')
    # ### end Alembic commands ###

def downgrade():
    # ### commands auto generated by Alembic - please adjust! ###
    op.drop_index(op.f('ix_monday_modality_name'), table_name='modality', schema='monday')
    # ### end Alembic commands ###


print("Welcome to the GPA calculator.")

courses=int(input("Enter number of courses:"))
GpaList=[]
CreditList=[]
Markcount=0
Creditcount=0
print('Enter marks in percentage and then credit for that course in the next line')

for a in range(courses):
    Markcount+=1
    Creditcount+=1
    mark=int(input('mark'+ str(Markcount)+':'))
    credit=float(input('credit'+ str(Creditcount)+':'))

    if mark>=85 and mark<=100:
        gpa=float(4.0)

    elif mark>=80 and mark<=84:
        gpa=float(3.7)

    elif mark>=77 and mark<=79:
        gpa=float(3.3)

    elif mark>=73 and mark<=76:
        gpa=float(3.0)

    elif mark>=70 and mark<=72:
        gpa=float(2.7)

    elif mark>=67 and mark<=69:
        gpa=float(2.3)

    elif mark>=63 and mark<=66:
        gpa=float(2.0)

    elif mark>=60 and mark<=62:
        gpa=float(1.7)

    elif mark>=57 and mark<=59:
        gpa=float(1.3)

    elif mark>=53 and mark<=56:
        gpa=float(1.0)

    elif mark>=50 and mark<=52:
        gpa=float(0.7)

    else:
        gpa=float(0.0)

    weightGpa= float(gpa*credit)
    (GpaList.append(weightGpa))
    (CreditList.append(credit))

    totalSum=float(sum(GpaList))
    totalCredit=float(sum(CreditList))
    FinalGpa=totalSum/totalCredit
    print(FinalGpa)


from django.shortcuts import render , get_object_or_404 , get_list_or_404
from django.contrib.auth.decorators import login_required

from .models import Members

# Create your views here.
@login_required(login_url="/")
def onemember_record(request , name):
	objlist = get_list_or_404(Members , name  = name)
	objlist = objlist[::-1]

	cd = totalcd(objlist)

	next_pay = next_month_pay(objlist)

	last_loanmonth = loan_last_month(objlist)

	context = {
	"objectlist" : objlist[1:],
	"user":name,
	"totalcd" : cd,
	"nextpay" : next_pay,
	"loan_end" : last_loanmonth
	}

	return render(request , "members/one_member_record.html" , context)

def totalcd(record):
	total_cd = 0
	for i in record[1:]:
		total_cd += i.cd

	return total_cd

def next_month_pay(record):
	nextmonthpay = record[0].total
	return nextmonthpay

def loan_last_month(record):
	bal = record[0].loan_bal
	install = record[0].installment
	month = record[0].month
	mon , yr = month.split("-")

	if bal == 0:
		return None

	no_of_months = round(bal/install)

	if int(no_of_months) + int(mon) <= 12:
		end_month = f"{int(mon)+int(no_of_months)}-{yr}"

	year = 0
	while no_of_months > 12:
		no_of_months -= 12
		year += 1
		end_month = f"{no_of_months}-{int(yr)+int(year)}"

	return end_month


from unittest import mock

from django.http import HttpRequest

from google_optimize.utils import _parse_experiments, get_experiments_variants

def test_parses_single_experiment_cookie():
    request = HttpRequest()
    request.COOKIES["_gaexp"] = "GAX1.2.utSuKi3PRbmxeG08en8VNw.18147.1"
    experiments = _parse_experiments(request)
    assert experiments == dict(utSuKi3PRbmxeG08en8VNw=1)

def test_parses_multiple_experiment_cookies():
    request = HttpRequest()
    request.COOKIES[
        "_gaexp"
    ] = "GAX1.2.3x8_BbSCREyqtWm1H1OUrQ.18166.1!7IXTpXmLRzKwfU-Eilh_0Q.18166.0"
    experiments = _parse_experiments(request)
    assert experiments == {"7IXTpXmLRzKwfU-Eilh_0Q": 0, "3x8_BbSCREyqtWm1H1OUrQ": 1}

def test_parses_without_cookie():
    request = HttpRequest()
    experiments = _parse_experiments(request)
    assert experiments is None

@mock.patch("logging.Logger.warning")
def test_logs_missing_gaexp_cookie(logger):
    request = HttpRequest()
    get_experiments_variants(request, [{"id": "abc"}])
    logger.assert_called_with("Missing _ga_exp cookie")

@mock.patch("logging.Logger.error")
def test_logs_no_settings(logger):
    request = HttpRequest()
    request.COOKIES["_gaexp"] = "test"
    get_experiments_variants(request, None)
    logger.assert_called_with("Setting GOOGLE_OPTIMIZE_EXPERIMENTS not defined")

@mock.patch("logging.Logger.error")
def test_logs_failed_cookie_parsing(logger):
    request = HttpRequest()
    request.COOKIES["_gaexp"] = "test"
    get_experiments_variants(request, [{"id": "abc"}])
    logger.assert_called_with("Failed to parse _gaexp %s", "test")

@mock.patch("logging.Logger.warning")
def test_logs_settings_missing_experiment_id(logger):
    request = HttpRequest()
    request.COOKIES["_gaexp"] = "GAX1.2.3x8_BbSCREyqtWm1H1OUrQ.18166.1"
    get_experiments_variants(request, [{"test": "test"}])
    logger.assert_called_with("experiment id not found in experiment settings")

@mock.patch("logging.Logger.warning")
def test_logs_experiment_id_not_in_cookies(logger):
    request = HttpRequest()
    gaexp = "GAX1.2.3x8_BbSCREyqtWm1H1OUrQ.18166.1"
    experiment_id = "test"
    request.COOKIES["_gaexp"] = gaexp
    get_experiments_variants(request, [{"id": experiment_id}])
    logger.assert_called_with(
        "experiment id %s not found in experiments cookie %s", experiment_id, gaexp
    )

def test_parses_single_experiment():
    request = HttpRequest()
    request.COOKIES["_gaexp"] = "GAX1.2.utSuKi3PRbmxeG08en8VNw.18147.1"
    experiments = [
        {
            "id": "utSuKi3PRbmxeG08en8VNw",
            "alias": "redesign",
            "variant_aliases": {0: "old_design", 1: "new_design"},
        }
    ]
    values = get_experiments_variants(request, experiments)
    assert values == {"redesign": "new_design"}

def test_parses_multiple_experiments():
    request = HttpRequest()
    request.COOKIES[
        "_gaexp"
    ] = "GAX1.2.3x8_BbSCREyqtWm1H1OUrQ.18166.1!7IXTpXmLRzKwfU-Eilh_0Q.18166.0"
    experiments = [
        {
            "id": "3x8_BbSCREyqtWm1H1OUrQ",
            "alias": "redesign_page",
            "variant_aliases": {0: "old_design", 1: "new_design"},
        },
        {
            "id": "7IXTpXmLRzKwfU-Eilh_0Q",
            "alias": "resign_header",
            "variant_aliases": {0: "old_header", 1: "new_header"},
        },
    ]
    values = get_experiments_variants(request, experiments)

    assert values == {"redesign_page": "new_design", "resign_header": "old_header"}

def test_parses_experiments_without_variant_aliases():
    request = HttpRequest()
    request.COOKIES["_gaexp"] = "GAX1.2.utSuKi3PRbmxeG08en8VNw.18147.1"
    experiments = [{"id": "utSuKi3PRbmxeG08en8VNw", "alias": "redesign"}]
    values = get_experiments_variants(request, experiments)
    assert values == {"redesign": 1}

def test_parses_experiments_without_experiment_alias():
    request = HttpRequest()
    request.COOKIES["_gaexp"] = "GAX1.2.utSuKi3PRbmxeG08en8VNw.18147.1"
    experiments = [{"id": "utSuKi3PRbmxeG08en8VNw"}]
    values = get_experiments_variants(request, experiments)
    assert values == {"utSuKi3PRbmxeG08en8VNw": 1}


import torch

#Linear regression for f(x) = 4x+3

X= torch.tensor([1,2,3,4,5,6,7,8,9,10], dtype=torch.float32)
Y=torch.tensor([7,11,15,19,23,27,31,35,39,43], dtype= torch.float32)

w= torch.tensor(0.0,dtype=torch.float32,requires_grad=True)

def forward(x):
    return (w*x)+3
def loss(y,y_exp):
    return ((y_exp-y)**2).mean()

testVal = 100
print(f'Prediction before training: f({testVal}) = {forward(testVal).item():.3f}')

learningRate = 0.01
numTrainings=25
for training in range(numTrainings):
    y_exp=forward(X)
    error = loss(Y,y_exp)
    error.backward()
    with torch.no_grad():
        w -= learningRate* w.grad
    w.grad.zero_()
    print(f'training {training+1}: W = {w.item():.3f}, loss = {error.item():.3f}')
print(f'Prediction after all training of f({testVal}) = {forward(testVal).item():.3f}')


from unittest import mock
from itertools import product

import pytest

@pytest.mark.parametrize(
    'user_agent, session',
    product(
        [None, mock.Mock()],
        [None, mock.Mock()]
    )
)

def test_init(user_agent, session):
    with mock.patch('Raitonoberu.raitonoberu.aiohttp') as m_aio:
        from Raitonoberu.raitonoberu import Raitonoberu
        # run
        obj = Raitonoberu(user_agent, session)
        # test
        if user_agent is None:
            obj.headers == {"User-Agent": "Raitonoberu"}
        else:
            obj.headers == user_agent
        if session is None:
            obj.session == m_aio.ClientSession.return_value
            m_aio.ClientSession.assert_called_once_with(headers=obj.headers)
        else:
            obj.session == session

def test_del():
    session = mock.Mock()
    with mock.patch('Raitonoberu.raitonoberu.Raitonoberu.__init__', return_value=None):
        from Raitonoberu.raitonoberu import Raitonoberu
        obj = Raitonoberu()
        obj.session = session
        # run
        del obj
        # test
        session.close.assert_called_once_with()

@pytest.mark.asyncio
@pytest.mark.parametrize('term', ['term'])
async def test_get_search_page(term):
    from Raitonoberu.raitonoberu import Raitonoberu
    obj = Raitonoberu()
    # run
    res = await obj.get_search_page(term=term)
    # test
    # the actual result with 'term' as input is
    # 'http://www.novelupdates.com/series/the-last-apostle/'
    assert res.startswith('http://www.novelupdates.com/series/')

@pytest.mark.asyncio
@pytest.mark.parametrize(
    'term, exp_res',
    [
        (
            'smiling proud wanderer',
            {
                'aliases': [
                    'Laughing in the Wind',
                    'State of Divinity',
                    'The Peerless Gallant Errant',
                    'The Proud and Gallant Wanderer',
                    'Xiao Ao Jiang Hu',
                    '笑傲江湖'
                ],
                'artists': None,
                'authors': ['Jin Yong'],
                'completely_translated': True,
                'cover': 'http://cdn.novelupdates.com/images/2017/02/IMG_2801.jpg',
                'description': (
                    'The Smiling, Proud Wanderer is a wuxia novel by Jin Yong (Louis Cha). '
                    'It was first serialised in Hong Kong in the newspaper Ming Pao '
                    'from 20 April 1967 to 12 October 1969. The Chinese title of the novel, '
                    'Xiao Ao Jiang Hu, '
                    'literally means to live a carefree life in a mundane world of strife. '
                    'Alternate English translations of the title include '
                    'Laughing in the Wind, '
                    'The Peerless Gallant Errant, and The Proud and Gallant Wanderer. '
                    'Another alternative title, State of Divinity, '
                    'is used for some of the novel’s adaptations.'
                ),
                'english_publisher': None,
                'genre': ['Action', 'Adventure', 'Martial Arts', 'Wuxia'],
                'language': 'Chinese',
                'licensed': False,
                'link': 'http://www.novelupdates.com/series/smiling-proud-wanderer/',
                'novel_status': '4 Volumes (Completed)\n40 Chapters (Completed)',
                'publisher': 'Ming Pao',
                'related_series': None,
                'tags': [
                    'Adapted To Drama', 'Adapted to Manhua', 'Adapted To Movie', 'Betrayal',
                    'Misunderstandings', 'Politics', 'Revenge', 'Special Abilities'
                ],
                'title': 'Smiling Proud Wanderer',
                'type': 'Chinese Novel',
                'year': '1967'
            }
        )
    ]

)
async def test_get_first_search_result(term, exp_res):
    from Raitonoberu.raitonoberu import Raitonoberu
    obj = Raitonoberu()
    # run
    res = await obj.get_first_search_result(term=term)
    # test
    assert res == exp_res

@pytest.mark.asyncio
@pytest.mark.parametrize(
    'term, exp_res',
    [
        (
            'I shall seal the heavens',
            [
                'Xian Ni (Shared Universe)',
                'Beseech The Devil (Shared Universe)',
                'Against Heaven (Shared Universe)',
                'A Will Eternal (Shared Universe)'
            ]
        ),
        ('Curing incurable diseases with semen', None),
        (
            'S.A.O.',
            [
                'Sword Art Online Alternative – Gun Gale Online (Spin-Off)',
                'Sword Art Online – Progressive (Spin-Off)',
                'Mahouka Koukou no Rettousei x Sword Art Online (Spin-Off)',
                'Sword Art Online Alternative – Clover’s Regret (Spin-Off)',
            ]
        ),
    ]
)
async def test_related_series(term, exp_res):
    """test related series category."""
    from Raitonoberu.raitonoberu import Raitonoberu
    obj = Raitonoberu()
    # run
    res = await obj.get_first_search_result(term=term)
    # test
    res['related_series'] == exp_res

@pytest.mark.asyncio
@pytest.mark.parametrize(
    'term, exp_res',
    [
        ['Curing incurable diseases with semen', None],
        ['S.A.O.', 'Yen Press'],
        ['I shall seal the heavens', None],
    ]
)
async def test_english_publisher(term, exp_res):
    """test related series category."""
    from Raitonoberu.raitonoberu import Raitonoberu
    obj = Raitonoberu()
    # run
    res = await obj.get_first_search_result(term=term)
    # test
    res['english_publisher'] == exp_res


from PIL import Image
from torchvision import transforms
import torch
import numpy as np
import pandas as pd
import sys
sys.path.append("d:\\Codes\\AI\\kaggle\\kaggle-CIFAR-10\\")

def loadImages():
    # image list
    images = np.zeros((300000, 3, 32, 32))
    print("begining loading images")
    i = 0
    while True:
        print(i)
        try:
            # open a image
            imageLabel = i + 1
            img_path = "datas/test/" + str(imageLabel) + ".png"
            img = Image.open(img_path)
        except FileNotFoundError: # 没有该图片或者图片读取完成
            break
        else:
            # transfer image type into numpy
            img = np.array(img)
            img = torch.from_numpy(img)
            img = img.transpose(0, 2)
            img = img.transpose(1, 2)
            images[i, :, :, :] = img
            i += 1
    return images

images = loadImages()

np.save("test_images.npy", images)


import g2d

x, y, dx, dy = 240, 240, 5,5
s=4
ARENA_W, ARENA_H = 480, 360
image = g2d.load_image("ball.png")

def tick():
    global x,y, dy, dx, s

    g2d.clear_canvas()             # Draw background
    g2d.draw_image(image, (x, y))  # Draw foreground

    if g2d.key_pressed("w"):
        s=1
        # y-=dy
    elif g2d.key_pressed("a"):
        s=2
        # x-=dx
    elif g2d.key_pressed("s"):
        s=3
        # y+=dy
    elif g2d.key_pressed("d"):
        s=4
        # x+=dx

    if s==1:
        y-=dy
    elif s==2:
        x-=dx
    elif s==3:
        y+=dy
    elif s==4:
        x+=dx

def main():
    g2d.init_canvas((ARENA_W, ARENA_H))
    g2d.main_loop(tick)  # call tick 30 times/second

main()


from rest_framework import serializers
from review_app.models import FarmersMarket, Vendor

class FarmersMarketSerializer(serializers.ModelSerializer):
    rating = serializers.ReadOnlyField(source='get_rating')

    class Meta:
        model = FarmersMarket
        fields = ['id', 'fm_name', 'fm_description', 'rating', 'fm_picture_url', 'fm_banner_picture_url',
                  'fm_contact_name', 'fm_contact_email', 'fm_website', 'fm_facility_type',
                  'fm_county', 'fm_address', 'fm_lat', 'fm_long', 'fm_programs_accepted',
                  'fm_phone', 'fm_seasons_of_operation', 'fm_handicap_accessible', 'fm_updated']

class VendorSerializer(serializers.ModelSerializer):
    rating = serializers.ReadOnlyField(source='get_rating')

    class Meta:
        model = Vendor
        fields = ['id', 'at_farmers_market', 'vendor_name', 'vendor_description', 'rating', 'vendor_contact_name',
                  'vendor_contact_email', 'vendor_website', 'vendor_phone', 'vendor_type',
                  'vendor_picture_url', 'vendor_banner_picture_url', 'vendor_updated']


#!/usr/bin/env python
# -*- coding:utf-8 -*-
"""code_info
@Time    : 2020 2020/7/10 15:42
@Author  : Blanc
@File    : double_color_ball2.py
"""
import random
import time
'''
name = time.strftime('%Y-%m-%d', time.localtime())
print(name)
f = open(file=name + '.txt', mode='w', encoding='utf-8-sig')
a = list()

for i in range(0, 5):
    b = random.randint(1, 64)
    a.append(b)
a = str(a)
f.write('双色球号开奖：' + a)
f.close()'''
list1 = random.sample(range(1, 65), 5)
list1 = str(list1)
name = time.strftime('%Y-%m-%d', time.localtime())
f = open(file=name + '.txt', mode='w', encoding='utf-8-sig')
f.write('双色球号开奖：' + list1)
f.close()


from django.conf.urls import url
from mainapp import views

urlpatterns = [
    url(r'^$', views.index, name='index'),
    url(r'^category/(?P<category_name_slug>[\w\-]+)/$', views.view_category, name='category'),
    url(r'^search_dictionary/$', views.search_dictionary, name="search_dictionary"),
    url(r'^search/$', views.search, name='search'),
    url(r'^dictionary/', views.dictionary, name='dictionary'),
    url(r'^local_help/', views.local_help, name='local_help'),
    url(r'^talk_to_someone/', views.talk_to_someone, name='talk_to_someone'),
    url(r'^search_questions/$', views.search_questions, name="search_questions")
]


#!/usr/bin/env python3
# from https://stackoverflow.com/a/55902915/5555077

# from contextlib import contextmanager
#
# @contextmanager
# def nullcontext(enter_result=None):
#     yield enter_result

import contextlib

cm = contextlib.nullcontext()

if __name__ == "__main__":
    with cm as context:
        print("abc")


import bpy
import csv
import os
from bpy import context
import builtins as __builtin__

def console_print(*args, **kwargs):
    for a in context.screen.areas:
        if a.type == 'CONSOLE':
            c = {}
            c['area'] = a
            c['space_data'] = a.spaces.active
            c['region'] = a.regions[-1]
            c['window'] = context.window
            c['screen'] = context.screen
            s = " ".join([str(arg) for arg in args])
            for line in s.split("\n"):
                bpy.ops.console.scrollback_append(c, text=line)

def print(*args, **kwargs):
    """Console print() function."""

    console_print(*args, **kwargs) # to py consoles
    __builtin__.print(*args, **kwargs) # to system console

def importLogos():
    for i in range(1,22):
        image_name = "Team{}.Logo1".format(i)
        file_name = image_name + ".png"
        bpy.ops.import_image.to_plane(files=[{"name":file_name, "name":file_name}], directory="Users/hyungsoobae/Desktop/K-League/image/")
        models[image_name].location= (0,position1[i-1],1)
        bpy.ops.object.editmode_toggle()
        bpy.ops.transform.translate(value=(0,0,0.5), constraint_axis=(False,False,True), constraint_orientation='GLOBAL', mirror=False, proportional='DISABLED', proportional_edit_falloff='SMOOTH', proportional_size=1)
        bpy.ops.object.editmode_toggle()

models = bpy.data.objects
scn = bpy.context.scene
data_file_path = "/Users/hyungsoobae/Desktop/K-League/data"
position1 = [0.0, 1.1, 2.2, 3.3000000000000003, 4.4, 5.5, 6.6000000000000005, 7.700000000000001, 8.8, 9.9, 11.0, 12.100000000000001, 13.200000000000001, 14.3, 15.400000000000002, 16.5, 17.6, 18.700000000000003, 19.8, 20.900000000000002, 22.0, 23.1]
tposition1 = [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]

outlier = 27

def reset():
    scn.frame_set(0)

    for model in models:
        if 'Year' in model.name:
            continue
        if 'Team' in model.name and 'Name' in model.name:
            index = []
            for i,action in enumerate(model.animation_data.action.fcurves):
                if action.data_path == 'location':
                    index.append(i)
            for i in range(len(index)):
                print (index)
                model.animation_data.action.fcurves.remove(model.animation_data.action.fcurves[index[i]])
                index = list(map(lambda x: x-1, index))
                print (index)
            continue

        model.animation_data_clear()
        model.data.animation_data_clear()

    for i in range(1,23):
        #print (models['Team{}'.format(i)].location)
        models['Team{}'.format(i)].location[1] = position1[i-1]
        models['Team{}'.format(i)].scale[2] = 0
        models['Team{}.Point'.format(i)].location[0] = 0.4
        models['Team{}.Point'.format(i)].location[1] = position1[i-1]
        models['Team{}.Point'.format(i)].location[2] = 0.4
        models['Team{}.Point'.format(i)].data.text_counter_props.ifAnimated=True
        models['Team{}.Point'.format(i)].data.text_counter_props.counter = 0

        for j in range(1,6):
            try:
                models['Team{}.Name{}'.format(i,j)].location[1] = position1[i-1]
                models['Team{}.Name{}'.format(i,j)].location[2] = 2.1
                models['Team{}.Name{}'.format(i,j)].rotation_euler[1] = -0.872665
                models['Team{}.Name{}'.format(i,j)].data.size = 0.3
            except:
                pass

        for j in range(1,8):
            try:
                models['Team{}.Logo{}'.format(i, j)].location[1] = position1[i-1]
                models['Team{}.Logo{}'.format(i, j)].location[2] = 1.0
            except:
                pass

def get_current_teams(frame=0):
    result = []
    scn.frame_set(frame)
    for model in models:
        if 'Team' in model.name and '.' not in model.name:
            if (model.location[1]) < outlier:
                result.append(model)
    result.sort(key=lambda x : x.location[1])
    result = list(map(lambda x: x.name, result))
    return result

def setNameLocation(ffrom, frame, teamName, value):
    for i in range(1,6):
        try:
            scn.frame_set(ffrom)
            models['{}.Name{}'.format(teamName,i)].keyframe_insert(data_path='location')

            scn.frame_set(ffrom+frame)
            models['{}.Name{}'.format(teamName, i)].location[1] = value
            models['{}.Name{}'.format(teamName, i)].location[2] = models[teamName].scale[2] * 2 + 2.1
            models['{}.Name{}'.format(teamName, i)].keyframe_insert(data_path='location')
        except:
            pass

def setLogoLocation(ffrom, frame, teamName, value):
    for i in range(1,8):
        try:
            scn.frame_set(ffrom)
            models['{}.Logo{}'.format(teamName,i)].keyframe_insert(data_path='location')

            scn.frame_set(ffrom+frame)
            models['{}.Logo{}'.format(teamName, i)].location[1] = value
            models['{}.Logo{}'.format(teamName, i)].location[2] = models[teamName].scale[2] * 2 + 1.0
            models['{}.Logo{}'.format(teamName, i)].keyframe_insert(data_path='location')
        except:
            pass

def setPointLocation(ffrom, frame, teamName, value, point=None):
        scn.frame_set(ffrom)
        models['{}.Point'.format(teamName)].keyframe_insert(data_path='location')

        if point is not None:
            models['{}.Point'.format(teamName)].data.keyframe_insert(data_path='text_counter_props.counter')

        scn.frame_set(ffrom+frame)
        models['{}.Point'.format(teamName)].location[1] = value
        if models[teamName].scale[2] > 0:
            models['{}.Point'.format(teamName)].location[2] = models[teamName].scale[2] * 2 + 0.4
        else:
            models['{}.Point'.format(teamName)].location[2] = 0.4

        if point is not None:
            models['{}.Point'.format(teamName)].data.text_counter_props.counter = point
            models['{}.Point'.format(teamName)].data.keyframe_insert(data_path='text_counter_props.counter')

        models['{}.Point'.format(teamName)].keyframe_insert(data_path='location')

def transition(year, ffrom, frame):
    new_teams = []
    new_teams_set = set()

    fp = data_file_path + "/" + year + ".csv"
    with open(fp, 'r', encoding="utf-8") as csvfile:
        rdr = csv.reader(csvfile)
        for i,v in enumerate(rdr):
            new_teams.append((i,v[2],int(v[1])))
            new_teams_set.add(v[2])

    current_teams = get_current_teams(ffrom)
    print (current_teams)

    #Remove all non participitating teams from the table
    np_teams = set(current_teams) - new_teams_set

    for team in np_teams:
        #print (team)
        scn.frame_set(ffrom)
        models[team].keyframe_insert(data_path='location')
        models[team].keyframe_insert(data_path='scale')

        scn.frame_set(ffrom+frame)
        models[team].location[1] = outlier
        models[team].scale[2] = 0
        models[team].keyframe_insert(data_path='location')
        models[team].keyframe_insert(data_path='scale')

        setNameLocation(ffrom, frame, team, outlier)
        setLogoLocation(ffrom, frame, team, outlier)
        setPointLocation(ffrom, frame, team, outlier, 0)

    #Move the old teams in order
    current_teams = list(filter(lambda x: x not in np_teams, current_teams))
    current_number = len(current_teams)
    for i,team in enumerate(current_teams):
        scn.frame_set(ffrom)
        models[team].keyframe_insert(data_path='location')

        scn.frame_set(ffrom+frame)
        models[team].location[1] = position1[i]
        models[team].keyframe_insert(data_path='location')

        setNameLocation(ffrom, frame, team, position1[i])
        setLogoLocation(ffrom, frame, team, position1[i])
        setPointLocation(ffrom, frame, team, position1[i])

    #Add new teams
    new_teams_set = new_teams_set - set(current_teams)
    for i,team in enumerate(new_teams_set):
        scn.frame_set(ffrom)
        models[team].keyframe_insert(data_path='location')

        scn.frame_set(ffrom+frame)
        models[team].location[1] = position1[current_number+i]
        models[team].keyframe_insert(data_path='location')

        setNameLocation(ffrom, frame, team, position1[current_number+i])
        setLogoLocation(ffrom, frame, team, position1[current_number+i])
        setPointLocation(ffrom, frame, team, position1[current_number+i])

def league_type_1(year, ffrom, frame, scale=10):
    new_teams = []
    new_teams_set = set()

    fp = data_file_path + "/" + year + ".csv"
    with open(fp, 'r', encoding="utf-8") as csvfile:
        rdr = csv.reader(csvfile)
        for i,v in enumerate(rdr):
            new_teams.append((i,v[2],int(v[1])))
            new_teams_set.add(v[2])
    #print (new_teams)

    for team in new_teams:
        scn.frame_set(ffrom)
        models[team[1]].keyframe_insert(data_path='location')
        models[team[1]].keyframe_insert(data_path='scale')

        scn.frame_set(ffrom+frame)
        models[team[1]].location[1] = position1[team[0]]
        models[team[1]].scale[2] = team[2] / scale
        models[team[1]].keyframe_insert(data_path='location')
        models[team[1]].keyframe_insert(data_path='scale')

        setNameLocation(ffrom, frame, team[1], position1[team[0]])
        setLogoLocation(ffrom, frame, team[1], position1[team[0]])
        setPointLocation(ffrom, frame, team[1], position1[team[0]], team[2])

def league_type_3(year, ffrom, frame, scale):
    league_type_1(year,ffrom,frame, scale)

def league_type_4(year, ffrom, frame, scale):
    league_type_1(year,ffrom,frame, scale)

def post_season(year, ffrom, frame, scale):
    league_type_1(year+'p',ffrom,frame, scale)

def league_type_5(year, ffrom, frame, scale):
    league_type_1(year,ffrom,frame, scale)

def split(year, ffrom, frame, gap=2, scale=10):
    new_teams = []
    new_teams_set = set()

    #GROUP A
    fp = data_file_path + "/" + year + "a.csv"
    with open(fp, 'r', encoding="utf-8") as csvfile:
        rdr = csv.reader(csvfile)
        for i,v in enumerate(rdr):
            new_teams.append((i,v[2],int(v[1])))
            new_teams_set.add(v[2])

    length = len(new_teams)

    for team in new_teams:
        scn.frame_set(ffrom)
        models[team[1]].keyframe_insert(data_path='location')
        models[team[1]].keyframe_insert(data_path='scale')

        scn.frame_set(ffrom+frame)
        models[team[1]].location[1] = position1[team[0]]
        models[team[1]].scale[2] = team[2] / scale
        models[team[1]].keyframe_insert(data_path='location')
        models[team[1]].keyframe_insert(data_path='scale')

        setNameLocation(ffrom, frame, team[1], position1[team[0]])
        setLogoLocation(ffrom, frame, team[1], position1[team[0]])
        setPointLocation(ffrom, frame, team[1], position1[team[0]], team[2])

    #GROUP B
    new_teams = []
    new_teams_set = set()

    fp = data_file_path + "/" + year + "b.csv"
    with open(fp, 'r', encoding="utf-8") as csvfile:
        rdr = csv.reader(csvfile)
        for i,v in enumerate(rdr):
            new_teams.append((i,v[2],int(v[1])))
            new_teams_set.add(v[2])

    length = len(new_teams)

    for team in new_teams:
        scn.frame_set(ffrom)
        models[team[1]].keyframe_insert(data_path='location')
        models[team[1]].keyframe_insert(data_path='scale')

        scn.frame_set(ffrom+frame)
        models[team[1]].location[1] = position1[length-1+gap+team[0]]
        models[team[1]].scale[2] = team[2] / scale
        models[team[1]].keyframe_insert(data_path='location')
        models[team[1]].keyframe_insert(data_path='scale')

        setNameLocation(ffrom, frame, team[1],position1[length-1+gap+team[0]])
        setLogoLocation(ffrom, frame, team[1],position1[length-1+gap+team[0]])
        setPointLocation(ffrom, frame, team[1],position1[length-1+gap+team[0]], team[2])

'''
reset()

transition("1983", 0, 5)
league_type_1("1983", 5, 50, 40)

transition("1984a", 105, 15)
league_type_1("1984a", 120, 50, 40)
league_type_1("1984b", 195, 50, 40)
league_type_1("1984c", 270, 25, 40)

transition("1985", 345, 15)
league_type_1("1985", 360, 50, 40)

transition("1986a", 460, 15)
league_type_1("1986a", 475, 50, 40)
league_type_1("1986b", 550, 50, 40)
league_type_1("1986c", 625, 25, 40)

transition("1987", 700, 15)
league_type_1("1987", 715, 50, 40)

transition("1988", 815, 15)
league_type_1("1988", 830, 50, 40)

transition("1989", 930, 15)
league_type_1("1989", 945, 50, 40)

transition("1990", 1045, 15)
league_type_1("1990", 1060, 50, 40)

transition("1991", 1160, 15)
league_type_1("1991", 1175, 50, 40)

transition("1992", 1275, 15)
league_type_1("1992", 1290, 50, 40)

transition("1993", 1390, 15)
league_type_1("1993", 1405, 50, 40)

transition("1994", 1505, 15)
league_type_1("1994", 1520, 50, 40)

transition("1995a", 1620, 15)
league_type_1("1995a", 1635, 50, 40)
league_type_1("1995b", 1710, 50, 40)
league_type_1("1995c", 1785, 25, 40)

transition("1996a", 1860, 15)
league_type_1("1996a", 1875, 50, 40)
league_type_1("1996b", 1950, 50, 40)
league_type_1("1996c", 2025, 25, 40)

transition("1997", 2100, 15)
league_type_1("1997", 2115, 50, 40)

transition("1998", 2215, 15)
league_type_1("1998", 2230, 50, 40)
post_season("1998", 2305, 25, 40)

transition("1999", 2380, 15)
league_type_1("1999", 2395, 50, 40)
post_season("1999", 2470, 25, 40)

transition("2000", 2545, 15)
league_type_1("2000", 2560, 50, 40)
post_season("2000", 2635, 25, 40)

transition("2001", 2710, 15)
league_type_1("2001", 2725, 50, 40)

transition("2002", 2825, 15)
league_type_1("2002", 2840, 50, 40)

transition("2003", 2940, 15)
league_type_1("2003", 2955, 50, 40)

transition("2004a", 3055, 15)
league_type_1("2004a", 3070, 50, 40)
league_type_1("2004b", 3145, 50, 40)
league_type_1("2004c", 3220, 40, 40)
league_type_1("2004d", 3285, 25, 40)

transition("2005a", 3360, 15)
league_type_1("2005a", 3375, 50, 40)
league_type_1("2005b", 3450, 50, 40)
league_type_1("2005c", 3525, 40, 40)
league_type_1("2005d", 3590, 25, 40)

transition("2006a", 3665, 15)
league_type_1("2006a", 3680, 50, 40)
league_type_1("2006b", 3680+50+25, 50, 40)
league_type_1("2006c", 3680+50+25+50+25, 40, 40)
league_type_1("2006d", 3695+50+25+50+25+25+25, 25, 40)

transition("2007a", 3970, 15)
league_type_1("2007a", 3985, 50, 40)
league_type_1("2007b", 3985+50+25, 25, 40)

transition("2008a", 4135, 15)
league_type_1("2008a", 4150, 50, 40)
league_type_1("2008b", 4150+50+25, 25, 40)

transition("2009a", 4300, 15)
league_type_1("2009a", 4315, 50, 40)
league_type_1("2009b", 4315+50+25, 25, 40)

transition("2010a", 4465, 15)
league_type_1("2010a", 4480, 50, 40)
league_type_1("2010b", 4480+50+25, 25, 40)

transition("2011a", 4630, 15)
league_type_1("2011a", 4645, 50, 40)
league_type_1("2011b", 4645+50+25, 25, 40)

transition("2012", 4795, 15)
league_type_1("2012", 4810, 50, 40)
split("2012", 4885, 40, 2, 40)

transition("2013", 4975, 15)
league_type_1("2013", 4990, 50, 40)
split("2013", 4990+50+25, 40, 2, 40)

transition("2014", 5155, 15)
league_type_1("2014", 5170, 50, 40)
split("2014", 5245, 40, 2, 40)

transition("2015", 5335, 15)
league_type_1("2015", 5350, 50, 40)
split("2015", 5350+50+25, 40, 2, 40)

transition("2016", 5515, 15)
league_type_1("2016", 5530, 50, 40)
split("2016", 5530+50+25, 40, 2, 40)

transition("2017", 5700, 15)
league_type_1("2017", 5715, 50, 40)
split("2017", 5715+50+25, 40, 2, 40)

transition("2018", 5880, 15)
league_type_1("2018", 5910-15, 50, 40)
split("2018", 5910+50+25-15, 40, 2, 40)
'''