# -*- mode: python -*-
# -*- coding: utf-8 -*-

##############################################################################
#
# Gestion scolarite IUT
#
# Copyright (c) 1999 - 2021 Emmanuel Viennet.  All rights reserved.
#
# 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 2 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, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#
#   Emmanuel Viennet      emmanuel.viennet@viennet.net
#
##############################################################################

""" Gestion des relations avec les entreprises

Note: Code très ancien, porté de Zope/DTML, peu utilisable

=> Voir si des départements utilisent encore ce module et envisager de le supprimer.

"""

import time
import urllib

from flask import request
from flask_login import current_user

from app.scodoc import sco_utils as scu

# MIGRATION EN COURS => MODULE DESACTIVE !

# A REVOIR
# from sco_permissions import ScoEntrepriseView, ScoEntrepriseChange
# from app import log
# from scolog import logdb
# from sco_utils import SCO_ENCODING
# import app.scodoc.sco_utils as scu
# import html_sidebar
# from app.scodoc.gen_tables import GenTable
# from app.scodoc.TrivialFormulator import TrivialFormulator, TF
# import sco_etud
# import sco_entreprises

def entreprise_header(page_title=""):
    "common header for all Entreprises pages"
    return html_sco_header.sco_header(page_title=page_title)

def entreprise_footer():
    "common entreprise footer"
    return html_sco_header.sco_footer()

security.declareProtected(ScoEntrepriseView, "sidebar")

def sidebar():
    "barre gauche (overide std sco sidebar)"
    # rewritten from legacy DTML code
    # XXX rare cas restant d'utilisation de l'acquisition Zope2: à revoir
    params = {"ScoURL": scu.ScoURL()}
    H = [
        """

""",
        html_sidebar.sidebar_common(),
        """
Entreprises

"""
        % params,
    ]
    if current_user.has_permission(Permission.ScoEntrepriseChange):
        H.append(
            """
Nouvelle entreprise
"""
            % params
        )

    H.append(
        """
Contacts

 """
        % params
    )

    # --- entreprise selectionnée:
    vals = scu.get_request_args()
    if "entreprise_id" in vals:
        entreprise_id = vals["entreprise_id"]
        E = sco_entreprises.do_entreprise_list(args={"entreprise_id": entreprise_id})
        if E:
            E = E[0]
            params.update(E)
            H.append(
                """

%(nom)s

Corresp.
"""
                % params
            )
            if current_user.has_permission(Permission.ScoEntrepriseChange):
                H.append(
                    """
Nouveau Corresp.
"""
                    % params
                )
            H.append(
                """
Contacts
"""
                % params
            )
            if current_user.has_permission(Permission.ScoEntrepriseChange):
                H.append(
                    """
Nouveau "contact"
"""
                    % params
                )
            H.append("

")

    #
    H.append("""

%s""" % scu.icontag("entreprise_side_img"))
    if not current_user.has_permission(Permission.ScoEntrepriseChange):
        H.append("""
(Lecture seule)""")
    H.append("""

 """)
    return "".join(H)

# --------------------------------------------------------------------
#
#   Entreprises : Vues
#
# --------------------------------------------------------------------
security.declareProtected(ScoEntrepriseView, "index_html")

def index_html(etud_nom=None, limit=50, offset="", format="html"):
    """Accueil module entreprises"""
    # Traduit du DTML - utilise table standard
    if limit:
        limit = int(limit)
    if offset:
        offset = int(offset or 0)
    vals = scu.get_request_args()
    if etud_nom:
        entreprises = sco_entreprises.do_entreprise_list_by_etud(
            args=vals, sort_on_contact=True
        )
        table_navigation = ""
    else:
        entreprises = sco_entreprises.do_entreprise_list(
            args=vals,
            test="~*",
            sort_on_contact=True,
            limit=limit,
            offset=offset,
        )
        # Liens navigation précédent/suivant
        webparams = {"limit": limit}
        if offset:
            webparams["offset"] = max((offset or 0) - limit, 0)
            prev_lnk = 'précédentes' % (
                request.base_url + "?" + urllib.parse.urlencode(webparams)
            )
        else:
            prev_lnk = ""
        if len(entreprises) >= limit:
            webparams["offset"] = (offset or 0) + limit
            next_lnk = 'suivantes' % (
                request.base_url + "?" + urllib.parse.urlencode(webparams)
            )
        else:
            next_lnk = ""
        table_navigation = (
            '
'
            + prev_lnk
            + ''
            + next_lnk
            + "
"
        )
    # Ajout des liens sur la table:
    for e in entreprises:
        e["_nom_target"] = "entreprise_edit?entreprise_id=%(entreprise_id)s" % e
        e["correspondants"] = sco_entreprises.do_entreprise_correspondant_list(
            args={"entreprise_id": e["entreprise_id"]}
        )
        e["nbcorr"] = "%d corr." % len(e["correspondants"])
        e["_nbcorr_target"] = (
            "entreprise_correspondant_list?entreprise_id=%(entreprise_id)s" % e
        )
        e["contacts"] = sco_entreprises.do_entreprise_contact_list(
            args={"entreprise_id": e["entreprise_id"]}
        )
        e["nbcontact"] = "%d contacts." % len(e["contacts"])
        e["_nbcontact_target"] = (
            "entreprise_contact_list?entreprise_id=%(entreprise_id)s" % e
        )
    tab = GenTable(
        rows=entreprises,
        columns_ids=("nom", "ville", "secteur", "nbcorr", "nbcontact"),
        titles={
            "nom": "Entreprise",
            "ville": "Ville",
            "secteur": "Secteur",
            "nbcorr": "Corresp.",
            "contacts": "Contacts",
        },
        origin="Généré par %s le " % sco_version.SCONAME + scu.timedate_human_repr(),
        filename=scu.make_filename(
            "entreprises_%s" % context.get_preference("DeptName")
        ),
        caption="Entreprises du département %s" % context.get_preference("DeptName"),
        html_sortable=True,
        html_class="entreprise_list table_leftalign",
        html_with_td_classes=True,
        html_next_section=table_navigation,
        base_url=request.base_url + "?",
        preferences=context.get_preferences(),
    )
    if format != "html":
        return tab.make_page(format=format)
    else:
        H = [
            entreprise_header(page_title="Suivi entreprises"),
            """
Suivi relations entreprises
""",
            """
""",
            tab.html(),
            """
""",
            entreprise_footer(),
        ]
        return "\n".join(H)

security.declareProtected(ScoEntrepriseView, "entreprise_contact_list")

def entreprise_contact_list(entreprise_id=None, format="html"):
    """Liste des contacts de l'entreprise"""
    H = [entreprise_header(page_title="Suivi entreprises")]
    if entreprise_id:
        E = sco_entreprises.do_entreprise_list(args={"entreprise_id": entreprise_id})[0]
        C = sco_entreprises.do_entreprise_contact_list(
            args={"entreprise_id": entreprise_id}
        )
        H.append(
            """
Listes des contacts avec l'entreprise %(nom)s

        """
            % E
        )
    else:
        C = sco_entreprises.do_entreprise_contact_list(args={})
        H.append(
            """
Listes des contacts

        """
        )
    for c in C:
        c["_date_target"] = "%s/entreprise_contact_edit?entreprise_contact_id=%s" % (
            scu.EntreprisesURL(),
            c["entreprise_contact_id"],
        )
        c["entreprise"] = sco_entreprises.do_entreprise_list(
            args={"entreprise_id": c["entreprise_id"]}
        )[0]
        if c["etudid"]:
            c["etud"] = context.getEtudInfo(etudid=c["etudid"], filled=1)[0]
            c["etudnom"] = c["etud"]["nomprenom"]
            c["_etudnom_target"] = "%s/ficheEtud?etudid=%s" % (
                scu.ScoURL(),
                c["etudid"],
            )
        else:
            c["etud"] = None
            c["etudnom"] = ""

    tab = GenTable(
        rows=C,
        columns_ids=("date", "type_contact", "etudnom", "description"),
        titles={
            "date": "Date",
            "type_contact": "Object",
            "etudnom": "Étudiant",
            "description": "Description",
        },
        origin="Généré par %s le " % sco_version.SCONAME + scu.timedate_human_repr(),
        filename=scu.make_filename("contacts_%s" % context.get_preference("DeptName")),
        caption="",
        html_sortable=True,
        html_class="contact_list table_leftalign",
        html_with_td_classes=True,
        base_url=request.base_url + "?",
        preferences=context.get_preferences(),
    )
    if format != "html":
        return tab.make_page(format=format)

    H.append(tab.html())

    if current_user.has_permission(Permission.ScoEntrepriseChange):
        if entreprise_id:
            H.append(
                """
nouveau "contact"

            """
                % E
            )

    H.append(entreprise_footer())
    return "\n".join(H)

security.declareProtected(ScoEntrepriseView, "entreprise_correspondant_list")

def entreprise_correspondant_list(
    entreprise_id=None,
    format="html",
):
    """Liste des correspondants de l'entreprise"""
    E = sco_entreprises.do_entreprise_list(args={"entreprise_id": entreprise_id})[0]
    H = [
        entreprise_header(page_title="Suivi entreprises"),
        """

Listes des correspondants  dans l'entreprise %(nom)s

        """
        % E,
    ]
    correspondants = sco_entreprises.do_entreprise_correspondant_list(
        args={"entreprise_id": entreprise_id}
    )
    for c in correspondants:
        c["nomprenom"] = c["nom"].upper() + " " + c["nom"].capitalize()
        c[
            "_nomprenom_target"
        ] = "%s/entreprise_correspondant_edit?entreprise_corresp_id=%s" % (
            scu.EntreprisesURL(),
            c["entreprise_corresp_id"],
        )

        c["nom_entreprise"] = E["nom"]
        l = []
        if c["phone1"]:
            l.append(c["phone1"])
        if c["phone2"]:
            l.append(c["phone2"])
        if c["mobile"]:
            l.append(c["mobile"])
        c["telephones"] = " / ".join(l)
        c["mails"] = " ".join(
            [
                '%s' % (c["mail1"], c["mail1"])
                if c["mail1"]
                else "",
                '%s' % (c["mail2"], c["mail2"])
                if c["mail2"]
                else "",
            ]
        )
        c["modifier"] = (
            'modifier'
            % c["entreprise_corresp_id"]
        )
        c["supprimer"] = (
            'supprimer'
            % c["entreprise_corresp_id"]
        )
    tab = GenTable(
        rows=correspondants,
        columns_ids=(
            "nomprenom",
            "nom_entreprise",
            "fonction",
            "telephones",
            "mails",
            "note",
            "modifier",
            "supprimer",
        ),
        titles={
            "nomprenom": "Nom",
            "nom_entreprise": "Entreprise",
            "fonction": "Fonction",
            "telephones": "Téléphone",
            "mails": "Mail",
            "note": "Note",
            "modifier": "",
            "supprimer": "",
        },
        origin="Généré par %s le " % sco_version.SCONAME + scu.timedate_human_repr(),
        filename=scu.make_filename(
            "correspondants_%s_%s" % (E["nom"], context.get_preference("DeptName"))
        ),
        caption="",
        html_sortable=True,
        html_class="contact_list table_leftalign",
        html_with_td_classes=True,
        base_url=request.base_url + "?",
        preferences=context.get_preferences(),
    )
    if format != "html":
        return tab.make_page(format=format)

    H.append(tab.html())

    if current_user.has_permission(Permission.ScoEntrepriseChange):
        H.append(
            """
Ajouter un correspondant dans l'entreprise %(nom)s

            """
            % E
        )

    H.append(entreprise_footer())
    return "\n".join(H)

security.declareProtected(ScoEntrepriseView, "entreprise_contact_edit")

def entreprise_contact_edit(entreprise_contact_id):
    """Form edit contact"""
    c = sco_entreprises.do_entreprise_contact_list(
        args={"entreprise_contact_id": entreprise_contact_id}
    )[0]
    link_create_corr = (
        'créer un nouveau correspondant'
        % (scu.EntreprisesURL(), c["entreprise_id"])
    )
    E = sco_entreprises.do_entreprise_list(args={"entreprise_id": c["entreprise_id"]})[
        0
    ]
    correspondants = sco_entreprises.do_entreprise_correspondant_listnames(
        args={"entreprise_id": c["entreprise_id"]}
    ) + [("inconnu", "")]

    H = [
        entreprise_header(page_title="Suivi entreprises"),
        """
Suivi entreprises

Contact avec entreprise %(nom)s
"""
        % E,
    ]
    tf = TrivialFormulator(
        request.base_url,
        scu.get_request_args(),
        (
            (
                "entreprise_contact_id",
                {"default": entreprise_contact_id, "input_type": "hidden"},
            ),
            (
                "entreprise_id",
                {"input_type": "hidden", "default": c["entreprise_id"]},
            ),
            (
                "type_contact",
                {
                    "input_type": "menu",
                    "title": "Objet",
                    "allowed_values": (
                        "Prospection",
                        "Stage étudiant",
                        "Contrat Apprentissage",
                        "Projet",
                        "Autre",
                    ),
                },
            ),
            (
                "date",
                {
                    "size": 12,
                    "title": "Date du contact (j/m/a)",
                    "allow_null": False,
                },
            ),
            (
                "entreprise_corresp_id",
                {
                    "input_type": "menu",
                    "title": "Correspondant entreprise",
                    "explanation": link_create_corr,
                    "allow_null": True,
                    "labels": [x[0] for x in correspondants],
                    "allowed_values": [x[1] for x in correspondants],
                },
            ),
            (
                "etudiant",
                {
                    "size": 16,
                    "title": "Etudiant concerné",
                    "allow_null": True,
                    "default": c["etudid"],
                    "explanation": "nom (si pas ambigu) ou code",
                },
            ),
            (
                "enseignant",
                {"size": 16, "title": "Enseignant (tuteur)", "allow_null": True},
            ),
            (
                "description",
                {
                    "input_type": "textarea",
                    "rows": 3,
                    "cols": 40,
                    "title": "Description",
                },
            ),
        ),
        cancelbutton="Annuler",
        initvalues=c,
        submitlabel="Modifier les valeurs",
        readonly=not current_user.has_permission(Permission.ScoEntrepriseChange),
    )

    if tf[0] == 0:
        H.append(tf[1])
        if current_user.has_permission(
            Permission.ScoEntrepriseChange,
        ):
            H.append(
                """
Supprimer ce contact
"""
                % entreprise_contact_id
            )
    elif tf[0] == -1:
        return flask.redirect(scu.EntreprisesURL(context))
    else:
        etudok = sco_entreprises.do_entreprise_check_etudiant(tf[2]["etudiant"])
        if etudok[0] == 0:
            H.append("""
%s
""" % etudok[1])
        else:
            tf[2].update({"etudid": etudok[1]})
            sco_entreprises.do_entreprise_contact_edit(tf[2])
            return flask.redirect(
                scu.EntreprisesURL()
                + "/entreprise_contact_list?entreprise_id="
                + str(c["entreprise_id"])
            )
    H.append(entreprise_footer())
    return "\n".join(H)

security.declareProtected(ScoEntrepriseView, "entreprise_correspondant_edit")

def entreprise_correspondant_edit(entreprise_corresp_id):
    """Form édition d'un correspondant"""
    c = sco_entreprises.do_entreprise_correspondant_list(
        args={"entreprise_corresp_id": entreprise_corresp_id}
    )[0]
    H = [
        entreprise_header(page_title="Suivi entreprises"),
        """
Édition contact entreprise
""",
    ]
    tf = TrivialFormulator(
        request.base_url,
        scu.get_request_args(),
        (
            (
                "entreprise_corresp_id",
                {"default": entreprise_corresp_id, "input_type": "hidden"},
            ),
            (
                "civilite",
                {
                    "input_type": "menu",
                    "labels": ["M.", "Mme"],
                    "allowed_values": ["M.", "Mme"],
                },
            ),
            ("nom", {"size": 25, "title": "Nom", "allow_null": False}),
            ("prenom", {"size": 25, "title": "Prénom"}),
            (
                "fonction",
                {
                    "input_type": "menu",
                    "allowed_values": (
                        "Directeur",
                        "RH",
                        "Resp. Administratif",
                        "Tuteur",
                        "Autre",
                    ),
                    "explanation": "fonction via à vis de l'IUT",
                },
            ),
            (
                "phone1",
                {
                    "size": 14,
                    "title": "Téléphone 1",
                },
            ),
            (
                "phone2",
                {
                    "size": 14,
                    "title": "Téléphone 2",
                },
            ),
            (
                "mobile",
                {
                    "size": 14,
                    "title": "Tél. mobile",
                },
            ),
            (
                "fax",
                {
                    "size": 14,
                    "title": "Fax",
                },
            ),
            (
                "mail1",
                {
                    "size": 25,
                    "title": "e-mail",
                },
            ),
            (
                "mail2",
                {
                    "size": 25,
                    "title": "e-mail 2",
                },
            ),
            (
                "note",
                {"input_type": "textarea", "rows": 3, "cols": 40, "title": "Note"},
            ),
        ),
        cancelbutton="Annuler",
        initvalues=c,
        submitlabel="Modifier les valeurs",
        readonly=not current_user.has_permission(Permission.ScoEntrepriseChange),
    )
    if tf[0] == 0:
        H.append(tf[1])
    elif tf[0] == -1:
        return flask.redirect(
            "%s/entreprise_correspondant_list?entreprise_id=%s"
            % (scu.EntreprisesURL(), c["entreprise_id"])
        )
    else:
        sco_entreprises.do_entreprise_correspondant_edit(tf[2])
        return flask.redirect(
            "%s/entreprise_correspondant_list?entreprise_id=%s"
            % (scu.EntreprisesURL(), c["entreprise_id"])
        )
    H.append(entreprise_footer())
    return "\n".join(H)

security.declareProtected(ScoEntrepriseChange, "entreprise_contact_create")

def entreprise_contact_create(entreprise_id):
    """Form création contact"""
    E = sco_entreprises.do_entreprise_list(args={"entreprise_id": entreprise_id})[0]
    correspondants = sco_entreprises.do_entreprise_correspondant_listnames(
        args={"entreprise_id": entreprise_id}
    )
    if not correspondants:
        correspondants = [("inconnu", "")]
    curtime = time.strftime("%d/%m/%Y")
    link_create_corr = (
        'créer un nouveau correspondant'
        % (scu.EntreprisesURL(), entreprise_id)
    )
    H = [
        entreprise_header(page_title="Suivi entreprises"),
        """
Nouveau "contact" avec l'entreprise %(nom)s
"""
        % E,
    ]
    tf = TrivialFormulator(
        request.base_url,
        scu.get_request_args(),
        (
            ("entreprise_id", {"input_type": "hidden", "default": entreprise_id}),
            (
                "type_contact",
                {
                    "input_type": "menu",
                    "title": "Objet",
                    "allowed_values": (
                        "Prospection",
                        "Stage étudiant",
                        "Contrat Apprentissage DUT GTR1",
                        "Contrat Apprentissage DUT GTR2",
                        "Contrat Apprentissage Licence SQRT",
                        "Projet",
                        "Autre",
                    ),
                    "default": "Stage étudiant",
                },
            ),
            (
                "date",
                {
                    "size": 12,
                    "title": "Date du contact (j/m/a)",
                    "allow_null": False,
                    "default": curtime,
                },
            ),
            (
                "entreprise_corresp_id",
                {
                    "input_type": "menu",
                    "title": "Correspondant entreprise",
                    "explanation": link_create_corr,
                    "allow_null": True,
                    "labels": [x[0] for x in correspondants],
                    "allowed_values": [x[1] for x in correspondants],
                },
            ),
            (
                "etudiant",
                {
                    "size": 16,
                    "title": "Etudiant concerné",
                    "allow_null": True,
                    "explanation": "nom (si pas ambigu) ou code",
                },
            ),
            (
                "enseignant",
                {"size": 16, "title": "Enseignant (tuteur)", "allow_null": True},
            ),
            (
                "description",
                {
                    "input_type": "textarea",
                    "rows": 3,
                    "cols": 40,
                    "title": "Description",
                },
            ),
        ),
        cancelbutton="Annuler",
        submitlabel="Ajouter ce contact",
        readonly=not current_user.has_permission(Permission.ScoEntrepriseChange),
    )
    if tf[0] == 0:
        H.append(tf[1])
    elif tf[0] == -1:
        return flask.redirect(scu.EntreprisesURL(context))
    else:
        etudok = sco_entreprises.do_entreprise_check_etudiant(tf[2]["etudiant"])
        if etudok[0] == 0:
            H.append("""
%s
""" % etudok[1])
        else:
            tf[2].update({"etudid": etudok[1]})
            sco_entreprises.do_entreprise_contact_create(tf[2])
            return flask.redirect(scu.EntreprisesURL())
    H.append(entreprise_footer())
    return "\n".join(H)

security.declareProtected(ScoEntrepriseChange, "entreprise_contact_delete")

def entreprise_contact_delete(entreprise_contact_id):
    """Form delete contact"""
    c = sco_entreprises.do_entreprise_contact_list(
        args={"entreprise_contact_id": entreprise_contact_id}
    )[0]
    H = [
        entreprise_header(page_title="Suivi entreprises"),
        """
Suppression du contact
""",
    ]
    tf = TrivialFormulator(
        request.base_url,
        scu.get_request_args(),
        (("entreprise_contact_id", {"input_type": "hidden"}),),
        initvalues=c,
        submitlabel="Confirmer la suppression",
        cancelbutton="Annuler",
        readonly=not current_user.has_permission(ScoEntrepriseChange),
    )
    if tf[0] == 0:
        H.append(tf[1])
    elif tf[0] == -1:
        return flask.redirect(scu.EntreprisesURL(context))
    else:
        sco_entreprises.do_entreprise_contact_delete(c["entreprise_contact_id"])
        return flask.redirect(scu.EntreprisesURL(context))
    H.append(entreprise_footer())
    return "\n".join(H)

security.declareProtected(ScoEntrepriseChange, "entreprise_correspondant_create")

def entreprise_correspondant_create(entreprise_id):
    """Form création correspondant"""
    E = sco_entreprises.do_entreprise_list(args={"entreprise_id": entreprise_id})[0]
    H = [
        entreprise_header(page_title="Suivi entreprises"),
        """
Nouveau correspondant l'entreprise %(nom)s
"""
        % E,
    ]
    tf = TrivialFormulator(
        request.base_url,
        scu.get_request_args(),
        (
            ("entreprise_id", {"input_type": "hidden", "default": entreprise_id}),
            (
                "civilite",
                {
                    "input_type": "menu",
                    "labels": ["M.", "Mme"],
                    "allowed_values": ["M.", "Mme"],
                },
            ),
            ("nom", {"size": 25, "title": "Nom", "allow_null": False}),
            ("prenom", {"size": 25, "title": "Prénom"}),
            (
                "fonction",
                {
                    "input_type": "menu",
                    "allowed_values": (
                        "Directeur",
                        "RH",
                        "Resp. Administratif",
                        "Tuteur",
                        "Autre",
                    ),
                    "default": "Tuteur",
                    "explanation": "fonction via à vis de l'IUT",
                },
            ),
            (
                "phone1",
                {
                    "size": 14,
                    "title": "Téléphone 1",
                },
            ),
            (
                "phone2",
                {
                    "size": 14,
                    "title": "Téléphone 2",
                },
            ),
            (
                "mobile",
                {
                    "size": 14,
                    "title": "Tél. mobile",
                },
            ),
            (
                "fax",
                {
                    "size": 14,
                    "title": "Fax",
                },
            ),
            (
                "mail1",
                {
                    "size": 25,
                    "title": "e-mail",
                },
            ),
            (
                "mail2",
                {
                    "size": 25,
                    "title": "e-mail 2",
                },
            ),
            (
                "note",
                {"input_type": "textarea", "rows": 3, "cols": 40, "title": "Note"},
            ),
        ),
        cancelbutton="Annuler",
        submitlabel="Ajouter ce correspondant",
        readonly=not current_user.has_permission(Permission.ScoEntrepriseChange),
    )
    if tf[0] == 0:
        H.append(tf[1])
    elif tf[0] == -1:
        return flask.redirect(scu.EntreprisesURL(context))
    else:
        sco_entreprises.do_entreprise_correspondant_create(tf[2])
        return flask.redirect(scu.EntreprisesURL(context))
    H.append(entreprise_footer())
    return "\n".join(H)

security.declareProtected(ScoEntrepriseChange, "entreprise_correspondant_delete")

def entreprise_correspondant_delete(entreprise_corresp_id):
    """Form delete correspondant"""
    c = sco_entreprises.do_entreprise_correspondant_list(
        args={"entreprise_corresp_id": entreprise_corresp_id}
    )[0]
    H = [
        entreprise_header(page_title="Suivi entreprises"),
        """
Suppression du correspondant %(nom)s %(prenom)s
""" % c,
    ]
    tf = TrivialFormulator(
        request.base_url,
        scu.get_request_args(),
        (("entreprise_corresp_id", {"input_type": "hidden"}),),
        initvalues=c,
        submitlabel="Confirmer la suppression",
        cancelbutton="Annuler",
        readonly=not current_user.has_permission(Permission.ScoEntrepriseChange),
    )
    if tf[0] == 0:
        H.append(tf[1])
    elif tf[0] == -1:
        return flask.redirect(scu.EntreprisesURL())
    else:
        sco_entreprises.do_entreprise_correspondant_delete(c["entreprise_corresp_id"])
        return flask.redirect(scu.EntreprisesURL())
    H.append(entreprise_footer())
    return "\n".join(H)

security.declareProtected(ScoEntrepriseChange, "entreprise_delete")

def entreprise_delete(entreprise_id):
    """Form delete entreprise"""
    E = sco_entreprises.do_entreprise_list(args={"entreprise_id": entreprise_id})[0]
    H = [
        entreprise_header(page_title="Suivi entreprises"),
        """
Suppression de l'entreprise %(nom)s

Attention: supression définitive de l'entreprise, de ses correspondants et contacts.

"""
        % E,
    ]
    Cl = sco_entreprises.do_entreprise_correspondant_list(
        args={"entreprise_id": entreprise_id}
    )
    if Cl:
        H.append(
            """
Correspondants dans l'entreprise qui seront supprimés:

"""
        )
        for c in Cl:
            H.append("""
%(nom)s %(prenom)s (%(fonction)s)
""" % c)
        H.append("""
""")

    Cts = sco_entreprises.do_entreprise_contact_list(
        args={"entreprise_id": entreprise_id}
    )
    if Cts:
        H.append(
            """
Contacts avec l'entreprise qui seront supprimés:

"""
        )
        for c in Cts:
            H.append("""
%(date)s %(description)s
""" % c)
        H.append("""
""")
    tf = TrivialFormulator(
        request.base_url,
        scu.get_request_args(),
        (("entreprise_id", {"input_type": "hidden"}),),
        initvalues=E,
        submitlabel="Confirmer la suppression",
        cancelbutton="Annuler",
        readonly=not current_user.has_permission(Permission.ScoEntrepriseChange),
    )
    if tf[0] == 0:
        H.append(tf[1])
    elif tf[0] == -1:
        return flask.redirect(scu.EntreprisesURL())
    else:
        sco_entreprises.do_entreprise_delete(E["entreprise_id"])
        return flask.redirect(scu.EntreprisesURL())
    H.append(entreprise_footer())
    return "\n".join(H)

# -------- Formulaires: traductions du DTML
security.declareProtected(ScoEntrepriseChange, "entreprise_create")

def entreprise_create():
    """Form. création entreprise"""
    H = [
        entreprise_header(page_title="Création d'une entreprise"),
        """
Création d'une entreprise
""",
    ]
    tf = TrivialFormulator(
        request.base_url,
        scu.get_request_args(),
        (
            ("nom", {"size": 25, "title": "Nom de l'entreprise"}),
            (
                "adresse",
                {"size": 30, "title": "Adresse", "explanation": "(numéro, rue)"},
            ),
            ("codepostal", {"size": 8, "title": "Code Postal"}),
            ("ville", {"size": 30, "title": "Ville"}),
            ("pays", {"size": 30, "title": "Pays", "default": "France"}),
            (
                "localisation",
                {
                    "input_type": "menu",
                    "labels": ["Ile de France", "Province", "Etranger"],
                    "allowed_values": ["IDF", "Province", "Etranger"],
                },
            ),
            ("secteur", {"size": 30, "title": "Secteur d'activités"}),
            (
                "privee",
                {
                    "input_type": "menu",
                    "title": "Statut",
                    "labels": [
                        "Entreprise privee",
                        "Entreprise Publique",
                        "Association",
                    ],
                    "allowed_values": ["privee", "publique", "association"],
                },
            ),
            (
                "plus10salaries",
                {
                    "title": "Masse salariale",
                    "type": "integer",
                    "input_type": "menu",
                    "labels": [
                        "10 salariés ou plus",
                        "Moins de 10 salariés",
                        "Inconnue",
                    ],
                    "allowed_values": [1, 0, -1],
                },
            ),
            (
                "qualite_relation",
                {
                    "title": "Qualité relation IUT/Entreprise",
                    "input_type": "menu",
                    "default": "-1",
                    "labels": [
                        "Très bonne",
                        "Bonne",
                        "Moyenne",
                        "Mauvaise",
                        "Inconnue",
                    ],
                    "allowed_values": ["100", "75", "50", "25", "-1"],
                },
            ),
            ("contact_origine", {"size": 30, "title": "Origine du contact"}),
            (
                "note",
                {"input_type": "textarea", "rows": 3, "cols": 40, "title": "Note"},
            ),
        ),
        cancelbutton="Annuler",
        submitlabel="Ajouter cette entreprise",
        readonly=not current_user.has_permission(Permission.ScoEntrepriseChange),
    )
    if tf[0] == 0:
        return "\n".join(H) + tf[1] + entreprise_footer()
    elif tf[0] == -1:
        return flask.redirect(scu.EntreprisesURL())
    else:
        sco_entreprises.do_entreprise_create(tf[2])
        return flask.redirect(scu.EntreprisesURL())

security.declareProtected(ScoEntrepriseView, "entreprise_edit")

def entreprise_edit(entreprise_id, start=1):
    """Form. edit entreprise"""
    authuser = current_user
    readonly = not authuser.has_permission(Permission.ScoEntrepriseChange)
    F = sco_entreprises.do_entreprise_list(args={"entreprise_id": entreprise_id})[0]
    H = [
        entreprise_header(page_title="Entreprise"),
        """
%(nom)s
""" % F,
    ]
    tf = TrivialFormulator(
        request.base_url,
        scu.get_request_args(),
        (
            ("entreprise_id", {"default": entreprise_id, "input_type": "hidden"}),
            ("start", {"default": 1, "input_type": "hidden"}),
            (
                "date_creation",
                {"default": time.strftime("%Y-%m-%d"), "input_type": "hidden"},
            ),
            ("nom", {"size": 25, "title": "Nom de l'entreprise"}),
            (
                "adresse",
                {"size": 30, "title": "Adresse", "explanation": "(numéro, rue)"},
            ),
            ("codepostal", {"size": 8, "title": "Code Postal"}),
            ("ville", {"size": 30, "title": "Ville"}),
            ("pays", {"size": 30, "title": "Pays", "default": "France"}),
            (
                "localisation",
                {
                    "input_type": "menu",
                    "labels": ["Ile de France", "Province", "Etranger"],
                    "allowed_values": ["IDF", "Province", "Etranger"],
                },
            ),
            ("secteur", {"size": 30, "title": "Secteur d'activités"}),
            (
                "privee",
                {
                    "input_type": "menu",
                    "title": "Statut",
                    "labels": [
                        "Entreprise privee",
                        "Entreprise Publique",
                        "Association",
                    ],
                    "allowed_values": ["privee", "publique", "association"],
                },
            ),
            (
                "plus10salaries",
                {
                    "title": "Masse salariale",
                    "input_type": "menu",
                    "labels": [
                        "10 salariés ou plus",
                        "Moins de 10 salariés",
                        "Inconnue",
                    ],
                    "allowed_values": ["1", "0", "-1"],
                },
            ),
            (
                "qualite_relation",
                {
                    "title": "Qualité relation IUT/Entreprise",
                    "input_type": "menu",
                    "labels": [
                        "Très bonne",
                        "Bonne",
                        "Moyenne",
                        "Mauvaise",
                        "Inconnue",
                    ],
                    "allowed_values": ["100", "75", "50", "25", "-1"],
                },
            ),
            ("contact_origine", {"size": 30, "title": "Origine du contact"}),
            (
                "note",
                {"input_type": "textarea", "rows": 3, "cols": 40, "title": "Note"},
            ),
        ),
        cancelbutton="Annuler",
        initvalues=F,
        submitlabel="Modifier les valeurs",
        readonly=readonly,
    )

    if tf[0] == 0:
        H.append(tf[1])
        Cl = sco_entreprises.do_entreprise_correspondant_list(
            args={"entreprise_id": F["entreprise_id"]}
        )
        Cts = sco_entreprises.do_entreprise_contact_list(
            args={"entreprise_id": F["entreprise_id"]}
        )
        if not readonly:
            H.append(
                """
%s Supprimer cette entreprise
"""
                % (
                    scu.icontag("delete_img", title="delete", border="0"),
                    F["entreprise_id"],
                )
            )
        if len(Cl):
            H.append(
                """
%d correspondants dans l'entreprise %s (liste complète) :

"""
                % (len(Cl), F["nom"], F["entreprise_id"])
            )
            for c in Cl:
                H.append(
                    """
"""
                    % c["entreprise_corresp_id"]
                )
                if c["nom"]:
                    nom = (
                        c["nom"]
                        .decode(SCO_ENCODING)
                        .lower()
                        .capitalize()
                        .encode(SCO_ENCODING)
                    )
                else:
                    nom = ""
                if c["prenom"]:
                    prenom = (
                        c["prenom"]
                        .decode(SCO_ENCODING)
                        .lower()
                        .capitalize()
                        .encode(SCO_ENCODING)
                    )
                else:
                    prenom = ""
                H.append("""%s %s (%s)
""" % (nom, prenom, c["fonction"]))
            H.append("
")
        if len(Cts):
            H.append(
                """
%d contacts avec l'entreprise %s (liste complète) :

"""
                % (len(Cts), F["nom"], F["entreprise_id"])
            )
            for c in Cts:
                H.append(
                    """
%s   """
                    % (c["entreprise_contact_id"], c["date"])
                )
                if c["type_contact"]:
                    H.append(c["type_contact"])
                if c["etudid"]:
                    etud = context.getEtudInfo(etudid=c["etudid"], filled=1)
                    if etud:
                        etud = etud[0]
                        H.append(
                            """%s"""
                            % (scu.ScoURL(), c["etudid"], etud["nomprenom"])
                        )
                if c["description"]:
                    H.append("(%s)" % c["description"])
                H.append("
")
            H.append("
")
        return "\n".join(H) + entreprise_footer()
    elif tf[0] == -1:
        return flask.redirect(scu.EntreprisesURL() + "?start=" + str(start))
    else:
        sco_entreprises.do_entreprise_edit(tf[2])
        return flask.redirect(scu.EntreprisesURL() + "?start=" + str(start))


import os
import random
import torch
import numpy as np
from collections import defaultdict
from torch.optim import Optimizer
# from Config import CFG
from sklearn.metrics import accuracy_score
# cfg = CFG()

# def scheduler(epoch):
#         #return start_lr
#         # num_epoch = cfg.epochs / 2
#         num_epoch = cfg.decay_epochs
#         start_lr = cfg.start_lr
#         min_lr = cfg.min_lr

#         lr = (num_epoch-epoch)/num_epoch * (start_lr-min_lr) + min_lr
#         lr = max(min_lr,lr)
#         return lr

def adjust_learning_rate(optimizer, lr):
    for param_group in optimizer.param_groups:
        param_group['lr'] = lr

def get_learning_rate(optimizer):
    return optimizer.param_groups[0]['lr']
    # return optimizer.param_groups[0]['lr']

def time_to_str(t, mode='min'):
    if mode == 'min':
        t  = int(t) / 60
        hr = t // 60
        min = t % 60
        return '%2d hr %02d min' % (hr, min)

    elif mode=='sec':
        t   = int(t)
        min = t // 60
        sec = t % 60
        return '%2d min %02d sec' % (min, sec)

    else:
        raise NotImplementedError

""" Seeding the randomness. """
def seeding(seed):
    random.seed(seed)
    os.environ["PYTHONHASHSEED"] = str(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed(seed)
    torch.backends.cudnn.deterministic = True

def set_all_random_seed(seed):
    random.seed(seed)
    np.random.seed(seed)
    torch.manual_seed(seed)
    torch.cuda.manual_seed_all(seed)
    return seed

""" Metrics ------------------------------------------ """
def precision(y_true, y_pred):
    intersection = (y_true * y_pred).sum()
    return (intersection + 1e-15) / (y_pred.sum() + 1e-15)

def recall(y_true, y_pred):
    intersection = (y_true * y_pred).sum()
    return (intersection + 1e-15) / (y_true.sum() + 1e-15)

def F2(y_true, y_pred, beta=2):
    p = precision(y_true,y_pred)
    r = recall(y_true, y_pred)
    return (1+beta**2.) *(p*r) / float(beta**2*p + r + 1e-15)

# def dice_score(y_true, y_pred):
#     return (2 * (y_true * y_pred).sum() + 1e-15) / (y_true.sum() + y_pred.sum() + 1e-15)

# def jac_score(y_true, y_pred):
#     intersection = (y_true * y_pred).sum()
#     union = y_true.sum() + y_pred.sum() - intersection
#     return (intersection + 1e-15) / (union + 1e-15)

def calculate_metrics(y_true, y_pred):
    # y_true = y_true.detach().cpu().numpy()
    # y_pred = y_pred.detach().cpu().numpy()

    y_pred = y_pred > 0.5
    y_pred = y_pred.reshape(-1)
    y_pred = y_pred.astype(np.float32)

    y_true = y_true > 0.5
    y_true = y_true.reshape(-1)
    y_true = y_true.astype(np.float32)

    ## Score
    score_recall = recall(y_true, y_pred)
    score_precision = precision(y_true, y_pred)
    score_fbeta = F2(y_true, y_pred)
    score_acc = accuracy_score(y_true, y_pred)

    return [score_recall, score_precision, score_acc, score_fbeta]

class dotdict(dict):
    __setattr__ = dict.__setitem__
    __delattr__ = dict.__delitem__

    def __getattr__(self, name):
        try:
            return self[name]
        except KeyError:
            raise AttributeError(name)

def Specifity(y_true, y_pred):
    specifity = []
    # threshold = np.linspace(0.45, 0.55, 100)
    threshold = np.linspace(0, 1, 100)
    # pdb.set_trace()
    for t in threshold:
        predict = (y_pred > t).astype(np.float32)

        tp = ((predict>=0.5) & (y_true>=0.5)).sum()
        tn = ((predict<0.5) & (y_true<0.5)).sum()
        fp = ((predict>=0.5) & (y_true< 0.5)).sum()
        fn = ((predict< 0.5) & (y_true>=0.5)).sum()

        # acc2 = (tp+tn)/(tp+tn+fp+fn+1e-15)
        # p = tp/(tp+fp+1e-15)
        # r = tp/(tp+fn+1e-15)
        spe = tn/(tn+fp+1e-15)

        # accuracy1.append(acc1)
        # accuracy2.append(acc2)
        # precision.append(p)
        # recall.append(r)
        specifity.append(spe)

    specifity=np.array(specifity)

    return specifity.mean()

def calculate_acc_pre_rec(y_true, y_pred):

    y_pred = y_pred > 0.5
    y_pred = y_pred.reshape(-1)
    y_pred = y_pred.astype(np.float32)

    y_true = y_true > 0.5
    y_true = y_true.reshape(-1)
    y_true = y_true.astype(np.float32)

    ## Score
    score_acc = accuracy_score(y_true, y_pred)
    score_precision = precision(y_true, y_pred)
    score_recall = recall(y_true, y_pred)

    return [score_acc, score_precision, score_recall]


from PIL import Image as _PIL_Image
import numpy as _numpy

class Hex:
    """Stores the values as an int and converts to a string for display"""
    def __init__(self, num):
        if isinstance(num, int):
            self.__val = num

    def __repr__(self):
        return str(self)

    def __str__(self):
        return "{:#04x}".format(self.__val)

    def __int__(self):
        return self.__val

    def __eq__(self, other):
        try:
            other = int(other)
            return other == int(self)
        except:
            return False

    @classmethod
    def from_str(cls, num, delimiter=" "):
        num = num.split(delimiter)

        if len(num) == 1:
            return Hex(int(num, 16))
        else:
            out = []
            for i in num:
                out.append(Hex(int(i, 16)))
            return out

    @classmethod
    def from_int(cls, num):
        return Hex(num)

    @classmethod
    def from_bytes(cls, num):
        if len(num) > 1:
            return [Hex(n) for n in num]
        else:
            return Hex(num[0])

    @classmethod
    def from_array(cls, nums):
        out = []
        for i, num in enumerate(nums):
            if isinstance(num, int):
                out.append(Hex(num))
            elif isinstance(num, str):
                result = Hex.from_str(num)
                if isinstance(result, list):
                    out.extend(result)
                else:
                    out.append(result)
            elif isinstance(num, bytes):
                out.append(Hex.from_bytes(num))
        return out

# ITF STANDS FOR "IMAGE TEXT FORMAT" ---> TESTING PURPOSES

# class Image:
#     elements = []
#
#     supported = ["itf", "png"]
#     def __init__(self, fileName):
#         ext = fileName.split(".")[-1]
#         if ext not in Image.supported:
#             raise TypeError("File format '{}' not supported".format(ext))
#         self.__file = open(fileName, "rb")
#         self.__read()
#
#     def __read(self):
#         EOF = int(self.__file.seek(0, 2))
#         __raw = []
#         self.__file.seek(0)
#         while self.__file.tell() < EOF:
#             chunk = self.__file.read(1000)
#             print(chunk)
#             chunk = Hex.from_bytes(chunk)
#             if isinstance(chunk, list):
#                 __raw.extend(chunk)
#             else:
#                 __raw.append(chunk)
#
#         if __raw[:8] != Hex.from_str("89 50 4e 47 0d 0a 1a 0a"):
#             print("FORMAT NOT SUPPORTED")
#             print(__raw[:8])
#             return -1
#
#         print(__raw)
#
#     def __del__(self):
#         self.__file.close()

class Image:
    def __init__(self, path):
        __img = _PIL_Image.open(path)
        # __img.show()
        print(__img.info)
        self.__height = __img.height
        self.__width = __img.width
        self.pixels = list(__img.getdata())

    def __del__(self):
        del self.pixels

    @property
    def height(self):
        return self.__height

    @property
    def width(self):
        return self.__width

i = Image("../../resources/BCobble.png")
print(i.pixels[0])
print(i.height, i.width)


import os

PARTITIONS = 3  # Number of partitions
REG_LAMBDA = 1e-5  # Lambda for regularization
EPOCHS = 1000  # Number of epochs to train
BATCH = 100  # Batch size
PERSISTENCE = 15  # Number of epochs of no change in loss as a stopping criteria
LEARNING_RATE = 0.03 * (100 / BATCH) / PARTITIONS  # Learning rate

DATASET_DIR = '/data/datasets/'
TOPICS_FILE = os.path.join(DATASET_DIR, 'rcv1-v2.topics.qrels')
TRAIN_FILE = os.path.join(DATASET_DIR, 'lyrl2004_vectors_train.dat')
TEST_FILES = [os.path.join(DATASET_DIR, f) for f in ['lyrl2004_vectors_test_pt0.dat',
                                                     'lyrl2004_vectors_test_pt1.dat',
                                                     'lyrl2004_vectors_test_pt2.dat',
                                                     'lyrl2004_vectors_test_pt3.dat']]
VAL_SPLIT = 0.1


# -*- coding: utf-8 -*-
import os
import confy

# Define loader. It should be awere of possition in file system to
# make "confy.rootpath" feature work properly
confy = confy.loader(__file__)

# All the settings defined inside 'base', 'development' (or other file
# which name might be defined under 'CONFIGURATION_MODE' environ
# variable in this case), and 'local' modules will be merged together
# (if 'local' doesn't exists "confy" won't complain about it becase of
# "silent" param)
config = confy.merge(
    confy.from_modules('base', os.environ.get('CONFIGURATION_MODE', 'development')),
    confy.from_modules('local', silent=True),
)

# If you wish to have all the variables defined on the module level,
# you can simply type:
#
# confy.define_module(__name__, [
#     confy.from_modules('base', os.environ.get('CONFIGURATION_MODE', 'development')),
#     confy.from_modules('local', silent=True),
# ])
#
# this doing exactly what "confy.merge" does plus it defines module in
# "sys.modules" for you


#!/usr/bin/env python2
# -*- coding: utf-8 -*-
"""
Created on Wed Dec  4 21:41:43 2019

@author: carene
"""
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

def interp_modele(depth,key):
    ind = np.where(modele['depth']<=depth)[0][-1]
    db = modele['depth'][ind]
    de = modele['depth'][ind+1]
    vb = modele[key].values[ind]
    ve = modele[key].values[ind+1]
    v = vb #+ (depth-db)/(de-db)*(ve-vb)
    return v

modele=pd.DataFrame(np.loadtxt('SEIS1_BM_resampled.dat',skiprows=3),columns=['depth','rho','vp','vs','Qp','Qs'])
plt.figure()
plt.plot(modele['vp'],3389.5-modele['depth']*1000.0,label='vp')
plt.plot(modele['vs'],3389.5-modele['depth']*1000.0,label='vs')
plt.plot(modele['rho'],3389.5-modele['depth']*1000.0,label='rho')
plt.legend()
plt.ylabel('radius (km)')
plt.xlabel('v in km/s; rho in g/cm3')

plt.ylim([3390-20,3390])

dout = open('SEIS1_BM_v2.xyz','w')
depth = np.linspace(0,18,int(18/0.004))
for d in depth:
    vp = interp_modele(d,'vp')*1000.0
    vs = interp_modele(d,'vs')*1000.0
    rho = interp_modele(d,'rho')*1000.0
    qp = interp_modele(d,'Qp')
    qs = interp_modele(d,'Qs')
    dout.write('0 0 '+str(-2700-d*1000.0)+' '+str(vp)+' '+str(vs)+' '+str(rho)+' '+str(qp)+' '+str(qs)+'\n')

dout.close()


a=input()
x=a.split()
a=[]
for i in x:
    a.append(i.capitalize())
fs=' '.join(a)
print(fs)

"""
You are given a string STR. You have to convert the first alphabet of each word in a string to UPPER CASE.
For example: If the given string STR = ”I am a student of the third year.” so you have to transform this string to
”I Am A Student Of The Third Year.”
"""


#!/usr/bin/python3
# models/base.py
#Write the first class Base

"""
This module contains the Base class.

"""

class Base:
    """the base class"""

    __nb_objects = 0

    def __init__(self, id=None):
        """__Init__ method"""
        if id is not None:
            self.id = id
        else:
            self.id = self.__class__.__nb_objects + 1
            self.__class__.__nb_objects += 1

    def __repr__(self):
        """this shows the base"""
        return f"<Base id={self.id}>"


from config import constants
from utils import logutils
from git.gitsearch import GitDataIngestion

logger = logutils.get_logger("Git Data Fetch")

def git_fetch_and_persist():
    git_search_agent = GitDataIngestion()
    for product, search_query_list in constants.PRODUCT_SEARCH_QUERY_DICT.items():
        for search_query in search_query_list:
            try:
                git_search_agent.data_ingestion_pipeline(search_query=search_query, product=product)
                logger.info("Successfully inserted data for product %s" % product)
            except Exception:
                logger.error("An error occurred while querying for %s " % search_query)


# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations

class Migration(migrations.Migration):

    dependencies = [
        ('eatery_profile', '0014_auto_20150522_0955'),
    ]

    operations = [
        migrations.AlterField(
            model_name='location',
            name='eatery_profile',
            field=models.OneToOneField(to='eatery_profile.eatery_profile'),
        ),
    ]


"""
Напишіть користувацький клас виключення з функционалом на свій вибір.
Викличте його за допомогою інструкції raise.
"""

class MyError(Exception):
    def __init__(self, text, num):
        self.txt = text
        self.n = num

number = input("Input positive integer: ")

try:
    number = int(number)
    if number < 0:
        raise MyError("You give negative!", number)
except ValueError:
    print("Error type of value!")
except MyError as mr:
    #print(mr)
    print(mr.args[0], mr.args[1])
else:
    print(number)


#!/usr/bin/env python

import os, sys

os.environ['DJANGO_SETTINGS_MODULE'] = 'framework.settings'
sys.path.append('.')
sys.path.append('../')

import django
django.setup()
from annotate.models import Annotation

if __name__ == '__main__':
    outfile = 'data/annotations.tsv'
    out = open(outfile, 'w')
    for annotation in Annotation.objects.all():
        instance = annotation.instance
        user = annotation.user.username
        task = instance.task.name
        fields = [task, instance.text, user, annotation.value]
        out.write('\t'.join(fields) + '\n')
    out.close()

# vim: et sw=4 sts=4


def solution(data):
    answer=[]
    deagi=[]
    print(data)

    for i in range(len(data)):

        for _ in range(data[i][2]):
            deagi.append(data[i][0])

    print(deagi)
    # print(len(data))
    # for i in range(n):
    #     num=data[i][2]
    #     if num
    #     deagi.append()
    # print(deagi)

    return answer

print(solution([[1, 0, 5],[2, 2, 2],[3, 3, 1],[4, 4, 1],[5, 10, 2]]))

코테/프린터의 우선순위.py

프린터의 우선순위.py


from traceback import format_exc
import asyncio

from aiogram import Router, types, filters
from aiogram.fsm.context import FSMContext
from aiogram.fsm.state import StatesGroup, State
from aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton, ReplyKeyboardMarkup, ReplyKeyboardRemove, KeyboardButton

import config
from db import db

router = Router()

class ChatsState(StatesGroup):
    user_input = State()
    delete = State()

def check_chat(chat):
    if '+' in chat:
        return chat
    if 'AAAAA' in chat and 'joinchat' in chat:
        return chat
    return chat.replace('http://t.me', '').replace('https://t.me', '').replace('/', '').replace('@', '').strip()

@router.callback_query(filters.Text('chats'))
async def keywords(callback: types.CallbackQuery):
    markup = InlineKeyboardMarkup(inline_keyboard=[
            [InlineKeyboardButton(text='Добавить чат 📥', callback_data='add_chat'), InlineKeyboardButton(text='Удалить чат 🗑', callback_data='delete_chat')],
            [InlineKeyboardButton(text='Список чатов 📋', callback_data='chat_list')],
            [InlineKeyboardButton(text='◀ Назад', callback_data='chats_settings')]
    ])
    await callback.message.answer('🗂 Меню чатов.', reply_markup=markup)

@router.callback_query(filters.Text('add_chat'))
async def add_chat(callback: types.CallbackQuery, state: FSMContext):
    markup = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text='❌ Отмена')]], resize_keyboard=True)
    await callback.message.answer('🗂 Укажите чат (ссылка или ID).\nМожно несколько через запятую.', reply_markup=markup)
    await state.set_state(ChatsState.user_input)

@router.message(ChatsState.user_input)
async def user_input(message: types.Message, state: FSMContext):
    try:
        msg = '✅ Успешно добавлено'
        for chat in map(check_chat, message.text.split('\n')):
            if chat == '❌ Отмена':
                msg = 'Возвращаемся назад.'
                break
            if chat in config.chats:
                await message.answer(f"""Чат <a href="{'http://t.me/' + chat if 'joinchat' not in chat and '+' not in chat else chat}"{chat.strip()} уже добавлен.""", parse_mode='html')
                continue
            print(chat, 'chatik')
            config.chats.append(chat)
            db.create('chats', chat)
        await message.answer(msg, reply_markup=ReplyKeyboardRemove())
    except:
        await message.answer('❌ Ошибка при добавлении', reply_markup=ReplyKeyboardRemove())
        print(format_exc())
    finally:
        await state.clear()
        markup = InlineKeyboardMarkup(inline_keyboard=[
                [InlineKeyboardButton(text='Добавить чат 📥', callback_data='add_chat'), InlineKeyboardButton(text='Удалить чат 🗑', callback_data='delete_chat')],
                [InlineKeyboardButton(text='Список чатов 📋', callback_data='chat_list')],
                [InlineKeyboardButton(text='◀ Назад', callback_data='chats_settings')]
        ])
        await message.answer('🗂 Меню чатов.', reply_markup=markup)

@router.callback_query(filters.Text('chat_list'))
async def chat_list(callback: types.CallbackQuery):
    msgs = ['🗂 Список чатов:\n\n']

    for index, chat in enumerate(config.chats):
        if len(msgs[-1]) < 2250:
            msgs[-1] += f"""{index+1}. {chat}\n"""
        else:
            msgs.append('')
            msgs[-1] += f"""{index+1}. {chat}\n"""

    if (not len(config.chats)):
        msgs[-1] += 'Список пуст.'

    for msg in msgs:
        await callback.message.answer(msg, 'html', disable_web_page_preview=True)

@router.callback_query(filters.Text('delete_chat'))
async def delete_chat(callback: types.CallbackQuery, state: FSMContext):
    msgs = ['🗑 Укажите номер чата, который нужно удалить (можно несколько, через запятую)\n\n']

    for index, chat in enumerate(config.chats):
        if len(msgs[-1]) < 2250:
            msgs[-1] += f"""{index+1}. {chat.strip()}\n"""
        else:
            msgs.append('')
            msgs[-1] += f"""{index+1}. {chat}\n"""

    if (not len(config.chats)):
        await callback.message.answer('Нет чатов для удаления.')
        return

    markup = ReplyKeyboardMarkup(keyboard=[[KeyboardButton(text='❌ Отмена')]], resize_keyboard=True)
    for msg in msgs:
        await callback.message.answer(msg, 'html', disable_web_page_preview=True, reply_markup=markup)
    await state.set_state(ChatsState.delete)

@router.message(ChatsState.delete)
async def delete(message: types.Message, state: FSMContext):
    try:
        msg = '✅ Успешно удалено'
        values = map(check_chat, message.text.split('\n'))
        for value in values:
            if value.strip() == '❌ Отмена':
                msg = 'Возвращаемся назад.'
                break
            if value.strip() not in config.chats:
                await message.answer(f"""Чат {value.strip()} отсутствует""", parse_mode='html')
                continue
            config.chats.remove(value)
            db.delete('chats', 'chat_id', value)
        await message.answer(msg, reply_markup=ReplyKeyboardRemove())
    except:
        await message.answer('❌ Ошибка при удалении', reply_markup=ReplyKeyboardRemove())
        print(format_exc())
    finally:
        await state.clear()
        markup = InlineKeyboardMarkup(inline_keyboard=[
                [InlineKeyboardButton(text='Добавить чат 📥', callback_data='add_chat'), InlineKeyboardButton(text='Удалить чат 🗑', callback_data='delete_chat')],
                [InlineKeyboardButton(text='Список чатов 📋', callback_data='chat_list')],
                [InlineKeyboardButton(text='◀ Назад', callback_data='chats_settings')]
        ])
        await message.answer('🗂 Меню чатов.', reply_markup=markup)


from typing import List

class Node:
    def __init__(self, name, host, tcp_port, http_port):
        self.name = name
        self.host = host
        self.id = 0
        self.tcp_port = tcp_port
        self.http_port = http_port
        self.external_ip = ''

    def set_id(self, id):
        self.id = id

    def get_str_info(self):
        ret = 'name: ' + self.name + ', '
        ret += 'host: ' + self.host + ', '
        ret += 'external_ip: ' + self.external_ip + ', '
        ret += 'tcp_port: ' + str(self.tcp_port) + ', '
        ret += 'http_port: ' + str(self.http_port)
        return ret

class ManufacturerNode(Node):
    def __init__(self, name, host, tcp_port, http_port):
        super().__init__(name, host, tcp_port, http_port)
        self.clients : List[ManufacturerNode] = []

class ClientNode(Node):
    def __init__(self, name, host, tcp_port, http_port, node : ManufacturerNode):
        super().__init__(name, host, tcp_port, http_port)
        self.father_node : ManufacturerNode = node

class SwitchNode:
    def __init__(self, name, host):
        self.name = name
        self.id = 0
        self.host = host
        self.nodes : List[ManufacturerNode] = []

    def set_id(self, id):
        self.id = id

class RouterNode:
    def __init__(self, name):
        self.name = name
        self.id = 0
        self.switchs : List[SwitchNode] = []

    def set_id(self, id):
        self.id = id

class Network:
    def __init__(self, file_path):
        self.routers : List[RouterNode] = []
        with open(file_path) as file:
            for line in file:
                if line[0] == 'R':
                    name = line.split('\n')[0]
                    self.routers.append(RouterNode(name))
                elif line[0] == 'S':
                    (name, host) = line.split(',')
                    host = host.split('\n')[0]
                    router = self.routers[-1]
                    router.switchs.append(SwitchNode(name, host))
                elif line[0] == 'F':
                    (name, host, tcp_port, http_port) = line.split(',')
                    router = self.routers[-1]
                    switch = router.switchs[-1]
                    switch.nodes.append(ManufacturerNode(name, host, int(tcp_port), int(http_port)))
                elif line[0] == 'C':
                    (name, host, tcp_port, http_port) = line.split(',')
                    router = self.routers[-1]
                    switch = router.switchs[-1]
                    node = switch.nodes[-1]
                    node.clients.append(ClientNode(name, host, int(tcp_port), int(http_port), node))

    def get_manufacturer_nodes(self) -> List[ManufacturerNode]:
        nodes : List[ManufacturerNode] = []
        for router in self.routers:
            for switch in router.switchs:
                for node in switch.nodes:
                    nodes.append(node)
        return nodes

    def get_client_nodes(self) -> List[ClientNode]:
        clients : List[ClientNode] = []
        for router in self.routers:
            for switch in router.switchs:
                for node in switch.nodes:
                    for client in node.clients:
                        clients.append(client)
        return clients

    def get_manufacturer_nodes_len(self):
        nodes = self.get_manufacturer_nodes()
        return len(nodes)

    def get_manufacturer_node_info(self, internal_ip, external_ip) -> ManufacturerNode:
        nodes = self.get_manufacturer_nodes()
        for node in nodes:
            if node.host == internal_ip:
                node.external_ip = external_ip
                return node
        return None

    def get_manufacturer_node(self, name) -> ManufacturerNode:
        nodes = self.get_manufacturer_nodes()
        for node in nodes:
            if node.name == name:
                return node
        return None

    def get_client_node_info(self, internal_ip, external_ip) -> ManufacturerNode:
        nodes = self.get_client_nodes()
        for node in nodes:
            if node.host == internal_ip:
                node.external_ip = external_ip
                return node
        return None


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Использовать словарь, содержащий следующие ключи:
# название пункта назначения;номер поезда; время отправления.
# Написать программу, выполняющую следующие действия:
# ввод с клавиатуры данных в список, состоящий из словарей заданной структуры;
# записи должны быть упорядочены по времени отправления поезда;
# вывод на экран информации о поездах, направляющихся в пункт,
# название которого введено с клавиатуры;
# если таких поездов нет,выдать на дисплей соответствующее сообщение

import sys

if __name__ == '__main__':
    stations = []

    while True:
        command = input(">>> ").lower()

        if command == "exit":
            break

        elif command == 'add':
            punkt = input("Пункт назначения: ")
            nomer = input("Номер поезда: ")
            time = input("Время отправления: ")

            station = {
                'punkt':  punkt,
                'nomer': nomer,
                'time': time,
                }

            stations.append(station)

            if len(stations) > 1:
                stations.sort(key=lambda item: item.get('time', ''))

        elif command == 'select':
            punkt = input("Введите пункт прибытия для поиска: ")

            if not punkt:
                print("Вы ничего не ввели")

            else:
                for station in stations:
                    if station.get('punkt', '') == punkt:
                        print(
                            "Город прибытия: ", station.get('punkt', ''),
                            " Номер поезда: ", station.get('nomer', ''),
                            " Время отправления: ", station.get('time', '')
                            )
                        break
                    else:
                        print(f"Такого города нет: {punkt}", file=sys.stderr)

        elif command == "show":
            line = '+-{}-+-{}-+-{}-+-{}-+'.format(
                '-' * 4,
                '-' * 30,
                '-' * 20,
                '-' * 15
            )
            print(line)
            print(
                '| {:^4} | {:^30} | {:^20} | {:^15} |'.format(
                    "№",
                    "Город прибытия",
                    "Номер поезда",
                    "Время отправления"
                )
            )
            print(line)

            for idx, station in enumerate(stations, 1):
                print(
                    '| {:>4} | {:<30} | {:<20} | {:>15} |'.format(
                        idx,
                        station.get('punkt', ''),
                        station.get('nomer', ''),
                        station.get('time', '')
                    )
                )

            print(line)

        elif command == 'help':
            print("Список команд:\n")
            print("add - для добовления маршрутов")
            print("select - для поиска маршпута")
            print("show - для демонстрации всех машрутов")

        else:
            print(f"Неизвестная команда {command}", file=sys.stderr)


from numpy.random import RandomState
from torch.utils.data import DataLoader, Dataset
import pytorch_lightning as pl
import os
import json
import numpy as np

import canonical_network.utils as utils

RNG = RandomState(0)

def pc_normalize(pc):
    centroid = np.mean(pc, axis=0)
    pc = pc - centroid
    m = np.max(np.sqrt(np.sum(pc ** 2, axis=1)))
    pc = pc / m
    return pc

class PartNormalDataset(Dataset):
    def __init__(
        self,
        root,
        npoints,
        split="train",
        class_choice=None,
        normal_channel=False,
    ):
        self.npoints = npoints
        self.root = root
        self.catfile = os.path.join(self.root, "synsetoffset2category.txt")
        self.cat = {}
        self.normal_channel = normal_channel

        with open(self.catfile, "r") as f:
            for line in f:
                ls = line.strip().split()
                self.cat[ls[0]] = ls[1]
        self.cat = {k: v for k, v in self.cat.items()}
        self.classes_original = dict(zip(self.cat, range(len(self.cat))))

        if not class_choice is None:
            self.cat = {k: v for k, v in self.cat.items() if k in class_choice}
        # print(self.cat)

        self.meta = {}
        with open(os.path.join(self.root, "train_test_split", "shuffled_train_file_list.json"), "r") as f:
            train_ids = set([str(d.split("/")[2]) for d in json.load(f)])
        with open(os.path.join(self.root, "train_test_split", "shuffled_val_file_list.json"), "r") as f:
            val_ids = set([str(d.split("/")[2]) for d in json.load(f)])
        with open(os.path.join(self.root, "train_test_split", "shuffled_test_file_list.json"), "r") as f:
            test_ids = set([str(d.split("/")[2]) for d in json.load(f)])
        for item in self.cat:
            # print('category', item)
            self.meta[item] = []
            dir_point = os.path.join(self.root, self.cat[item])
            fns = sorted(os.listdir(dir_point))
            # print(fns[0][0:-4])
            if split == "trainval":
                fns = [fn for fn in fns if ((fn[0:-4] in train_ids) or (fn[0:-4] in val_ids))]
            elif split == "train":
                fns = [fn for fn in fns if fn[0:-4] in train_ids]
            elif split == "val":
                fns = [fn for fn in fns if fn[0:-4] in val_ids]
            elif split == "test":
                fns = [fn for fn in fns if fn[0:-4] in test_ids]
            else:
                print("Unknown split: %s. Exiting.." % (split))
                exit(-1)

            # print(os.path.basename(fns))
            for fn in fns:
                token = os.path.splitext(os.path.basename(fn))[0]
                self.meta[item].append(os.path.join(dir_point, token + ".txt"))

        self.datapath = []
        for item in self.cat:
            for fn in self.meta[item]:
                self.datapath.append((item, fn))

        self.classes = {}
        for i in self.cat.keys():
            self.classes[i] = self.classes_original[i]

        # Mapping from category ('Chair') to a list of int [10,11,12,13] as segmentation labels
        self.seg_classes = {
            "Earphone": [16, 17, 18],
            "Motorbike": [30, 31, 32, 33, 34, 35],
            "Rocket": [41, 42, 43],
            "Car": [8, 9, 10, 11],
            "Laptop": [28, 29],
            "Cap": [6, 7],
            "Skateboard": [44, 45, 46],
            "Mug": [36, 37],
            "Guitar": [19, 20, 21],
            "Bag": [4, 5],
            "Lamp": [24, 25, 26, 27],
            "Table": [47, 48, 49],
            "Airplane": [0, 1, 2, 3],
            "Pistol": [38, 39, 40],
            "Chair": [12, 13, 14, 15],
            "Knife": [22, 23],
        }

        self.cache = {}  # from index to (point_set, cls, seg) tuple
        self.cache_size = 20000

    def __getitem__(self, index):
        if index in self.cache:
            point_set, cls, seg = self.cache[index]
        else:
            fn = self.datapath[index]
            cat = self.datapath[index][0]
            cls = self.classes[cat]
            cls = np.array([cls]).astype(np.int32)
            data = np.loadtxt(fn[1]).astype(np.float32)
            if not self.normal_channel:
                point_set = data[:, 0:3]
            else:
                point_set = data[:, 0:6]
            seg = data[:, -1].astype(np.int32)
            if len(self.cache) < self.cache_size:
                self.cache[index] = (point_set, cls, seg)
        point_set[:, 0:3] = pc_normalize(point_set[:, 0:3])

        choice = np.random.choice(len(seg), self.npoints, replace=True)
        # resample
        point_set = point_set[choice, :]
        seg = seg[choice]

        return point_set, cls, seg

    def __len__(self):
        return len(self.datapath)

class ShapenetPartDataModule(pl.LightningDataModule):
    def __init__(self, hyperparams):
        super().__init__()
        self.data_path = hyperparams.data_path
        self.hyperparams = hyperparams

    def setup(self, stage=None):
        if stage == "fit" or stage is None:
            self.train_dataset = PartNormalDataset(
                root=self.data_path, npoints=self.hyperparams.num_points, split="trainval",
                normal_channel=self.hyperparams.normal_channel
            )
            self.valid_dataset = PartNormalDataset(
                root=self.data_path, npoints=self.hyperparams.num_points, split="test",
                normal_channel=self.hyperparams.normal_channel
            )
        if stage == "test":
            self.test_dataset = PartNormalDataset(
                root=self.data_path, npoints=self.hyperparams.num_points, split="test",
                normal_channel=self.hyperparams.normal_channel
            )

    def train_dataloader(self):
        train_loader = DataLoader(
            self.train_dataset,
            batch_size=self.hyperparams.batch_size,
            shuffle=True,
            num_workers=self.hyperparams.num_workers,
        )
        return train_loader

    def val_dataloader(self):
        valid_loader = DataLoader(
            self.valid_dataset,
            batch_size=self.hyperparams.batch_size,
            shuffle=False,
            num_workers=self.hyperparams.num_workers,
        )
        return valid_loader

    def test_dataloader(self):
        test_loader = DataLoader(
            self.test_dataset,
            batch_size=self.hyperparams.batch_size,
            shuffle=False,
            num_workers=self.hyperparams.num_workers,
        )
        return test_loader


import logging
import os.path
import xml.etree.ElementTree as ET

from xml.dom import minidom

logging.basicConfig(level=logging.INFO, format=logging.BASIC_FORMAT)
BASE_DIR = "/opt/component"
SERVICE_NAME = "hadoop"
CONF_DIR = "etc/hadoop"
HOSTNAME = os.uname().nodename
HDFS_META_HOME = os.getenv("HDFS_META_HOME")
PATH = os.path.join(BASE_DIR, SERVICE_NAME, CONF_DIR)

def add_property_on_root(root, name, value):
    content = ET.tostring(root).decode()
    if name in content:
        return
    property = root.makeelement("property", {})
    root.append(property)

    name_tag = property.makeelement("name", {})
    property.append(name_tag)
    name_tag.text = name

    value_tag = property.makeelement("value", {})
    property.append(value_tag)
    value_tag.text = value

def core_site_xml():
    logging.info("脚本初始化core-site.xml中")
    tree: ET.ElementTree = ET.parse(f"{PATH}/samples/core-site.xml")
    root = tree.getroot()
    add_property_on_root(root, name="fs.defaultFS", value=f"hdfs://{HOSTNAME}")
    add_property_on_root(root, name="hadoop.tmp.dir", value=f"{HDFS_META_HOME}/temporarily")
    xml_str = (ET.tostring(root).decode()
               .replace("\n", "")
               .replace("\r", "")
               .replace(" ", ""))
    with open(f"{PATH}/core-site.xml", "w", encoding="UTF-8") as file:
        file.write(minidom.parseString(xml_str).toprettyxml(indent="   ", newl=os.linesep))
        file.close()
    logging.info("脚本初始化core-site.xml成功")

def hdfs_site_xml():
    logging.info("脚本初始化hdfs-site.xml中")
    tree: ET.ElementTree = ET.parse(f"{PATH}/samples/hdfs-site.xml")
    root = tree.getroot()
    add_property_on_root(root, name="dfs.namenode.name.dir", value=f"file:{HDFS_META_HOME}/namenode")
    add_property_on_root(root, name="dfs.datanode.data.dir", value=f"file:{HDFS_META_HOME}/datanode")
    xml_str = (ET.tostring(root).decode()
               .replace("\n", "")
               .replace("\r", "")
               .replace(" ", ""))
    with open(f"{PATH}/hdfs-site.xml", "w", encoding="UTF-8") as file:
        file.write(minidom.parseString(xml_str).toprettyxml(indent="   ", newl=os.linesep))
        file.close()
    logging.info("脚本初始化hdfs-site.xml成功")

def mapred_site():
    logging.info("脚本初始化mapred-site.xml中")
    tree: ET.ElementTree = ET.parse(f"{PATH}/samples/mapred-site.xml")
    root = tree.getroot()
    xml_str = (ET.tostring(root).decode()
               .replace("\n", "")
               .replace("\r", "")
               .replace(" ", ""))
    with open(f"{PATH}/mapred-site.xml", "w", encoding="UTF-8") as file:
        file.write(minidom.parseString(xml_str).toprettyxml(indent="   ", newl=os.linesep))
        file.close()
    logging.info("脚本初始化mapred-site.xml成功")

def yarn_site():
    logging.info("脚本初始化yarn-site.xml中")
    tree: ET.ElementTree = ET.parse(f"{PATH}/samples/yarn-site.xml")
    root = tree.getroot()
    xml_str = (ET.tostring(root).decode()
               .replace("\n", "")
               .replace("\r", "")
               .replace(" ", ""))
    add_property_on_root(root, name="yarn.resourcemanager.hostname", value=f"{HOSTNAME}")
    with open(f"{PATH}/yarn-site.xml", "w", encoding="UTF-8") as file:
        file.write(minidom.parseString(xml_str).toprettyxml(indent="   ", newl=os.linesep))
        file.close()
    logging.info("脚本初始化yarn-site.xml成功")

def main():
    # if not os.path.exists(path):
    #     os.makedirs(path)

    # uname: uname_result = os.uname()
    # logging.info(f"当前获取的节点信息为 {uname}")
    # logging.info(f"解析的节点名称是 {uname.nodename}")
    #
    # splits: Sequence = uname.nodename.split("-")
    #
    # identity = splits[-1]
    # logging.info(f"解析的id是 {identity}")
    #
    # shutil.copy2(os.path.join(path, "server_sample.properties"), os.path.join(path, "server.properties"))

    # core-site.xml
    if not os.path.exists(HDFS_META_HOME):
        os.makedirs(HDFS_META_HOME)
    core_site_xml()
    hdfs_site_xml()
    mapred_site()
    yarn_site()

if __name__ == '__main__':
    main()


'''电脑的连通集问题'''

'''问：有n台电脑，每两台之间可以选择连接一根网线，两台直接或间接连接的电脑认为是联通的
   如：1-2，2-4，4-7，则1和7也是联通的
'''
'''现在，给出一些连接情况，要求输出判断，指定的两台电脑是否连通的情况'''

class Set:
    def __init__(self,max_size):
        self.set_ground = [None]*max_size
        self.elements_size = max_size - self.set_ground.count(None)

    def add_element(self,data,parent):  # 方法：向集合数组中添加元素或集合
        self.set_ground[data] = parent

        if parent < 0:  # 默认集合的parent=-1，即含有一个元素
            print(f'集合{data}添加成功')  # 集合的根节点，也是该集合中的一个元素而已
        else:
            print(f'元素{data}添加成功')  # 若parent>0，意味着这是某个集合中的元素
            # （注意此处是-=）
            while self.set_ground[parent] >= 0:
                parent = self.set_ground[parent]
            self.set_ground[parent] -= 1  # 集合中元素数量 计数（-2：2个  -n：n个）

    def find_set(self,find_data):  # 方法：寻找某个元素所属集合的下标（元素值）
        # 实现了“路径压缩”的查找运算
        temporary_index = find_data
        if self.set_ground[temporary_index] < 0:  # 此处没错误，不用管波浪线
            return temporary_index  # 若内容<0，则代表是集合，返回
        else:
            # 否则，代表该节点有父节点
            # 递归：每次都顺便把 该节点的 父节点的 5.集合 赋给它，这样一层一层下来
            # 整条查询路径上面的节点，都直接指向了最终的集合点，减少了大量树高！！
            # 虽然对于一次查询没什么作用，但是多次查询后，速度明显提升
            self.set_ground[temporary_index] = self.find_set(self.set_ground[temporary_index])
            # 该节点的集合  =  查询-它父节点所在的集合
            return self.set_ground[temporary_index]

    def union(self,data_1,data_2):  # 实现了“按秩归并”的并运算
        set_index_1 = self.find_set(data_1)
        set_index_2 = self.find_set(data_2)
        if set_index_1 == set_index_2:  # 若一样
            print(f'元素{data_1}和元素{data_2}所属同一个集合，无需要并运算')
        else:  # 否则
            if self.set_ground[set_index_1] < self.set_ground[set_index_2]:
                self.set_ground[set_index_1] += self.set_ground[set_index_2]
                self.set_ground[set_index_2] = set_index_1
                return
            else:
                self.set_ground[set_index_2] += self.set_ground[set_index_1]
                self.set_ground[set_index_1] = set_index_2

    def display_element_number(self):  # 方法：显示数组中所有集合，以及包含元素数量
        tem = 0
        for i in range(len(self.set_ground)):
            if self.set_ground[i] is not None and self.set_ground[i] < 0:  # 此处没错误，不用管标亮
                print(f'集合{i}元素个数为{-self.set_ground[i]}')
                tem += 1
        if tem == 0:
            print('网络中无任何连通集')
        elif tem == 1:
            print('网络已经整体连通')
        else:
            print(f'网络中包含{tem}个连通集')

    def check_same_set(self,data_1,data_2):
        set_index_1 = self.find_set(data_1)
        set_index_2 = self.find_set(data_2)
        if set_index_1 == set_index_2:
            print(f'电脑{data_1}和电脑{data_2}已连通')
        else:
            print(f'电脑{data_1}和电脑{data_2}未连通')

def main():
    # 初始化5台计算机
    computer_set = Set(5)
    computer_set.add_element(0, -1)
    computer_set.add_element(1, -1)
    computer_set.add_element(2, -1)
    computer_set.add_element(3, -1)
    computer_set.add_element(4, -1)

    # 连接指定的计算机
    computer_set.union(2,1)
    computer_set.union(3,4)
    computer_set.union(1,3)
    computer_set.union(1,3)

    # 检查某两台计算机是否连通
    computer_set.check_same_set(1,4)
    computer_set.check_same_set(2,3)
    computer_set.check_same_set(0,2)

    # 检查整个网络的连通集个数
    computer_set.display_element_number()

if __name__ == '__main__':
    main()

5.集合/（3）电脑的连通集问题-按秩归并、路径压缩.py

（3）电脑的连通集问题-按秩归并、路径压缩.py


#!/usr/bin/env python3
# -*- coding: UTF-8 -*-
from Alphabet import RUNES, white_rune, rune_map, primes_map

#########################################
#  Rune  :  Stores a single rune. Incl. text, prime, index, and kind
#########################################

class Rune(object):
    def __init__(self, r=None, t=None, i=None, p=None):
        self._rune = r
        self._text = t
        self._index = i
        self._prime = p
        self._kind = None  # one of: r n s l w

    def __repr__(self):
        return f'<{self._rune}, {self._text}, {self._index}, {self._prime}>'

    @property
    def rune(self):
        if self._rune is None:
            self._rune = RUNES[self._index] if self._index < 29 else '•'
        return self._rune

    @property
    def text(self):
        if self._text is None:
            r = self.rune
            try:
                self._text = rune_map[self.rune]
            except KeyError:
                self._text = white_rune.get(r, r)
        return self._text

    @property
    def index(self):
        if self._index is None:
            r = self._rune
            self._index = RUNES.index(r) if r in RUNES else 29
        return self._index

    @property
    def prime(self):
        if self._prime is None:
            self._prime = primes_map.get(self.rune, 0)
        return self._prime

    @property
    def kind(self):
        if self._kind is None:
            x = self.rune
            if x in rune_map:
                self._kind = 'r'  # rune
            elif x == '⁜':
                self._kind = 's'  # paragraph, but treat as sentence
            elif x == '⁘':
                self._kind = 's'  # sentence
            elif x == '\n' or x == '\r':
                self._kind = 'l'  # line end
            elif x in '1234567890':
                self._kind = 'n'  # number
            else:
                self._kind = 'w'  # whitespace (explicitly not n or s)
        return self._kind

    def __add__(self, o):
        if isinstance(o, Rune):
            o = o.index
        if self.index == 29 or o == 29:
            return self
        return Rune(i=(self.index + o) % 29)

    def __sub__(self, o):
        if isinstance(o, Rune):
            o = o.index
        if self.index == 29 or o == 29:
            return self
        return Rune(i=(self.index - o) % 29)

    def __invert__(self):
        return self if self.index == 29 else Rune(i=28 - self.index)


print("Bem-vindo ao meu Quiz")

playing = input("Você quer jogar? ")

if playing.lower() != "sim":
    quit()

print("Ok! Vamos jogar :)")
score = 0

answer = input("Qual é a letra que antecede a letra S no alfabeto brasileiro? ")
if answer.lower() == "R":
    print('Acertou!')
    score += 1
else:
    print("Errou!")

answer = input("O cantor britânico Fred Mercury pertenceu a qual banda de rock? ")
if answer.lower() == "queen":
    print('Acertou!')
    score += 1
else:
    print("Errou!")

answer = input("Qual cidade brasileira é conhecida como a terra da garoa? ")
if answer.lower() == "são paulo":
    print('Acertou!')
    score += 1
else:
    print("Errou!")

answer = input("Qual é a sigla do estado de Minas Gerais? ")
if answer.lower() == "mg":
    print('Acertou!')
    score += 1
else:
    print("Errou!")

answer = input("Qual o nome da capital da Inglaterra? ")
if answer.lower() == "londres":
    print('Acertou!')
    score += 1
else:
    print("Errou!")

print("Você tem " + str(score) + "pontos!")
print("Você tem " + str((score / 4) * 100) + "%.")


from maneuvers.aerialturn import AerialTurnManeuver
from maneuvers.maneuver import Maneuver
from utility.field_sdf import sdf_contains, sdf_normal
from utility.info import Car
from utility.predict import DummyObject, fall
from utility.vec import normalize, xy, Vec3, cross, Mat33, norm

class RecoveryManeuver(Maneuver):
    def __init__(self, bot):
        super().__init__()

    def exec(self, bot):
        self.done = bot.info.my_car.on_ground
        target_rot = self.find_landing_orientation(bot.info.my_car, 120)
        return bot.fly.align(bot, target_rot)

    @staticmethod
    def find_landing_orientation(car: Car, num_points: int) -> Mat33:
        dummy = DummyObject(car)

        for i in range(num_points):
            fall(dummy, 0.0333)  # Apply physics and let car fall through the air

            if i > 5 and sdf_contains(dummy.pos):
                up = normalize(sdf_normal(dummy.pos))
                left = cross(normalize(dummy.vel), up)
                forward = cross(up, left)

                return Mat33.from_columns(forward, left, up)

        # No wall/ground intersections found in fall
        # Default to looking in direction of velocity, but upright

        forward = normalize(xy(car.vel)) if norm(xy(car.vel)) > 20 else car.forward
        up = Vec3(z=1)
        left = cross(up, forward)

        return Mat33.from_columns(forward, left, up)


# 问题描述
# 给定一个数字列表，返回其所有可能的排列

# 示例
# 输入：[1]
# 输出：[[1]]

# 输入：[1,2,3]
# 输出：[[1,2,3],[1,3,2],[2,1,3],[2,3,1],[3,1,2],[3,2,1]]

# 源码实现
class Solution:
    def permute(self, nums):
        def _permute(result, temp, nums):
            if nums == []:
                result += [temp]
            else:
                for i in range(len(nums)):
                    _permute(result, temp + [nums[i]], nums[:i] + nums[i + 1:])
        if nums is None:
            return []
        if nums is []:
            return [[]]
        result = []
        _permute(result, [], sorted(nums))
        return result

# 主函数
if __name__ == '__main__':
    nums = [1,2,3]
    s = Solution()
    ans = s.permute(nums)
    print("Input: ", nums)
    print("Output: ", ans)

# 运行结果
# Input:  [1, 2, 3]
# Output:  [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]