import json
import logging
from collections import defaultdict
from typing import Any, DefaultDict, Iterable

import requests
from django.conf import settings
from django.db import transaction
from requests_gssapi import HTTPSPNEGOAuth

from corgi.collectors.brew import Brew
from corgi.collectors.models import (
    CollectorErrataProduct,
    CollectorErrataProductVariant,
    CollectorErrataProductVersion,
    CollectorErrataRelease,
)
from corgi.core.models import SoftwareBuild

logger = logging.getLogger(__name__)

BREW_TAG_CANDIDATE_SUFFIX = "-candidate"

class ErrataTool:
    """Interface to the Errata Tool APIs."""

    GSSAPI_AUTH = HTTPSPNEGOAuth()

    def __init__(self):
        self.session = requests.Session()
        self.session.auth = self.GSSAPI_AUTH

    def get(
        self,
        path: str,
        **request_kwargs: Any,
    ) -> dict[str, Any]:
        """Get the response to a REST API call or raise an exception."""
        url = f"{settings.ERRATA_TOOL_URL}/{path}"
        response = self.session.get(url, **request_kwargs)
        response.raise_for_status()
        return response.json()

    def get_paged(
        self, path: str, page_data_attr: str = "data", pager: str = "page[number]"
    ) -> list[dict[str, Any]]:
        """Generator to iterate over data from paged Errata Tool API endpoint."""
        params = {pager: 1}
        data: list[dict[str, Any]] = []
        while True:
            page = self.get(path, params=params)
            page_data: Iterable[dict[str, Any]] = page[page_data_attr]
            if page_data:
                data.extend(page_data)
                params[pager] += 1
            else:
                break
        return data

    def load_et_products(self) -> None:
        # preload the data from ET before starting a DB transaction
        products_and_versions = self.get_products_and_versions()
        releases = self.get_paged("api/v1/releases")
        variants = self.get_paged("api/v1/variants")
        with transaction.atomic():
            self._delete_collector_objects()
            self.load_products_and_versions(products_and_versions)
            self.load_releases(releases)
            self.load_variants(variants)

    def _delete_collector_objects(self) -> None:
        CollectorErrataProduct.objects.all().delete()
        CollectorErrataProductVersion.objects.all().delete()
        CollectorErrataRelease.objects.all().delete()
        CollectorErrataProductVariant.objects.all().delete()

    @staticmethod
    def load_products_and_versions(products_and_versions: list[dict[str, Any]]) -> None:
        for product in products_and_versions:
            product_versions = product.pop("product_versions", [])
            et_product = CollectorErrataProduct.objects.create(
                et_id=product.pop("id"),
                name=product["attributes"].pop("name"),
                short_name=product["attributes"].pop("short_name"),
                meta_attr=product,
            )
            logger.debug(f"Created ET Product: {et_product.short_name}")
            for product_version in product_versions:
                name = product_version["attributes"].pop("name")
                brew_tags = ErrataTool.strip_brew_tag_candidate_suffixes(
                    product_version.pop("brew_tags")
                )
                CollectorErrataProductVersion.objects.create(
                    et_id=product_version.pop("id"),
                    name=name,
                    product=et_product,
                    brew_tags=brew_tags,
                    meta_attr=product_version,
                )
                logger.debug(f"Created ET ProductVersion: {name}")

    @staticmethod
    def strip_brew_tag_candidate_suffixes(brew_tags: list[str]) -> list[str]:
        return [t.removesuffix(BREW_TAG_CANDIDATE_SUFFIX) for t in brew_tags]

    def load_releases(self, releases: list[dict[str, Any]]) -> None:
        for release in releases:
            attributes = release["attributes"]
            name = attributes.pop("name")
            relationships = release["relationships"]
            brew_tags_dict = relationships.pop("brew_tags")
            brew_tags = [tag["name"] for tag in brew_tags_dict]
            release_obj = CollectorErrataRelease.objects.create(
                et_id=release.pop("id"),
                name=name,
                is_active=attributes.pop("is_active"),
                enabled=attributes.pop("enabled"),
                brew_tags=self.strip_brew_tag_candidate_suffixes(brew_tags),
                meta_attr=attributes,
            )
            logger.debug(f"Created ET Release: {name}")

            # Sometimes releases can refer to Product Versions which no longer exist
            product_version_names = [pv["name"] for pv in relationships.pop("product_versions")]
            product_versions = CollectorErrataProductVersion.objects.filter(
                name__in=product_version_names
            )
            release_obj.product_versions.set(product_versions)

    def load_variants(self, variants: list[dict[str, Any]]) -> None:
        for variant in variants:
            attributes = variant["attributes"]
            product_version = attributes["relationships"].pop("product_version")
            product_version_name = product_version["name"]

            # Sometimes variants can refer to Product Versions which no longer exist
            et_product_version = CollectorErrataProductVersion.objects.filter(
                name=product_version_name
            ).first()
            name = attributes.pop("name")
            cpe = attributes.pop("cpe", "")
            # CORGI-648 the value can be null
            if not cpe:
                cpe = ""
            CollectorErrataProductVariant.objects.create(
                name=name,
                cpe=cpe,
                product_version=et_product_version,
                et_id=variant.pop("id"),
                meta_attr=attributes,
            )
            logger.debug(f"Created ET Product Variant: {name}")

    def get_erratum_components(self, erratum_id: str):
        """Fetch components attached to erratum and index by their Variant.

        Example:

        {
          "RHEL-7.6-AUS": {
            "name": "RHEL-7.6-AUS",
            "description": "Red Hat Enterprise Linux 7.6 Advanced Update Support",
            "builds": [
              {
                "polkit-0.112-18.el7_6.3": {
                  "nvr": "polkit-0.112-18.el7_6.3",
                  "nevr": "polkit-0:0.112-18.el7_6.3",
                  "id": 1848203,
                  "is_module": false,
                  "variant_arch": {
                    "7Server-7.6.AUS": {
                      "SRPMS": [
                        "polkit-0.112-18.el7_6.3.src.rpm"
                      ],
                      "x86_64": [
                        "polkit-0.112-18.el7_6.3.x86_64.rpm",
                        "polkit-0.112-18.el7_6.3.i686.rpm",
                        "polkit-devel-0.112-18.el7_6.3.x86_64.rpm",
                        "polkit-devel-0.112-18.el7_6.3.i686.rpm",
                        "polkit-debuginfo-0.112-18.el7_6.3.x86_64.rpm",
                        "polkit-debuginfo-0.112-18.el7_6.3.i686.rpm"
                      ],
                      "noarch": [
                        "polkit-docs-0.112-18.el7_6.3.noarch.rpm"
                      ]
                    }
                  },
                  "added_by": "jrybar"
                }
              }
            ]
          }
        }
        """
        variant_to_component_map: DefaultDict[str, list] = defaultdict(list)
        builds = self.get(f"api/v1/erratum/{erratum_id}/builds_list.json")
        brew = Brew(SoftwareBuild.Type.BREW)
        for product_version in builds.values():
            for build in product_version["builds"]:
                for build_nvr, build_data in build.items():
                    if build_data["is_module"]:
                        self._parse_module(
                            build_nvr, build_data["variant_arch"], brew, variant_to_component_map
                        )
                        continue
                    build_id = build_data["id"]
                    for variant, components_by_arch in build_data["variant_arch"].items():
                        variant_components = []
                        for _, components in components_by_arch.items():
                            # Collect all components as a single list, their arch information is
                            # included in the NVRA string anyway.
                            variant_components.extend(components)
                        variant_to_component_map[variant].append({build_id: variant_components})

        return dict(variant_to_component_map)

    def save_variant_cdn_repo_mapping(self):
        """Fetches all existing Errata Tool Variants and the CDN repos they are configured with.

        Each erratum's builds are mapped against individual Variants that determine which repos
        the content gets pushed to.
        """

        for repo in self.get_paged("api/v1/cdn_repos"):
            repo_attrs = repo["attributes"]
            repo_rels = repo["relationships"]

            for variant in repo_rels["variants"]:
                variant_name = variant["name"]
                try:
                    variant_obj = CollectorErrataProductVariant.objects.get(name=variant_name)
                except CollectorErrataProductVariant.DoesNotExist:
                    logger.debug(
                        "Repo %s links to a non-existent variant: %s",
                        repo_attrs["name"],
                        variant_name,
                    )
                    continue
                uniq_repos = set(variant_obj.repos)
                uniq_repos.add(repo_attrs["name"])
                variant_obj.repos = list(uniq_repos)
                logger.info("Linking repo %s to variant %s", repo_attrs["name"], variant_name)
                variant_obj.save()

    @staticmethod
    def get_variant_cdn_repo_mapping() -> dict[str, list[str]]:
        variants_with_repos = {
            variant.name: variant.repos
            for variant in CollectorErrataProductVariant.objects.exclude(repos__len=0)
        }
        return variants_with_repos

    def get_errata_key_details(self, name: str) -> tuple[int, bool]:
        erratum_details = self.get(f"api/v1/erratum/{name}")
        errata_type_details = list(erratum_details["errata"].values())
        if len(errata_type_details) != 1:
            raise ValueError(
                f"Erratum with name {name} has more than one type key: {errata_type_details}"
            )
        erratum_id = errata_type_details[0]["id"]
        shipped_live = errata_type_details[0]["status"] == "SHIPPED_LIVE"
        return erratum_id, shipped_live

    def get_builds_for_errata(self, errata_id: int) -> list[int]:
        build_ids = set()
        for variant in self.get_erratum_components(str(errata_id)).values():
            for component in variant:
                build_ids.update(component.keys())
        return list(build_ids)

    def _parse_module(
        self,
        module_name: str,
        module_data: dict[str, dict[str, list[str]]],
        brew: Brew,
        variant_to_component_map: DefaultDict[str, list],
    ) -> None:
        """Persist collector models for modular builds from errata build_list.json. This allows
        later processing of modular builds in the Brew task slow_fetch_modular_build"""
        for variant, components_by_arch in module_data.items():
            modular_rpms = []
            for arch, components in components_by_arch.items():
                # SRPMS are looked up in persist_modules from Brew via RPMs
                if arch == "SRPMS":
                    continue
                # persist_modules expects the .rpm suffix stripped
                rpm_suffix_len = ".rpm"
                stripped_components = [
                    rpm[: -len(rpm_suffix_len)] for rpm in components if rpm.endswith(".rpm")
                ]
                modular_rpms.extend(stripped_components)
            build_ids = brew.persist_modules({module_name: modular_rpms})
            for build_id in build_ids:
                # persist_modules returns a flat list of build_ids, so its no longer possible to
                # map modular_rpms to build_ids. In slow_save_errata these are only saved as
                # meta_attr so, let's just save the entire list for each build_id
                variant_to_component_map[variant].append({build_id: modular_rpms})

    def get_erratum_notes(self, erratum_id: int) -> dict:
        # Get the contents of the "Notes" (formerly "How to test") field from an erratum.
        # Quarkus uses this field to associate an SBOM with an erratum.
        erratum_json = self.get(f"api/v1/erratum/{erratum_id}?format=json")
        try:
            # All products that use SBOMer should have notes set
            # NB: Though the field in the ET UI is called "Notes", the field name in the API
            # is "how_to_test", which was the original purpose of the Notes field.
            notes = json.loads(erratum_json["content"]["content"]["how_to_test"])
        except json.JSONDecodeError as error:
            logger.warning(f"Couldn't load Notes for erratum {erratum_id}")
            raise error
        return notes

    def get_products_and_versions(self) -> list[dict[str, Any]]:
        products = self.get_paged("api/v1/products")
        for product in products:
            product_versions: list[dict[str, Any]] = []
            pv_relation = product["relationships"].pop("product_versions")
            for pv in pv_relation:
                response = self.get(f"api/v1/products/{product['id']}/product_versions/{pv['id']}")
                data = response["data"]
                product_versions.append(data)
            product["product_versions"] = product_versions
        return products


"""
"make 4 inline" classical game
Network realiastion
23/11/2020
Author A.V.Korovin [a.v.korovin73@gmail.com]
"""
from rougejaune import Game

if __name__ == '__main__':
    game = Game()
    game.wait_server_connection()


from flask import Blueprint, request, jsonify, current_app
from app.serializer.address_locksmith import AddressLocksmithSchema as ma
from app.model.address_locksmith import AddressLocksmith as md
from app.jwt import locksmith_required, user_required
from flask_jwt_extended import get_jwt_identity
from sqlalchemy import and_

bp_address_locksmith = Blueprint('address_locksmith', __name__)

@bp_address_locksmith.route('/get-locksmith-address-list', methods=['GET'])
@locksmith_required
def locksmith_address_list():
    _filter = and_(md.active == True, md.locksmith_id == get_jwt_identity())
    return ma(many=True).jsonify(md.query.filter(_filter).all()), 200

@bp_address_locksmith.route('/add-locksmith-address', methods=['POST'])
@locksmith_required
def add_locksmith_address():
    request.json['locksmith_id'] = get_jwt_identity()
    value = ma().load(request.json)
    if value.main:
        _filter = and_(md.locksmith_id == get_jwt_identity())
        md.query.filter(_filter).update({"main": False})
        current_app.db.session.commit()
    current_app.db.session.add(value)
    current_app.db.session.commit()
    return jsonify({'msg': 'sucess'}), 201

@bp_address_locksmith.route('/update-locksmith-address', methods=['POST'])
@locksmith_required
def update_locksmith_address():
    request.json['locksmith_id'] = get_jwt_identity()
    _filter = and_(md.locksmith_id == get_jwt_identity(), md.id == request.json['id'])
    result = md.query.filter(_filter).first()
    address = ma().dump(result)
    if address:
        tmp_filter = md.locksmith_id == get_jwt_identity()
        md.query.filter(tmp_filter).update({"main": False})
        md.query.filter(_filter).update(request.json)
        current_app.db.session.commit()
        return jsonify({'msg': 'sucess'}), 201
    else:
        return jsonify({'msg': 'Failed'}), 409

@bp_address_locksmith.route('/delete-locksmith-address', methods=['POST'])
@locksmith_required
def delete_locksmith_address():
    _filter = and_(md.locksmith_id == get_jwt_identity(), md.id == request.json['id'])
    result = md.query.filter(_filter).first()
    address = ma().dump(result)
    if address:
        md.query.filter(_filter).update({"active": False})
        current_app.db.session.commit()
        return jsonify({'msg': 'sucess'}), 201
    else:
        return jsonify({'msg': 'Failed'}), 409


from datetime import datetime
import requests
import json

def format_time(timestamp_str):
    '''
    convert timestamp to pronounce.
    '''
    timestamp = datetime.strptime(timestamp_str, '%Y-%m-%dT%H:%M:%S%z')
    time_to_pronounce = datetime.strftime(timestamp, '%#m月%#d日%p%#I時')

    time_in_jp = time_to_pronounce.replace('AM', '午前').replace('PM', '午後')

    return time_in_jp

def is_json(json_str):
    '''
    judge if json_str is valid.
    '''
    result = False
    try:
        json.loads(json_str)
        result = True
    except json.JSONDecodeError as jde:
        logger.info('got invalid response json, retrying.')

    return result

def get(rotation_code):
    uri = 'https://spla3.yuu26.com/api/coop-grouping/{}'.format(rotation_code)
    headers = {'Content-Type': 'application/json'}

    schedule = ''
    while True:
        schedule = requests.get(uri, headers=headers)
        valid_json = is_json(schedule.text)

        if valid_json:
            break

    schedule = schedule.json()
    map_detail = schedule['results'][0]

    result = {
        'stage': map_detail['stage']['name'],
        'start_time': map_detail['start_time'],
        'end_time': map_detail['end_time'],
        'weapons': [ weapon['name'] for weapon in map_detail['weapons']],
        'big_run': map_detail['is_big_run']
    }

    return result


"""
This is example how to use postgresql DB local settings
Rename _local_settings.py to local_settings.py locally
change DB_NAME, DB_USER as you wish, enjoy

To create DB on ubuntu, login to psql console:
sudo -u postgres psql
>
> CREATE DATABASE let_me_app;
> CREATE USER developer WITH PASSWORD '123456';
> GRANT ALL PRIVILEGES ON DATABASE light_recipe TO developer;
> ALTER USER developer WITH SUPERUSER;
> \q

"""

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.sqlite3',
        'NAME': 'db.sqlite3',
    }
}

### Social network secure keys
# twitter
#Go to https://apps.twitter.com/app/new and create the new application
#The callback URL should be something like http://test1.com:8000/complete/twitter/
SOCIAL_AUTH_TWITTER_KEY = ''
SOCIAL_AUTH_TWITTER_SECRET = ''

#google OAuth2
#Go to https://console.developers.google.com/ and create a new application.
#Under APIs and Auth > Credentials, create a new Client ID.
#Make sure to specify the right callback URL: http://test1.com:8000/complete/google-oauth2/
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = ''
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = ''

#facebook
#Go to https://developers.facebook.com/apps/?action=create and click the green “Create New App” button.
#In the settings of the newly-created application, click “Add Platform”.
# From the options provided, choose Web,
# and fill in the URL of the site (http://test1.com:8000 in our example).
SOCIAL_AUTH_FACEBOOK_KEY = ''
SOCIAL_AUTH_FACEBOOK_SECRET = ''

#VK
#http://psa.matiasaguirre.net/docs/backends/vk.html#oauth2
SOCIAL_AUTH_VK_OAUTH2_KEY = ''
SOCIAL_AUTH_VK_OAUTH2_SECRET = ''

#OK
SOCIAL_AUTH_ODNOKLASSNIKI_OAUTH2_KEY = ''
SOCIAL_AUTH_ODNOKLASSNIKI_OAUTH2_SECRET = ''
SOCIAL_AUTH_ODNOKLASSNIKI_OAUTH2_PUBLIC_NAME = ''

SOCIAL_AUTH_LOGIN_REDIRECT_URL = '/home/'
SOCIAL_AUTH_LOGIN_URL = '/'


"""
This module provides a graphical user interface for downloading images using the gallery-dl command.
"""

import sys
import sqlite3
import platform

from PyQt6 import QtWidgets, QtGui
from PyQt6.QtWidgets import QAbstractItemView
from PyQt6.QtCore import QSettings, Qt, QDateTime, QMutex, QThreadPool
from PyQt6.QtSql import QSqlDatabase, QSqlTableModel, QSqlRecord, QSqlField, QSqlQuery

from threads import DownloadThread, InitialWorker
from tables_views import ProcessedTableView, QueueTableView
from windows import LogWindow, MessageWindow

# Create a mutex to synchronize access to the database
db_mutex = QMutex()

class MainWindow(QtWidgets.QMainWindow):
    """Main window class for GalleryDL Beyond application."""

    def __init__(self, *args, **kwargs):
        """Initialize the main window."""
        super(MainWindow, self).__init__(*args, **kwargs)

        self.setWindowTitle("GalleryDL Beyond")
        self.settings = QSettings("ZCode", "GalleryDLBeyond")

        geometry = self.settings.value("geometry")
        if geometry is not None:
            self.restoreGeometry(geometry)

        window_state = self.settings.value("windowState")
        if window_state is not None:
            self.restoreState(window_state)

        # Create the urls table if it doesn"t exist
        conn = sqlite3.connect("database.db")
        c = conn.cursor()
        c.execute(
            """
            CREATE TABLE IF NOT EXISTS urls (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                url TEXT NOT NULL,
                processed INTEGER NOT NULL DEFAULT 0,
                date_processed TEXT
            );
        """
        )
        conn.commit()
        conn.close()

        self.downloading = False
        self.blocked = True
        self.aborted = False

        # Main layout
        main_layout = QtWidgets.QVBoxLayout()
        list_layout = QtWidgets.QHBoxLayout()

        # Create the queue table view
        queue_layout = QtWidgets.QVBoxLayout()
        queue_layout.addWidget(QtWidgets.QLabel("Queue"))
        self.queue_table = QueueTableView()
        queue_layout.addWidget(self.queue_table)

        # Create the processed table view
        done_layout = QtWidgets.QVBoxLayout()
        done_layout.addWidget(QtWidgets.QLabel("Processed"))
        self.processed_table = ProcessedTableView()
        done_layout.addWidget(self.processed_table)

        # Assign each table the reference of the other
        self.processed_table.set_queue_table(self.queue_table)

        # Create the model for the queue table view
        self.queue_model = QSqlTableModel()

        list_layout.addLayout(queue_layout)
        list_layout.addLayout(done_layout)

        log_layout = QtWidgets.QHBoxLayout()

        # Log window
        self.log_text = LogWindow()
        log_layout.addWidget(self.log_text)

        # Message window
        self.messages = MessageWindow()
        log_layout.addWidget(self.messages)

        # Add references to message window in the table views
        self.queue_table.set_message_window(self.messages)
        self.processed_table.set_message_window(self.messages)

        add_layout = QtWidgets.QHBoxLayout()
        self.url_input = QtWidgets.QLineEdit()
        self.queue_button = QtWidgets.QPushButton("Queue")
        self.queue_button.setShortcut("Return")
        add_layout.addWidget(self.url_input)
        add_layout.addWidget(self.queue_button)

        self.start_button = QtWidgets.QPushButton()
        self.set_button_blocked()

        main_layout.addLayout(list_layout)
        main_layout.addLayout(log_layout)
        main_layout.addLayout(add_layout)
        main_layout.addWidget(self.start_button)

        # Set the stretch factors of the items
        main_layout.setStretch(0, 8)  # list_layout
        main_layout.setStretch(1, 4)  # log_text
        main_layout.setStretch(2, 1)  # add_layout
        main_layout.setStretch(3, 1)  # start_button

        layout = QtWidgets.QVBoxLayout()
        layout.addWidget(self.url_input)
        layout.addWidget(self.log_text)

        widget = QtWidgets.QWidget()
        widget.setLayout(main_layout)
        self.setCentralWidget(widget)

        # Set up the database connection
        database = QSqlDatabase.addDatabase("QSQLITE")
        database.setDatabaseName("database.db")
        database.open()

        # Set up the queue model
        self.queue_model = QSqlTableModel(db=database)
        self.queue_model.setTable("urls")
        self.queue_model.setFilter("processed = 0")
        self.queue_model.select()

        # Set up the table view
        self.queue_table.setModel(self.queue_model)
        self.queue_table.setSelectionBehavior(
            QAbstractItemView.SelectionBehavior.SelectRows
        )
        self.queue_table.setSelectionMode(
            QAbstractItemView.SelectionMode.ExtendedSelection
        )
        self.queue_table.hideColumn(0)
        self.queue_table.hideColumn(2)
        self.queue_table.hideColumn(3)
        self.queue_table.horizontalHeader().setSectionResizeMode(
            1, QtWidgets.QHeaderView.ResizeMode.Stretch
        )

        # Set up the processed model
        self.processed_model = QSqlTableModel(db=database)
        self.processed_model.setTable("urls")
        self.processed_model.setFilter("processed = 1")
        self.processed_model.setSort(3, Qt.SortOrder.DescendingOrder)
        self.processed_model.select()

        # Set up the processed table view
        self.processed_table.setModel(self.processed_model)
        self.processed_table.setSelectionBehavior(
            QAbstractItemView.SelectionBehavior.SelectRows
        )
        self.processed_table.setSelectionMode(
            QAbstractItemView.SelectionMode.ExtendedSelection
        )
        self.processed_table.hideColumn(0)
        self.processed_table.hideColumn(2)
        self.processed_table.resizeColumnToContents(3)
        self.processed_table.horizontalHeader().setSectionResizeMode(
            1, QtWidgets.QHeaderView.ResizeMode.Stretch
        )

        # Define the download_thread attribute and set its initial value to None
        self.download_thread = None

        # Connect the add button"s clicked signal to the add_queue method
        self.queue_button.clicked.connect(self.add_queue)

        # Connect the start button"s clicked signal to the start method
        self.start_button.clicked.connect(self.start)

        # Check pĺatform
        os_name = platform.system()
        self.gallerydl_bin = ""

        if os_name == "Windows":
            gallerydl_ext = ".exe"
        elif os_name == "Linux":
            gallerydl_ext = ".bin"
        else:
            self.messages.append(f"Unsupported platform: {os_name}")
            return

        self.gallerydl_bin = "gallery-dl" + gallerydl_ext

        worker = InitialWorker(self.messages, self.gallerydl_bin)
        worker.signals.finished.connect(self.set_button_start)
        QThreadPool.globalInstance().start(worker)

    def keyPressEvent(self, event):
        if event.matches(QtGui.QKeySequence.StandardKey.Paste):
            # Handle the Ctrl+V shortcut in a custom way
            clipboard_text = QtGui.QGuiApplication.clipboard().text()
            self.url_input.setText(clipboard_text)
        else:
            super().keyPressEvent(event)

    # pylint: disable=invalid-name
    def closeEvent(self, event):
        """
        Reimplemented closeEvent method to save the window size and position when the application
        is closed.
        """

        self.settings.setValue("geometry", self.saveGeometry())
        self.settings.setValue("windowState", self.saveState())
        super().closeEvent(event)

    def add_queue(self):
        # Acquire the mutex before writing to the database
        db_mutex.lock()

        url = self.url_input.text()
        if url:
            # Check if the URL already exists in the database
            query = QSqlQuery()
            query.prepare("SELECT COUNT(*) FROM urls WHERE url = ?")
            query.addBindValue(url)
            query.exec()
            query.next()
            count = query.value(0)

            if count > 0:
                # URL already exists, print an error message
                self.messages.warning(f"{url} already exists in the database")
            else:
                record = QSqlRecord()
                record.append(QSqlField("url"))
                record.setValue("url", url)
                self.queue_model.insertRecord(-1, record)
                self.queue_model.submitAll()
                self.url_input.clear()
                self.messages.add_message(f"{url} added to queue")

        # Release the mutex after writing to the database
        db_mutex.unlock()

    def set_button_blocked(self):
        self.start_button.setStyleSheet("background-color: #9c0d20;")
        self.start_button.setText("Waiting...")

    def set_button_start(self):
        self.blocked = False
        self.start_button.setStyleSheet("background-color: #0b5e26;")
        self.start_button.setText("Start")
        self.start_button.setShortcut("Ctrl+Return")

    def set_button_abort(self):
        self.start_button.setStyleSheet("background-color: #9c0d20;")
        self.start_button.setText("Abort")
        self.start_button.setShortcut("Ctrl+Return")

    def start(self):
        """Start the downloading of all URLS in the queue"""
        if self.blocked == True:
            self.messages.warning("Can't start yet, please wait.")
            return

        if self.downloading == True:
            self.aborted = True
            self.download_thread.stop()
        else:
            # Connect to the SQLite database
            conn = sqlite3.connect("database.db")
            c = conn.cursor()

            # Query the urls table for the next URL that is not processed
            c.execute(
                "SELECT id, url FROM urls WHERE processed = 0 ORDER BY id LIMIT 1"
            )
            row = c.fetchone()

            # Download URLs until there are no more URLs with processed = 0
            if row:
                self.set_button_abort()
                self.downloading = True
                url_id, url = row

                self.messages.add_message(f"Starting download of URL: {url}")

                # Create and start a download thread for the URL
                self.download_thread = DownloadThread(url_id, url, self.gallerydl_bin)
                self.download_thread.output.connect(self.append_output)
                self.download_thread.finished.connect(
                    lambda: self.download_finished(conn, c)
                )
                self.download_thread.start()
            else:
                conn.close()

    def download_finished(self, conn, c):
        # Acquire the mutex before writing to the database
        db_mutex.lock()

        if self.aborted == True:
            self.aborted = False
            self.set_button_start()
            self.downloading = False

            self.messages.error("Download process aborted.")
        else:
            # Get the URL ID from the sender
            download_thread = self.sender()
            url_id = download_thread.url_id
            url = download_thread.url

            # Get the index of the record with the specified url_id
            record_index = self.queue_model.match(
                self.queue_model.index(0, 0),
                Qt.ItemDataRole.DisplayRole,
                url_id,
                1,
                Qt.MatchFlag.MatchExactly,
            )[0]

            # Update the processed and date_processed columns for the record
            self.queue_model.setData(
                self.queue_model.index(
                    record_index.row(), self.queue_model.fieldIndex("processed")
                ),
                1,
            )
            self.queue_model.setData(
                self.queue_model.index(
                    record_index.row(), self.queue_model.fieldIndex("date_processed")
                ),
                QDateTime.currentDateTimeUtc().toString("yyyy-MM-dd hh:mm:ss"),
            )

            # Submit the changes to the database
            self.queue_model.submitAll()

            self.messages.success(f"Finished download of URL: {url}")

            # Refresh the models
            self.queue_model.select()
            self.processed_model.select()

            # Query the urls table for the next URL that is not processed
            c.execute(
                "SELECT id, url FROM urls WHERE processed = 0 ORDER BY id LIMIT 1"
            )
            row = c.fetchone()

            if row:
                url_id, url = row

                self.messages.add_message(f"Starting download of URL: {url}")

                # Create and start a download thread for the URL
                self.download_thread = DownloadThread(url_id, url, self.gallerydl_bin)
                self.download_thread.output.connect(self.append_output)
                self.download_thread.finished.connect(
                    lambda: self.download_finished(conn, c)
                )
                self.download_thread.start()
            else:
                conn.close()
                self.messages.success("No more urls to download, queue finished.")
                self.set_button_start()
                self.downloading = False
        # Release the mutex after writing to the database
        db_mutex.unlock()

    def append_output(self, output):
        """Append the output to the text widget."""

        # Split the output by the "/" character and get the last element
        filename = output.strip().split("/")[-1]

        # Append the filename to the text widget
        self.log_text.append(filename)

        lines = self.log_text.toPlainText().splitlines()
        if len(lines) > 2000:
            self.log_text.setPlainText("\n".join(lines[-1000:]))
            self.log_text.verticalScrollBar().setValue(
                self.log_text.verticalScrollBar().maximum()
            )

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)

    if sys.platform == "win32":
        app.setStyle("Windows")

    window = MainWindow()
    window.show()
    app.exec()


from multiprocessing import context
from django.shortcuts import render
from users.models import Profile

def profiles(request):
    profile = Profile.objects.all()
    context = {
        'profiles' : profile
    }
    return render(request, 'users/profiles.html', context)

def user_profile(request, pk):
    user_profile = Profile.objects.get(id=pk)

    top_skills = user_profile.skill_set.exclude(description__exact="")
    other_skills = user_profile.skill_set.filter(description="")

    context = {
        'profile' : user_profile,
        'top_skills' : top_skills,
        'other_skills' : other_skills,
    }
    return render(request, 'users/user_profile.html', context)


# coding: utf-8
import os
import numpy as np
from sklearn import preprocessing
from sklearn.cross_validation import train_test_split
from sklearn.grid_search import GridSearchCV
from sklearn.metrics import classification_report
from sklearn.pipeline import Pipeline
from sklearn.externals import joblib
from sklearn import svm
import matplotlib.pyplot as plt
from sayuri.machine import MachineLoader

MODEL_FILE = os.path.join(os.path.dirname(__file__), MachineLoader.MACHINE_FILE)

def load_data(skip_header=1):
    import os
    data_file = os.path.join(os.path.dirname(__file__), "training_data_with_label.csv")
    header = []
    with open(data_file, newline=os.linesep) as f:
        header = next(f).replace(os.linesep, "").split(",")
    dataset = np.genfromtxt(data_file, delimiter=",", skip_header=skip_header)
    y = dataset[:, 0]  # left side data is label
    X = dataset[:, range(1, dataset.shape[1])]

    return {"dataset": dataset, "header": header, "y": y, "X": X}

def make_model(y, X, columns, save_model=False):
    # select feature
    _X = X[:, columns]

    # reguralization
    scaler = preprocessing.StandardScaler()
    _X = scaler.fit_transform(_X)

    x_train, x_test, y_train, y_test = train_test_split(_X, y, test_size=0.25, random_state=42)

    candidates = [{'kernel': ["rbf"], 'gamma': [1e-3, 1e-4], 'C': [1, 10, 100]},
                  {'kernel': ['linear'], 'C': [1, 10, 100]}]

    clf = GridSearchCV(svm.SVC(C=1), candidates, cv=5, scoring="f1")
    clf.fit(x_train, y_train)

    for params, mean_score, scores in sorted(clf.grid_scores_, key=lambda s: s[1], reverse=True):
        print("%0.3f (+/-%0.03f) for %r" % (mean_score, scores.std() / 2, params))

    model = clf.best_estimator_
    y_predict = model.predict(x_test)

    print(classification_report(y_test, y_predict, target_names=["good", "bad"]))

    # plot boundary
    x_min, x_max = x_test[:, 0].min() - 1, x_test[:, 0].max() + 1
    y_min, y_max = x_test[:, 1].min() - 1, x_test[:, 1].max() + 1
    h = .02  # step size
    xx, yy = np.meshgrid(np.arange(x_min, x_max, h), np.arange(y_min, y_max, h))
    z = model.predict(np.c_[xx.ravel(), yy.ravel()])
    mean = {}
    mean["0"] = [np.average(xx.ravel()[z == 0]), np.average(yy.ravel()[z == 0])]
    mean["1"] = [np.average(xx.ravel()[z == 1]), np.average(yy.ravel()[z == 1])]
    z = z.reshape(xx.shape)
    plt.contourf(xx, yy, z, cmap=plt.cm.Paired)
    plt.axis('off')

    # plot test result (2d)
    plt.scatter(x_test[y_test == y_predict, 0], x_test[y_test == y_predict, 1], color="blue", cmap=plt.cm.Paired)
    plt.scatter(x_test[y_test != y_predict, 0], x_test[y_test != y_predict, 1], color="red", cmap=plt.cm.Paired)
    plt.scatter(mean["0"][0], mean["0"][1], color="green", cmap=plt.cm.Paired)
    plt.scatter(mean["1"][0], mean["1"][1], color="green", cmap=plt.cm.Paired)

    plt.show()

    if save_model:
        pipe = Pipeline([("scaling", scaler), ("estimator", model)])
        if sum(pipe.predict(scaler.inverse_transform(x_test)) != y_predict) > 0:
            raise Exception("Pipeline is not correct")
        joblib.dump(pipe, MODEL_FILE)
        return pipe

    return model


command = input()

people = {}

while not command == "Results":
    data = command.split(":")
    action = data[0]

    if action == "Add":
        person_name = data[1]
        health = int(data[2])
        energy = int(data[3])
        if person_name not in people:
            people[person_name] = {"health": health, "energy": energy}
        else:
            people[person_name]["health"] += health

    elif action == "Attack":
        attacker_name = data[1]
        defender_name = data[2]
        damage = int(data[3])
        if attacker_name in people and defender_name in people:
            people[defender_name]["health"] -= damage
            people[attacker_name]["energy"] -= 1
            if people[defender_name]["health"] <= 0:
                people.pop(defender_name)
                print(f"{defender_name} was disqualified!")
            if people[attacker_name]["energy"] <= 0:
                people.pop(attacker_name)
                print(f"{attacker_name} was disqualified!")

    elif action == "Delete":
        user_name = data[1]
        if user_name == "All":
            people.clear()
        else:
            if user_name in people:
                people.pop(user_name)

    command = input()

count_of_people_left = len(people)

print(f"People count: {count_of_people_left}")

sorted_people = sorted(people.items(), key=lambda kvp: (-kvp[1]["health"], [0]))

for person_name, data in sorted_people:
    print(f"{person_name} - {data['health']} - {data['energy']}")


import numpy as np

data_path = "data/"

joint_locations_filename_intial = "joint_data_2"
pose_data_filename_initial = "pose_data_194389"
file_extension = ".npy"

num_pose_data_points = 194388
num_joint_data_points = 918

num_body_parts = 24

def load_data():
    """
    Loads the joint locations and the rotation vectors (pose data) for each body model.

    The data is set in such a way that the pose data and the joint locations correspond
    for each data point.

    OUTPUTS:
    ------------
    joint_data
        A list of length amount_of_data
        Each element of the list is a 24x3 np array.
        Each row of the np array is the joint location in x,y,z for a body part

    pose_data
        Similar to joint_data for pose, i.e. rotation vectors

    """
    joint_filename = data_path + joint_locations_filename_intial + file_extension
    pose_filename = data_path + pose_data_filename_initial + file_extension

    joint_data = np.load(open(joint_filename, "rb"))
    joint_data = joint_data.reshape(num_joint_data_points, num_body_parts, 3)

    pose_data = np.load(open(pose_filename, "rb"))
    pose_data = pose_data.reshape(num_pose_data_points, num_body_parts, 3)

    return joint_data, pose_data


import dataclasses
from dataclasses import dataclass
from typing import Any, Dict, List, Optional, Set

from taipy.config.common.scope import Scope

from ..common.alias import JobId

@dataclass
class _DataNodeModel:

    id: str
    config_id: str
    scope: Scope
    storage_type: str
    name: str
    owner_id: Optional[str]
    parent_ids: List[str]
    last_edit_date: Optional[str]
    job_ids: List[JobId]
    version: str
    cacheable: bool
    validity_days: Optional[float]
    validity_seconds: Optional[float]
    edit_in_progress: bool
    data_node_properties: Dict[str, Any]

    def to_dict(self) -> Dict[str, Any]:
        return {**dataclasses.asdict(self), "scope": repr(self.scope)}

    @staticmethod
    def from_dict(data: Dict[str, Any]):
        return _DataNodeModel(
            id=data["id"],
            config_id=data["config_id"],
            scope=Scope._from_repr(data["scope"]),
            storage_type=data["storage_type"],
            name=data["name"],
            owner_id=data.get("owner_id", data.get("parent_id")),
            parent_ids=data["parent_ids"],
            last_edit_date=data.get("last_edit_date", data.get("last_edition_date")),
            job_ids=data["job_ids"],
            version=data["version"],
            cacheable=data["cacheable"],
            validity_days=data["validity_days"],
            validity_seconds=data["validity_seconds"],
            edit_in_progress=bool(data.get("edit_in_progress", data.get("edition_in_progress", False))),
            data_node_properties=data["data_node_properties"],
        )


from django.urls import path
from .views import*
from django.contrib.auth import views as auth_views
urlpatterns = [path('',home,name='home'),
               path('notes',notes,name='notes'),
               path('delete_note/<int:pk>',delete_note,name='delete_note'),
               path('notes_detail/<int:pk>',notedetails,name='notes_detail'),
               path('homework',homework,name='homework'),
               path('update_homework/<int:pk>',update_homework,name='updatehomework'),
               path('delete_homework/<int:pk>',delete_homework,name='deletehomework'),
               path('youtube',youtube,name='youtube'),
               path('todo',todo,name='todo'),
               path('updatetodo/<int:pk>',updatetodo,name='updatetodo'),
               path('deletetodo/<int:pk>',deletetodo,name='deletetodo'),
               path('books',books,name='books'),
               path('dictionary',dictionary,name='dictionary'),
               path('WikiPedia',WikiPedia,name='WikiPedia'),

               path('register',register,name='register'),
               path('login',auth_views.LoginView.as_view(template_name='login.html'),name='login'),
               path('profile',profile,name='profile'),
               path('logout',logout,name='logout'),

]


import heapq
from collections import defaultdict
from typing import List

class Solution:
    def maxProbability(self, n: int, edges: List[List[int]], succProb: List[float], start: int, end: int) -> float:
        def dijkstra(start, end):
            dist[start] = 0
            q = [(0, start)]
            while q:
                nod = heapq.heappop(q)[1]
                for vecin, cost in graph[nod]:
                    if dist[nod] * cost < dist[vecin]:
                        dist[vecin] = dist[nod] * cost
                        heapq.heappush(q, (dist[vecin], vecin))
                    if vecin == end:
                        return

        graph = defaultdict(list)
        for i, edge in enumerate(edges):
            x = edge[0]
            y = edge[1]
            graph[x].append((y, -succProb[i]))
            graph[y].append((x, -succProb[i]))

        dist = [float("inf")] * (len(graph) + 1)
        dijkstra(start, end)
        return -dist[end]

if __name__ == '__main__':
    print(Solution().maxProbability(3, [[0, 1], [1, 2], [0, 2]], [0.5, 0.5, 0.2], 0, 2))


# -*- coding: utf-8 -*-
import cv2,os
video_path = input("input video path:")
video_dir =os.path.splitext(video_path)[0] + "-crop" + os.path.splitext(video_path)[1]

def crop_video(video_path):
    video=cv2.VideoCapture(video_path)
    fps = int(round(video.get(cv2.CAP_PROP_FPS)))
    print("fps:"+str(fps))
    width = int(video.get(cv2.CAP_PROP_FRAME_WIDTH))
    height = int(video.get(cv2.CAP_PROP_FRAME_HEIGHT))
    new_hight = 1080
    new_width = int(width*new_hight/height)
    cv2.namedWindow(video_path, 0)
    cv2.resizeWindow(video_path, new_width, new_hight)  # 设置窗口大小
    grabbed, frame = video.read()
    cv2.imshow(video_path,frame)
    # 选择ROI
    roi = cv2.selectROI(windowName=video_path, img=frame, showCrosshair=True, fromCenter=False)
    x, y, w, h = roi
    print(roi)
    # 显示ROI并保存图片
    if roi != (0, 0, 0, 0):
        crop = frame[y:y+h, x:x+w]
        cv2.imshow(video_path, crop)
    else:
        crop = frame
        w = width
        h = height
        cv2.imshow(video_path, crop)
    fourcc = cv2.VideoWriter_fourcc(*'mp4v')
    videoWriter = cv2.VideoWriter(video_dir,fourcc,fps,(w,h),True)
    videoWriter.write(crop)
    while True:
        grabbed, frame = video.read()
        crop = frame[y:y+h, x:x+w]
        cv2.imshow(video_path, crop)
        cv2.waitKey(5)
        videoWriter.write(crop)
        if not grabbed:
            print("End of video")
            break
    video.release()
    videoWriter.release()
    cv2.destroyAllWindows()
crop_video(video_path)


import os
from pathlib import Path

import torch

def main():
    base_dir = Path('/home/kirill/data/stanford/')
    print(os.listdir(base_dir / 'models'))
    checkpoint = torch.load(base_dir / 'models/resnet50.pth.tar')
    print(checkpoint)

if __name__ == '__main__':
    main()


import torch
import torch.nn as nn
import torch.nn.functional as F
from torch.autograd import Variable
from collections import OrderedDict
import numpy as np
import pickle
from utils import load_data,preprocess_features,preprocess_adj,tuple_to_torchSparseTensor
from gcn_model import GCN

adj, features, y_train, y_val, y_test, train_mask, val_mask, test_mask = load_data("cora")

print(adj.shape)  # (2708, 2708)
adj_hat = preprocess_adj(adj)
features = preprocess_features(features)
# features[0].shape == (49216, 2)
# features[1].sahpe == (49216,)
# features[2] === (2708, 1433)

# Convert to torch.Tensor
sparse_adj_hat = tuple_to_torchSparseTensor(adj_hat)
sparse_features = tuple_to_torchSparseTensor(features)

y_train = torch.FloatTensor(y_train)  # dtype = torch.float32
y_val = torch.FloatTensor(y_val)
y_test = torch.FloatTensor(y_test)

train_mask = torch.from_numpy(train_mask)  # dtype = torch.bool
val_mask = torch.from_numpy(val_mask)
test_mask = torch.from_numpy(test_mask)

# Build model and optimizer
model = GCN(input_dim=features[2][1],out_dim=y_train.shape[1],hidden_dims=[32])
optimizer = torch.optim.Adam(model.parameters(), lr = 0.01)  #NOTE Adam performs much better than SGD when training this GCN

# train loop
iter_all = 200
val_loss_dec_max = 10
val_loss_dec_count = 0
previous_val_loss = 999.9
from tqdm import tqdm
for ii in tqdm(range(iter_all)):
    optimizer.zero_grad() # zero the gradient buffers
    # output = model(sparse_adj_hat,sparse_features,is_sparse=True)
    output = model(sparse_adj_hat,sparse_features)

    train_loss = model.loss(output,y_train,train_mask)
    train_acc = model.accuracy(output,y_train,train_mask)
    val_loss = model.loss(output,y_val,val_mask)
    val_acc = model.accuracy(output,y_val,val_mask)

    if ii%20==0:
        print("iter_{}:train_loss=={},train_acc=={}; val_loss=={},val_acc=={},dec_count={}".format(ii,train_loss.item(),train_acc.item(),val_loss.item(),val_acc.item(),val_loss_dec_count))

    if val_loss.item() >= previous_val_loss:
        val_loss_dec_count += 1
    else:
        val_loss_dec_count = 0
    previous_val_loss = val_loss.item()

    if val_loss_dec_count >= val_loss_dec_max:
        print("Early stop occurred! The validation loss does not decrease for {} consecutive epochs".format(val_loss_dec_max))
        print("current iter={}, train_loss=={},train_acc=={}; val_loss=={},val_acc=={}".format(ii,train_loss.item(),train_acc.item(),val_loss.item(),val_acc.item()))
        break

    train_loss.backward()
    optimizer.step()

torch.save(model, 'training_dir/gcn_model.pkl')


class Solution:
    def createTargetArray(self, nums: List[int], index: List[int]) -> List[int]:

        out = []
        for num, idx in zip(nums, index):

            if len(out) <= idx:
                out.append(num)

            else:
                out.insert(idx, num)

        return out

leetcode/scripts/algorithms/C/Create Target Array in the Given Order/Create Target Array in the Given Order.py


import streamlit as st
import numpy as np
import pickle as pkl
import pandas as pd
import xgboost as xgb
from sklearn.preprocessing import MinMaxScaler
scal=MinMaxScaler()

# Loading the saved model
#model = xgb.XGBRegressor()
#model.load_model("C:/Users/Andrea/Downloads/model_scv.json")
model=pkl.load(open("C:/Users/Andrea/Downloads/finalno.p","rb"))

# Loading the dataset
df=pd.read_csv("C:/Users/Andrea/Downloads/heart.csv")

st.set_page_config(
    page_title="Предвидување на ризик од КВЗ",
    page_icon="⚕",
    layout="centered",
    initial_sidebar_state="expanded"
    )

def preprocess(age,sex,cp,trestbps,chol,fbs,restecg,thalach,exang,oldpeak,slope,ca,thal):

    # Pre-processing user input
    if sex=="машки":
        sex=1
    else: sex=0

    if cp=="Типична ангина":
        cp=3
    elif cp=="Атипична ангина":
        cp=1
    elif cp=="Не-ангинална болка":
        cp=2
    elif cp=="Асимптоматски":
        cp=0

    if exang=="Да":
        exang=1
    elif exang=="Не":
        exang=0

    if fbs=="Да":
        fbs=1
    elif fbs=="Не":
        fbs=0

    if slope=="Нагорен: подобар пулс со вежбање (невообичаено)":
        slope=2
    elif slope=="Рамно: минимална промена (типично здраво срце)":
          slope=1
    elif slope=="Наведнат: знаци на нездраво срце":
        slope=0

    if restecg=="Нема ништо да се забележи":
        restecg=1
    elif restecg=="Абнормалност на ST-T бран":
        restecg=2
    elif restecg=="Можна или дефинитивна хипертрофија на левата комора":
        restecg=0

    feat=['age', 	'sex', 	'cp', 'trestbps', 'chol', 	'fbs', 	'restecg', 	'thalach' ,	'exang', 	'oldpeak' ,	'slope', 	'ca', 'thal']
    df[feat] = scal.fit_transform(df[feat])

    user_input=[age,sex,cp,trestbps,chol,fbs,restecg,thalach,exang,oldpeak,slope,ca,thal]
    user_input=np.array(user_input)
    user_input=user_input.reshape(1,-1)
    user_input = scal.transform(user_input)
    prediction = model.predict(user_input)

    return prediction

# Front-End

html_temp = """

Предвидување на ризик од
 кардиоваскуларни заболувања

    """

# Header
st.markdown(html_temp, unsafe_allow_html = True)

# Form
age=st.selectbox ("Возраст:",range(1,99,1))
sex = st.radio("Пол:", ('машки', 'женски'))
cp = st.selectbox('Тип на болка во градите:',("Асимптоматски","Атипична ангина","Не-ангинална болка", "Типична ангина"))
trestbps=st.selectbox('Систолен крвен притисок во мирување (во милиметри живен столб - mmHg):',range(1,500,1))
chol=st.selectbox('Серумскиот холестерол во mg/dl:',range(1,1000,1))
fbs=st.radio("Шеќер во крвта на гладно повисок од 120 mg/dl:", ['Да','Не'])
restecg=st.selectbox('Електрокардиографски резултати во мирување:',("Можна или дефинитивна хипертрофија на левата комора", "Нема ништо да се забележи","Абнормалност на ST-T бран"))
thalach=st.selectbox('Максимален пулс (отчукувања во минута):',range(1,300,1))
exang=st.radio('Ангина индуцирана при вежбање или физички напор:',["Да","Не"])
oldpeak=st.number_input('Депресија на ST-сегментот предизвикана при физички напор во однос на мирување (mV):')
slope = st.selectbox('Наклон на ST-сегментот:',("Нагорен: подобар пулс со вежбање (невообичаено)","Рамно: минимална промена (типично здраво срце)","Наведнат: знаци на нездраво срце"))
ca=st.slider('Број на главни садови на кои се детектирани наслаги користејќи флуроскопија:', min_value=0, max_value=4)
thal=st.slider('Крвно пореметување наречено таласемија (1 – веќе поправен дефект; 2 – нормално; 3 – реверзибилен дефект)', min_value=1, max_value=3)

pred=preprocess(age,sex,cp,trestbps,chol,fbs,restecg,thalach,exang,oldpeak,slope,ca,thal)

if st.button("Предвиди"):
  if pred[0] == 0:
    st.error('Предупредување! Имате висок ризик да се здобиете со кардиоваскуларна болест!')

  else:
    st.success('Честитки! Имате помал ризик да добиете кардиоваскуларна болест!')

# Sidebar
st.sidebar.header("ЗА АПЛИКАЦИЈАТА")
st.sidebar.subheader("Дипломска работа на Факултетот за Електортехника и информациски технологии")
st.sidebar.info("Оваа веб-апликација со помош на машинско учење ви помага да откриете дали сте изложени на ризик да развиете кардиоваскуларна болест.")
st.sidebar.info("Внесете ги бараните полиња и кликнете на копчето „Предвиди“ за да проверите дали имате здраво срце")
st.sidebar.warning("Внимание: ова е само предвидување, а не докторски совет. Ве молиме посетете лекар ако чувствувате дека симптомите продолжуваат.")
st.sidebar.text('Изработил: Андреа Ивановска 16/2017')
st.sidebar.text("Верзија: 1.0.0 | Септември 2022")


import sqlite3

class Connection:
    def __init__(self, db_file):
        self.conn = None
        self.db_file = db_file

    def __enter__(self):
        self.conn = sqlite3.Connection(self.db_file)
        return self.conn

    def __exit__(self, exc_type, exc_val, exc_tb):
        if exc_tb or exc_val or exc_tb:
            self.conn.close()
            print(f"error {exc_type}, {exc_val}, {exc_tb}")
        else:
            self.conn.commit()
            self.conn.close()


import streamlit as st
import urllib.parse as parse

# fixed values
S_default_value = r'''\begin{align*}
R(g) &= \frac{1}{n} \sum_{i=1}^{n} \ell(y_i,g(x_i))\\
&=\frac{1}{2n} (\mathbf{X}\boldsymbol{w}-\mathbf{y})^T (\mathbf{X}\boldsymbol{w}-\mathbf{y})
\end{align*}
'''

text_area_height = 220

# input
st.title('tex image link generator')
S = st.text_area(label='Input tex equations',
                 value=S_default_value,
                 height=text_area_height)

# display styleを個々に追加したい
style_dict = {'default': '\displaystyle ',
              'inline': '\\textstyle '}
style_prefix = style_dict[
    st.selectbox('Select style', list(style_dict.keys()))]

size_dict = {'M': '',
             'L': '\large ',
             '2L': '\Large ',
             '3L': '\LARGE ',
             '4L': '\huge ',
             '5L': '\Huge '}

size_prefix = size_dict[st.selectbox('Select size', list(size_dict.keys()))]

color_dict = {'black': '\color{black}',
             'white': '\color{white}'}

color_prefix = color_dict[st.selectbox('Select color', list(color_dict.keys()))]

# encode
S_quote = parse.quote_plus(color_prefix + size_prefix + style_prefix + S)

url_prefix = 'https://render.githubusercontent.com/render/math?math='
URL = url_prefix + S_quote

tag_prefix = '<img src=\n"'
tag_suffix = '" \nalt="' + S + '">'
TAG = tag_prefix + URL + tag_suffix

md_prefix = '![' + S + ']('
md_suffix = ')'

MD = md_prefix + URL + md_suffix

'## Image Preview'
st.markdown(TAG, unsafe_allow_html=True)

'## HTML'
st.code(TAG, language='html')

'## Markdown'
st.code(MD, language='')
# st.code(URL)

# 'メモ書き'
# 'latex result'
# st.latex(S)
# 'markdown tex result'
# st.markdown('$$' + S + '$$')

# reference
''
''
''
'Project repository https://github.com/masakiaota/tex_image_link_generator'


import bpy

S1  ="builtin.select"
#背面選択アドオン「Box Select X-Ray」必須。
#https://blenderartists.org/t/box-select-x-ray/1212316
#なければデフォルトの物を選択ってやりたいけど未対応
S2  ="mesh_tool.select_box_xray"
S3  ="builtin.select_box"
S4  ="builtin.move"

def set_active_tool(tool_name):
    for area in bpy.context.screen.areas:
        if area.type == "VIEW_3D":
            override = bpy.context.copy()
            override["space_data"] = area.spaces[0]
            override["area"] = area
            bpy.ops.wm.tool_set_by_id(override, name=tool_name)

#選択オブジェクトの属性やモードによって選択を切り替える
def si_MoveComponent(a,b,c,select_tool):
    oSel = bpy.context.selected_objects
    for o in oSel:
        if o.type == "MESH":
            bpy.ops.object.mode_set(mode='EDIT')
            bpy.context.tool_settings.mesh_select_mode = (a,b,c)
            set_active_tool(select_tool)
        elif o.type == "CURVE":
            bpy.ops.object.mode_set(mode='EDIT')
            set_active_tool(S4)
        elif o.type == "SURFACE":
            bpy.ops.object.mode_set(mode='EDIT')
            set_active_tool(S4)

        #アーマチュアやカーブなど、オブジェクトモードなら編集に入るが
        #POSEモードなら何もしない。
        elif o.type == "ARMATURE":
            if bpy.context.mode == "POSE":
                print("Pose now")
            else:
                bpy.ops.object.mode_set(mode='EDIT')

class si_MoveComponent_OT_object(bpy.types.Operator):
    bl_idname = "object.si_movecomponent"
    bl_label = "Move Component Tool"
    bl_description = "Move Component Tool like Softimage"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context,):
        si_MoveComponent(True,True,True,S1)
        return {'FINISHED'}

class si_MoveComponent1_OT_object(bpy.types.Operator):
    bl_idname = "object.si_movecomponent1"
    bl_label = "Point Select Tool"
    bl_description = "Point Select Tool like Softimage"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context,):
        si_MoveComponent(True,False,False,S2)
        return {'FINISHED'}

class si_MoveComponent2_OT_object(bpy.types.Operator):
    bl_idname = "object.si_movecomponent2"
    bl_label = "Edge Select Tool"
    bl_description = "Edge Select Tool like Softimage"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context,):
        si_MoveComponent(False,True,False,S2)
        return {'FINISHED'}

class si_MoveComponent3_OT_object(bpy.types.Operator):
    bl_idname = "object.si_movecomponent3"
    bl_label = "Polygon Select Tool"
    bl_description = "Polygon Select Tool like Softimage"
    bl_options = {'REGISTER', 'UNDO'}

    def execute(self, context,):
        si_MoveComponent(False,False,True,S2)
        return {'FINISHED'}


from airflow.models.dag import DAG
from airflow.operators.python_operator import PythonOperator
from airflow.operators.sqlite_operator import SqliteOperator
from airflow.operators.bash_operator import BashOperator
from airflow.operators.sqlite_operator import SqliteOperator
from airflow.operators.sqlite_operator import SqliteOperator
from airflow.operators.bash_operator import BashOperator
from airflow.operators.bash_operator import BashOperator
from airflow.operators.email_operator import EmailOperator
from airflow.operators.bash_operator import BashOperator

store_dag = DAG(**{"dag_id": "store_DAG", "start_date": "'2020-6-30'"})

clean_raw_csv = PythonOperator(
    **{"python_callable": "data_cleaner", "task_id": "clean_raw_csv"},
    dag=store_dag
)
insert_into_table = SqliteOperator(
    **{
        "sql": "insert_into_table.sql",
        "sqlite_conn_id": "mysql_conn",
        "task_id": "insert_into_table",
    },
    dag=store_dag
)
check_file_exists = BashOperator(
    **{
        "bash_command": "shasum ~/store_files_airflow/raw_store_transactions_2020-06-30.csv",
        "task_id": "check_file_exists",
    },
    dag=store_dag
)
create_mysql_table = SqliteOperator(
    **{
        "sql": "create_table.sql",
        "sqlite_conn_id": "mysql_conn",
        "task_id": "create_mysql_table",
    },
    dag=store_dag
)
select_from_table = SqliteOperator(
    **{
        "sql": "select_from_table.sql",
        "sqlite_conn_id": "mysql_conn",
        "task_id": "select_from_table",
    },
    dag=store_dag
)
move_file1 = BashOperator(
    **{
        "bash_command": "cat ~/store_files_airflow/location_wise_profit.csv && mv ~/store_files_airflow/location_wise_profit.csv ~/store_files_airflow/location_wise_profit_%s.csv' % yesterday_date",
        "task_id": "move_file1",
    },
    dag=store_dag
)
move_file2 = BashOperator(
    **{
        "bash_command": "cat ~/store_files_airflow/store_wise_profit.csv && mv ~/store_files_airflow/store_wise_profit.csv ~/store_files_airflow/store_wise_profit_%s.csv' % yesterday_date",
        "task_id": "move_file2",
    },
    dag=store_dag
)
send_email = EmailOperator(
    **{
        "to": "shivanshsinghchauhan@gmail.com",
        "subject": "Daily report generated",
        "html_content": "
Congratulations! Your store reports are ready.
",
        "task_id": "send_email",
    },
    dag=store_dag
)
rename_raw = BashOperator(
    **{
        "bash_command": "mv ~/store_files_airflow/raw_store_transactions_2020-06-30.csv ~/store_files_airflow/raw_store_transactions_2020-06-31.csv",
        "task_id": "rename_raw",
    },
    dag=store_dag
)

check_file_exists >> clean_raw_csv >> create_mysql_table >> insert_into_table >> select_from_table >> move_file1 >> send_email >> rename_raw
select_from_table >> move_file2 >> send_email


"""
This module provides generic component methods for your Flask app.

A component is a class which provides the "glue" between your models and your
data marshalling/validation. The advantages to this pattern are that it allows
for extensive code reuse, a single place for business logic, and consistent
handling for validation that leverages the `marshmallow` library.
"""
from abc import ABC

from flask import current_app, url_for

from .model import GenericModel
from .schema import GenericSchema
from .shortcuts import (
    DEFAULT_DICT, MODEL_INST, MODEL_TYPE, SCHEMA_INST, SCHEMA_TYPE, SELECT_INST
)

class GenericComponent(ABC):
    """
    A generic component with all the basics needed to perform CRUD operations
    on a database table via your Python app. This component is designed to be
    extended for your model; simply inherit from it, and specify the
    appropriate model and corresponding schema.
    """
    schema: SCHEMA_TYPE = GenericSchema
    model: MODEL_INST = GenericModel

    def __init__(self, context=DEFAULT_DICT, *args, **kwargs):
        """
        Set context for the class. Context is a great way to pass data around
        the component and methods.
        """
        self.context: dict = context

    @classmethod
    def add_metadata(cls, query: SELECT_INST, context: dict) -> (
            SELECT_INST, dict):
        """
        Add in metadata for API methods. This enables for basic pagination
        support via the schema.
        """
        offset: int = context.get('offset', 1)
        limit: int = context.get('limit', 0)

        total: int = query.count()

        remaining: int = 0
        if query and offset:
            query: SELECT_INST = query.paginate(offset, limit)
            remaining: int = max(
                total - (limit * (offset - 1)) - query.count(), 0
            )

        context['metadata'] = {
            'count': total,
            'remaining': remaining,
            'offset': offset,
            'limit': limit,
            'next': context.get('next') if remaining > 0 else None,
            'previous': context.get('previous') if offset > 1 else None,
            'route_args': context.get('route_args', {}),
        }

        return query, context

    @staticmethod
    def context_urls(route_name: str, **kwargs: dict) -> (str, str):
        """
        Generate next and previous urls for pagination purposes.
        """
        context_next: str = url_for(
            route_name,
            _external=True,
            _scheme='https' if current_app.config.get('USE_HTTPS') else 'http',
            **kwargs
        )

        context_previous: str = url_for(
            route_name,
            _external=True,
            _scheme='https' if current_app.config.get('USE_HTTPS') else 'http',
            **kwargs
        )

        return context_next, context_previous

    def base_query(self) -> SELECT_INST:
        """
        Surface a base query for this model. This method is meant to be
        overridden for the specific model. For instance, if a JOIN condition
        should be part of the default querying, or if query optimization is
        needed, this is an excellent place to put it to avoid bloating the
        models.
        """
        return self.model.base_query()

    def search(self, query: SELECT_INST, request_args: dict=DEFAULT_DICT) -> (
            SELECT_INST):  # pylint: disable=unused-argument
        """
        This method is designed to be overridden to provide an interface for
        searching via query parameters passed in from the endpoint.
        """
        return query

    def get_by_id(self, item_id: int) -> MODEL_TYPE:
        """
        Convenience function for getting an item by ID. This may be overridden,
        for example to provide for permission schemes via business logic in the
        component.
        """
        return self.model.get(self.model.id == item_id)

    def get_items(self, request_args: dict=DEFAULT_DICT,
                  context: dict=DEFAULT_DICT) -> dict:
        """
        Generic method to retrieve all items from the database for the model
        associated with this component, and serialize it to a dictionary via
        the schema. This method is designed to be flexible in filtering results
        via overriding the `search` method.
        """
        items: SELECT_INST = self.search(self.base_query(), request_args)

        if self.context.get('wrapper'):
            items, context = self.add_metadata(items, self.context)

        return self.schema(context=context).dump(items, many=True).data

    def get_item(self, item_id) -> dict:
        """
        Retrieve a specific item from the database for the model associated
        with this component by ID, and serialize it to a dictionary via the
        schema.
        """
        return self.schema().dump(self.get_by_id(item_id), many=False).data

    def create_item(self, data: dict) -> dict:
        """
        Create an item for the associated model. This method will serialize
        and validate the data before model creation, then will serialize the
        return data into a dictionary.
        """
        schema: SCHEMA_INST = self.schema()
        item: MODEL_INST = schema.make_instance(data)
        item.save()
        return schema.dump(item, many=False).data

    def update_item(self, item_id: int, data: dict) -> dict:
        """
        Update an existing item from the database with new data. This method
        will serialize and validate the data before updating the model item,
        then will serialize the return data into a dictionary.
        """
        schema: SCHEMA_INST = self.schema()
        serialized_data: dict = schema.load(data).data
        item: MODEL_INST = self.get_by_id(item_id)
        item.update_instance(serialized_data)

        return schema.dump(item, many=False).data

    def delete_item(self, item_id: int) -> dict:
        """
        Delete an item via ID. This will return the data from the deleted item.
        """
        schema: SCHEMA_INST = self.schema(context=self.context)
        item: MODEL_INST = self.get_by_id(item_id)
        item.delete_instance()
        item.save()

        return schema.dump(item, many=False).data


from __future__ import absolute_import
from __future__ import division
from __future__ import print_function
from __future__ import unicode_literals

import os
import argparse
import sys

env_path = os.path.join(os.path.dirname(__file__), '..')
if env_path not in sys.path:
    sys.path.append(env_path)

from glob import glob
from tqdm import tqdm
from multiprocessing import Pool
from pysot_toolkit.toolkit.datasets import OTBDataset, UAVDataset, LaSOTDataset, VOTDataset, NFSDataset, VOTLTDataset
from pysot_toolkit.toolkit.evaluation import OPEBenchmark, AccuracyRobustnessBenchmark, EAOBenchmark, F1Benchmark
from pysot_toolkit.toolkit.visualization import draw_success_precision
from pysot_toolkit.toolkit.utils.statistics import success_overlap
import numpy as np
parser = argparse.ArgumentParser(description='transt evaluation')
parser.add_argument('--tracker_path', '-p', type=str, default='/home/zxh/project/TransT/results',
                    help='tracker result path')
parser.add_argument('--dataset', '-d', type=str, default='UAV123',
                    help='dataset name')
parser.add_argument('--num', '-n', default=1, type=int,
                    help='number of thread to eval')
parser.add_argument('--tracker_prefix', '-t', default='siamyolo',
                    type=str, help='tracker name')
parser.add_argument('--show_video_level', '-s', dest='show_video_level',
                    action='store_true')
parser.add_argument('--vis', dest='vis', action='store_true')
parser.set_defaults(show_video_level=False)
args = parser.parse_args()

class uav123_10fps(object):
    def __init__(self, name, dataset_root, pred_root, gt_root):
        self.name = name
        self.dataset_root = dataset_root
        self.pred_root = pred_root
        self.gt_root = gt_root
        self.videos = None

    def read_videos(self):
        videos = os.listdir(self.dataset_root)
        self.videos = {}
        for video in videos:
            gt_np = np.loadtxt(os.path.join(self.gt_root,video+'.txt'),dtype=np.float32,delimiter=',')
            self.videos[video] = gt_np
        return self.videos

    def cal_auc(self):
        success_ret_ = {}
        self.videos = self.read_videos()
        for video in self.videos:
            gt_np = self.videos[video]
            pred_np = np.loadtxt(os.path.join(self.pred_root, video+'.txt'), dtype=np.float32, delimiter=',')
            n_frame = len(gt_np)
            success_ret_[video] = success_overlap(gt_np, pred_np, n_frame)
        auc = np.mean(list(success_ret_.values()))
        return auc

    def set_tracker(self, path, tracker_names):
        """
        Args:
            path: path to tracker results,
            tracker_names: list of tracker name
        """
        self.tracker_path = path
        self.tracker_names = tracker_names

def main():

    tracker_dir = os.path.join(args.tracker_path, args.dataset)
    trackers = glob(os.path.join(args.tracker_path,
                                 args.dataset,
                                 args.tracker_prefix+'*'))
    # trackers = [x.split('/')[-1] for x in trackers]
    #
    # assert len(trackers) > 0
    # args.num = min(args.num, len(trackers))

    # root = os.path.realpath(os.path.join(os.path.dirname(__file__),
    #                                      'testing_dataset'))
    root = '/media/zxh/30CC86E5CC86A526/SOT_eval/UAV123'
    # root = os.path.join(root, args.dataset)
    '''dataset root:
    UAV123-10FPS:
    DATA:/media/zxh/E404D23504D20B06/UAV_dataset/uav123_10fps
    gt:/media/zxh/E404D23504D20B06/UAV_dataset/UAV123_10fps/anno/UAV123_10fps
    UAV20L:
    DATA:/media/zxh/E404D23504D20B06/UAV_dataset/uav20L
    gt:/media/zxh/E404D23504D20B06/UAV_dataset/UAV123/anno/UAV20L
    VTUAV:
    DATA:/media/zxh/30CC86E5CC86A526/SOT_eval/VTUAV/data
    gt:/media/zxh/30CC86E5CC86A526/SOT_eval/VTUAV/anno/ST
    UAVDT:
    DATA:/media/zxh/E404D23504D20B06/UAV_dataset/UAVDT
    gt:/media/zxh/E404D23504D20B06/UAVDT_toolkit/anno
    VisDrone:
    DATA:/media/zxh/E404D23504D20B06/UAV_dataset/VisDrone2018-SOT-test-dev/sequences
    gt:/media/zxh/E404D23504D20B06/UAV_dataset/VisDrone2018-SOT-test-dev/annotations
    DTB70:
    DATA:/media/zxh/E404D23504D20B06/UAV_dataset/DTB70
    gt:/media/zxh/E404D23504D20B06/UAV_dataset/DTB70_GT
    '''
    if 'UAV20L' == args.dataset:
        data_root = '/media/zxh/E404D23504D20B06/UAV_dataset/uav20L'
        pred_root = '/home/zxh/project/TransT/results/UAV123/now_uav20L'
        gt_root = '/media/zxh/E404D23504D20B06/UAV_dataset/UAV123/anno/UAV20L'
        dataset = uav123_10fps(args.dataset, data_root, pred_root, gt_root)
        print(dataset.cal_auc())

    if 'OTB' in args.dataset:
        dataset = OTBDataset(args.dataset, root)
        dataset.set_tracker(tracker_dir, trackers)
        benchmark = OPEBenchmark(dataset)
        success_ret = {}
        with Pool(processes=args.num) as pool:
            for ret in tqdm(pool.imap_unordered(benchmark.eval_success,
                trackers), desc='eval success', total=len(trackers), ncols=100):
                success_ret.update(ret)
        precision_ret = {}
        with Pool(processes=args.num) as pool:
            for ret in tqdm(pool.imap_unordered(benchmark.eval_precision,
                trackers), desc='eval precision', total=len(trackers), ncols=100):
                precision_ret.update(ret)
        benchmark.show_result(success_ret, precision_ret,
                show_video_level=args.show_video_level)
        if args.vis:
            for attr, videos in dataset.attr.items():
                if attr == 'ALL':
                    draw_success_precision(success_ret,
                                       name=dataset.name,
                                       videos=videos,
                                       attr=attr,
                                       precision_ret=precision_ret)
    elif 'LaSOT' == args.dataset:
        dataset = LaSOTDataset(args.dataset, root)
        dataset.set_tracker(tracker_dir, trackers)
        benchmark = OPEBenchmark(dataset)
        success_ret = {}
        with Pool(processes=args.num) as pool:
            for ret in tqdm(pool.imap_unordered(benchmark.eval_success,
                trackers), desc='eval success', total=len(trackers), ncols=100):
                success_ret.update(ret)
        precision_ret = {}
        with Pool(processes=args.num) as pool:
            for ret in tqdm(pool.imap_unordered(benchmark.eval_precision,
                trackers), desc='eval precision', total=len(trackers), ncols=100):
                precision_ret.update(ret)
        norm_precision_ret = {}
        with Pool(processes=args.num) as pool:
            for ret in tqdm(pool.imap_unordered(benchmark.eval_norm_precision,
                trackers), desc='eval norm precision', total=len(trackers), ncols=100):
                norm_precision_ret.update(ret)
        benchmark.show_result(success_ret, precision_ret, norm_precision_ret,
                show_video_level=args.show_video_level)
        if args.vis:
            draw_success_precision(success_ret,
                                   name=dataset.name,
                                   videos=dataset.attr['ALL'],
                                   attr='ALL',
                                   precision_ret=precision_ret,
                                   norm_precision_ret=norm_precision_ret)
    elif 'UAV' in args.dataset:
        dataset = UAVDataset(args.dataset, root)
        dataset.set_tracker(tracker_dir, trackers)
        benchmark = OPEBenchmark(dataset)
        success_ret = {}
        with Pool(processes=args.num) as pool:
            for ret in tqdm(pool.imap_unordered(benchmark.eval_success,
                trackers), desc='eval success', total=len(trackers), ncols=100):
                success_ret.update(ret)
        precision_ret = {}
        with Pool(processes=args.num) as pool:
            for ret in tqdm(pool.imap_unordered(benchmark.eval_precision,
                trackers), desc='eval precision', total=len(trackers), ncols=100):
                precision_ret.update(ret)
        benchmark.show_result(success_ret, precision_ret,
                show_video_level=args.show_video_level)
        if args.vis:
            for attr, videos in dataset.attr.items():
                if attr == 'ALL':
                    draw_success_precision(success_ret,
                                       name=dataset.name,
                                       videos=videos,
                                       attr=attr,
                                       precision_ret=precision_ret)
    elif 'NFS' in args.dataset:
        dataset = NFSDataset(args.dataset, root)
        dataset.set_tracker(tracker_dir, trackers)
        benchmark = OPEBenchmark(dataset)
        success_ret = {}
        with Pool(processes=args.num) as pool:
            for ret in tqdm(pool.imap_unordered(benchmark.eval_success,
                trackers), desc='eval success', total=len(trackers), ncols=100):
                success_ret.update(ret)
        precision_ret = {}
        with Pool(processes=args.num) as pool:
            for ret in tqdm(pool.imap_unordered(benchmark.eval_precision,
                trackers), desc='eval precision', total=len(trackers), ncols=100):
                precision_ret.update(ret)
        benchmark.show_result(success_ret, precision_ret,
                show_video_level=args.show_video_level)
        if args.vis:
            for attr, videos in dataset.attr.items():
                if attr == 'ALL':
                    draw_success_precision(success_ret,
                                       name=dataset.name,
                                       videos=videos,
                                       attr=attr,
                                       precision_ret=precision_ret)
    elif args.dataset in ['VOT2016', 'VOT2017', 'VOT2018', 'VOT2019']:
        dataset = VOTDataset(args.dataset, root)
        dataset.set_tracker(tracker_dir, trackers)
        ar_benchmark = AccuracyRobustnessBenchmark(dataset)
        ar_result = {}
        with Pool(processes=args.num) as pool:
            for ret in tqdm(pool.imap_unordered(ar_benchmark.eval,
                trackers), desc='eval ar', total=len(trackers), ncols=100):
                ar_result.update(ret)

        benchmark = EAOBenchmark(dataset)
        eao_result = {}
        EAO_list = [] # newly added (2020.07.05)
        with Pool(processes=args.num) as pool:
            for ret in tqdm(pool.imap_unordered(benchmark.eval,
                trackers), desc='eval eao', total=len(trackers), ncols=100):
                eao_result.update(ret)
        for name in eao_result:
            EAO_list.append(eao_result[name]['all'])
        mean_eao = np.mean(np.array(EAO_list))
        print('Mean EAO = ',mean_eao)
        ar_benchmark.show_result(ar_result, eao_result,
                show_video_level=args.show_video_level)
    elif 'VOT2018-LT' == args.dataset:
        dataset = VOTLTDataset(args.dataset, root)
        dataset.set_tracker(tracker_dir, trackers)
        benchmark = F1Benchmark(dataset)
        f1_result = {}
        with Pool(processes=args.num) as pool:
            for ret in tqdm(pool.imap_unordered(benchmark.eval,
                trackers), desc='eval f1', total=len(trackers), ncols=100):
                f1_result.update(ret)
        benchmark.show_result(f1_result,
                show_video_level=args.show_video_level)

if __name__ == '__main__':
    main()


"""
General utility functions
"""
import subprocess
import os
import shutil
import shlex
import glob
import logging

def parse_cmd(cmd):
    """Parse shell command for globbing and environment variables."""
    if not isinstance(cmd, list):
        cmd = shlex.split(cmd)
    parsed_cmd = [
        cmd[0],
    ]
    for word in cmd[1:]:
        if word[0] == "$":
            var = word[1:].strip("{").strip("}")
            varval = os.environ.get(var, word)
            parsed_cmd.append(varval)
        else:
            if "*" in word:
                items = glob.glob(word)
                for item in items:
                    parsed_cmd.append(item)
            else:
                parsed_cmd.append(word)
    return parsed_cmd

def execute(cmd, workdir=".", outfile="run.log", purge_workdir=False, **kwargs):
    """Execute external command in workdir, streaming output/error to outfile.

    Args:
        cmd (str): command; executed in `workir`; if it contains `$` or
                   `*`-globbing, these are shell-expanded
        workdir (path-like): execution directory relative to workroot
        outfile (str): output file for the stdout/stderr stream; continuously
                       updated during execution
        purge_workdir (bool): if true, any existing working directory is purged
        kwargs (dict): passed directly to the underlying `subprocess.call()`

    Returns:
        None

    Raises:
        OSError: if `cmd` cannot be executed
        RuntimeError: if `cmd` returncode is nonzero
        SubprocessError: other possible circumstances
    """
    # prepare workdir
    origdir = os.getcwd()
    try:
        os.makedirs(workdir)
    except OSError:
        # directory exists
        if purge_workdir:
            # that's a bit brutal, but saves to worry of links and subdirs
            shutil.rmtree(workdir)
            os.makedirs(workdir)
    os.chdir(workdir)
    # prepare out/err handling
    filename = kwargs.pop("stdout", outfile)
    if filename:
        kwargs["stdout"] = open(filename, "w")
    filename = kwargs.pop("stderr", None)
    if filename:
        kwargs["stderr"] = open(filename, "w")
    else:
        kwargs["stderr"] = subprocess.STDOUT
    # execute the command, make sure output is not streamed
    _cmd = parse_cmd(cmd)
    try:
        returncode = subprocess.call(_cmd, **kwargs)
        if returncode:
            LOGGER.critical(
                "Execution of {:s} FAILED with exit status {:d}".format(
                    _cmd, returncode
                )
            )
            raise RuntimeError
    #
    except subprocess.SubprocessError:
        LOGGER.critical("Subprocess call of {:s} FAILED".format(_cmd))
        raise
    #
    except (OSError, FileNotFoundError) as exc:
        LOGGER.critical(
            "Abnormal termination: OS could not execute %s in %s", _cmd, workdir
        )
        LOGGER.critical(
            "If the command is a script ,"
            "check permissions and that is has a shebang!"
        )
        raise
    #
    finally:
        # make sure we return to where we started from in any case!
        os.chdir(origdir)

def configure_logger(name, filename=None, verbosity=logging.INFO):
    """Get parent logger: logging INFO on the console and DEBUG to file."""
    if filename is None:
        filename = name + ".debug.log"
    logger = logging.getLogger(name)
    logger.setLevel(logging.DEBUG)
    # may need this if running within ipython notebook, to avoid duplicates
    logger.propagate = False
    # console handler with a higher log level
    ch = logging.StreamHandler()
    ch.setLevel(verbosity)
    # file handler with full debug info
    fh = logging.FileHandler(filename, mode="w")
    fh.setLevel(logging.DEBUG)
    # message formatting
    fileformat = logging.Formatter("%(name)s - %(levelname)s: %(message)s")
    consformat = logging.Formatter("%(levelname)7s: %(message)s")
    fh.setFormatter(fileformat)
    ch.setFormatter(consformat)
    # add the configured handlers
    logger.addHandler(fh)
    logger.addHandler(ch)
    return logger

def get_logger(name, filename=None, verbosity=logging.INFO):
    """Return a named logger with file and console handlers.

    Get a `name`-logger. Check if it is(has) a parent logger.
    If parent logger is not configured, configure it, and if a child logger
    is needed, return the child.
    The check for parent logger is based on `name`: a child if it contains '.',
    i.e. looking for 'parent.child' form of `name`.
    A parent logger is configured by defining a console handler at `verbosity`
    level, and a file handler at DEBUG level, writing to `filename`.
    """
    parent = name.split(".")[0]
    if filename is None:
        filename = parent + ".debug.log"
    parent_logger = logging.getLogger(parent)
    if not parent_logger.handlers:
        configure_logger(parent, filename, verbosity)
    return logging.getLogger(name)

LOGGER = get_logger(__name__)


from django.conf.urls import patterns, include, url
from django.contrib import admin
admin.autodiscover()

urlpatterns = patterns('',
    url(r'^$', 'roomManager.views.index', name = 'index'),
    url(r'^checkIn/$', 'roomManager.views.checkIn', name = 'checkIn'),

    #url(r'^checkIn/(?P<id>\d+)/$', 'roomManager.views.checkIn', name = 'checkIn'),
    url(r'^payBalance/$', 'roomManager.views.payBalance', name = 'payBalance'),
    url(r'^addalance/$', 'roomManager.views.addBalance', name = 'addBalance'),

    url(r'^queryCenter/$', 'roomManager.views.queryCenter', name = 'queryCenter'),
    url(r'^queryByRoomId/$', 'roomManager.views.queryByRoomId', name = 'queryByRoomId'),
    url(r'^queryByRoomType/$', 'roomManager.views.queryByRoomType', name = 'queryByRoomType'),
    url(r'^queryByBedType/$', 'roomManager.views.queryByBedType', name = 'queryByBedType'),
    url(r'^queryByFloorId/$', 'roomManager.views.queryByFloorId', name = 'queryByFloorId'),

    url(r'^myRoom/$', 'roomManager.views.myRoom', name = 'myRoom'),
    url(r'^checkOut/$', 'roomManager.views.checkOut', name = 'checkOut'),
    url(r'^deleteRoom/(?P<id>\d+)/$', 'roomManager.views.deleteRoom', name = 'deleteRoom'),
)


# -*- coding: utf-8 -*-
"""
Created on Sat Feb 13 09:58:46 2021

@author: andre
"""

import threading
import json
import os.path
from os import path
from shared.ipc import *
from shared.jsonhandler import *
class Application:

    def __init__(self, jsonFilePath, jsonWs2812bPath):

        self.__jsonFilePath = jsonFilePath
        self.__jsonWs2812bPath = jsonWs2812bPath
        self.__readFromJsonFile()
        self.__isJsonValid = self.validateJson(self.__jsonFilePath)

        if (self.__isJsonValid):
            self.stop_threads = False;
            self.updateJsonCounter = 0;
            self.__application_thread = threading.Thread(target = self.applicationThread, args = (lambda : self.stop_threads, lambda : self.updateJsonCounter, lambda : self.__jsonConfig))
            self.applicationInit()
        else:
            print("The file: ", jsonFilePath, " was not valid. Application will exit!")
            exit()

    def __writeJsonFile(self):
        if (self.__isJsonValid):
            with open(self.__jsonFilePath, "w") as write_file:
                json.dump(self.__jsonConfig, write_file, indent=4)

    def __readFromJsonFile(self):
        if path.exists(self.__jsonFilePath):
            with open(self.__jsonFilePath, "r") as jsonReadFile:
                self.__jsonConfig = json.load(jsonReadFile)

        if path.exists(self.__jsonWs2812bPath):
            with open(self.__jsonWs2812bPath, "r") as jsonReadFile:
                self.__jsonWs2812b = json.load(jsonReadFile)

    def modifyJsonConfig(self, jsonConfig, operationType):
        print ("Request json config update")
        _tempJsonConfig = self.__jsonConfig.copy()

        isUpdated = False
        if ((operationType == NEW_JSON_UPDATE)):
            isUpdated = updateJson(_tempJsonConfig, jsonConfig)
        elif (operationType == NEW_JSON_ADD):
            isUpdated = addSomethingToJson(_tempJsonConfig, jsonConfig)
        elif (operationType == NEW_JSON_REMOVE):
            isUpdated = removeArrayElement(_tempJsonConfig, jsonConfig)
        if (isUpdated):
             if (self.validateJson(_tempJsonConfig)):
                 self.__jsonConfig = _tempJsonConfig.copy()
                 self.__writeJsonFile()
                 self.updateJsonCounter = (self.updateJsonCounter + 1) & 0xFF
             else:
                print("Given json config is not valid!")

    def increaseBrightness(self, inc):
        tmpJson = self.__jsonConfig.copy()
        if (tmpJson["brightness"] < 255):
            tmpJson["brightness"] = tmpJson["brightness"] + inc
            self.modifyJsonConfig(tmpJson, NEW_JSON_UPDATE)

    def decreaseBrightness(self, dec):
        tmpJson = self.__jsonConfig.copy()
        print(tmpJson["brightness"])
        if (tmpJson["brightness"] > 0):
            tmpJson["brightness"] = tmpJson["brightness"] - dec
            self.modifyJsonConfig(tmpJson, NEW_JSON_UPDATE)

    def getJsonConfig(self):
        return self.__jsonConfig

    def getWs2812bJson(self):
        return self.__jsonWs2812b

    def validateJson(self, jsonConfig):
        return True

    def start(self):
        self.__application_thread.start()

    def stop(self):
        print("Request application thread to stop")
        self.stop_threads = True;

    def applicationThread(self, stop_threads, updateJsonCounter, jsonConfig):
        oldUpdateCounter = 0
        print("Start runner")
        while(True):

            if stop_threads():
                print("Application thread will stop")
                break

            if (oldUpdateCounter != updateJsonCounter()):
                print("Detect json Update")
                oldUpdateCounter = updateJsonCounter()
                self.applicationTask(jsonConfig(), True)
            else:
                self.applicationTask(jsonConfig(), False)

    def applicationTask(self, jsonConfig, isUpdateJson):
        pass

    def applicationInit(self):
        pass


'''Modules for terminal menu and screen clear.'''
import os
from simple_term_menu import TerminalMenu
from dog import Dog
import dogs_sql

def menu():
    '''Loops through menu until quit.'''
    options = ["Add Dog", "Delete Dog", "Get Info", "Feeding/Meds", "Grooming/Belongings", "Quit"]
    main_menu = TerminalMenu(options)
    info_options = ["All", "Large", "Small", "Search Name"]
    info_menu = TerminalMenu(info_options)

    quit = False

    while quit is False:
        options_list = main_menu.show()
        options_choice = options[options_list]

        if options_choice == "Quit":
            quit = True

        if options_choice == "Add Dog":
            name = input("Dog's name: ")
            owner = input("Owner's name: ")
            breed = input("Breed: ")
            while True:
                size = input("Large or Small: ")
                if size not in ("Large", "Small"):
                    print("Please enter Large or Small")
                else:
                    break
            while True:
                try:
                    age = int(input("Age: "))
                except ValueError:
                    print("Please enter a number")
                else:
                    break
            gender = input("Gender: ")
            feed_meds = input("Medication or special food required: ")
            grooming = input("Do they need grooming?: ")
            belongings = input("Do they have any belongings?: ")
            friendly = input("Are they friendly?: ")
            dog = Dog(name, owner, breed, size, age, gender,
                    feed_meds, grooming, belongings, friendly)
            dogs_sql.add_dog(dog)

        if options_choice == "Delete Dog":
            name = input("Name: ")
            dogs_sql.delete_dog(name)

        if options_choice == "Get Info":
            options_list = info_menu.show()
            options_choice = info_options[options_list]
            if options_choice == "All":
                print(dogs_sql.get_dogs())
            if options_choice == "Large":
                print(dogs_sql.get_large_dogs())
            if options_choice == "Small":
                print(dogs_sql.get_small_dogs())
            if options_choice == "Search Name":
                name = input("Name: ")
                print(dogs_sql.get_info(name))

        if options_choice == "Feeding/Meds":
            print(dogs_sql.feed_meds())

        if options_choice == "Grooming/Belongings":
            print(dogs_sql.out_groom())
            print(dogs_sql.out_belongings())

        else:
            print(options_choice)

    os.system("clear")

menu()


import numpy as np

grid = []

 # to keep track of the row entered by the user
row_num = 1

# loop to input the sudoku data row wise from the user
while True:
    print_statement = f'Enter Row {row_num}:'
    row = list(input(print_statement)) #takes input from the user
    row_num += 1
    inputs = []

    # splits the data into 9 numbers and converts it into a number list
    for n in row:
        inputs.append(int(n))
    grid.append(inputs)

    if len(grid) == 9:
        break
    print('Row ' + str(len(grid)) + ' Complete')

# SOLVES THE SUDOKU PUZZLE
def possible(x, y, n):
    # Checks if the number is present across the row
    for i in range(0, 9):
        if grid[i][x] == n and i != y:
            return False

    # Checks if the number is present across the column
    for i in range(0, 9):
        if grid[y][i] == n and i != x:
            return False

    # Checks if the number in the small 3 x 3 grid
    x_square = (x // 3) * 3
    y_square = (y // 3) * 3
    for X in range(x_square, x_square + 3):
        for Y in range(y_square, y_square + 3):
            if grid[Y][X] == n:
                return False
    return True

def solve():
    global grid
    for y in range(9):
        for x in range(9):
            if grid[y][x] == 0:
                for n in range(1, 10):
                    if possible(x, y, n):
                        grid[y][x] = n
                        solve()
                        grid[y][x] = 0
                return

    # prints the solved sudoku grid
    print()
    print("Solved sudoku puzzle:")
    print(np.matrix(grid))

solve()


class Solution:
    def maxProfit(self, prices: List[int]) -> int:
        if len(prices) == 0:
            return 0
        else:
            res=0
            min_val=prices[0]
            for i in range(1,len(prices)):
                res=max(res,prices[i]-min_val)
                min_val=min(min_val,prices[i])
            return res


import os
import sys

fich=sys.argv[1]
desc=os.open(fich,os.O_RDONLY)

size=1
cont=" "
cpC=0
cpL=0
while(len(cont)!=0):
    cont=os.read(desc,size)
    carac=cont.decode(encoding='UTF-8',errors='strict')
    if(carac=='\n'):
        cpL=cpL+1
    cpC=cpC+1

print(cpL)
print(cpC)
os.close(desc)
#os.unlink(fich)