#
# PySNMP MIB module PANASAS-VOLUMES-MIB-V1 (http://snmplabs.com/pysmi)
# ASN.1 source file:///Users/davwang4/Dev/mibs.snmplabs.com/asn1/PANASAS-VOLUMES-MIB-V1
# Produced by pysmi-0.3.4 at Mon Apr 29 20:28:01 2019
# On host DAVWANG4-M-1475 platform Darwin version 18.5.0 by user davwang4
# Using Python version 3.7.3 (default, Mar 27 2019, 09:23:15)
#
ObjectIdentifier, OctetString, Integer = mibBuilder.importSymbols("ASN1", "ObjectIdentifier", "OctetString", "Integer")
NamedValues, = mibBuilder.importSymbols("ASN1-ENUMERATION", "NamedValues")
ConstraintsUnion, ConstraintsIntersection, ValueRangeConstraint, ValueSizeConstraint, SingleValueConstraint = mibBuilder.importSymbols("ASN1-REFINEMENT", "ConstraintsUnion", "ConstraintsIntersection", "ValueRangeConstraint", "ValueSizeConstraint", "SingleValueConstraint")
panFs, = mibBuilder.importSymbols("PANASAS-PANFS-MIB-V1", "panFs")
NotificationGroup, ModuleCompliance = mibBuilder.importSymbols("SNMPv2-CONF", "NotificationGroup", "ModuleCompliance")
NotificationType, MibScalar, MibTable, MibTableRow, MibTableColumn, IpAddress, ModuleIdentity, Counter64, Unsigned32, Gauge32, iso, Counter32, TimeTicks, ObjectIdentity, Bits, Integer32, MibIdentifier = mibBuilder.importSymbols("SNMPv2-SMI", "NotificationType", "MibScalar", "MibTable", "MibTableRow", "MibTableColumn", "IpAddress", "ModuleIdentity", "Counter64", "Unsigned32", "Gauge32", "iso", "Counter32", "TimeTicks", "ObjectIdentity", "Bits", "Integer32", "MibIdentifier")
DisplayString, TextualConvention = mibBuilder.importSymbols("SNMPv2-TC", "DisplayString", "TextualConvention")
panVol = ModuleIdentity((1, 3, 6, 1, 4, 1, 10159, 1, 3, 4))
panVol.setRevisions(('2011-04-07 00:00',))
if mibBuilder.loadTexts: panVol.setLastUpdated('201104070000Z')
if mibBuilder.loadTexts: panVol.setOrganization('Panasas, Inc')
panVolTable = MibTable((1, 3, 6, 1, 4, 1, 10159, 1, 3, 4, 1), )
if mibBuilder.loadTexts: panVolTable.setStatus('current')
panVolEntry = MibTableRow((1, 3, 6, 1, 4, 1, 10159, 1, 3, 4, 1, 1), ).setIndexNames((0, "PANASAS-VOLUMES-MIB-V1", "panVolPath"))
if mibBuilder.loadTexts: panVolEntry.setStatus('current')
panVolPath = MibTableColumn((1, 3, 6, 1, 4, 1, 10159, 1, 3, 4, 1, 1, 1), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: panVolPath.setStatus('current')
panVolBladeSet = MibTableColumn((1, 3, 6, 1, 4, 1, 10159, 1, 3, 4, 1, 1, 2), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: panVolBladeSet.setStatus('current')
panVolSoftQuota = MibTableColumn((1, 3, 6, 1, 4, 1, 10159, 1, 3, 4, 1, 1, 3), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: panVolSoftQuota.setStatus('current')
panVolHardQuota = MibTableColumn((1, 3, 6, 1, 4, 1, 10159, 1, 3, 4, 1, 1, 4), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: panVolHardQuota.setStatus('current')
panVolUsed = MibTableColumn((1, 3, 6, 1, 4, 1, 10159, 1, 3, 4, 1, 1, 5), Unsigned32()).setMaxAccess("readonly")
if mibBuilder.loadTexts: panVolUsed.setStatus('current')
panVolRaid = MibTableColumn((1, 3, 6, 1, 4, 1, 10159, 1, 3, 4, 1, 1, 6), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: panVolRaid.setStatus('current')
panVolInfo = MibTableColumn((1, 3, 6, 1, 4, 1, 10159, 1, 3, 4, 1, 1, 7), DisplayString()).setMaxAccess("readonly")
if mibBuilder.loadTexts: panVolInfo.setStatus('current')
mibBuilder.exportSymbols("PANASAS-VOLUMES-MIB-V1", panVolTable=panVolTable, panVolSoftQuota=panVolSoftQuota, panVolRaid=panVolRaid, panVol=panVol, panVolPath=panVolPath, panVolInfo=panVolInfo, panVolBladeSet=panVolBladeSet, panVolEntry=panVolEntry, PYSNMP_MODULE_ID=panVol, panVolUsed=panVolUsed, panVolHardQuota=panVolHardQuota)


import pyterrier as pt
pt.init()
from collections import defaultdict
import logging
import torch
import argparse
import os
import ir_datasets
import re
import pandas as pd
import numpy as np
from sklearn.metrics import pairwise_distances
import sentence_transformers

### BEGIN EVAL MODELS ###

class Encoder:
    def __init__(self, model_id, device=None) -> None:
        from sentence_transformers import SentenceTransformer
        if device is None:
            device = 'cuda' if device else 'cpu'
        self.device = torch.device(device)
        self.model = SentenceTransformer(model_id, device=self.device)

    def embedding(self, text):
        return self.model.encode([text], convert_to_numpy=True)[0]

    def compare(self, q, d1, d2):
        q_enc = self.embedding(q)
        d1_enc = self.embedding(d1)
        d2_enc = self.embedding(d2)

        dist = pairwise_distances(q_enc.reshape(1, -1), np.stack([d1_enc, d2_enc], axis=0), metric='cosine')[0]
        return dist[0] - dist[1], dist[0], dist[1]

def clean_text(text):
    text = re.sub(r'[^A-Za-z0-9 ]+', '', text)
    return re.sub(r'/[^\x00-\x7F]/g', '', text).strip()

### END EVAL MODELS ###

### BEGIN CONVIENIENCE FUNCTIONS ###

def compile_lookup(df):
    lookup = defaultdict(dict)
    for row in df.itertuples():
        lookup[row.qid][row.docno]=row.adversary
    return lookup

def read_frame(f, c):
    with open(f, 'r') as f:
        text_items = map(lambda x : [y.strip('\n') for y in x.split('\t')], f.readlines())
    v = list(map(list, zip(*text_items)))
    return pd.DataFrame.from_dict({r : v for r, v in zip(c, v)})

### END CONVIENIENCE FUNCTIONS ###
parser = argparse.ArgumentParser()

parser.add_argument('-ctxsource', type=str)
parser.add_argument('-staticsource', type=str)
parser.add_argument('-full_path', type=str)
parser.add_argument('-type', type=str)
parser.add_argument('-embedding_model', type=str)
parser.add_argument('-qrels', type=str)
parser.add_argument('-sink', type=str)

parser.add_argument('--gpu', action='store_true')

def main(args):

    ### BEGIN LOOKUPS AND MODELS INIT ###
    ds = ir_datasets.load(args.qrels)
    queries = pd.DataFrame(ds.queries_iter()).set_index('query_id').text.to_dict()

    semantic_distance = Encoder(args.embedding_model)

    def get_diff(qid, context, static):
        query = queries[qid]
        return semantic_distance.compare(query, context, static)

    ### END LOOKUPS AND MODELS INIT ###

    cols = ['qid', 'docno', 'adversary', 'rel', 'pos', 'salience', 'salience_type', 'sentence', 'context']
    ctxcols = ['qid', 'docno', 'adversary', 'sentence', 'rel', 'pos', 'salience', 'salience_type', 'context']

    frames = []

    ctxtext = read_frame(args.ctxsource, ctxcols)
    statictext = read_frame(args.staticsource, cols)

    filtercol = lambda x, y, z : x[x[y]==z].copy()

    for ctx in ctxtext.context.unique().tolist():
            ctxsub = filtercol(ctxtext, 'context', ctx)
            staticsub = filtercol(statictext, 'context', ctx)
            sets = []
            if args.type == 'salience':
                for sal in ['salient', 'nonsalient']:
                    ctxsubsub = filtercol(ctxsub, 'salience', sal)
                    staticsubsub = filtercol(staticsub, 'salience', sal)
                    for pos in ['before', 'after']:
                        sets.append((filtercol(ctxsubsub, 'pos', pos), filtercol(staticsubsub, 'pos', pos)))
            else:
                for pos in ['before', 'middle', 'after']:
                    sets.append((filtercol(ctxsub, 'pos', pos), filtercol(staticsub, 'pos', pos)))
            for c, s in sets:
                position = c.pos.tolist()[0]
                salience = c.salience.tolist()[0]

                ctxlookup = compile_lookup(c)
                staticlookup = compile_lookup(s)

                res = []
                for key, item in ctxlookup.items():
                    for doc, _ in item.items():
                        try:
                            diff, d1, d2 = get_diff(key, ctxlookup[key][doc], staticlookup[key][doc])
                        except KeyError:
                            logging.info('Failed to find {key}:{doc} in static')
                            continue
                        res.append({'qid' : key, 'docno' : doc, 'context' : ctx, 'pos' : position, 'salience' : salience, 'semantic_difference' : diff, 'context_score' : d1, 'static_score' : d2})

                frames.append(pd.DataFrame.from_records(res))
    pd.concat(frames).to_csv(args.sink)

if __name__ == '__main__':
    args = parser.parse_args()
    logging.basicConfig(format='%(asctime)s - %(message)s', level=logging.INFO)
    main(args)


# coding: utf-8

import os

import webbrowser

import APIRequest

# Class for creating HTML document with google map with polylines
class GeometryDoc():
    def __init__(self):
        self.polys = 0
        self.markers = 0
        self.document = """<!DOCTYPE html>

                        <meta name="viewport" content="initial-scale=1.0, user-scalable=no">
                        <meta charset="utf-8">
                        <title>Karta</title>

                    """

    # Add the polylines to the map
    def addPoly(self, points, colour):
        #print(points)
        document = "var route" + str(self.polys) + """ = [];
                            var flightPath""" + str(self.polys) + """ = new google.maps.Polyline({
                              path: route""" + str(self.polys) + """,
                              geodesic: true,
                              strokeColor: '#FF0000',
                              strokeOpacity: 1.0,
                              strokeWeight: 4
                            });

                            flightPath""" + str(self.polys) + """.setMap(map);

                            //NEW"""

        # Replace characters so google maps understands it
        document = document.replace(" = []", " = " + str(points).replace("},", "},\n").replace("'", "").replace('"', ""))
        document = document.replace("lon:", "lng:")

        document = document.replace("strokeColor: '#FF0000'", "strokeColor: '" + colour + "'")

        self.document = self.document.replace("//NEW", document)
        self.polys += 1

        #print(self.document)
        self.save()

    # Add a marker to the map
    def addMarker(self, points):
        if type(points) != dict:
            raise TypeError(f'Expected dict, {str(type(points))} received.')

        # print("Adding marker")
        document = "var point" + str(self.markers) + "= " + str(points) + """
                var marker""" + str(self.markers) + """ = new google.maps.Marker({
                    position: point""" + str(self.markers) + """,
                    icon: image,
                    title: name,
                    map: map
                });

                //NEW"""

        document = document.replace("'lon'", "lng").replace("'", "").replace('"', "")

        self.document = self.document.replace("//NEW", document)
        self.markers += 1
        self.save()

    # Save the HTML document
    def save(self):
        with open("tempfiles/document.html", "w") as file:
            file.write(self.document)
            file.close()
        # print("saved")

# Function called when you want to create a map
def geometryBackEnd(ref, colour=None):
    document = GeometryDoc()

    # If there are multiple legs
    if type(ref) == list:
        for item in ref:
            geoRef = item.get("GeometryRef").get("ref")
            points = APIRequest.APIRequest().geometry(geoRef)

            colour = item.get("fgColor")
            if colour is None: colour = "#00FF00"

            document.addPoly(points, colour)
            document.addMarker(points[0])
        document.addMarker(points[-1])

    # If there is only one leg
    else:
        points = APIRequest.APIRequest().geometry(ref)
        document.addPoly(points, colour)
        document.addMarker(points[0])
        document.addMarker(points[-1])

    # Open the file in a web browser
    folder = os.path.dirname(__file__).replace("\\", "/")
    path = f'file:///{folder}/tempfiles/document.html'
    webbrowser.open(path)

if __name__ == "__main__":
	print("This file is only supposed to be used as a module.")


'''
LeetCode - problem 834
'''

class Solution(object):
    def sumOfDistancesInTree(self, N, edges):
        if N == 1: return [0]

        neighbors = collections.defaultdict(set)
        for n1,n2 in edges:
            neighbors[n1].add(n2)
            neighbors[n2].add(n1)
        dis2child = [0] * N
        population = [1] * N
        dis2all = [0] * N

        def dfs1(node = 0,parent = None):
            for child in neighbors[node]:
                if child != parent:
                    dfs1(child,node)
                    population[node] += population[child]
                    dis2child[node] += dis2child[child] + population[child]
            return
        dis2all = dis2child
        def dfs2(node = 0,parent = None):
            for child in neighbors[node]:
                if child != parent:
                    dis2all[child] = dis2all[node] + N - 2*population[child]
                    dfs2(child,node)

        dfs1()
        dfs2()
        return dis2all


# -*- coding: utf-8 -*-
"""
This file contains all classes for object relational mappings.
"""

__author__ = "Lukas Reiter"
__license__ = "GPL v3.0"
__copyright__ = """Copyright 2018 Lukas Reiter

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
"""
__version__ = 0.1

import os
import re
import enum
import magic
import hashlib
import logging
import hexdump
from sqlalchemy import Column
from sqlalchemy import Integer
from sqlalchemy import Boolean
from sqlalchemy import String
from sqlalchemy import DateTime
from sqlalchemy import ForeignKey
from sqlalchemy import Text
from sqlalchemy import Enum
from sqlalchemy import Table
from sqlalchemy import LargeBinary
from sqlalchemy.orm import relationship
from sqlalchemy.orm import backref
from sqlalchemy import UniqueConstraint
from sqlalchemy.ext.declarative import declarative_base
from datetime import datetime
from termcolor import colored
from typing import List

DeclarativeBase = declarative_base()

logger = logging.getLogger('model')

class WorkspaceNotFound(Exception):
    def __init__(self, workspace: str):
        super().__init__("workspace '{}' does not exist in database".format(workspace))

class HunterType(enum.Enum):
    smb = enum.auto()
    ftp = enum.auto()
    nfs = enum.auto()
    local = enum.auto()

class ReviewResult(enum.Enum):
    irrelevant = enum.auto()
    relevant = enum.auto()
    tbd = enum.auto()

class FileRelevance(enum.Enum):
    low = 200
    medium = 2000
    high = 20000

class MatchRuleAccuracy(enum.Enum):
    low = 100
    medium = 1000
    high = 10000

class SearchLocation(enum.Enum):
    file_name = 1
    full_path = 1000
    file_content = 10000

file_match_rule_mapping = Table("file_match_rule_mapping", DeclarativeBase.metadata,
                                Column("id", Integer, primary_key=True),
                                Column("file_id", Integer, ForeignKey('file.id',
                                                                      ondelete='cascade'), nullable=False),
                                Column("match_rule_id", Integer, ForeignKey('match_rule.id',
                                                                            ondelete='cascade'), nullable=False),
                                Column("creation_date", DateTime, nullable=False, default=datetime.utcnow()),
                                Column("last_modified", DateTime, nullable=True, onupdate=datetime.utcnow()))

class Workspace(DeclarativeBase):
    """This class holds all information about a project."""

    __tablename__ = "workspace"
    id = Column(Integer, primary_key=True)
    name = Column(String(25), nullable=False, unique=True)
    hosts = relationship("Host",
                         backref=backref("workspace"),
                         cascade="delete, delete-orphan",
                         order_by="asc(Host.address)")
    files = relationship("File",
                         backref=backref("workspace"),
                         cascade="all",
                         order_by="desc(File.size_bytes)")
    creation_date = Column(DateTime, nullable=False, default=datetime.utcnow())
    last_modified = Column(DateTime, nullable=True, onupdate=datetime.utcnow())

class Host(DeclarativeBase):
    """This class holds all information about a host."""

    __tablename__ = "host"
    id = Column("id", Integer, primary_key=True)
    address = Column("address", Text, nullable=False, unique=False)
    workspace_id = Column(Integer, ForeignKey("workspace.id", ondelete='cascade'), nullable=False, unique=False)
    creation_date = Column(DateTime, nullable=False, default=datetime.utcnow())
    last_modified = Column(DateTime, nullable=True, onupdate=datetime.utcnow())
    services = relationship("Service",
                            backref=backref("host"),
                            cascade="all, delete-orphan",
                            order_by="asc(Service.port)")
    __table_args__ = (UniqueConstraint('workspace_id', 'address', name='_host_unique'),)

class Service(DeclarativeBase):
    """This class holds all information about a service."""

    __tablename__ = "service"
    id = Column(Integer, primary_key=True)
    port = Column(Integer, nullable=True, unique=False)
    name = Column(Enum(HunterType), nullable=False, unique=False)
    complete = Column(Boolean, nullable=True, unique=False)
    host_id = Column(Integer, ForeignKey("host.id", ondelete='cascade'), nullable=False, unique=False)
    creation_date = Column(DateTime, nullable=False, default=datetime.utcnow())
    last_modified = Column(DateTime, nullable=True, onupdate=datetime.utcnow())
    paths = relationship("Path",
                         backref=backref("service"),
                         cascade="all",
                         order_by="asc(Path._full_path)")
    __table_args__ = (UniqueConstraint("port", "host_id", name="_service_host_unique"),)

    def __repr__(self):
        result = ""
        if self.host:
            if self.name == HunterType.smb:
                result = "//{}".format(self.host.address)
            elif self.name != HunterType.local:
                result = "{}://{}".format(self.name.name, self.host.address)
            if self.port and (self.name == HunterType.smb and self.port != 445 or
                              self.name == HunterType.ftp and self.port != 21 or
                              self.name == HunterType.nfs and self.port != 2049):
                result += ":{}".format(self.port)
        return result

class Path(DeclarativeBase):
    """This class holds all information about identified paths."""

    __tablename__ = "path"
    id = Column(Integer, primary_key=True)
    _full_path = Column("full_path", Text, nullable=False, unique=False)
    file_name = Column(Text, nullable=False, unique=False)
    extension = Column(Text, nullable=False, unique=False)
    share = Column(Text, nullable=True, server_default='')
    access_time = Column(DateTime, nullable=True)
    modified_time = Column(DateTime, nullable=True)
    creation_time = Column(DateTime, nullable=True)
    service_id = Column(Integer, ForeignKey("service.id", ondelete='cascade'), nullable=False, unique=False)
    file_id = Column(Integer, ForeignKey("file.id", ondelete='cascade'), nullable=True, unique=False)
    creation_date = Column(DateTime, nullable=False, default=datetime.utcnow())
    last_modified = Column(DateTime, nullable=True, onupdate=datetime.utcnow())
    file = relationship("File",
                        backref=backref("paths"),
                        cascade="all",
                        order_by="desc(File.size_bytes)")
    __table_args__ = (UniqueConstraint('full_path', 'share', 'service_id', name='_path_unique'),)

    @property
    def full_path(self) -> str:
        return self._full_path

    @full_path.setter
    def full_path(self, value: str) -> None:
        self.extension = os.path.splitext(value)[1]
        if self.extension:
            self.extension = self.extension.lstrip(".")
        self._full_path = value.replace("\\", "/")
        self.file_name = os.path.basename(self._full_path)

    def __repr__(self):
        result = ""
        if self.service and self.service.host:
            result = str(self.service)
            if self.service.name == HunterType.smb and self.share:
                result += "/{}".format(self.share)
            if self.full_path:
                result += self.full_path if self.full_path[0] == "/" else ("/" + self.full_path)
        return result

class File(DeclarativeBase):
    """This class holds all files"""

    __tablename__ = "file"
    id = Column(Integer, primary_key=True)
    _content = Column("content", LargeBinary, nullable=True, unique=False)
    size_bytes = Column(Integer, nullable=False, unique=False)
    sha256_value = Column(Text, nullable=False, unique=False)
    file_type = Column(Text, nullable=True, unique=False)
    mime_type = Column(Text, nullable=True, unique=False)
    comment = Column(Text, nullable=True, unique=False)
    review_result = Column(Enum(ReviewResult), nullable=True, unique=False)
    workspace_id = Column(Integer, ForeignKey("workspace.id", ondelete='cascade'), nullable=False, unique=False)
    creation_date = Column(DateTime, nullable=False, default=datetime.utcnow())
    last_modified = Column(DateTime, nullable=True, onupdate=datetime.utcnow())
    __table_args__ = (UniqueConstraint('sha256_value', 'workspace_id', name='_file_unique'),)
    matches = relationship("MatchRule",
                           secondary=file_match_rule_mapping,
                           backref=backref("files",
                                           order_by="asc(MatchRule._relevance)"))
    @property
    def content(self) -> bytes:
        return self._content

    @content.setter
    def content(self, value: bytes):
        self._content = value
        self.size_bytes = len(value)
        self.sha256_value = self.calculate_sha256_value(value)
        self.file_type = magic.from_buffer(value)
        self.mime_type = magic.from_buffer(value, mime=True)

    @property
    def review_result_str(self) -> str:
        return self.review_result.name if self.review_result else ReviewResult.tbd.name

    @property
    def review_result_with_color_str(self) -> str:
        result = self.review_result_str
        colors = {"": None,
                  ReviewResult.tbd.name: "blue",
                  ReviewResult.irrelevant.name: "grey",
                  ReviewResult.relevant.name: "red"}
        return colored(result, colors[result], attrs=["bold"])

    def add_match_rule(self, match_rule):
        """
        This method shall be used to add a match rule to tis file
        :param match_rule: The match rule object that shall be added
        :return:
        """
        if match_rule not in self.matches:
            self.matches.append(match_rule)

    @staticmethod
    def calculate_sha256_value(content: bytes) -> str:
        """
        This method calculates the sha256 value of the given content.
        :param content:
        :return:
        """
        return hashlib.sha256(content).hexdigest()

    @staticmethod
    def apply_highlights(text: str, markers: list) -> str:
        """
        This method color-codes the text based on the given marker ranges.
        """
        if not markers:
            return text
        color_code = lambda x: colored(x, "red",  attrs=['bold'])
        result = ""
        current_position = 0
        markers.sort()
        for i, j in markers:
            result += text[current_position:i]
            result += color_code(text[i:j])
            current_position = j
        result += text[current_position:]
        return result

    def get_text(self, color: bool = False, match_rules: list = [], threshold: int = 0) -> List[str]:
        """
        This method returns the details about the review.
        """
        result = []
        markers = []
        print_bold = lambda x: colored(x, attrs=['bold']) if color else x
        review_result = self.review_result_with_color_str if color else self.review_result_str
        try:
            content = self.content.decode("utf-8")
            for item in match_rules:
                markers = item.get_text_markers(content, markers)
            if color:
                content = self.apply_highlights(content, markers)
            result.append(content)
        except:
            try:
                for line in hexdump.dumpgen(self.content):
                    result.append(line)
            except Exception as ex:
                result.append(print_bold("exception while decoding file: {}".format(str(ex))))
                result.append(print_bold("could not print file. try to export and analyze with another program"))
        result.append("")
        result.append("{}       {}".format(print_bold("File ID"), self.id))
        result.append("{}         {}".format(print_bold("Paths"),
                                             "; ".join([str(item) for item in self.paths])))
        result.append("{}     {}".format(print_bold("MIME type"), self.mime_type))
        if threshold:
            result.append("{}     {} ({})".format(print_bold("File size"),
                                                  self.size_bytes,
                                                  "<= threshold" if self.size_bytes < threshold else "> threshold"))
        else:
            result.append("{}     {}".format(print_bold("File size"), self.size_bytes))
        result.append(print_bold("Match rules"))
        for item in self.matches:
            result.append("- {}".format(item.get_text(color)))
        result.append("{} {}".format(print_bold("Review result"), review_result))
        if self.comment:
            result.append("{}       {}".format(print_bold("Comment"), self.comment))
        if color:
            result.append("{}          {}".format(print_bold("Hits"), colored(len(markers), "red", attrs=["bold"])))
        else:
            result.append("{}          {}".format(print_bold("Hits"), len(markers)))
        return result

class MatchRule(DeclarativeBase):
    """This class holds all files"""

    __tablename__ = "match_rule"
    id = Column(Integer, primary_key=True)
    _search_location = Column("search_location", Integer, nullable=False, unique=False)
    _search_pattern = Column("search_pattern", Text, nullable=False, unique=False)
    category = Column(Text, nullable=True, unique=False)
    _relevance = Column("relevance", Integer, nullable=False, unique=False)
    _accuracy = Column("accuracy", Integer, nullable=False, unique=False)
    creation_date = Column(DateTime, nullable=False, default=datetime.utcnow())
    last_modified = Column(DateTime, nullable=True, onupdate=datetime.utcnow())
    _search_pattern_re = None
    action = None
    __table_args__ = (UniqueConstraint('search_location', 'search_pattern', name='_match_rule_unique'),)

    @property
    def priority(self):
        """Returns the priority of the given rule"""
        result = 0
        if self._search_location and self._relevance and self._accuracy and self.search_pattern:
            result = self._search_location + self._relevance + self._accuracy + len(self.search_pattern)
        return result

    @property
    def search_pattern(self) -> str:
        return self._search_pattern

    @search_pattern.setter
    def search_pattern(self, value: str) -> None:
        self._search_pattern = value
        self._search_pattern_re = re.compile(value.encode("utf-8"), re.IGNORECASE)

    @property
    def search_location(self):
        result = None
        if self._search_location:
            result = SearchLocation(self._search_location)
        return result

    @search_location.setter
    def search_location(self, value):
        if value:
            self._search_location = value.value

    @property
    def relevance(self) -> FileRelevance:
        result = None
        if self._relevance:
            result = FileRelevance(self._relevance)
        return result

    @relevance.setter
    def relevance(self, value: FileRelevance):
        if value:
            self._relevance = value.value

    @property
    def accuracy(self) -> MatchRuleAccuracy:
        result = None
        if self._accuracy:
            result = MatchRuleAccuracy(self._accuracy)
        return result

    @accuracy.setter
    def accuracy(self, value: MatchRuleAccuracy):
        if value:
            self._accuracy = value.value

    @property
    def search_pattern_re(self):
        if self._search_pattern_re is None:
            self._search_pattern_re = re.compile(self._search_pattern.encode("utf-8"), re.IGNORECASE)
        return self._search_pattern_re

    @property
    def search_pattern_re_text(self):
        if self._search_pattern_re is None:
            self._search_pattern_re = re.compile(self._search_pattern, re.IGNORECASE)
        return self._search_pattern_re

    @property
    def relevance_str(self):
        return self.relevance.name if self._relevance else ""

    @property
    def relevance_with_color_str(self):
        result = self.relevance_str
        colors = {"": None,
                  FileRelevance.high.name: "red",
                  FileRelevance.medium.name: "yellow",
                  FileRelevance.low.name: "blue"}
        return colored(result, colors[result], attrs=["bold"])

    @property
    def accuracy_str(self):
        return self.accuracy.name if self.accuracy else ""

    @property
    def accuracy_with_color_str(self):
        result = self.accuracy_str
        colors = {"": None,
                  MatchRuleAccuracy.high.name: "red",
                  MatchRuleAccuracy.medium.name: "yellow",
                  MatchRuleAccuracy.low.name: "blue"}
        return colored(result, colors[result], attrs=["bold"])

    def __eq__(self, value):
        return self.search_location == value.search_location and self.search_pattern == value.search_pattern

    def is_match(self, path: Path) -> bool:
        """
        This method determines whether the given path object matches this match rule.
        :param path: The path object that is analyzed.
        :return:
        """
        if self.search_location == SearchLocation.file_content:
            result = len(self.search_pattern_re.findall(path.file.content)) > 0
        elif self.search_location == SearchLocation.file_name:
            result = self.search_pattern_re.match(path.file_name.encode("utf-8")) is not None
        elif self.search_location == SearchLocation.full_path:
            result = self.search_pattern_re.match(path.full_path.encode("utf-8")) is not None
        else:
            raise NotImplementedError("this case is not implemented")
        return result

    @staticmethod
    def from_json(json_object: dict):
        """
        This method converts the given json_object into a MatchRule object
        :param json_object: The json_object containing all information to create a MatchRule object
        :return: The match rule object
        """
        search_location = SearchLocation[json_object["search_location"]]
        category = json_object["category"]
        relevance = FileRelevance[json_object["relevance"]]
        accuracy = MatchRuleAccuracy[json_object["accuracy"]]
        search_pattern = json_object["search_pattern"]
        rule = MatchRule(search_location=search_location,
                         category=category,
                         relevance=relevance,
                         search_pattern=search_pattern,
                         accuracy=accuracy)
        return rule

    def __repr__(self):
        return "priority: {}, category: {}, search_location: {}, relevance: {}, " \
               "accuracy: {}, search_pattern: {}".format(self.priority,
                                                         self.category,
                                                         self.search_location.name,
                                                         self.relevance_str,
                                                         self.accuracy.name,
                                                         self.search_pattern)

    def get_text_markers(self, text: str, known_markers: list = []) -> list:
        """
        This method determines searches the given text for a matches and returns a list of tuples documenting the
        locations where the matches started and stopped.
        :param text: The text that is searched.
        :param known_markers: Markers that have previously already identified.
        """
        result = list(known_markers)
        if self.search_pattern_re_text is not None and text:
            for item in self.search_pattern_re_text.finditer(text):
                if known_markers:
                    for new_index in range(0, len(item.regs)):
                        i, j = item.regs[new_index]
                        for current_index in range(0, len(result)):
                            k, m = result[current_index]
                            if i <= k and j >= m:
                                result[current_index] = (i, j)
                                break
                            elif k <= i <= m and k <= j <= m:
                                break
                            elif k <= i <= m and j >= m:
                                result[current_index] = (k, j)
                                break
                            elif i <= k and k <= j <= m:
                                result[current_index] = (i, m)
                                break
                        else:
                            result.append((i, j))
                elif item.regs:
                    result.extend(item.regs)
        return result

    def get_text(self, color: bool = False) -> str:
        """
        Returns the current object state as string
        """
        relevance = self.relevance_with_color_str if color else self.relevance_str
        accuracy = self.accuracy_with_color_str if color else self.accuracy_str
        print_bold = lambda x: colored(x, attrs=['bold']) if color else x
        if self.category:
            result = "{}: {}; {}: {}; {}: {}; {}: {}, {}: {}".format(print_bold("search location"),
                                                                     self.search_location.name,
                                                                     print_bold("pattern"),
                                                                     self._search_pattern,
                                                                     print_bold("category"),
                                                                     self.category,
                                                                     print_bold("relevance"),
                                                                     relevance,
                                                                     print_bold("accuracy"),
                                                                     accuracy)
        else:
            result = "{}: {}; {}: {}; {}: {}, {}: {}".format(print_bold("search location"),
                                                             self.search_location.name,
                                                             print_bold("pattern"),
                                                             self._search_pattern,
                                                             print_bold("relevance"),
                                                             relevance,
                                                             print_bold("accuracy"),
                                                             accuracy)
        return result


from rest_framework import serializers
from .models import Venue, Seat

class VenueSerializer(serializers.HyperlinkedModelSerializer):
    seats = serializers.HyperlinkedRelatedField(
        view_name='seat_detail',
        many=True,
        read_only=True
    )

    venue_url = serializers.ModelSerializer.serializer_url_field(     view_name='venue_detail'
    )

    class Meta:
       model = Venue
       fields = ('id', 'venue_url', 'name', 'location', 'indoor', 'outdoor', 'photo_url', 'seats',)

class SeatSerializer(serializers.HyperlinkedModelSerializer):
    venue = serializers.HyperlinkedRelatedField(
        view_name='seat_detail',
        read_only=True
    )

    venue_id = serializers.PrimaryKeyRelatedField(
    queryset=Venue.objects.all(),
    source='venue'
    )

    class Meta:
        model = Seat
        fields = ('id', 'venue', 'venue_id', 'slocation', 'rating', 'image_url', 'reviewer', 'description')


#criar um loop que identifica numero primo

numero = int(input("Bota numero aqui:"))

divisao = 0

contador = numero

while contador > 0:
    if (numero % contador == 0):
        divisao += 1

    contador -= 1

if (divisao == 2):
    print("O número %d é primo" % numero)
else:
    print("O número %d NÃO é primo" % numero)


import requests

from requests.structures import CaseInsensitiveDict

import os

import sys

import time

os.system("pip install requests")

os.system("clear")

red="\033[0;31m"          # Red

yellow="\033[0;33m"       # Yellow

green="\033[0;32m"        # Green

color_off="\033[0m"       # Text Reset

bblack="\033[1;30m"       # Black

bred="\033[1;31m"         # Red

ured="\033[4;31m"         # Red

on_green="\033[42m"       # Green

blue="\033[0;34m"         # Blue

lightblue = '\033[94m'

red = '\033[91m'

white = '\33[97m'

yellow = '\33[93m'

green = '\033[1;32m'

cyan  = "\033[96m"

end = '\033[0m'

purple="\033[0;35m"

logo=(green+"""  _   _ _           _
| \ | (_)_ __ ___ | |__
|  \| | | '__/ _ \| '_ \
| |\  | | | | (_) | |_) |
|_| \_|_|_|  \___/|_.__/  """)

line=(yellow+"======================================================")
tversion=(cyan+"\t\t     Version : 1.0.2 ")

line2=("\t\t~~~~~~~~~~~~~~~~~~~~~~~~~~")

dtls=(yellow+"\t\tCreated ʙʏ : Mizanur Rahman Nirob \n \t\thttps://t.me/Unknown_Helper_O02\n \t\thttps://github.com/Cyber-Foxx")

note=(red+"Note: I wont be responsible fo any illigal activites.")

print(logo)

print(" ")

print(dtls)

print(tversion)

print(line)

print(note)

print(line)

print(green+"\t\t[•]Checking For Updates...")

version = open(".version.txt", "r")

mainversion = requests.get("https://raw.githubusercontent.com/Cyber-Foxx/Inbox-killer/main/.version.txt")

time.sleep(0.6)

if(version.read() == mainversion.text):

	print(cyan+"You are using the latest version of Inbox-killer")

else:

	print(' ')
	print(' ')
	print(red+"\t\t[✓]Tool Update Found")

	print(blue+"\t\tUpdating Tool...")

	os.system("cd .. && rm -rf Inbox-killer && git clone https://github.com/Cyber-Foxx/Inbox-killer > /dev/null 2>&1 && cd Inbox-killer && python Inbox killer.py")

os.system("clear")

print(logo)

print(" ")

print(dtls)

print(tversion)

print(line)

print(note)

print(line)

print(lightblue+'\t\t If You Type [1] sent it 5 SMS')

print(' ')

number=str(input(red+"[➙] Enter Your Number [Ex: 018********] "))
amount=int(input(cyan+"[➙] Enter The Amount : "))

url1 = "https://ss.binge.buzz/otp/send/login"

headers1 = CaseInsensitiveDict()
headers1["Content-Type"] = "application/x-www-form-urlencoded"

data1 = "phone="+number

url2 = "https://api.daktarbhai.com/api/v2/otp/generate?=&api_key=BUFWICFGGNILMSLIYUVH&api_secret=WZENOMMJPOKHYOMJSPOGZNAGMPAEZDMLNVXGMTVE&mobile=%2B88"+number+"&platform=app&activity=login"

headers2 = CaseInsensitiveDict()
headers2["Content-Type"] = "application/json"
headers2["Content-Length"] = "0"

url3 = "https://stage.bioscopelive.com/en/login/send-otp?phone=88"+number+"&operator=bd-otp"

url4 = "https://xrides.shohoz.com/api/v2/user/send-mobile-verification-code"

headers4 = CaseInsensitiveDict()
headers4["Content-Type"] = "application/json"

data4 = '{\"mobile\":\"'+number+'\"}'

url5 = "https://addabaji.mobi/twocups-v1-robi/otp.php"

headers5 = CaseInsensitiveDict()
headers5["Content-Type"] = "application/x-www-form-urlencoded"

data5 = "msisdn="+number

url6 = "https://developer.quizgiri.xyz/api/v2.0/send-otp"
headers6 = CaseInsensitiveDict()
headers6["Content-Type"] = "application/json"

data6 = '{"phone":"'+number+'","country_code":"+880","fcm_token":null}'

for i in range (amount):
	resp1 = requests.post(url1, headers=headers1, data=data1)
	resp2 = requests.post(url2, headers=headers2)
	resp3 = requests.get(url3)
	resp4 = requests.post(url4, headers=headers4,data=data4)
	resp5 = requests.post(url5, headers=headers5, data=data5)
	resp = requests.post(url6, headers=headers6, data=data6)
	print(str(i+1)+green+'.	➙Success Requests')

print('					')
print(cyan+'\t\tThanks For Using Inbox-killer ')

os.system("xdg-open https://t.me/Unknown_Helper_O02")


from flask import Flask, jsonify, request
from bs4 import BeautifulSoup
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service
from flask_cors import CORS
import csv
import time

app = Flask(__name__)
CORS(app)

@app.route('/ScrapeLetterboxdFavourites', methods=['GET'])
def ScrapeLetterboxdFavourites():
    print("Scraping favourites for... " + str(request.args.get('username')))
    favouriteFilms = []

    options = Options()
    service = Service()
    options.add_argument('--headless')
    driver = webdriver.Chrome(service=service, options=options)

    driver.get('https://letterboxd.com/'+str(request.args.get('username'))+'/')

    time.sleep(0.4)
    # 0.08 Seems to be the smallest amount of time that works
    # can go as low as 0.05 but sometimes doesn't get all titles

    page_source = driver.page_source
    soup = BeautifulSoup(page_source, 'html.parser')
    favorite_films_section = soup.find_all('li', class_='poster-container')

    count = 0
    for film in favorite_films_section:
        for title in film.find_all('span', class_='frame-title'):
            if count < 4:
                print(title.text)
                favouriteFilms.append(title.text)
                count += 1
        if count == 4:
            break

    driver.quit()
    return jsonify({'favourite_films': favouriteFilms})

if __name__ == '__main__':
    app.run(host='0.0.0.0', port=1122)


import numpy as np

from constants import *
from utils import stairs

def a2f_direct(qpoints, smoothing, dtype=np.float16):
    """
    Computes Eliashberg functions a2F directly from lambdas and gammas without any integration.
    """
    freqs, a2f_lambda, a2f_gamma = list(), list(), list()
    for q_point in qpoints:
        dyn_elph = q_point['DynElph']
        lambdas = dyn_elph.lambdas
        gammas = dyn_elph.gammas
        nef = dyn_elph.DOS
        weight = q_point['weight']
        q_freqs = np.sqrt(np.abs(dyn_elph.sqr_freqs)) * np.sign(dyn_elph.sqr_freqs) * k_Ry_THz
        smooth = np.exp(-np.square(smoothing / q_freqs))
        q_a2f_lambda = smooth * lambdas * q_freqs / 2 * weight
        q_a2f_gamma = smooth * gammas / q_freqs / nef / k_Ry_GHz / np.pi / 2 * weight * k_Ry_THz ** 2
        a2f_lambda.append(q_a2f_lambda)
        a2f_gamma.append(q_a2f_gamma)
        freqs.append(q_freqs)
    freqs, a2f_lambda, a2f_gamma = map(lambda x: np.array(x).flatten(), (freqs, a2f_lambda, a2f_gamma))
    idxs = freqs.argsort()
    freqs = freqs[idxs]
    a2f_lambda = a2f_lambda[idxs]
    a2f_gamma = a2f_gamma[idxs]
    a2f_lambda[a2f_lambda <= 0] = 0
    a2f_gamma[a2f_gamma <= 0] = 0
    out_dict = {
        'freqs, THz': freqs,
        'a2f (lambda), THz': a2f_lambda,
        'a2f (gamma), THz': a2f_gamma
    }
    return out_dict

def lambdas_direct(qpoints, smoothing, dtype=np.float16):
    """
    Computes lambdas directly from lambdas and gammas without any integration.
    WARNING: Avoid using dtype=np.float32 or better, sometimes it leads to computational errors.
    """
    freqs_smooth, lambdas_lambda_smooth, lambdas_gamma_smooth = list(), list(), list()
    freqs, lambdas_lambda, lambdas_gamma = list(), list(), list()
    # print(len(qpoints))
    for q_point in qpoints:
        dyn_elph = q_point['DynElph']
        lambdas = dyn_elph.lambdas
        gammas = dyn_elph.gammas
        nef = dyn_elph.DOS
        weight = q_point['weight']
        q_freqs = np.sqrt(np.abs(dyn_elph.sqr_freqs)) * np.sign(dyn_elph.sqr_freqs) * k_Ry_THz
        smooth = np.exp(-np.square(smoothing / q_freqs))
        q_lambdas_lambda_smooth = smooth * lambdas * weight
        q_lambdas_gamma_smooth = smooth * gammas * weight / np.square(q_freqs) / nef * k_Ry_THz / 1000 / np.pi
        q_lambdas_lambda = lambdas * weight
        q_lambdas_gamma = gammas * weight / np.square(q_freqs) / nef * k_Ry_THz / 1000 / np.pi
        lambdas_lambda_smooth.append(q_lambdas_lambda_smooth)
        lambdas_gamma_smooth.append(q_lambdas_gamma_smooth)
        lambdas_lambda.append(q_lambdas_lambda)
        lambdas_gamma.append(q_lambdas_gamma)
        freqs_smooth.append(q_freqs)
        freqs.append(q_freqs)
    freqs_smooth, lambdas_lambda_smooth, lambdas_gamma_smooth = map(lambda x: np.array(x).flatten(), (
        freqs_smooth, lambdas_lambda_smooth, lambdas_gamma_smooth))
    freqs, lambdas_lambda, lambdas_gamma = map(lambda x: np.array(x).flatten(), (freqs, lambdas_lambda, lambdas_gamma))
    idxs = freqs_smooth.argsort()
    lambdas_lambda_smooth = lambdas_lambda_smooth[idxs]
    # print(lambdas_lambda_smooth, np.sum(lambdas_lambda_smooth))
    lambdas_gamma_smooth = lambdas_gamma_smooth[idxs]
    lambda_lambda_stairs_smooth = stairs(lambdas_lambda_smooth)
    lambda_gamma_stairs_smooth = stairs(lambdas_gamma_smooth)
    idxs = freqs.argsort()
    lambdas_lambda = lambdas_lambda[idxs]
    lambdas_gamma = lambdas_gamma[idxs]
    lambda_lambda_stairs = stairs(lambdas_lambda)
    lambda_gamma_stairs = stairs(lambdas_gamma)
    out_dict = {
        'lambdas (lambda)': lambdas_lambda_smooth,
        'lambdas (gamma)': lambdas_gamma_smooth,
        'lambda (lambda)': lambda_lambda_stairs_smooth,
        'lambda (gamma)': lambda_gamma_stairs_smooth,
        'lambda (lambda, not smooth)': lambda_lambda_stairs,
        'lambda (gamma, not smooth)': lambda_gamma_stairs
    }
    return out_dict

def wlogs_direct(direct):
    """
    Computes wlogs directly from lambdas and gammas without any integration.
    First you need to calculate lambdas.
    """
    freqs, lambdas_lambda, lambdas_gamma = direct['freqs, THz'], direct['lambdas (lambda)'], direct['lambdas (gamma)']
    lambda_lambda = np.sum(lambdas_lambda)
    lambda_gamma = np.sum(lambdas_gamma)
    freqs_K = freqs[freqs > 0] / k_Ry_THz * k_Ry_K
    zeros = np.zeros(freqs[freqs <= 0].shape)
    wlogs_lambda = lambdas_lambda[freqs > 0] * np.log(freqs_K) / lambda_lambda
    wlogs_gamma = lambdas_gamma[freqs > 0] * np.log(freqs_K) / lambda_gamma
    wlogs_lambda[wlogs_lambda <= 0] = 0
    wlogs_gamma[wlogs_gamma <= 0] = 0
    wlogs_lambda_stairs = np.concatenate((np.zeros(wlogs_lambda[wlogs_lambda <= 0].shape),
                                          np.exp(stairs(wlogs_lambda[wlogs_lambda > 0]))))
    wlogs_gamma_stairs = np.concatenate((np.zeros(wlogs_gamma[wlogs_gamma <= 0].shape),
                                         np.exp(stairs(wlogs_gamma[wlogs_gamma > 0]))))
    wlogs_lambda, wlogs_gamma, wlogs_lambda_stairs, wlogs_gamma_stairs = \
        map(lambda x: np.concatenate((zeros, x)), (wlogs_lambda, wlogs_gamma, wlogs_lambda_stairs, wlogs_gamma_stairs))
    out_dict = {
        'wlogs (lambda), K': wlogs_lambda,
        'wlogs (gamma), K': wlogs_gamma,
        'wlog (lambda), K': wlogs_lambda_stairs,
        'wlog (gamma), K': wlogs_gamma_stairs,
    }
    return out_dict

def w2s_direct(direct):
    """
    Computes w2s directly from lambdas and gammas without any integration.
    First you need to calculate lambdas.
    """
    freqs, lambdas_lambda, lambdas_gamma = direct['freqs, THz'], direct['lambdas (lambda)'], direct['lambdas (gamma)']
    lambda_lambda = np.sum(lambdas_lambda)
    lambda_gamma = np.sum(lambdas_gamma)
    freqs_K = freqs / k_Ry_THz * k_Ry_K
    w2s_lambda = lambdas_lambda * np.square(freqs_K) / lambda_lambda
    w2s_gamma = lambdas_gamma * np.square(freqs_K) / lambda_gamma
    w2s_lambda_stairs = np.sqrt(stairs(w2s_lambda, dtype=np.longdouble))
    w2s_gamma_stairs = np.sqrt(stairs(w2s_gamma, dtype=np.longdouble))
    out_dict = {
        'w2s (lambda), K': w2s_lambda,
        'w2s (gamma), K': w2s_gamma,
        'w2 (lambda), K': w2s_lambda_stairs,
        'w2 (gamma), K': w2s_gamma_stairs,
    }
    return out_dict


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from sklearn.linear_model import LinearRegression
from sklearn.model_selection import train_test_split

df = pd.read_csv("AutoInsurSweden.csv", sep = '\t')
df['Y'] = [x.replace(',', '.') for x in df['Y']]
df['Y'] = df['Y'].astype(float)
print(df.head())
X = df['X']
Y = df['Y']
X_train, X_test, Y_train, Y_test = np.asarray(train_test_split(X, Y, test_size = 0.15))

plt.scatter(X_train, Y_train)
plt.xlabel("X_train")
plt.ylabel("Y_train")
plt.show()

print("X_train contain = ", X_train.shape, "    and    Y_train contain = ", Y_train.shape)
print("X_test  contain = ", X_test.shape, "    and    Y_test   contain = ", Y_test.shape)

model = LinearRegression()
model.fit(X_train.values.reshape(-1,1), Y_train.values.reshape(-1,1))
#prediction = model.predict(X_test.values.reshape(-1,1))

score = model.score(X_test.values.reshape(-1,1), Y_test.values.reshape(-1,1))

print("Score = ", score)


Mike_Tomlin = [164.33, 175.00, 750,50]
Bill_Gates = [100000.00]
Charles_Barkley = [1130.80, 100.00]
Bill_Clinton = [250.00, 800.00, 1200.00]
Rosanne_Barr = [86.98, 124.30]
Donors = [Mike_Tomlin, Bill_Gates, Charles_Barkley, Bill_Clinton, Rosanne_Barr]
Donors_names = ['Mike Tomlin', 'Bill Gates', 'Charles Barkley', 'Bill Clinton', 'Rosanne Barr']

def send_a_thankyou():
	print('Send a Thank You card')
	users_thank_choice = input('Please enter a full name or type list: ')
	if users_thank_choice == 'list':
		print(Donors_names)
		users_thank_choice = input('Please enter a full name: ')

	elif users_thank_choice in Donors_names:
		pass

	else:
		Donors_names.append(users_thank_choice)
		add_to_donors = users_thank_choice.replace(' ','_')
		add_to_donors = []
		Donors.append(add_to_donors)

	donation_amount = input('Enter the donation amount: ')
	donation_amount = float(donation_amount)
	for i in Donors:
		if Donors.index(i) == Donors_names.index(users_thank_choice):
			i.insert(0 , donation_amount)

	#print(Donors_names)
	#print(Donors)

	letter = 'Thank you so much {} for the generous donation of ${:.2f}'.format(users_thank_choice, donation_amount)
	print(letter)
	maincode()

def create_a_report():
	donor_total = []
	donor_ave = []
	for j in Donors:
		total = sum(j)
		donor_total.append(total)
		ave = total/len(j)
		donor_ave.append(ave)

	print('{:22}{:>10}{:10}{:>10}'.format('Donor Name ','| Total Given |',' Num Gifts |',' Average Gift'))

	print('-' * 64)
	for x in range(len(Donors_names)):
		print('{:24}{}{:>10.2f}{:12}{:>4}{:>10.2f}'.format(Donors_names[x], '$', donor_total[x], len(Donors[x]), '$', donor_ave[x]))

	#print(donor_total)
	#print(donor_ave)
	maincode()

if __name__ == '__main__':
	def maincode():
		print('menu: ''\n' , '1: Send a Thank You','\n'' 2: Create a Report', '\n',
			'3: Quit')
		choice = input('Please enter # 1, 2, or 3: ')
		while choice != '1' and choice != '2' and choice != '3':
			print('Invalad choice please choose again')
			choice = input('Please enter # 1, 2, or 3: ')
		if choice == '1':
			send_a_thankyou()
		if choice == '2':
			create_a_report()
		if choice == '3':
			print("quitting")
			exit()

maincode()


from contextlib import suppress

from .common import ul_nas_msg_container_from_rlc, get_rlcs

GSM_RP_ACK_NAME = 'RP-ACK'
RP_ACK_MESSAGE_TYPE = 2

def create(pkt):
    results = []
    mac_layer = pkt['mac-lte']
    for rlc in get_rlcs(mac_layer):
        with suppress(KeyError, AttributeError):
            rp = ul_nas_msg_container_from_rlc(rlc).get('gsm_a.rp')
            if int(rp.msg_type, 0) == RP_ACK_MESSAGE_TYPE:
                results.append({
                    'event': GSM_RP_ACK_NAME,
                    'rnti': int(mac_layer.context_tree.rnti),
                    'data': {
                        'message_reference': int(
                            rp.get('RP-Message Reference').get_field('gsm_a.rp.rp_message_reference'), 0
                        ),
                    },
                })
    return results


import numpy as np

class InputFrame:

    x = []
    inp = []

    def __init__(self, patch, featureSize, inputSize):
        self.x = np.random.rand(featureSize, patch)
        self.inp = np.zeros([inputSize, patch])

    def inputFiller(self, patches):
        if self.x.shape[1] == 1:
            self.inp[:, 0] = patches
        else:
            for i in range(self.x.shape[1]):
                self.inp[:, i] = patches[i]


from typing import List

from flat_colors import FlatUiColors
from point import Point
from renderer import Renderer

class SvgRendererImpl(Renderer):

    def __init__(self, filename, outline=FlatUiColors.WET_ASPHALT, fill=FlatUiColors.ALIZARIN):
        self.filename = filename
        self.lines = ['<svg xmlns="http://www.w3.org/2000/svg">']
        self.outline = outline
        self.fill = fill

    def save_and_close(self) -> None:
        self.lines.append("</svg>")
        with open(self.filename, "w") as f:
            f.writelines(self.lines)

    def draw_line(self, s: Point, e: Point):
        line = f'    <line x1="{s.x}" y1="{s.y}" x2="{e.x}" y2="{e.y}" stroke="{self.outline}" stroke-width="{4}" />'
        self.lines.append(line)

    def fill_polygon(self, points: List[Point]):
        line = '   <polygon points="{}" style="fill:{};stroke:{};stroke-width:{}" />'.format(
            ",".join([str(p.x) + "," + str(p.y) for p in points]), self.fill, self.outline, 1)
        self.lines.append(line)


from project.booths.open_booth import OpenBooth
from project.booths.private_booth import PrivateBooth
from project.delicacies.gingerbread import Gingerbread
from project.delicacies.stolen import Stolen

class ChristmasPastryShopApp:
    def __init__(self):
        self.booths = []
        self.delicacies = []
        self.income = 0.0

    def add_delicacy(self, type_delicacy: str, name: str, price: float):
        if self.__find_delicacy_by_name(name):
            raise Exception(f"{name} already exists!")

        if type_delicacy not in ["Gingerbread", "Stolen"]:
            raise Exception(f"{type_delicacy} is not on our delicacy menu!")

        delicacy = self.__create_delicacy(type_delicacy, name, price)
        self.delicacies.append(delicacy)
        return f"Added delicacy {name} - {type_delicacy} to the pastry shop."

    def add_booth(self, type_booth: str, booth_number: int, capacity: int):
        if self.__find_booth_by_number(booth_number):
            raise Exception(f"Booth number {booth_number} already exists!")

        if type_booth not in ["Open Booth", "Private Booth"]:
            raise Exception(f"{type_booth} is not a valid booth!")

        booth = self.__create_booth(type_booth, booth_number, capacity)
        self.booths.append(booth)
        return f"Added booth number {booth_number} in the pastry shop."

    def reserve_booth(self, number_of_people: int):

        booth = self.__get_suitable_booth(number_of_people)
        if booth is None:
            raise Exception(f"No available booth for {number_of_people} people!")
        booth.reserve(number_of_people)
        return f"Booth {booth.booth_number} has been reserved for {number_of_people} people."

    def order_delicacy(self, booth_number: int, delicacy_name: str):
        booth = self.__find_booth_by_number(booth_number)
        if booth is None:
            raise Exception(f"Could not find booth {booth_number}!")

        delicacy = self.__find_delicacy_by_name(delicacy_name)
        if delicacy is None:
            raise Exception(f"No {delicacy_name} in the pastry shop!")

        booth.delicacy_orders.append(delicacy)
        return f"Booth {booth_number} ordered {delicacy_name}."

    def leave_booth(self, booth_number: int):
        booth = self.__find_booth_by_number(booth_number)
        delicacy_amount = 0
        for delicacy in booth.delicacy_orders:
            delicacy_amount += delicacy.price
        booth_bill = delicacy_amount + booth.price_for_reservation
        self.income += booth_bill
        booth.delicacy_orders = []
        booth.price_for_reservation = 0
        booth.is_reserved = False
        return f"Booth {booth_number}:\n" \
               f"Bill: {booth_bill:.2f}lv."

    def get_income(self):
        return f"Income: {self.income:.2f}lv."

    def __get_suitable_booth(self, number_of_people):
        for booth in self.booths:
            if booth.capacity >= number_of_people and not booth.is_reserved:
                return booth
        return None

    def __find_booth_by_number(self, booth_number):
        for booth in self.booths:
            if booth.booth_number == booth_number:
                return booth
        return None

    def __create_booth(self, type_booth, booth_number, capacity):
        if type_booth == "Open Booth":
            return OpenBooth(booth_number, capacity)
        if type_booth == "Private Booth":
            return PrivateBooth(booth_number, capacity)

    def __find_delicacy_by_name(self, delicacy_name):
        for delicacy in self.delicacies:
            if delicacy.name == delicacy_name:
                return delicacy
        return None

    def __create_delicacy(self, delicacy_type, name, price):
        if delicacy_type == "Gingerbread":
            return Gingerbread(name, price)
        if delicacy_type == "Stolen":
            return Stolen(name, price)


import numpy as np
from efficient_apriori import apriori
import pandas as pd

#Header=None,第一行不是标题
dataset = pd.read_csv('E://Python_proj//python_Homework//L4//Market_Basket_Optimisation.csv',header=None)
print(dataset.shape)

#将数据放到transactions里
transactions = []
for i in range(dataset.shape[0]):
    temp = []
    for j in range(0,20):
        if str(dataset.values[i,j])!= 'nan':
            temp.append(str(dataset.values[i,j]))
    transactions.append(temp)

#print(transactions)

# 挖掘频繁项集和频繁规则
itemsets, rules = apriori(transactions,min_support=0.05, min_confidence=0.2)
print('频繁项集：',itemsets)
print('关联规则：',rules)


import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from sklearn.preprocessing import MinMaxScaler, StandardScaler, Imputer

from pandas.tools.plotting import parallel_coordinates

from clumpy import importance
from clumpy.preprocessing import process_data

sns.set_style('white')

CLUSTER_COLOR = sns.color_palette('Reds_d')[5]
MARGINAL_COLOR = sns.color_palette('Blues_d')[5]

def plot_clusters(X, labels=None, centers=None, size=10, aspect=2):
    if labels is None:
        labels = np.zeros(X.shape[0])
    data = pd.DataFrame({'x': X[:, 0], 'y': X[:, 1], 'labels': labels})

    p = sns.lmplot('x', 'y', hue='labels', fit_reg=False, data=data[labels != -1], size=size, aspect=aspect)

    outliers = data[labels == -1]
    plt.scatter(outliers.x.values, outliers.y.values, color='black', alpha=0.25)

    if centers is not None:
        for center in centers:
            plt.plot(center[0], center[1], marker='o', color='black')

    return p

def categorical_plot(y, cluster_labels, data, order='relevance', figsize=(10, 20)):
    cluster_ids = np.unique(cluster_labels)

    relevance = importance.categorical_relevance(y, cluster_labels, data)

    fig, axes = plt.subplots(len(cluster_ids), 1, sharex=True, figsize=figsize)
    for ax, cluster_id in zip(axes, cluster_ids):
        cluster_mask = (cluster_labels == cluster_id)
        sns.countplot(y=y, data=data, color=MARGINAL_COLOR, order=relevance[cluster_id], ax=ax)
        sns.countplot(y=y, data=data[cluster_mask], color=CLUSTER_COLOR, order=relevance[cluster_id], ax=ax)

def cat_plot(y, cluster_labels, cluster_id, data, ax=None):
    if ax is None:
        ax = plt.gca()

    relevance = importance.single_cluster_relevance(y, cluster_labels, cluster_id, data)
    cluster_mask = (cluster_labels == cluster_id)
    sns.countplot(y=y, data=data, color=MARGINAL_COLOR, order=relevance, ax=ax)
    sns.countplot(y=y, data=data[cluster_mask], color=CLUSTER_COLOR, order=relevance, ax=ax)

# this should be a parallel coordinate plot (means of cluster vs. marginal mean)
def quant_plot(y, cluster_labels, cluster_id, data, ax=None, scale=False):
    if ax is None:
        ax = plt.gca()

    width = 1
    cluster_mask = (cluster_labels == cluster_id)

    # for now print statistics
    unscaled_marginal = data[y].mean().to_frame().transpose()
    unscaled_marginal['id'] = 'marginal'
    unscaled_cluster = data[y][cluster_labels == cluster_id].mean().to_frame().transpose()
    unscaled_cluster['id'] = 'cluster'
    print(pd.concat((unscaled_marginal, unscaled_cluster)))

    if scale:
        scaled_data = data.copy()
        #scaled_data[data.columns] = MinMaxScaler().fit_transform(data)
        scaled_data[y], num_cols, cat_cols = process_data(data[y], impute='mean', num_preprocessing='standardize')
    else:
        scaled_data = data

    marginal_means = scaled_data[y].mean().to_frame()
    marginal_means = marginal_means.sort_values(by=0, ascending=False).transpose()
    columns = marginal_means.columns
    marginal_means['id'] = 'marginal'

    cluster_means = scaled_data[y][cluster_mask].mean().to_frame().transpose()
    cluster_means['id'] = 'cluster'.format(cluster_id)

    # sort in descending order of marginal means

    ax = parallel_coordinates(
            pd.concat((marginal_means, cluster_means)), 'id', cols=columns,
            color=[MARGINAL_COLOR, CLUSTER_COLOR],
            ax=ax)
    ax.get_yaxis().set_ticks([])
    plt.setp(ax.get_xticklabels(), rotation=45)
    #marginal_mean = np.mean(data[y])
    #cluster_mean = np.mean(data[y][cluster_mask])

    #if cluster_mean > marginal_mean:
    #    ax.barh(0.5, np.mean(data[y][cluster_mask]), width, color=CLUSTER_COLOR)
    #    ax.barh(0.5, np.mean(data[y]), width, color=MARGINAL_COLOR)
    #else:
    #    ax.barh(0.5, np.mean(data[y]), width, color=MARGINAL_COLOR)
    #    ax.barh(0.5, np.mean(data[y][cluster_mask]), width, color=CLUSTER_COLOR)
    #ax.get_yaxis().set_ticks([])
    #ax.set_xlabel(y)

def plot_cluster_statistics(cluster_labels, cluster_id, data, quant_var=[], qual_var=[], figsize=None, scale=False):
    n_plots = len(qual_var) + 1 if quant_var else len(qual_var)

    fig, axes = plt.subplots(n_plots, 1, sharex=False, figsize=figsize)
    if not isinstance(axes, np.ndarray):
        axes = [axes]

    for ax, var in zip(axes[:-1], qual_var):
        cat_plot(var, cluster_labels, cluster_id, data, ax=ax)

    if quant_var:
        quant_plot(quant_var, cluster_labels, cluster_id, data, scale=scale, ax=axes[-1])


def base_10(num, base):
    res = ""
    while num >= base:
        num, rem = divmod(num, base)
        res += str(rem)
    res += str(num)
    return res[::-1]

while True:
    line = input()
    if line == "0":
        break

    b, p, m = line.split()

    b = int(b)

    p = int(p, base=b)
    m = int(m, base=b)

    print(base_10(p % m, b))


import socket
import os
from _thread import *

ThreadCount = 0

def threaded_client(connection):
    #connection.send(str.encode('Welcome to the Servern'))
    req = sc.recv(50).decode('utf-8')
    if req == "GET":
        questions = os.listdir("./questions")
        response = ",".join(questions)
        print(response)
        sc.send(response.encode('utf-8'))
        sc.shutdown(socket.SHUT_WR)
    elif req.startswith("VIEW"):
        print(req)
        req = req.replace("VIEW","")
        print(req)
        que_text = open(f"./questions/{req}/{req}.txt","r").read()
        print(que_text)
        sc.send(que_text.encode('utf-8'))
        sc.shutdown(socket.SHUT_WR)
    else:
        id =req
        print("ID = ",id)
        if not os.path.isdir(id):
            os.system(f"mkdir {id}")
        sc.send('id_received'.encode('utf-8'))
        #sc.shutdown(socket.SHUT_WR)
        Q_NO = sc.recv(50).decode('utf-8')
        print("QNO = ",Q_NO)
        sc.send('qno_received'.encode('utf-8'))
        lang = sc.recv(7).decode('utf-8')
        print("lang = ",lang)
        sc.send('lang_received'.encode('utf-8'))
        if lang=="Python3":
            k = f"{id}/"+Q_NO+".py"
        else:
            k = f"{id}/"+Q_NO+".cpp"
        print(k)
        f = open(str(k),'wb')
        l = sc.recv(1024)

        while l:
            f.write(l)
            l = sc.recv(10)

        f.close()
        sc.send('received'.encode('utf-8'))
        if lang=="Python3":
            os.system("python3 "+k+f"< questions/{Q_NO}/input.txt > "+k+".txt")
        else:
            os.system("g++ -o "+k+".obj "+k)
            os.system("./"+k+f".obj < questions/{Q_NO}/input.txt > "+k+".txt")
        x = open(k+".txt","r")
        p = x.read()
        y = open(f"questions/{Q_NO}/output.txt","r")
        q = y.read()
        p = p.replace(" ","")
        p = p.replace("\n","")
        q = q.replace(" ","")
        q = q.replace("\n","")
        print(p)
        print(q)
        if p=='':
            print("Error")
            sc.send("error_pls_re_write".encode('utf-8'))
        elif p==q:
            print("accepted")
            sc.send("accepted".encode('utf-8'))
        else:
            print("Wrong Ans")
            sc.send("wrong_ans".encode('utf-8'))
        sc.close()
    connection.close()

s = socket.socket()
s.bind(("localhost",9999))
s.listen(10)

while True:
    sc, address = s.accept()
    print('Connected to: ' + address[0] + ':' + str(address[1]))
    start_new_thread(threaded_client, (sc, ))
    ThreadCount += 1
    print('Thread Number: ' + str(ThreadCount))

s.close()


import setuptools

import teec

with open("README.md", "r") as handler:
    long_description = handler.read()

setuptools.setup(
    name="teec",
    version=teec.__version__,
    author=teec.__author__,
    author_email="ilia.orlov93@gmail.com",
    description="Custom implementation of tee util",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/raymon-02/utils",
    packages=setuptools.find_packages(),
    classifiers=[
        "Programming Language :: Python :: 3",
        "Operating System :: Linux, Mac OS"
    ],
    python_requires=">=3.7",
    tests_require=[
        "pytest"
    ],
    entry_points={
        "console_scripts": [
            "teec = teec.__main__:main",
        ],
    }
)


import random
import time

x = "Loading."
for i in range(0, 5):
    print(x)
    x += "."
    time.sleep(2) #waits for two seconds
print("Loaded")

an_Example_List = ["a" , "b" , "C", 'G'] #defines a list
print(random.choice(an_Example_List)) #prints a random item from the list
print(random.randrange(0, 5)) #prints a rand number 0-4

#variables
x = "a value"

#Conditionals
if True:
    print("yep")

if True and False: # will output False
    print("if either side of an AND is false the output is false")
elif True:
    print("see above")
else:
    print("Why bother true is always true")
if True or False: # will output True
    print("if either side of an OR is true the output is true")

#loops
v = "This is a sample string"
for letter in v:
    print(letter)

for letter in range(0,len(v)): #does the same thing as the loop above
    print(v[letter])

for item in an_Example_List: # printed each item from the list on new lines
    print(item)

while True:
    print("Looped")
    break #ends a loop

num = 5
while num > 0:
    print(num)
    num -= 1

def function_Name(number):
    return number * number
# def variable (any or no parameters):
        #parameters are any data a function needs to run
    #return value        is how you pass data out of a function
print(function_Name(5))

a_num = 65
print(chr(a_num))
b_value = ord("B")
print(b_value)


a = int(input())
last = 2 * a - 1
for i in range(last+1):
    if i+1 <= a:
        num = 2 * (i+1) - 1
        bin_num = (last - num)//2
        print(' '*bin_num + '*'*num)
    else:
        num = 2 * (2*a - (i+1)) - 1
        bin_num = (last - num)//2
        print(' '*bin_num + '*'*num)


# Palindrome Algorithm

str1 = "Murder for a jar of red rum" # return true
str2 = "python algorithm" # return false

def isPalindrome(inputStr):
    i = 0
    j = len(inputStr) - 1
    while i < j:
        while not inputStr[i].isalnum() and i < j:
            i += 1
        while not inputStr[j].isalnum() and i < j:
            j -= 1

        if inputStr[i].lower() != inputStr[j].lower():
            return False
        i += 1
        j -= 1
    return True

#print(isPalindrome(str1))
#print(isPalindrome(str2))

# get the string from the user and check if it's palindrome
userInput = input("Input your string : ")
print(isPalindrome(userInput))


import numpy as np
import torch
from pytest import approx
from dodonaphy import utils, Cutils, Chyp_torch, Chyp_np
import random
from dendropy.simulate import treesim

def test_dir_to_cart_1d():
    u = torch.tensor(10.0)
    r = torch.norm(u)
    directional = u / r
    loc = utils.dir_to_cart(r, directional)
    assert loc == approx(u)

def test_dir_to_cart_5d():
    u = torch.tensor((10.0, 2.3, 43.0, -4.0, 4.5))
    r = torch.norm(u)
    directional = u / r
    loc = utils.dir_to_cart(r, directional)
    assert loc == approx(u)

def test_euclidean_distance():
    r1 = torch.tensor([0.3])
    r2 = torch.tensor([0.6])
    dir1 = torch.tensor(
        [torch.as_tensor(1.0 / np.sqrt(2)), torch.as_tensor(1.0 / np.sqrt(2))],
        dtype=torch.double,
    )
    dir2 = torch.tensor(
        [torch.as_tensor(-0.5), torch.as_tensor(np.sqrt(0.75))], dtype=torch.double
    )
    x1 = r1 * dir1
    x2 = r2 * dir2
    dist = Chyp_torch.hyperbolic_distance(x1, x2, torch.zeros(1))
    norm = torch.norm(x2 - x1)
    assert norm == approx(dist.item(), 0.0001)

def test_pdm_almost_euclidean():
    n_tips = 4
    leaf_r = np.random.uniform(0, 1, n_tips)
    leaf_dir = np.random.normal(0, 1, (n_tips, 2))
    leaf_norm = np.tile(np.linalg.norm(leaf_dir, axis=1), (2, 1)).T
    leaf_dir /= leaf_norm
    leaf_x = Cutils.dir_to_cart_np(leaf_r, leaf_dir)
    curvature = -0.01
    _ = Chyp_np.get_pdm(leaf_x, curvature=curvature)

def test_LogDirPrior():
    blen = torch.full([5], 0.1, requires_grad=True)
    aT = torch.ones(1)
    bT = torch.full((1,), 0.1)
    a = torch.ones(1)
    c = torch.ones(1)
    prior = utils.LogDirPrior(blen, aT, bT, a, c)
    assert prior.requires_grad

def test_tip_distances():
    n_taxa = 6
    rng = random.Random(1)
    simtree = treesim.birth_death_tree(
        birth_rate=2.0,
        death_rate=0.5,
        num_extant_tips=n_taxa,
        rng=rng,
    )
    dists = utils.tip_distances(simtree)
    assert dists.shape == (6, 6)

def test_all_distances():
    n_taxa = 6
    rng = random.Random(1)
    simtree = treesim.birth_death_tree(
        birth_rate=2.0,
        death_rate=0.5,
        num_extant_tips=n_taxa,
        rng=rng,
    )
    dists = utils.all_distances(simtree)
    assert dists.shape == (11, 11)


import random
import numpy as np
from matplotlib import pyplot as plt

plt.rcParams['font.sans-serif'] = ['SimHei']
plt.rcParams['axes.unicode_minus'] = False
x1=np.zeros(100)
x2=np.zeros(100)
y=np.zeros(100)
for i in range(100):
    x1[i] = random.random()
    x2[i] = x1[i] ** 2
    y[i] = 20 + 5 * x1[i] + 5 * x2[i] + random.random() * 2-1

plt.scatter(x1, y)#散点图

a = 0.2
p0 = 1
p1 = 1
p2 = 1
m = 100
for j in range(10000):
    sum1 = 0
    sum2 = 0
    sum0 = 0
    for i in range(100):
        sum0 = sum0 + (p0 + p1 * x1[i] + p2 * x2[i] - y[i])
        sum1 = sum1 + (p0 + p1 * x1[i] + p2 * x2[i] - y[i]) * x1[i]
        sum2 = sum2 + (p0 + p1 * x1[i] + p2 * x2[i] - y[i]) * x2[i]
    p0 = p0 - a * (1/m) * sum0
    p1 = p1 - a * (1/m) * sum1
    p2 = p2 - a * (1/m) * sum2
print(p0, p1, p2)

X = np.linspace(0, 1, 1000)
Y = p0 + p1 * X + p2 * X**2
plt.plot(X, Y)
plt.title('散点及拟合曲线')
plt.text(0, 29, 'h(x) = '+str(round(p0, 2))+' + '+str(round(p1, 2))+'x '+' + '+str(round(p2, 2))+'x^2')
plt.xlabel('X')
plt.ylabel('h(X)')
plt.show()


"""Provide helpers for representing data in a way that can be safely stored in an .xlsx file,
and displaying data in a user-friendly format."""

import datetime

def remove_illegal_characters(string):
    """Strip all characters that cannot be stored in an .xlsx file from the
    provided string"""
    string = string.replace("\x00", "")
    return string.encode('unicode_escape').decode('utf-8')

def value_to_safe_string(value):
    """Convert a Python value to a string that can be safely handled in a .xlsx
    file by openpyxl"""
    if isinstance(value, (str, datetime.datetime, float, int)):
        return remove_illegal_characters(value) if isinstance(value,
                                                              str) else value

    else:
        return repr(value)

def num_secs_display(num_secs):
    """Convert a number of seconds toa nicely formatted string, e.g. 3601 > 1h0m1s.
    num_secs can be a float or an int."""

    negative = "-" if num_secs < 0 else ""
    num_secs = abs(num_secs)

    secs = num_secs % 60
    mins = (num_secs // 60) % 60
    hours = (num_secs // 3600)

    secs = int(secs) if int(secs) == secs else secs
    mins = int(mins) if int(mins) == mins else mins
    hours = int(hours) if int(hours) == hours else hours

    if hours <= 0:
        if mins <= 0:  # Only need to display seconds
            return "{}{:02}s".format(negative, secs)
        else:  # Display minutes, seconds
            return "{}{:02}m{:02}s".format(negative, mins, secs)
    else:  # Display hours, minutes, seconds
        return "{}{:02}h{:02}m{:02}s".format(negative, hours, mins, secs)

def num_bytes_display(num_bytes):
    "Convert a number of bytes to a nicely formatted string, e.g. 1100 > 1.1kb"
    display_format = min(len(str(num_bytes)) // 3, 6)

    display_suffixes = {
        0: "b",
        1: "Kb",
        2: "Mb",
        3: "Gb",
        4: "Tb",
        5: "Pb",
        6: "Eb"
    }

    display_suffix = display_suffixes[display_format]

    shown_value = num_bytes / (10**(display_format * 3))

    shown_value = int(shown_value) if int(
        shown_value) == shown_value else shown_value

    return "{}{}".format(shown_value, display_suffix)


# https://stepik.org/lesson/298795/step/8?unit=280622

n = int(input())

for i in range(1, n + 1):
    for j in range(i):
        if i + j <= n:
            print('*', end='')

    print()

7. stepik/7.8. stepik.py/7.8.8. stepik.py


"""
This function is triggered by an Amazon EventBridge rule when a new sns topic is created.
It extracts the identity of the resource creator and tags each newly created topic with this identity
and it's associated tags
"""
import os
import boto3
import json
import logging
from botocore.exceptions import ClientError

log_level = {
                "CRITICAL": logging.CRITICAL,
                "ERROR" : logging.ERROR,
                "WARNING" : logging.WARNING,
                "INFO" : logging.INFO,
                "DEBUG" : logging.DEBUG
            }
log = logging.getLogger(__name__)
log.setLevel(log_level[os.environ.get('LOG_LEVEL',"DEBUG")])

def get_iam_identity_tags(user_name=None, role_name=None):
    """
    Gets and returns a list of tags from an iam user or role
    """
    iam_client = boto3.client('iam')

    if user_name:
        response = iam_client.list_user_tags(UserName=user_name)
    elif role_name:
        response = iam_client.list_role_tags(RoleName=role_name)

    tags = response.get("Tags")
    while response.get("Marker"):
        if user_name:
            response = iam_client.list_user_tags(UserName=user_name, Marker=response.get("Marker"))
        elif role_name:
            response = iam_client.list_role_tags(RoleName=role_name, Marker=response.get("Marker"))
        tags.extend(response.get('Tags'))

    log.debug(f"Tags parsed from IAM identity: {tags}")
    return tags

def get_resource_tag(event):
    """
    Takes in a cloudtrail event, extract IAM identity and returns a list of resource tags
    """
    resource_tags = []
    user_id = event.get("detail").get("userIdentity")

    if user_id.get("type") == "IAMUser" and user_id.get("userName"):
        user_name = user_id.get("userName")
        resource_tags.append( {"Key": "CreatedByUser", "Value": user_name} )
        resource_tags.append( {"Key": "DateCreated", "Value": event.get("detail").get("eventTime")} )
        log.debug(f"IAM user tags parsed from Cloudtrail event: {resource_tags}")
        try:
            tags = get_iam_identity_tags(user_name=user_name)
            resource_tags.extend(tags)
        except ClientError as error:
            log.exception(error)

    elif user_id.get("type") == "AssumedRole" and user_id.get("arn"):
        role_name = user_id.get("arn").split("/")[-2]
        resource_tags.append( {"Key": "CreatedByRole", "Value": role_name} )
        resource_tags.append( {"Key": "DateCreated", "Value": event.get("detail").get("eventTime")} )
        log.debug(f"IAM Role tags parsed from Cloudtrail event: {resource_tags}")
        try:
            tags = get_iam_identity_tags(role_name=role_name)
            resource_tags.extend(tags)
        except ClientError as error:
            log.exception(error)

    return resource_tags

def lambda_handler(event, context):
    """
    If SNS topic is created successfully, get the resource tags
    from the event and append them to the newly created SNS topic
    """
    log.info(json.dumps(event))
    event_name = event.get("detail").get("eventName")

    if "errorCode" not in event.get("detail") and event_name == "CreateTopic":

        resource_tags = get_resource_tag(event)
        if resource_tags:
            log.info(f"Resource tag to be appended\n{resource_tags}")
            topic_arn = event.get("detail").get("responseElements").get("topicArn")
            sns_client = boto3.client('sns')
            try:
                sns_client.tag_resource(ResourceArn=topic_arn,Tags=resource_tags)
                log.info(f'Successfully tagged SNS topic: {topic_arn}')
            except ClientError as error:
                log.exception(error)


import cv2
from pathlib import Path
import os

def vid_to_frame(cam_id):
    os.makedirs(f'cam_{cam_id}_resized', exist_ok=True)
    cam_id = str(cam_id)
    vid_dir = f'cam_{cam_id}/cam_{cam_id}.mp4'
    vid_dir = str(Path(vid_dir))
    vid = cv2.VideoCapture(vid_dir)
    length = int(vid.get(cv2.CAP_PROP_FRAME_COUNT))
    fps = int(vid.get(cv2.CAP_PROP_FPS))
    frame_num = 0
    while True:
        success, frame = vid.read()
        if success:
            frame = cv2.resize(frame, (448, 448))
            target_dir = f'cam_{cam_id}_resized/{frame_num}.jpg'
            target_dir = str(Path(target_dir))
            cv2.imwrite(target_dir, frame)
            print(f'Wrote {frame_num} to {target_dir}')
        else:
            break
        frame_num += 1
    print(f'Obtained {length} frames with a frame rate of {fps}')


###################################################################
#                       LINDO-API
#                    Sample Programs
#                  Copyright (c) 2011
#
#         LINDO Systems, Inc.           312.988.7422
#         1415 North Dayton St.         info@lindo.com
#         Chicago, IL 60622             http://www.lindo.com
###################################################################
#
#  File   : Derived from samples/c/ex_nlp1/ex_nlp1.c
#
#  Purpose: Solve a NLP using the black-box style interface.
#  Model  : A nonlinear model with multiple local minimizers.
#
#        minimize  f(x,y) =  3*(1-x)^2*exp(-(x^2) - (y+1)^2)
#                         - 10*(x/5 - x^3 - y^5)*exp(-(x^2)-y^2)
#                         - 1/3*exp(-((x+1)^2) - y^2);
#        subject to
#                         x^2 + y   <=  6;
#                         x   + y^2 <=  6;
#                         x, y unconstrained in sign;
import math
import sys

####
##
def logFunc(pModel,line, udict):
    print("%s" % (line),end =" ")
    sys.stdout.flush()
####
##
def cbFunc(pModel,iloc, udict):
    dObj = N.array([-1.0],dtype=N.double)
    errorcode = lindo.pyLSgetProgressInfo(pModel,iloc,LSconst.LS_DINFO_CUR_OBJ,dObj)
    dIter = N.array([-1.0],dtype=N.double)
    errorcode = lindo.pyLSgetProgressInfo(pModel,iloc,LSconst.LS_DINFO_CUR_ITER,dIter)
    print("\ncbFunc| LOC:%d Iter:%g, Obj=%g" % (iloc,dIter[0],dObj[0]),end =" ")
    sys.stdout.flush()
####
##
def cbMIPFunc(pModel,udict,dObj,padPrimal):
    dIter = N.array([-1.0],dtype=N.double)
    errorcode = lindo.pyLSgetProgressInfo(pModel,0,LSconst.LS_DINFO_CUR_ITER,dIter)
    print("\ncbMIPFunc| Iter:%g, Obj=%g" % (dIter[0],dObj,),end =" ")
    for k,x in enumerate(padPrimal):
        print("\n%.5f %s" % (padPrimal[k],udict["varType"][k]),end=" ")
    sys.stdout.flush()

####
## FDE calculations
# Function evals
def  g1(X,Y): return math.exp( -pow(X  ,2)  - pow(Y+1,2) )
def  g2(X,Y): return math.exp( -pow(X  ,2)  - pow(Y  ,2) )
def  g3(X,Y): return math.exp( -pow(X+1,2)  - pow(Y  ,2) )
def  f1(X,Y): return pow(1-X,2)
def  f2(X,Y): return X/5 - pow(X  ,3)  - pow(Y  ,5)

# Partial derivatives of the summands  (only to be used with cbGradcalc)
def dxg1(X,Y): return ( g1(X,Y)*(-2)*X     )
def dyg1(X,Y): return ( g1(X,Y)*(-2)*(Y+1) )
def dxg2(X,Y): return ( g2(X,Y)*(-2)*X     )
def dyg2(X,Y): return ( g2(X,Y)*(-2)*Y     )
def dxg3(X,Y): return ( g3(X,Y)*(-2)*(X+1) )
def dyg3(X,Y): return ( g3(X,Y)*(-2)*Y     )
def dxf1(X,Y): return ( 2*(1-X)            )
def dyf1(X,Y): return ( 0                  )
def dxf2(X,Y): return ( 1/5 - 3*pow(X,2)   )
def dyf2(X,Y): return ( -5*pow(Y,4)        )

def cbFuncalc(pModel,udict,nRow,padPrimal,nJDiff,dXJBase,pyFuncVal,pReserved):
  nerr = 0
  # compute objective's functional value*/
  X = padPrimal[0]
  Y = padPrimal[1]
  if (nRow==-1):
    val = 3*f1(X,Y)*g1(X,Y) - 10*f2(X,Y)*g2(X,Y) - g3(X,Y)/3;
  # compute constaint 0's functional value */
  elif (nRow==0):
    val = X*X + Y - 6.0;
  # compute constaint 1's functional value */
  elif (nRow==1):
    val = X + Y*Y - 6.0;

  pyFuncVal[0]=val
  udict["nfunc"] = udict["nfunc"] + 1
  return nerr

def cbGradcalc(pModel,udict,nRow,pdX,lb,ub,NewPnt,NPar,parlist,partial):
  nerr = 0
  # compute objective's gradient values*/
  X = padPrimal[0]
  Y = padPrimal[1]

  for i2 in range(NPar): partial[i2]=0.0;

  # partial derivatives of the objective function */
  if (nRow==-1):
     for i2 in range(NPar):
       if (lb[parlist[i2]]!=ub[parlist[i2]]):
           if (parlist[i2]==0):
             partial[i2]= 3*(dxf1(X,Y)*g1(X,Y) + f1(X,Y)*dxg1(X,Y) ) -  10*(dxf2(X,Y)*g2(X,Y) + f2(X,Y)*dxg2(X,Y) ) - 1/3*(dxg3(X,Y));
           elif (parlist[i2]==1):
             partial[i2]= 3*(dyf1(X,Y)*g1(X,Y) + f1(X,Y)*dyg1(X,Y) ) -  10*(dyf2(X,Y)*g2(X,Y) + f2(X,Y)*dyg2(X,Y) ) - 1/3*(dyg3(X,Y));

  # partial derivatives of Constraint 0 */
  elif (nRow==0):
     for i2 in range(NPar):
       if (lb[parlist[i2]]!=ub[parlist[i2]]):
         if (parlist[i2]==0):
           partial[i2]=2.0*X;
         elif (parlist[i2]==1):
           partial[i2]=1;

  # partial derivatives of Constraint 1 */
  elif (nRow==1):
     for i2 in range(NPar):
       if (lb[parlist[i2]]!=ub[parlist[i2]]):
         if (parlist[i2]==0):
           partial[i2]=1;
         elif (parlist[i2]==1):
           partial[i2]=2.0*Y;
  udict["ngrad"] = udict["ngrad"] + 1
  return nerr

####################################
## MAIN
####################################
from pyLindo import *
import os
#model LP data
nCons = 2
nVars = 2
nDir = 1
dObjConst = 0.0
adC = N.array([0.0,0.0],dtype=N.double)
adB = N.array([0.0,0.0],dtype=N.double)
acConTypes = N.array(['L','L'],dtype=N.character)
nNZ = 4;
Abegcol = N.array([0,2,4],dtype=N.int32)
Alencol = N.array([2,2],dtype=N.int32)
Acoef = N.array([0.,1.,1.,0.],dtype=N.double)
Arowndx = N.array([0,1,0,1],dtype=N.int32)
lb = N.array([-3.,-3.],dtype=N.double)
ub = N.array([3.,3.],dtype=N.double)
pachVarType = N.array(['C','C'],dtype=N.character)
# NLP data
Nobjndx = N.array([0,1],dtype=N.int32)
Nnlobj = 2

#create LINDO environment and model objects
LicenseKey = N.array('',dtype='S1024')
lindo.pyLSloadLicenseString(os.getenv('LINDOAPI_HOME')+'/license/lndapi130.lic',LicenseKey)

pnErrorCode = N.array([-1],dtype=N.int32)

pEnv = lindo.pyLScreateEnv(pnErrorCode,LicenseKey)
geterrormessage(pEnv,pnErrorCode[0])

verstr = getversion(pEnv)

pModel = lindo.pyLScreateModel(pEnv,pnErrorCode)
geterrormessage(pEnv,pnErrorCode[0])

#load LP data into the model
print("Loading LP data...")
errorcode = lindo.pyLSloadLPData(pModel,nCons,nVars,nDir,
                                 dObjConst,adC,adB,acConTypes,nNZ,Abegcol,
                                 Alencol,Acoef,Arowndx,lb,ub)
geterrormessage(pEnv,errorcode)

errorcode = lindo.pyLSloadVarType(pModel,pachVarType)
geterrormessage(pEnv,errorcode)

#load NLP data
# The number of nonlinear variables in each column
Alencol[0]=1; Alencol[1]=1;

# The indices of the first nonlinear variable in each column
Abegcol[0]=0; Abegcol[1]=1; Abegcol[2]=2;

# The indices of nonlinear constraints
Arowndx[0]=0;
Arowndx[1]=1;

errorcode=lindo.pyLSloadNLPData(pModel,Abegcol,Alencol,
        N.asarray(None),Arowndx,Nnlobj,Nobjndx,N.asarray(None));

###############################
## Set callbacks
udict = {
  "prefix": "APILOG",
  "postfix": "..",
  "version": verstr,
  "varType": pachVarType,
  "ngrad": 0,
  "nfunc": 0
}
errorcode = lindo.pyLSsetModelLogfunc(pModel,logFunc, udict)
geterrormessage(pEnv,errorcode)

#errorcode = lindo.pyLSsetCallback(pModel,cbFunc, udict)
#geterrormessage(pEnv,errorcode)

#errorcode = lindo.pyLSsetMIPCallback(pModel,cbMIPFunc, udict)
#geterrormessage(pEnv,errorcode)

errorcode = lindo.pyLSsetFuncalc(pModel,cbFuncalc, udict)
geterrormessage(pEnv,errorcode)

errorcode = lindo.pyLSsetGradcalc(pModel,cbGradcalc, udict)
geterrormessage(pEnv,errorcode)

###############################
## Set misc parameters

# Turn multi-start search on */
#errorcode = lindo.pyLSsetModelIntParameter(pModel,LSconst.LS_IPARAM_NLP_SOLVER,LSconst.LS_NMETHOD_MSW_GRG);
geterrormessage(pEnv,errorcode)

# Set maximum number of local optimizations */
errorcode = lindo.pyLSsetModelIntParameter(pModel,LSconst.LS_IPARAM_NLP_MAXLOCALSEARCH,5);
geterrormessage(pEnv,errorcode)

###############################
# Get model stats
ibuf = N.array([1],dtype=N.int32)
errorcode = lindo.pyLSgetInfo(pModel,LSconst.LS_IINFO_NUM_CONT,ibuf) # number of continuous variables
geterrormessage(pEnv,errorcode)
nCont = ibuf[0]

#####################################
## Load initial solution
padPrimal = N.empty((nVars),dtype=N.double)
padPrimal[0] = 0.25;  padPrimal[1] = -1.65;
errorcode=lindo.pyLSloadVarStartPoint(pModel,padPrimal);
geterrormessage(pEnv,errorcode)

#####################################
## Solve the model
print("Solving the model...")
pnStatus = N.array([-1],dtype=N.int32)
if nCont<nVars:
    errorcode = lindo.pyLSsolveMIP(pModel,pnStatus)
else:
    errorcode = lindo.pyLSoptimize(pModel,LSconst.LS_METHOD_FREE, pnStatus)
geterrormessage(pEnv,errorcode)

#####################################
## Retrieve the objective value
dObj = N.array([-1.0],dtype=N.double)
if nCont<nVars:
    errorcode = lindo.pyLSgetInfo(pModel,LSconst.LS_DINFO_MIP_OBJ,dObj)
else:
    errorcode = lindo.pyLSgetInfo(pModel,LSconst.LS_DINFO_POBJ,dObj)
geterrormessage(pEnv,errorcode)
print("")

#####################################
## Retrieve the primal solution
if nCont<nVars:
    errorcode = lindo.pyLSgetMIPPrimalSolution(pModel,padPrimal)
else:
    errorcode = lindo.pyLSgetPrimalSolution(pModel,padPrimal)
geterrormessage(pEnv,errorcode)

varType = N.empty((nVars),dtype=N.byte)
errorcode = lindo.pyLSgetVarType(pModel,varType)
geterrormessage(pEnv,errorcode)

print("Primal solution is: ")
for k,x in enumerate(padPrimal):
    print("x[%d] =%10.5f %c" % (k,padPrimal[k],varType[k]))

print("Objective is: %.5f (nfunc:%d, ngrad:%d)" % (dObj[0],udict["nfunc"],udict["ngrad"]))
################################
# Delete LINDO model pointer
errorcode = lindo.pyLSdeleteModel(pModel)
geterrormessage(pEnv,errorcode)

################################
# Delete LINDO environment pointer
errorcode = lindo.pyLSdeleteEnv(pEnv)
geterrormessage(pEnv,errorcode)


from datetime import datetime
import pandas as pd
from fuel_mappings import *

def get_ercot_data():
    all_dfs = []
    for year in range(2019, 2022 + 1):
        for month in list(range(1, 13)):
            newdf = _get_df(year, month)
            all_dfs.append(newdf)
            if year == 2022 and month == 5:
                break
    newdf = pd.concat(all_dfs)
    # Ignore incomplete weeks.
    newdf = newdf.query('Date < "2022-05-29"').copy()

    # Standardize on GWh
    newdf.loc[:, 'Total'] = newdf['Total'].divide(1000).round()
    newdf.loc[:, 'pct'] = newdf['pct'].round(3)
    return newdf

def _get_df(year: int, month: int):
    dateparse = lambda x: datetime.strptime(x, '%m/%d/%Y')
    decimalparse = lambda x: float(x.replace(',',''))

    df = pd.read_table(
        f'ERCOT/IntGenByFuel{year}{month:02d}.tsv',
        usecols=['Date','Fuel','Total', 'Settlement Type'],
        converters={'Date':dateparse,'Total':decimalparse},
    )

        # Find daily total
    alltotal=df.groupby('Date').sum()
    alltotal['Fuel']='ALL SOURCES'
    alltotal['Settlement Type']='Combined'
    alltotal = alltotal.reset_index(drop=False)
    newdf = pd.concat([df, alltotal])

    maxdf = newdf.groupby('Date').max()['Total'].reset_index(drop=False)

    newdf = newdf.merge(maxdf, left_on='Date', right_on='Date', suffixes=['', '_y']).rename({'Total_y': 'DailyMax'}, axis=1)

    newdf = newdf.assign(pct=lambda x: x['Total'] / x['DailyMax'])

    # Generate some type mappings
    newdf['FuelType'] = newdf['Fuel'].apply(get_fuel_type)
    newdf['LoadType'] = newdf['Fuel'].apply(get_load_type)
    newdf['SourceType'] = newdf['LoadType'] + ' ' + newdf['FuelType']
    newdf.loc[newdf['SourceType'] == 'Other Other', 'SourceType'] = 'Other'

    return newdf


"""
forms.py

Web forms based on Flask-WTForms

See: http://flask.pocoo.org/docs/patterns/wtforms/
     http://wtforms.simplecodes.com/

"""

from flaskext import wtf
from flaskext.wtf import validators
from wtforms.ext.appengine.db import model_form
from models import Post, Category

class ExampleForm(wtf.Form):
    example_name = wtf.TextField('Name', validators=[validators.Required()])
    example_description = wtf.TextAreaField('Description', validators=[validators.Required()])

class TagListField(wtf.Field):
    widget = wtf.TextInput()

    def _value(self):
        if self.data:
            return u', '.join(self.data)
        else:
            return u''

    def process_formdata(self, valuelist):
        if valuelist:
            self.data = [x.strip() for x in valuelist[0].split(',')]
        else:
            self.data = []

class BetterTagListField(TagListField):
    def __init__(self, label='', validators=None, remove_duplicates=True, **kwargs):
        super(BetterTagListField, self).__init__(label, validators, **kwargs)
        self.remove_duplicates = remove_duplicates

    def process_formdata(self, valuelist):
        super(BetterTagListField, self).process_formdata(valuelist)
        if self.remove_duplicates:
            self.data = list(self._remove_duplicates(self.data))

    @classmethod
    def _remove_duplicates(cls, seq):
        """Remove duplicates in a case insensitive, but case preserving manner"""
        d = {}
        for item in seq:
            if item.lower() not in d:
                d[item.lower()] = True
                yield item

BasePostForm = model_form(Post, base_class=wtf.Form)

class PostForm(BasePostForm):
    tags = BetterTagListField(u'Tags')

CategoryForm = model_form(Category, base_class=wtf.Form)


import io

from pytube import YouTube
from pytube.exceptions import VideoUnavailable

async def get_video_meta(video_url):
    video = YouTube(video_url)
    try:
        streams = (
            video.streams.filter(progressive=True, file_extension='mp4')
            .order_by('resolution')
            .desc()
        )
        return {
            'title': video.title,
            'resolutions': [s.resolution for s in streams],
        }
    except VideoUnavailable:
        return {}

async def get_video_url(video_url, resolution):
    video = YouTube(video_url)
    stream = video.streams.filter(res=resolution, progressive=True)[0]
    return {'url': stream.url}

async def get_video(video_url, resolution):
    video = YouTube(video_url)
    stream = video.streams.filter(res=resolution, progressive=True)[0]
    video_buffer = io.BytesIO()
    stream.stream_to_buffer(video_buffer)
    video_buffer.seek(0)

    return video_buffer


from .test_wrapper import *
from keras.datasets import cifar10
from keras.models import load_model
from hlib.frontend import relay_parser
import sys
sys.trackbacklimit = 0

batch = 1
(x_train, y_train), (x_test, y_test) = cifar10.load_data()
x = x_test[0:9984, 0:32, 0:32, 0:3] / 255
x_train_keras = np.reshape(x, (-1, batch, 32, 32, 3))
x = np.transpose(x_train_keras, [0, 1, 4, 2, 3])
x = np.reshape(x, (-1, batch, 3, 32, 32))
y = y_test[0:9984].reshape(-1, batch)
test = 1
if(test == 0):
    test_wrapper("cifar10.h5", "relay", "keras", "cifar10",
                 x, y, (batch, 10), {'input_1': (batch, 3, 32, 32)}, batch_size=32)
elif(test == 1):
    keras_model = load_model('cifar10.h5')
    correct = 0
    total = 0
    for i in range(y.shape[0]):
        x_p = keras_model.predict(x_train_keras[i])
        if(np.argmax(x_p, axis=1) == y[i]):
            correct += 1
        total += 1
    print("accuracy:", correct / (total * 1.0))


input_data = input().split("|")
health = 100
bitcoins = 0
for room in input_data:
    command, number = room.split()
    number = int(number)
    if command == "potion":
        if health + number > 100:
            print(f"You healed for {100 - health} hp.")
            health = 100

        else:
            health += number
            print(f"You healed for {number} hp.")
        print(f"Current health: {health} hp.")
    elif command == "chest":
        print(f"You found {number} bitcoins.")
        bitcoins += number
    else:
        monster = command
        health -= number
        if health > 0:
            print(f"You slayed {monster}.")
        else:
            print(f"You died! Killed by {monster}.")
            print(f"Best room: {input_data.index(room) + 1 }")
            exit()
print("You've made it!")
print(f"Bitcoins: {bitcoins}")
print(f"Health: {health}")


"""
    Main client for hh.ru SDK.
    Provides root interface for working with HeadHunter.
"""
from typing import Callable, Union, Dict, List, Optional

# Components.
from hhru.api import Api
from hhru.auth import Auth
from hhru.consts import VACANCY_SEARCH_MAX_PER_PAGE

class Client:
    """
    ## hh.ru SDK client.
    Main interface for working with HeadHunter.
    Provides auth, api interfaces.

    ### Example use:
    ```python
    import hhru
    client = hhru.Client()
    ```
    """

    # Authentication instance.
    # Used for authentication.
    auth = None

    # API instance.
    # Used for sending API HTTP requests.
    api = None

    def __init__(self):

        # Components.
        self.auth = Auth()
        self.api = Api(auth=self.auth)

    def search_vacancies(self, **kwargs) -> List:
        """Returns list of search results for vacancies"""
        response = self.api.method(name="vacancies", **kwargs)
        return response.items

    def search_vacancies_over_pages(self, *, page_limit: int = 21, **kwargs) -> List:
        """Returns list of search results for vacancies that was collected from all result pages (hh.ru has limit to 20 max pages search depth)."""
        search_current_page = 0
        while True:
            response = self.api.method(
                name="vacancies",
                page=search_current_page,
                per_page=VACANCY_SEARCH_MAX_PER_PAGE,
                **kwargs,
            )
            search_current_page += 1
            if response.raw_response().status_code != 200:
                # Temporary solution.
                print(response.raw_json())
                raise Exception
            for item in response.items:
                yield item
            if (
                search_current_page >= response.pages
                or search_current_page >= page_limit
            ):
                break


class calculater:
    def __init__(self,a,b):
        self.num1=a
        self.num2=b
    def add(self):
        a=self.num1
        b=self.num2
        print("the addition is = ",a+b)
    def sub(self):
        a=self.num1
        b=self.num2
        print("the subtraction is = ",a-b)
    def multi(self):
        a=self.num1
        b=self.num2
        print("the multiplication is = ",a*b)
    def divid(self):
        a=self.num1
        b=self.num2
        print("the divid is = ",a/b)
    def mod(self):
        a=self.num1
        b=self.num2
        print("the mod is = ",a%b)
print("Enter your Command\n 1 add\n 2 sub\n 3 multiply\n 4 divid\n 5 mod")
a=int(input("enter your num 1 = "))
b=int(input("enter your num 1 = "))
pr=calculater(a,b)
x=int(input("Enter your command"))
if(x==1):
    pr.add()
elif(x==2):
    pr.sub()
elif(x==3):
    pr.multi()
elif(x==4):
    pr.divid()
elif(x==5):
    pr.mod()
else:
    print("Plese enter valid command")


from utils import auth_required, admin_required

from flask import request
from flask_restx import Resource, Namespace

from dao.model.user import UserSchema
from implemented import user_service

genre_ns = Namespace('genres')

@genre_ns.route('/')
class UsersView(Resource):
    @auth_required
    def get(self):
        all_users = user_service.get_all()
        res = UserSchema(many=True).dump(all_users)
        return res, 200

    @admin_required
    def post(self):
        req_json = request.json
        user = user_service.create(req_json)
        return "", 201, {"location": f"/users/{user.id}"}

@genre_ns.route('/<int:rid>')
class UserView(Resource):
    @auth_required
    def get(self, rid):
        r = user_service.get_one(rid)
        sm_d = UserSchema().dump(r)
        return sm_d, 200

    @admin_required
    def put(self, rid):
        req_json = request.json
        if "id" not in req_json:
            req_json["id"] = rid

        user_service.update(req_json)
        return "", 204

    @admin_required
    def delete(self, bid):
        user_service.delete(bid)
        return "", 204