from instructions import base
from rtda import heap

class LDC(base.Index8Instruction):
    def Execute(self, frame):
        _ldc(frame, self.Index)

class LDC_W(base.Index16Instruction):
    def Execute(self, frame):
        _ldc(frame, self.Index)

class LDC2_W(base.Index16Instruction):
    def Execute(self, frame):
        stack = frame.OperandStack()
        cp = frame.Method().Class().ConstantPool()
        c = cp.GetConstant(self.Index)

        if isinstance(c, int):
            stack.PushLong(c)
        elif isinstance(c, float):
            stack.PushDouble(c)
        else:
            raise Exception("java.lang.ClassFormatError")

def _ldc(frame, index):
    stack = frame.OperandStack()
    clazz = frame.Method().Class()
    cp = clazz.ConstantPool()
    c = cp.GetConstant(index)

    if isinstance(c, int):
        stack.PushInt(c)
    elif isinstance(c, float):
        stack.PushFloat(c)
    elif isinstance(c, str):
        internedStr = heap.JString(clazz.Loader(), c)
        stack.PushRef(internedStr)
    elif isinstance(c, heap.ClassRef):
        classRef = c
        classObj = classRef.ResolvedClass().JClass()
        stack.PushRef(classObj)
    else:
        raise Exception("todo: ldc!")


import EmployeeClass as e
import PayrollDeductionClass as d

emp1 = e.employee('Jimmy Smith','58475','Information Systems','Developer',6800)

transaction1 = d.deduction('food court','8/14/2022',22.50,'39119')
transaction2 = d.deduction('gift contribution','8/12/2022',25.00,'58475')
transaction3 = d.deduction('food court','8/17/2022',15.25,'21547')
transaction4 = d.deduction('vending machine','8/22/2022',3.00,'58475')
transaction5 = d.deduction('vending machine','8/5/2022',2.75,'58475')

net_pay = emp1.get_salary() - transaction2.get_amt() - transaction4.get_amt() - transaction5.get_amt()

print('*** Employee Pay ***')
print('Name:', emp1.get_name())
print('Department:',emp1.get_department())
print('Gross Pay:', emp1.get_salary())
print('Net Pay:', net_pay)


"""OAuth utility functions."""

import json
import re
from urllib.parse import quote_plus, urlparse

import structlog
from allauth.socialaccount.providers.gitlab.views import GitLabOAuth2Adapter
from django.conf import settings
from oauthlib.oauth2.rfc6749.errors import InvalidGrantError, TokenExpiredError
from requests.exceptions import RequestException

from readthedocs.builds import utils as build_utils
from readthedocs.builds.constants import BUILD_STATUS_SUCCESS, SELECT_BUILD_STATUS
from readthedocs.integrations.models import Integration

from ..constants import GITLAB
from ..models import RemoteOrganization, RemoteRepository
from .base import Service, SyncServiceError

log = structlog.get_logger(__name__)

class GitLabService(Service):

    """
    Provider service for GitLab.

    See:
     - https://docs.gitlab.com/ce/integration/oauth_provider.html
     - https://docs.gitlab.com/ce/api/oauth2.html
    """

    adapter = GitLabOAuth2Adapter
    # Just use the network location to determine if it's a GitLab project
    # because private repos have another base url, eg. git@gitlab.example.com
    url_pattern = re.compile(
        re.escape(urlparse(adapter.provider_base_url).netloc),
    )

    PERMISSION_NO_ACCESS = 0
    PERMISSION_MAINTAINER = 40
    PERMISSION_OWNER = 50

    vcs_provider_slug = GITLAB

    def _get_repo_id(self, project):
        """
        Get the ID or URL-encoded path of the project.

        See https://docs.gitlab.com/ce/api/README.html#namespaced-path-encoding.
        """
        if project.remote_repository:
            repo_id = project.remote_repository.remote_id
        else:
            # Handle "Manual Import" when there is no RemoteRepository
            # associated with the project. It only works with gitlab.com at the
            # moment (doesn't support custom gitlab installations)
            username, repo = build_utils.get_gitlab_username_repo(project.repo)
            if (username, repo) == (None, None):
                return None

            repo_id = quote_plus(f"{username}/{repo}")
        return repo_id

    def get_next_url_to_paginate(self, response):
        return response.links.get("next", {}).get("url")

    def get_paginated_results(self, response):
        return response.json()

    def sync_repositories(self):
        remote_repositories = []
        try:
            repos = self.paginate(
                "{url}/api/v4/projects".format(url=self.adapter.provider_base_url),
                per_page=100,
                archived=False,
                order_by="path",
                sort="asc",
                membership=True,
            )

            for repo in repos:
                remote_repository = self.create_repository(repo)
                remote_repositories.append(remote_repository)
        except (TypeError, ValueError):
            log.warning("Error syncing GitLab repositories")
            raise SyncServiceError(
                SyncServiceError.INVALID_OR_REVOKED_ACCESS_TOKEN.format(
                    provider=self.vcs_provider_slug
                )
            )

        return remote_repositories

    def sync_organizations(self):
        remote_organizations = []
        remote_repositories = []

        try:
            orgs = self.paginate(
                "{url}/api/v4/groups".format(url=self.adapter.provider_base_url),
                per_page=100,
                all_available=False,
                order_by="path",
                sort="asc",
            )
            for org in orgs:
                remote_organization = self.create_organization(org)
                org_repos = self.paginate(
                    "{url}/api/v4/groups/{id}/projects".format(
                        url=self.adapter.provider_base_url,
                        id=org["id"],
                    ),
                    per_page=100,
                    archived=False,
                    order_by="path",
                    sort="asc",
                )

                remote_organizations.append(remote_organization)

                for repo in org_repos:
                    # TODO: Optimize this so that we don't re-fetch project data
                    # Details: https://github.com/readthedocs/readthedocs.org/issues/7743
                    try:
                        # The response from /groups/{id}/projects API does not contain
                        # admin permission fields for GitLab projects.
                        # So, fetch every single project data from the API
                        # which contains the admin permission fields.
                        resp = self.get_session().get(
                            "{url}/api/v4/projects/{id}".format(
                                url=self.adapter.provider_base_url, id=repo["id"]
                            )
                        )

                        if resp.status_code == 200:
                            repo_details = resp.json()
                            remote_repository = self.create_repository(
                                repo_details, organization=remote_organization
                            )
                            remote_repositories.append(remote_repository)
                        else:
                            log.warning(
                                "GitLab project does not exist or user does not have permissions.",
                                repository=repo["name_with_namespace"],
                            )

                    except Exception:
                        log.exception(
                            "Error creating GitLab repository",
                            repository=repo["name_with_namespace"],
                        )

        except (TypeError, ValueError):
            log.warning("Error syncing GitLab organizations")
            raise SyncServiceError(
                SyncServiceError.INVALID_OR_REVOKED_ACCESS_TOKEN.format(
                    provider=self.vcs_provider_slug
                )
            )

        return remote_organizations, remote_repositories

    def create_repository(self, fields, privacy=None, organization=None):
        """
        Update or create a repository from GitLab API response.

        ``admin`` field is computed using the ``permissions`` fields from the
        repository response. The permission from GitLab is given by an integer:
          * 0: No access
          * (... others ...)
          * 40: Maintainer
          * 50: Owner

        https://docs.gitlab.com/ee/api/access_requests.html
        https://gitlab.com/help/user/permissions

        :param fields: dictionary of response data from API
        :param privacy: privacy level to support
        :param organization: remote organization to associate with
        :type organization: RemoteOrganization
        :rtype: RemoteRepository
        """
        privacy = privacy or settings.DEFAULT_PRIVACY_LEVEL
        repo_is_public = fields["visibility"] == "public"
        if privacy == "private" or (repo_is_public and privacy == "public"):
            repo, _ = RemoteRepository.objects.get_or_create(
                remote_id=fields["id"], vcs_provider=self.vcs_provider_slug
            )
            remote_repository_relation = repo.get_remote_repository_relation(
                self.user, self.account
            )

            if repo.organization and repo.organization != organization:
                log.debug(
                    "Not importing because mismatched orgs",
                    repository=fields["name"],
                )
                return None

            repo.organization = organization
            repo.name = fields["name"]
            repo.full_name = fields["path_with_namespace"]
            repo.description = fields["description"]
            repo.ssh_url = fields["ssh_url_to_repo"]
            repo.html_url = fields["web_url"]
            repo.vcs = "git"
            repo.private = not repo_is_public
            repo.default_branch = fields.get("default_branch")

            owner = fields.get("owner") or {}
            repo.avatar_url = fields.get("avatar_url") or owner.get("avatar_url")

            if not repo.avatar_url:
                repo.avatar_url = self.default_user_avatar_url

            if repo.private:
                repo.clone_url = repo.ssh_url
            else:
                repo.clone_url = fields["http_url_to_repo"]

            repo.save()

            project_access_level = group_access_level = self.PERMISSION_NO_ACCESS

            project_access = fields.get("permissions", {}).get("project_access", {})
            if project_access:
                project_access_level = project_access.get(
                    "access_level", self.PERMISSION_NO_ACCESS
                )

            group_access = fields.get("permissions", {}).get("group_access", {})
            if group_access:
                group_access_level = group_access.get(
                    "access_level", self.PERMISSION_NO_ACCESS
                )

            remote_repository_relation.admin = any(
                [
                    project_access_level
                    in (self.PERMISSION_MAINTAINER, self.PERMISSION_OWNER),
                    group_access_level
                    in (self.PERMISSION_MAINTAINER, self.PERMISSION_OWNER),
                ]
            )
            remote_repository_relation.save()

            return repo

        log.info(
            "Not importing repository because mismatched type.",
            repository=fields["path_with_namespace"],
            visibility=fields["visibility"],
        )

    def create_organization(self, fields):
        """
        Update or create remote organization from GitLab API response.

        :param fields: dictionary response of data from API
        :rtype: RemoteOrganization
        """
        organization, _ = RemoteOrganization.objects.get_or_create(
            remote_id=fields["id"], vcs_provider=self.vcs_provider_slug
        )
        organization.get_remote_organization_relation(self.user, self.account)

        organization.name = fields.get("name")
        organization.slug = fields.get("path")
        organization.url = "{url}/{path}".format(
            url=self.adapter.provider_base_url,
            path=fields.get("path"),
        )
        organization.avatar_url = fields.get("avatar_url")

        if not organization.avatar_url:
            organization.avatar_url = self.default_user_avatar_url

        organization.save()

        return organization

    def get_webhook_data(self, repo_id, project, integration):
        """
        Get webhook JSON data to post to the API.

        See: http://doc.gitlab.com/ce/api/projects.html#add-project-hook
        """
        return json.dumps(
            {
                "id": repo_id,
                "push_events": True,
                "tag_push_events": True,
                "url": self.get_webhook_url(project, integration),
                "token": integration.secret,
                # Optional
                "issues_events": False,
                "merge_requests_events": True,
                "note_events": False,
                "job_events": False,
                "pipeline_events": False,
                "wiki_events": False,
            }
        )

    def get_provider_data(self, project, integration):
        """
        Gets provider data from GitLab Webhooks API.

        :param project: project
        :type project: Project
        :param integration: Integration for the project
        :type integration: Integration
        :returns: Dictionary containing provider data from the API or None
        :rtype: dict
        """

        if integration.provider_data:
            return integration.provider_data

        repo_id = self._get_repo_id(project)

        if repo_id is None:
            return None

        session = self.get_session()
        log.bind(
            project_slug=project.slug,
            integration_id=integration.pk,
        )

        rtd_webhook_url = self.get_webhook_url(project, integration)

        try:
            resp = session.get(
                "{url}/api/v4/projects/{repo_id}/hooks".format(
                    url=self.adapter.provider_base_url,
                    repo_id=repo_id,
                ),
            )

            if resp.status_code == 200:
                recv_data = resp.json()

                for webhook_data in recv_data:
                    if webhook_data["url"] == rtd_webhook_url:
                        integration.provider_data = webhook_data
                        integration.save()

                        log.info(
                            "GitLab integration updated with provider data for project.",
                        )
                        break
            else:
                log.info(
                    "GitLab project does not exist or user does not have permissions."
                )

        except Exception:
            log.exception("GitLab webhook Listing failed for project.")

        return integration.provider_data

    def setup_webhook(self, project, integration=None):
        """
        Set up GitLab project webhook for project.

        :param project: project to set up webhook for
        :type project: Project
        :param integration: Integration for a project
        :type integration: Integration
        :returns: boolean based on webhook set up success
        :rtype: bool
        """
        resp = None

        if not integration:
            integration, _ = Integration.objects.get_or_create(
                project=project,
                integration_type=Integration.GITLAB_WEBHOOK,
            )

        if not integration.secret:
            integration.recreate_secret()

        repo_id = self._get_repo_id(project)
        url = f"{self.adapter.provider_base_url}/api/v4/projects/{repo_id}/hooks"

        if repo_id is None:
            # Set the secret to None so that the integration can be used manually.
            integration.remove_secret()
            return (False, resp)

        log.bind(
            project_slug=project.slug,
            integration_id=integration.pk,
            url=url,
        )
        data = self.get_webhook_data(repo_id, project, integration)
        session = self.get_session()
        try:
            resp = session.post(
                url,
                data=data,
                headers={"content-type": "application/json"},
            )
            log.bind(http_status_code=resp.status_code)

            if resp.status_code == 201:
                integration.provider_data = resp.json()
                integration.save()
                log.debug("GitLab webhook creation successful for project.")
                return (True, resp)

            if resp.status_code in [401, 403, 404]:
                log.info(
                    "Gitlab project does not exist or user does not have permissions."
                )
            else:
                log.warning(
                    "GitLab webhook creation failed. Unknown response from GitLab."
                )

        except Exception:
            log.exception("GitLab webhook creation failed.")

        # Always remove secret and return False if we don't return True above
        integration.remove_secret()
        return (False, resp)

    def update_webhook(self, project, integration):
        """
        Update webhook integration.

        :param project: project to set up webhook for
        :type project: Project

        :param integration: Webhook integration to update
        :type integration: Integration

        :returns: boolean based on webhook update success, and requests Response
                  object

        :rtype: (Bool, Response)
        """
        provider_data = self.get_provider_data(project, integration)

        # Handle the case where we don't have a proper provider_data set
        # This happens with a user-managed webhook previously
        if not provider_data:
            return self.setup_webhook(project, integration)

        resp = None
        session = self.get_session()
        repo_id = self._get_repo_id(project)

        if repo_id is None:
            return (False, resp)

        if not integration.secret:
            integration.recreate_secret()

        data = self.get_webhook_data(repo_id, project, integration)

        log.bind(
            project_slug=project.slug,
            integration_id=integration.pk,
        )
        try:
            hook_id = provider_data.get("id")
            resp = session.put(
                "{url}/api/v4/projects/{repo_id}/hooks/{hook_id}".format(
                    url=self.adapter.provider_base_url,
                    repo_id=repo_id,
                    hook_id=hook_id,
                ),
                data=data,
                headers={"content-type": "application/json"},
            )

            if resp.status_code == 200:
                recv_data = resp.json()
                integration.provider_data = recv_data
                integration.save()
                log.info("GitLab webhook update successful for project.")
                return (True, resp)

            # GitLab returns 404 when the webhook doesn't exist. In this case,
            # we call ``setup_webhook`` to re-configure it from scratch
            if resp.status_code == 404:
                return self.setup_webhook(project, integration)

        except Exception:
            try:
                debug_data = resp.json()
            except ValueError:
                debug_data = resp.content
            except Exception:
                debug_data = None
            log.exception(
                "GitLab webhook update failed.",
                debug_data=debug_data,
            )

        integration.remove_secret()
        return (False, resp)

    def send_build_status(self, build, commit, status):
        """
        Create GitLab commit status for project.

        :param build: Build to set up commit status for
        :type build: Build
        :param status: build status failure, pending, or success.
        :type status: str
        :param commit: commit sha of the pull request
        :type commit: str
        :returns: boolean based on commit status creation was successful or not.
        :rtype: Bool
        """
        resp = None
        session = self.get_session()
        project = build.project

        repo_id = self._get_repo_id(project)

        if repo_id is None:
            return (False, resp)

        # select the correct status and description.
        gitlab_build_state = SELECT_BUILD_STATUS[status]["gitlab"]
        description = SELECT_BUILD_STATUS[status]["description"]

        if status == BUILD_STATUS_SUCCESS:
            # Link to the documentation for this version
            target_url = build.version.get_absolute_url()
        else:
            # Link to the build detail's page
            target_url = build.get_full_url()

        context = f"{settings.RTD_BUILD_STATUS_API_NAME}:{project.slug}"

        data = {
            "state": gitlab_build_state,
            "target_url": target_url,
            "description": description,
            "context": context,
        }
        url = f"{self.adapter.provider_base_url}/api/v4/projects/{repo_id}/statuses/{commit}"

        log.bind(
            project_slug=project.slug,
            commit_status=gitlab_build_state,
            user_username=self.user.username,
            url=url,
        )
        try:
            resp = session.post(
                url,
                data=json.dumps(data),
                headers={"content-type": "application/json"},
            )

            log.bind(http_status_code=resp.status_code)
            if resp.status_code == 201:
                log.debug("GitLab commit status created for project.")
                return True

            if resp.status_code in [401, 403, 404]:
                log.info(
                    "GitLab project does not exist or user does not have permissions."
                )
                return False

            return False

        # Catch exceptions with request or deserializing JSON
        except (RequestException, ValueError):
            # Response data should always be JSON, still try to log if not
            # though
            if resp is not None:
                try:
                    debug_data = resp.json()
                except ValueError:
                    debug_data = resp.content
            else:
                debug_data = resp

            log.exception(
                "GitLab commit status creation failed.",
                debug_data=debug_data,
            )
        except InvalidGrantError:
            log.info("Invalid GitLab grant for user.", exc_info=True)
        except TokenExpiredError:
            log.info("GitLab token expired for user.", exc_info=True)

        return False


import requests
from datetime import datetime, timezone, timedelta
from dateutil import parser
import logging

def get_jupyter_kernels(resource_url, user_token):
    """extracting information for each kernel on a Jupyter server"""
    sessions_url = f"{resource_url}api/sessions"
    headers = {"Authorization": f"token {user_token}"}
    response = requests.get(sessions_url, headers=headers)
    result = response.json()
    return result

def check_jupyter_needs_shutoff(kernels, idle_time_delta):
    """Given a Jupyter session check if any of the kernel's activity is more recent than idle limit.
    Return True if the server needs to be shut off. In the event there are no kernels, do not shut
    off the server, instead leave it to Saturn Cloud's built in logic to handle.
    """
    # getting time window to keep the server on
    min_time = datetime.now(timezone.utc) - idle_time_delta

    if len(kernels) == 0:
        return False  # There are no kernels at all so do not act

    for k in kernels:
        if (parser.parse(k["kernel"]["last_activity"]) >= min_time) or (
            k["kernel"]["execution_state"] != "idle"
        ):
            return False

    return True

def shutoff_resource(resource_id, base_url, user_token):
    """Turn off a Saturn Cloud resource for a user"""
    headers = {"Authorization": f"token {user_token}"}
    requests.post(
        f"{base_url}api/workspaces/{resource_id}/stop",
        headers=headers,
    )

time_delta_mapping = {
    "1 hour": timedelta(hours=1),  # hack for testing
    "6 hours": timedelta(hours=6),
    "24 hours": timedelta(hours=24),
    "3 days": timedelta(hours=24 * 3),
    "7 days": timedelta(hours=24 * 7),
}

def close_user_resources(base_url, username, user_token):
    """Given a user access token, close their idle resources
    idle_limit is the limit in hours before shutting down the resource.
    """

    # get all of their workspace resources
    workspaces = requests.get(
        f"{base_url}api/workspaces",
        headers={"Authorization": f"token {user_token}"},
    ).json()["workspaces"]

    # filter to only Jupyter servers (to exclude RStudio servers)
    jupyter_servers = list(filter(lambda w: w["resource_type"] == "Jupyter Workspace", workspaces))

    # for each resource check last activity of the Jupyter kernels
    for resource in jupyter_servers:
        if (
            resource["url"] is not None
        ):  # this means there is an actively running JupyterLab server we can query
            time_delta = time_delta_mapping.get(resource["auto_shutoff"], None)
            if time_delta is None:
                continue
            kernels = get_jupyter_kernels(resource["url"], user_token)
            needs_shutoff = check_jupyter_needs_shutoff(kernels, time_delta)
            if needs_shutoff:
                logging.warning(f"Shutting down resource: {username}/{resource['name']}")
                shutoff_resource(resource, base_url, user_token)


from collections import OrderedDict

class Data:
    def __init__(self, file):

        self.data = self.__load(file)

    def __iter__(self):
        return self.data.iteritems()

    def __load(self, file):

        result = OrderedDict()

        for line in file:

            fields = [f.strip() for f in line.split(',')]

            name, lookup, pack, time = fields

            time = float(time)
            key  = (name, lookup, pack)
            result[key] = min(time, result.get(key, time))

        return result


import busca_sequencial as bsequencial
import busca_binaria as bbinaria
from jogo import Jogo

listaDeJogos = []
identificador = 0

listaDeJogos.append(Jogo(0, 'Skirym', 'RPG'))
listaDeJogos.append(Jogo(1, 'God Of War', 'Fantasia'))
listaDeJogos.append(Jogo(2, 'Minecraft', 'Sandbox'))
listaDeJogos.append(Jogo(3, 'Minecraft', 'Sandbox'))
listaDeJogos.append(Jogo(4, 'Batlefield', 'FPS'))
listaDeJogos.append(Jogo(5, 'League Of Legends', 'Moba'))
listaDeJogos.append(Jogo(6, 'Age of Empires', 'Estratégia'))
listaDeJogos.append(Jogo(7, 'Age of Mitology', 'Estratégia'))
listaDeJogos.append(Jogo(8, 'Dragons Dogma', 'RPG'))
listaDeJogos.append(Jogo(9, 'The Division', 'Tiro'))

def ExibirLista(listaDeJogos):
    if len(listaDeJogos) == 0:
        print('\n\rA lista de jogos está vazia.')
    else:
        for item in listaDeJogos:
            print(f'{item.id}. {item.nome}, {item.categoria}')

def AdicionarJogo(identificador):
    try:
        identificador = listaDeJogos[-1].id + 1
    except:
        pass
    nomeDoJogo = input('\n\rDigite o nome do jogo que deseja adicionar: \n\r')
    categoria = input(f'\n\rCategoria do jogo {nomeDoJogo}: \n\r')
    listaDeJogos.append(Jogo(identificador, nomeDoJogo, categoria))
    print(f'jogo {nomeDoJogo} adicionado')

print('\n\r#######  GERENCIADOR DE LISTA DE JOGOS #######')
while True:
    print('\n\r[1] Exibir lista de jogos')
    print('[2] Adicionar jogo')
    print('[3] Buscar por um jogo usando busca sequencial')
    print('[4] Buscar por um jogo usando busca binária')
    print('[0] Sair')

    entrada = int(input('Escolha uma das opções acima: '))

    if entrada == 1:
        ExibirLista(listaDeJogos)

    if entrada == 2:
        AdicionarJogo(identificador)
        identificador += 1

    if entrada == 3:
        print('\n\rBUSCA SEQUENCIAL')
        identificador = int(input('Entre com o IDENTIFICADOR ou NOME do jogo que deseja pesquisar: '))
        jogo = bsequencial.BuscaSequencial(listaDeJogos, identificador)
        if jogo == None:
            print('Jogo não encontrado. Adicione o novo jogo ou exiba a lista completa e certifique-se que existe.')
        else:
            print(f'Jogo: {jogo.nome}, Categoria: {jogo.categoria}, ID: {jogo.id}')

    if entrada == 4:
        print('\n\rBUSCA BINARIA')
        identificador = int(input('Entre com o identificador do jogo que deseja pesquisar:'))
        jogo = bbinaria.BuscaBinaria(listaDeJogos, identificador)
        if jogo == None:
            print('Jogo não encontrado. Adicione o novo jogo ou exiba a lista completa e certifique-se que existe.')
        else:
            print(f'Jogo: {jogo.nome}, Categoria: {jogo.categoria}, ID: {jogo.id}')
    if entrada == 0:
        break


import numpy

class XOR():

	def __init__(self):

		self.evaluation_type = 'binary_classification'

		self.input_dimension = 2
		self.output_dimension = 1

		normalize = lambda x: (x - x.min()) / (x.max() - x.min())

		X = []
		Y = []
		for line in open('./Datasets/xor_train.txt').readlines():
			line = line.strip()
			y, x = line.split('\t')
			x0, x1 = x.split(' ')
			x0, x1, y = float(x0), float(x1), float(y)
			X.append([x0, x1])
			Y.append([y])

		X = numpy.array(X)
		Y = numpy.array(Y)

		self.train_x = normalize(X)
		self.train_y = normalize(Y)

		X = []
		Y = []
		for line in open('./Datasets/xor_test.txt').readlines():
			line = line.strip()
			y, x = line.split('\t')
			x0, x1 = x.split(' ')
			x0, x1, y = float(x0), float(x1), float(y)
			X.append([x0, x1])
			Y.append([y])

		X = numpy.array(X)
		Y = numpy.array(Y)

		self.test_x = normalize(X)
		self.test_y = normalize(Y)


class Solution:
    def matrixBlockSum(self, mat: List[List[int]], k: int) -> List[List[int]]:
        m,n = len(mat), len(mat[0])
        dp  = [[0]*(n) for _ in range(m)]
        ret = [[0]*(n) for _ in range(m)]
        inbound = lambda i, j: 0 <= i < m and 0 <= j < n
        val = lambda i, j, arr: arr[i][j] if inbound(i, j) else 0
        for i in range(m):
            for j in range(n):
                dp[i][j] = val(i, j, mat)+val(i-1, j, dp)+val(i, j-1, dp)-val(i-1, j-1, dp)
        for i in range(m):
            for j in range(n):
                hi_row, hi_col = min(m-1, i+k), min(n-1, j+k)
                lo_row, lo_col = i-k-1, j-k-1
                total= val(hi_row, hi_col, dp)
                top= val(lo_row, hi_col, dp)
                left= val(hi_row, lo_col, dp)
                dual = val(lo_row, lo_col, dp)
                ret[i][j] = total - top - left + dual
        return ret


#!/usr/bin/env python

from __future__ import print_function

import subprocess
import sys

from setuptools import setup, find_packages
from codecs import open

from fbfeed import __version__

# Get the long description from the README file
with open("README.md", encoding="utf-8") as f:
    long_description = f.read()

# Bump version and generate CHANGELOG
if sys.argv[:2] == ["setup.py", "bump"]:
    subprocess.check_call("standard-version")  # npm install -g standard-version

# Tag and release the package to PyPI
if sys.argv[:2] == ["setup.py", "release"]:
    subprocess.check_call("git push")
    subprocess.check_call("git push --tags")
    subprocess.check_call("rm -rf dist/")
    subprocess.check_call("python setup.py sdist")
    subprocess.check_call("python setup.py bdist_wheel")
    subprocess.check_call("twine upload dist/*")
    sys.exit()

setup(
    name="mezzanine-facebook-feed",
    version=__version__,
    description="Connect Mezzanine sites to Facebook feeds",
    long_description=long_description,
    long_description_content_type="text/markdown",
    url="https://github.com/unplugstudio/mezzanine-facebook-feed",
    author="Unplug Studio",
    author_email="hello@unplug.studio",
    license="MIT",
    classifiers=[
        "Development Status :: 5 - Production/Stable",
        "Intended Audience :: Developers",
        "Topic :: Software Development :: Libraries",
        "License :: OSI Approved :: MIT License",
        "Programming Language :: Python :: 2",
        "Programming Language :: Python :: 2.7",
        "Programming Language :: Python :: 3",
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
    ],
    keywords="django mezzanine facebook",
    packages=find_packages(),
    install_requires=["mezzanine>=4.3.0"],
    include_package_data=True,
)


import pymongo
import twitterAPI

MONGODB_URL = ''

def add_account():
    name = input("Enter a twitter name: ")
    connect = pymongo.MongoClient(MONGODB_URL)
    db = connect["EC601_MiniProject3_db"]
    myset = db["project1_record"]
    if myset.find({'username': name}):
        print("This account already existed")
        return

    time_offset = twitterAPI.main(name, 40)

    account = {"username": name, "labels": time_offset}
    myset.insert_one(account)

def query_account():
    account = input("Enter an existed twitter name: ")
    connect = pymongo.MongoClient(MONGODB_URL)
    database = connect["EC601_MiniProject3_db"]
    myset = database["project1_record"]
    match = myset.find({'username': account})
    if not match:
        print("No match found!")
    else:
        for row in match:
            print("account =", row['username'], "\nlabels=", row['labels'])

def main():
    do1 = input('Do you want to add an account? (y/n): ')
    if do1 not in ['y', 'n']:
        print('Invalid input')
    elif do1 in ['y']:
        add_account()
    else:
        do2 = input('Do you want to query an existed account? (y/n): ')
        if do2 not in ['y', 'n']:
            print('Invalid input')
        elif do2 in ['y']:
            query_account()
        else:
            pass

if __name__ == '__main__':
    main()


import os
import cv2
import pickle

class faces():

    def __init__(self):
        f = os.path.dirname(cv2.__file__) +  '/data/haarcascade_frontalface_alt2.xml'
        # print("* CascadeClassifier:", f)
        self.face_cascade = cv2.CascadeClassifier(f)

        self.recognizer = cv2.face.LBPHFaceRecognizer_create()
        self.recognizer.read("./trainer.yml")

        self.labels = {"person_name": 1}
        with open("labels.pickle", 'rb') as f:
            og_labels = pickle.load(f)
            self.labels = {v:k for k,v in og_labels.items()}

    def find(self, frame):

        gray  = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
        face_list = self.face_cascade.detectMultiScale(gray, scaleFactor=1.5, minNeighbors=5)

        for (x, y, w, h) in face_list:
            #print(x,y,w,h)
            roi_gray = gray[y:y+h, x:x+w]
            roi_color = frame[y:y+h, x:x+w]

            id_, conf = self.recognizer.predict(roi_gray)

            # print(conf, labels[id_])
            if conf >= 50 and conf <= 100:
                font = cv2.FONT_HERSHEY_DUPLEX
                name = self.labels[id_]

                color = (255, 0, 0)  #BGR
                stroke = 1
                end_cord_x = x + w
                end_cord_y = y + h
                cv2.rectangle(frame, (x, y), (end_cord_x, end_cord_y), color, stroke )
                cv2.rectangle(frame, (x, end_cord_y + 20 ), (end_cord_x, end_cord_y), color, cv2.FILLED )
                cv2.putText(frame, name, (x + 6, end_cord_y + 16), font, 0.5, (255,255,255), stroke, cv2.LINE_AA)

        return frame


import unittest
from logica import sessao
from logica import sala
from logica import filme

class TestSessao(unittest.TestCase):

	def setUp(self):
		sala.iniciar_salas()
		filme.iniciar_filmes()
		sessao.remover_todas_sessoes()

	def test_sem_sessao(self):
		sessoes = sessao.listar_sessoes()

		self.assertEqual(0, len(sessoes))

	def test_criar_uma_sessao(self):
		sessao.criar_sessao(1, 1, 1, "18h")

		sessoes = sessao.listar_sessoes()

		self.assertEqual(1, len(sessoes))

		s = sessoes[0]
		salas = sala.buscar_sala(1)
		filmes = filme.buscar_filme(1)
		self.assertEqual(1, s[0])
		self.assertEqual(filmes, s[1])
		self.assertEqual(salas, s[2])
		self.assertEqual("18h", s[3])

	def test_criar_duas_sessoes(self):
		sessao.criar_sessao(1, 1, 1, "18h")
		sessao.criar_sessao(2, 2, 2, "20h")

		sessoes = sessao.listar_sessoes()

		self.assertEqual(2, len(sessoes))

		s = sessoes[1]
		salas = sala.buscar_sala(2)
		filmes = filme.buscar_filme(2)
		self.assertEqual(2, s[0])
		self.assertEqual(filmes, s[1])
		self.assertEqual(salas, s[2])
		self.assertEqual("20h", s[3])

	def test_recuperar_sessao(self):
		sessao.criar_sessao(1, 1, 1, "18h")
		sessao.criar_sessao(2, 2, 2, "20h")

		s = sessao.recuperar_sessao(2)
		salas = sala.buscar_sala(2)
		filmes = filme.buscar_filme(2)
		self.assertEqual(2, s[0])
		self.assertEqual(filmes, s[1])
		self.assertEqual(salas, s[2])
		self.assertEqual("20h", s[3])

	def test_remover_sessao(self):
		sessao.criar_sessao(1, 1, 1, "18h")
		sessao.criar_sessao(2, 2, 2, "20h")

		sessao.remover_sessao(2)

		s = sessao.recuperar_sessao(2)

		self.assertIsNone(s)

	def test_remover_todas_sessoes(self):
		sessao.criar_sessao(1, 1, 1, "18h")
		sessao.criar_sessao(2, 2, 2, "20h")

		sessao.remover_todas_sessoes()

		sessoes = sessao.listar_sessoes()

		self.assertEqual(0, len(sessoes))

	def test_iniciar_sessaoes(self):
		sessao.iniciar_sessoes()

		sessoes = sessao.listar_sessoes()

		self.assertEqual(2, len(sessoes))

	def test_verificar_lotacao(self):
		sessao.criar_sessao(1, 1, 1, "18h")
		sessao.criar_sessao(2, 2, 2, "20h")

		s = sessao.verificar_lotacao(2)
		salas = sala.buscar_sala(2)
		self.assertEqual(salas[1], s)

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


from red_contour_grip import RedContoursPipeline

import config

import cv2
import time
import math
import numpy

def calculate_coords(u, v):

    # pulled from https://github.com/ligerbots/VisionServer, BallFinder2020

    cam_matrix = config.cameramtx

    x_prime = (u - cam_matrix[0, 2]) / cam_matrix[0, 0]
    y_prime = -(v - cam_matrix[1, 2]) / cam_matrix[1, 1]

    ax = math.atan2(x_prime, 1.0)
    ay = math.atan2(y_prime * math.cos(ax), 1.0)

    print(str(ax) + " vs " + str(math.atan(x_prime)))

    target_height = 21
    camera_height = 4
    tilt_angle = 0

    d = (target_height - camera_height) / math.tan(tilt_angle + ay)

    return math.degrees(ax), math.degrees(ay), d

def calc_contours(c):
    M = cv2.moments(c)
    if M['m00'] != 0:
        cx = int(M['m10']/M['m00'])
        cy = int(M['m01']/M['m00'])

    return cx,cy

cap = cv2.VideoCapture(1)

# Run the pipeline on the video stream
while True:

    _, frame = cap.read()

    if frame is None:
        continue

    # Undistort the frame
    temp = cv2.undistort(frame, config.cameramtx, config.dist, None, config.cameramtx)
    # TODO Crop the frame using roi
    frame = temp

    # Process frame
    visionPipeline = RedContoursPipeline() # LemonVisionGripPipeline()
    visionPipeline.process(frame)

    # Retrieve the blobs from the pipeline
    contours = visionPipeline.filter_contours_output # tuple of KeyPoint objects

    print(str(len(contours)) + " blobs detected")

    if len(contours) > 0:
        # Find largest contour
        largest_contour = []
        largest_contour_idx = 0
        for i in range(len(contours)):
            if (len(contours[i]) > len(largest_contour)):
                largest_contour = contours[i]
                largest_contour_idx = i

        # Find centroid of contour
        x, y = calc_contours(largest_contour)
        x = int(x)
        y = int(y)

        cv2.line(frame, (x - config.center_line_length, y), (x + config.center_line_length, y), config.color, config.line_thickness)
        cv2.line(frame, (x, y - config.center_line_length), (x, y + config.center_line_length), config.color, config.line_thickness)

        temp = cv2.drawContours(frame, contours, largest_contour_idx, config.color, config.line_thickness, cv2.LINE_8, maxLevel=0)
        frame = temp

        # Calculate angle to target
        pitch_angle, yaw_angle, d = calculate_coords(x, y)

        temp = cv2.putText(frame, "(" + str(round(pitch_angle, 3)) + ", " + str(round(yaw_angle, 3)) + ", " + str(round(d, 3)) +  ")", (x + config.text_offset, y - config.text_offset), cv2.FONT_HERSHEY_SIMPLEX, 0.5, config.color, config.line_thickness)
        frame = temp

        print("x: " + str(x) + "; y: " + str(y))
        print("pitch: " + str(pitch_angle) + "; yaw: " + str(yaw_angle))
        print(config.cameramtx[0, 2])
        print(config.cameramtx[0][2])

    cv2.imshow('image', frame)
    cv2.imshow('mask', visionPipeline.hsv_threshold_output)

    if cv2.waitKey(1000) & 0xFF == ord('q'):
        break


class Backpack:
    def __init__(self, string):
        self.compartment1String = string[slice(0, len(string)//2)]
        self.compartment2String = string[slice(len(string)//2, len(string))]

    def getMatch(self):
        for letter in self.compartment1String:
            if letter in self.compartment2String:
                return letter

def getPriority(letter):
    prioritys = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z']
    return prioritys.index(letter) + 1

def main():
    totalpriority = 0
    inputfile = open("input.txt", 'r')
    for line in inputfile.read().split("\n"):
        backpack = Backpack(line)
        match = backpack.getMatch()
        totalpriority = totalpriority + getPriority(match)

    print(totalpriority)

main()


from dataclasses import dataclass

from huobi.rest.endpoints import DONT_SEND, Endpoint
from huobi.rest.enums import HttpMethod

@dataclass
class LoanInterestRateAndQuotaIsolatedEndpoint(Endpoint):
    name: str = 'MarginLoanCI/LoanInterestRateAndQuotaIsolated'
    raw_path: str = '/v1/margin/loan-info'
    method: HttpMethod = HttpMethod.GET
    query_params = {
        'symbols': DONT_SEND,
    }

@dataclass
class SearchPastMarginOrdersIsolatedEndpoint(Endpoint):
    name: str = 'MarginLoanCI/SearchPastMarginOrders'
    raw_path: str = '/v1/margin/loan-orders'
    method: HttpMethod = HttpMethod.GET
    query_params = {
        'symbol': DONT_SEND,
        'states': DONT_SEND,
        'start-date': DONT_SEND,
        'end-date': DONT_SEND,
        'from': DONT_SEND,
        'direct': DONT_SEND,
        'size': DONT_SEND,
        'sub-uid': DONT_SEND,
    }

@dataclass
class BalanceOfTheMarginLoanAccountEndpoint(Endpoint):
    name: str = 'MarginLoanCI/BalanceOfTheMarginLoanAccount'
    raw_path: str = '/v1/cross-margin/accounts/balance'
    method: HttpMethod = HttpMethod.GET
    query_params = {
        'sub-uid': DONT_SEND,
    }

@dataclass
class BalanceOfTheMarginLoanAccountIsolatedEndpoint(Endpoint):
    name: str = 'MarginLoanCI/BalanceOfTheMarginLoanAccountIsolated'
    raw_path: str = '/v1/margin/accounts/balance'
    method: HttpMethod = HttpMethod.GET
    query_params = {
        'symbol': DONT_SEND,
        'sub-uid': DONT_SEND,
    }

@dataclass
class LoanInterestRateAndQuotaCrossEndpoint(Endpoint):
    name: str = 'MarginLoanCI/LoanInterestRateAndQuotaCross'
    raw_path: str = '/v1/cross-margin/loan-info'
    method: HttpMethod = HttpMethod.GET
    query_params = {
        'symbol': DONT_SEND,
        'sub-uid': DONT_SEND,
    }

@dataclass
class SearchPastMarginOrdersCrossEndpoint(Endpoint):
    name: str = 'MarginLoanCI/SearchPastMarginOrders'
    raw_path: str = '/v1/cross-margin/loan-orders'
    method: HttpMethod = HttpMethod.GET
    query_params = {
        'start-date': DONT_SEND,
        'end-date': DONT_SEND,
        'currency': DONT_SEND,
        'state': DONT_SEND,
        'from': DONT_SEND,
        'direct': DONT_SEND,
        'size': DONT_SEND,
        'sub-uid': DONT_SEND,
    }

@dataclass
class RepaymentRecordReferenceEndpoint(Endpoint):
    name: str = 'MarginLoanCI/RepaymentRecordReference'
    raw_path: str = '/v2/account/repayment'
    method: HttpMethod = HttpMethod.GET
    query_params = {
        'repayId': DONT_SEND,
        'accountId': DONT_SEND,
        'currency': DONT_SEND,
        'startTime': DONT_SEND,
        'endTime': DONT_SEND,
        'sort': DONT_SEND,
        'limit': DONT_SEND,
        'fromId': DONT_SEND,
    }


import pkg_resources

class Graph(dict):
    """A graph of egg dependencies.

    The nodes of the graph represent distributions (sometimes informally
    called 'packages' or 'eggs'). The edges represent dependencies.

    After creating a graph you need to populate it. To collect information
    about all installed packages, call::

        graph = Graph()
        graph.from_working_set()

    To get information about a subset of packages (and their dependencies),
    call::

        graph = Graph()
        graph.from_specifications('package1', 'package2')

    There are options for filtering the graph, described in the docstring of
    the constructor.

    To access a graph node, index the graph using the distribution name as the
    key::

        node = graph['zope.component']

    Setuptools has this notion of extra dependencies. These are optional and
    are grouped by feature names. For example, 'zope.component' has a 'test'
    extra that pulls in 'zope.testing' and 'zope.location'. Nodes are mappings
    of names of their dependencies to sets of extras by way of which the
    dependencies arise::

        list(nodes.iter_deps()) == [('zope.interface', set()),
                                    ('zope.testing', set(['test']))]

    """

    def __init__(self,
                 working_set=None,
                 show=lambda name: True,
                 follow=lambda name: True,
                 extras=True,
                 ):
        """Create a dependency graph.

        The graph is initially empty. To populate it with nodes and edges call
        either ``from_working_set`` or ``from_specifications``.

        You can specify filtering functions:

          show(name): Returns True if the package with the given name and its
                      dependencies ought to be included in the graph.

          follow(name): Return True if the package with the given name ought
                        to have its dependencies parsed and included in the
                        graph.

        You can also indicate whether you want to process information about
        extra dependencies: if extras is False, all information about extras
        will be discarded.

        """
        self.working_set = working_set or pkg_resources.WorkingSet()
        self.show = show
        self.follow = follow
        self.extras = extras
        self.roots = ()

    def from_specifications(self, *specifications):
        """Build the dependency graph starting from one or more eggs.
        """
        requirements = set(pkg_resources.parse_requirements(specifications))
        self.roots = self.names(requirements)

        for req, node in self.filter(requirements):
            self._add_requirement(req, node)

    def _add_requirement(self, req, node):
        """Add nodes for a distribution and its dependencies.

        This is the recursive part of building the graph from specifications.
        If the distribution can not be found at the required version, a node
        will still be added for it but its dependencies can not be determined.
        """
        if not (node.require(req) and node.follow):
            return

        if not node:
            for dep, dep_node in self.filter(node.dist.requires()):
                node.depend(dep_node.name, dep.extras)

        new_reqs = set(node.dist.requires())
        if self.extras:
            plain_names = self.names(new_reqs)
            for extra in req.extras:
                extra_reqs = node.dist.requires((extra,))
                new_reqs.update(extra_reqs)
                for dep in self.names(extra_reqs) - plain_names:
                    node.extra_depend(extra, dep)

        new_reqs -= node._requires
        node._requires |= new_reqs
        for req, req_node in self.filter(new_reqs):
            self._add_requirement(req, req_node)

    def from_working_set(self):
        """Build the dependency graph for the whole working set.
        """
        ws = set(self.filter(self.working_set))

        # Construct nodes and dependencies, ignoring any incompatibilities.
        for dist, node in ws:
            if not node.follow:
                continue

            if self.extras:
                for extra in dist.extras:
                    for dep, dep_node in self.filter(dist.requires((extra,)),
                                                     True):
                        node.extra_depend(extra, dep_node.name, dep.extras)

            for dep, dep_node in self.filter(dist.requires(), True):
                node.depend(dep_node.name, dep.extras)

        # Find roots, including one representative of each root cycle, by
        # removing all direct and implied dependencies of each node from the
        # set of root candidates.
        self.roots = set(node.name for spec, node in ws)

        # Consider candidates in alphabetic order for predictability.
        for candidate in sorted(self.roots):
            # When hitting a root cycle, all of its constituents except the
            # candidate being considered will be discarded. To prevent that
            # representative of the cycle from being discarded as a dependency
            # of each of the other cycle constituents, skip considering
            # dependencies of candidates that have already been discarded.
            if candidate not in self.roots:
                continue

            # Walking the candidate's dependencies needs to discard the
            # candidate temporarily in order to break infinite loops.
            self._walk(candidate)
            self.roots.add(candidate)

    def _walk(self, name):
        self.roots.remove(name)
        for dep in self[name]:
            if dep in self.roots:
                self._walk(dep)

    def filter(self, specifications, find=False):
        """Yield pairs of specifications and belonging nodes that should be
        included in the graph.

        Specifications are either requirements or distributions.

        """
        for spec in specifications:
            name = spec.project_name.lower()
            if not self.show(name):
                continue
            if find and not self.find(spec):
                continue
            if name not in self:
                self[name] = Node(self, spec)
            yield spec, self[name]

    def names(self, specifications):
        """Return a set of project names to be processed from an iterable of
        either requirements or distributions.
        """
        return set(node.name for spec, node in self.filter(specifications))

    def find(self, requirement):
        """Find a distribution in the working set associated with the graph.

        This is a convenience method to handle the VersionConflict exception.
        """
        try:
            return self.working_set.find(requirement)
        except pkg_resources.VersionConflict:
            return None

class Node(dict):
    """A graph node representing an egg and its dependencies.
    """

    dist = None
    compatible = True

    def __init__(self, graph, specification):
        self.graph = graph
        self.name = specification.project_name.lower()
        self.follow = self.graph.follow(self.name)
        self.extras_used = set()
        self.require(specification)
        self._requires = set()

    def __hash__(self):
        return hash(self.name)

    def require(self, specification):
        """Find a matching distribution in the working set.

        Returns whether a distribution compatible with the specification
        (requirement or another distribution) could be found.

        Raises ValueError if the specification is for a different project.
        """
        # Is this for us?
        if specification.project_name.lower() != self.name:
            raise ValueError("A %r node cannot satisfy a %r requirement." %
                             (self.name, specification.project_name))

        # Search even if the specification is already a distribution to make
        # sure it's active.
        if isinstance(specification, pkg_resources.Distribution):
            specification = specification.as_requirement()
        dist = self.graph.find(specification)

        # Store the distribution if it is found - there can be only one under
        # the same project name in the same working set.
        self.dist = self.dist or dist

        # Remember if at least one requirement could not be met.
        found = bool(dist)
        self.compatible &= found

        return found

    def depend(self, dep, dep_extras=()):
        """Store a dependency on another distribution.

        dep: name of a dependency

        """
        dep_edges = self.setdefault(dep, {})
        for dep_extra in dep_extras or (None,):
            dep_edges[dep_extra] = set()

    def extra_depend(self, extra, dep, dep_extras=()):
        """Store an extra dependency on another distribution.

        extra: name of an extra via which self depends on dep
        dep: name of a dependency

        """
        self.extras_used.add(extra)
        dep_edges = self.setdefault(dep, {})
        for dep_extra in dep_extras or (None,):
            # don't record extra dependencies that duplicate a non-extra one
            if dep_edges.get(dep_extra) != set():
                dep_edges.setdefault(dep_extra, set()).add(extra)

    def iter_deps(self):
        """Yield (name, source extras) pairs of dependencies.

        Source extras are extras of the distribution represented by self by
        way of which the respective named dependencies are connected.

        """
        for dep, dep_extras in self.items():
            extras = set()
            for src_extras in dep_extras.values():
                if src_extras == set():
                    yield dep, set()
                    break
                extras |= src_extras
            else:
                yield dep, extras

    def iter_deps_with_extras(self):
        """Yield (name, dep. extras, source extras) triples of dependencies.

        Source extras are extras of the distribution represented by self by
        way of which the respective named dependencies are connected.

        Dependency extras are those extras of each dependency that are being
        required by the distribution represented by self.

        """
        for dep, dep_extras in self.items():
            for extra, src_extras in dep_extras.items():
                yield dep, extra, src_extras


from functools import total_ordering
import sys
sys.path.append('../')
import cv2
import os
import numpy as np
import mtcnn
from mtcnn.utils import draw
from numpy.linalg import inv, lstsq
from numpy.linalg import matrix_rank as rank

#初始化人脸对齐前后的路径
source_dir = '/home/fxf/my_model/resnet50/resnet50_test/test_images'
save_dir=source_dir+"_aligned"
os.mkdir(save_dir)

#112*112的五点标准位置，如果是112*96，则左边一列的每个坐标减8
REFERENCE_FACIAL_POINTS = np.array([
    [38.29459953, 51.69630051],
    [73.53179932, 51.50139999],
    [56.02519989, 71.73660278],
    [41.54930115, 92.3655014 ],
    [70.72990036, 92.20410156]
], np.float32)

#使用最小二乘法进行仿射变换
def findNonreflectiveSimilarity(uv, xy, K=2):

    M = xy.shape[0]
    x = xy[:, 0].reshape((-1, 1))  # use reshape to keep a column vector
    y = xy[:, 1].reshape((-1, 1))  # use reshape to keep a column vector

    tmp1 = np.hstack((x, y, np.ones((M, 1)), np.zeros((M, 1))))
    tmp2 = np.hstack((y, -x, np.zeros((M, 1)), np.ones((M, 1))))
    X = np.vstack((tmp1, tmp2))

    u = uv[:, 0].reshape((-1, 1))  # use reshape to keep a column vector
    v = uv[:, 1].reshape((-1, 1))  # use reshape to keep a column vector
    U = np.vstack((u, v))

    # We know that X * r = U
    if rank(X) >= 2 * K:
        r, _, _, _ = lstsq(X, U)
        r = np.squeeze(r)
    else:
        raise Exception('cp2tform:twoUniquePointsReq')

    sc = r[0]
    ss = r[1]
    tx = r[2]
    ty = r[3]

    Tinv = np.array([
        [sc, -ss, 0],
        [ss,  sc, 0],
        [tx,  ty, 1]
    ])
    T = inv(Tinv)
    T[:, 2] = np.array([0, 0, 1])
    T = T[:, 0:2].T

    return T

#获取权重
pnet, rnet, onet = mtcnn.get_net_caffe('../output/converted')

# 创建检测器
detector = mtcnn.FaceDetector(pnet, rnet, onet, device='cuda:0')  #使用gpu时还需指定设备号:"cuda:0"     使用cpu:"cpu"

#特征提取
dir_class = next(os.walk(source_dir))[1]
img_class = next(os.walk(source_dir))[2]
dir_class.sort()
img_class.sort()

#对目录下的子目录照片进行人脸对齐
print("正在进行对齐运算中……")
success_num=0
fail_num=0
for dir in dir_class:
    index=1
    img_dir=os.path.join(source_dir,dir)
    img_dir_aligned=os.path.join(save_dir,dir)
    os.mkdir(img_dir_aligned)
    for img in os.listdir(img_dir):
        format=img.split(".")[1]
        img_rename="/"+dir+"_"+str(index)+"."+format
        img = cv2.imread(os.path.join(img_dir,img))
        boxes, landmarks = detector.detect(img, minsize=24)
        if(len(landmarks)==0):
            print(img_rename,"对齐运算失败")
            fail_num+=1
            continue
        landmark=landmarks[0]
        similar_trans_matrix = findNonreflectiveSimilarity(landmark.cuda().numpy().astype(np.float32), REFERENCE_FACIAL_POINTS)
        aligned_img = cv2.warpAffine(img.copy(), similar_trans_matrix, (112, 112))
        cv2.imwrite(img_dir_aligned+img_rename, aligned_img)
        print("文件已成功保存到",img_dir_aligned+img_rename)
        index+=1
    success_num=success_num+index

#对目录下的照片文件进行人脸对齐
for img in img_class:
    img_rename="/"+img
    img = cv2.imread(os.path.join(source_dir,img))
    boxes, landmarks = detector.detect(img, minsize=24)
    landmark=landmarks[0]
    similar_trans_matrix = findNonreflectiveSimilarity(landmark.cpu().numpy().astype(np.float32), REFERENCE_FACIAL_POINTS)
    aligned_img = cv2.warpAffine(img.copy(), similar_trans_matrix, (112, 112))
    cv2.imwrite(save_dir+img_rename, aligned_img)
    print("文件已成功保存到",save_dir+img_rename)
    success_num=success_num+1

print("人脸对齐运算完毕！")
print("成功:",success_num)
print("失败:",fail_num)


#coding:utf-8

import http.server

port = 80 #par defaut pour le port http
adress = ("", port) #comme c'est en local pas besoin de mettre le localhost

server = http.server.HTTPServer #ici on demarre le server

handler = http.server.CGIHTTPRequestHandler #un gestionnaire pour le http,mais foctionnel pour le script cgi
handler.cgi_directories = ["/"] #là ou il va execute les script on le met par defaut sur le meme ficheir

httpd = server(adress, handler) #ici on crée le server

print(f"server demarre sur le port {port}")

httpd.serve_forever()


# Copyright (C) 2022. Huawei Technologies Co., Ltd. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# ============================================================================

import os, re, sys
import pandas as pd
import argparse
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
import seaborn as sns
import logging

logger = logging.getLogger(__name__)

sns.set(style='whitegrid', font_scale=1.0, font='Georgia')
sns.set_context('talk')
# sns.set_palette(sns.color_palette("crest"))
sns.set_palette(sns.cubehelix_palette(start=.5, rot=-.5, reverse=False))
# sns.set_palette(sns.color_palette("Set2", 5))
# sns.set_palette(sns.color_palette("husl", 5))
# sns.set_palette(sns.color_palette("cubehelix"))
fig = plt.figure(figsize=(7, 4.6), dpi=300)

mapp = {'random': 'Random', 'competence-bias': 'TD-Var_comp', 'competence': 'TD_comp', 'annealing': 'TD_anneal',
        'annealing-bias': 'TD-Var_anneal', 'cross-review': 'CR_anneal', 'length': "Length", 'rarity': 'Rarity',
        'ppl': 'PPL'}

colors = sns.cubehelix_palette(start=.5, rot=-.5, reverse=False)

def get_scores(args):
    scores = {}
    current_curric = args.model_dir.split('/')[-1].split('_')[7]
    current_seed = args.model_dir.split('/')[-1].split('_')[2]

    for curric in args.curricula:
        filenames = []
        if curric == 'random':
            for seed in args.seeds:
                current = '_'.join(args.model_dir.split('/')[-1].split('_')[7:])
                model_dir = args.model_dir.replace(current, '')
                filenames.append(model_dir.replace(current_seed, str(seed)).strip('_'))

        elif curric == 'cross-review':
            for seed in args.seeds:
                current = '_'.join(args.model_dir.split('/')[-1].split('_')[7:])
                first_three = '_'.join(args.model_dir.split('/')[-1].split('_')[0:7])
                model_dir = args.model_dir.replace(current, f'annealing_{first_three}_cross-review')
                filenames.append(model_dir.replace(current_seed, str(seed)).strip('_'))

        elif curric == 'competence' or curric == 'competence-bias':
            for j, seed in enumerate(args.seeds):
                current = '_'.join(args.model_dir.split('/')[-1].split('_')[7:])
                first = '_'.join(args.model_dir.split('/')[-1].split('_')[0:7])
                model_dir = args.model_dir.replace(current, f'{curric}-0.01-0.9-{args.steps[j]}_{first}')
                filenames.append(model_dir.replace(current_seed, str(seed)).strip('_'))

        elif curric == 'length' or curric == 'rarity':
            for j, seed in enumerate(args.seeds):
                current = '_'.join(args.model_dir.split('/')[-1].split('_')[7:])
                first = '_'.join(args.model_dir.split('/')[-1].split('_')[0:7])
                model_dir = args.model_dir.replace(current, f'competence-0.01-0.9-{args.steps[j]}_{args.dataset_name}_heuristics-{curric}')
                filenames.append(model_dir.replace(current_seed, str(seed)).strip('_'))

        elif curric == 'ppl':
            for j, seed in enumerate(args.seeds):
                current = '_'.join(args.model_dir.split('/')[-1].split('_')[7:])
                first = '_'.join(args.model_dir.split('/')[-1].split('_')[0:7])
                model_dir = args.model_dir.replace(current,
                                                   f'competence-0.01-0.9-{args.steps[j]}_{args.dataset_name}_{args.model_name}_ppl-ppl')
                filenames.append(model_dir.replace(current_seed, str(seed)).strip('_'))

        else:
            for seed in args.seeds:
                model_dir = args.model_dir.replace(current_curric, curric)
                filenames.append(model_dir.replace(current_seed, str(seed)))

        scores[curric] = {}
        scores[f'{curric}_steps'] = {}
        scores[f'{curric}_stdev'] = {}

        for filename in filenames:
            scores[curric].update({filename: []})
            scores[f'{curric}_steps'].update({filename: []})

            with open(os.path.join(filename, 'train.log'), 'r') as infile:
                for line in infile:
                    if re.match(r".* val-langs .*", line):

                        if 'ACCURACY = ' in line:
                            acc = line.rstrip().split('|')[2].strip('ACCURACY =')
                            step = line.rstrip().split('|')[0].split('-')[-1].strip(' step ')

                            scores[curric][filename] += [float(acc)]
                            scores[f'{curric}_steps'][filename] += [int(step)]

        cutoff_steps = np.min([len(scores[f'{curric}_steps'][f]) for f in filenames])
        tmp_scores = np.vstack([np.array(scores[curric][f])[:cutoff_steps] for f in filenames])

        # if curric == 'cross-review':
            # tmp_scores = tmp_scores[:2, :]
            # print(tmp_scores)

        scores[curric] = np.mean(tmp_scores, axis=0)
        scores[f'{curric}_max'] = np.max(tmp_scores, axis=0)
        scores[f'{curric}_min'] = np.min(tmp_scores, axis=0)

        scores[f'{curric}_steps'] = [scores[f'{curric}_steps'][f][:cutoff_steps] for f in filenames][0]

    return scores

def plot_curves(args, acc_scores):
    max_random = 0
    max_random_step = 0
    n = 8
    k = 2
    markers = ['>', '<', 'o', '^', 's']
    for curric in args.curricula[:-1]:
        # plot curric
        plt.plot(acc_scores[f'{curric}_steps'][::n], acc_scores[curric][::n], label=mapp[curric],
                 color=colors[k], marker=markers[k], markersize=5)
        plt.fill_between(acc_scores[f'{curric}_steps'][::n], acc_scores[f'{curric}_min'][::n], acc_scores[f'{curric}_max'][::n],
                         alpha=0.3)
        k += 2

    # plot random
    plt.plot(acc_scores['random_steps'][::n], acc_scores['random'][::n], label='Random',
             color='tab:red')
    plt.fill_between(acc_scores['random_steps'][::n], acc_scores['random_min'][::n], acc_scores['random_max'][::n],
                     alpha=0.3,
                     facecolor='tab:red')

    for i, j in zip(acc_scores['random'], acc_scores['random_steps']):
        if i > max_random:
            max_random = i
            max_random_step = j

    max_curric = 0
    max_curric_step = 0
    max_curric_name = 'random'
    flag = False
    all_best_curric = []
    plotted = []
    plotted_steps = []
    for k, curric in enumerate(args.curricula):
        print(curric)
        for c_perf, c_steps in zip(acc_scores[curric], acc_scores[f'{curric}_steps']):
            # best curriculum
            if c_perf > max_curric:
                max_curric = c_perf
                max_curric_step = c_steps
                max_curric_name = curric

            # closest curriculum with less steps
            if ((c_perf >= max_random) and (c_steps <= max_random_step) and curric not in plotted) or \
                    ((c_perf >= max_random) and (c_steps > max_random_step) and curric not in plotted):
                print(c_perf, c_steps, curric)

                flag = True
                plotted.append(curric)
                plotted_steps.append(c_steps)

            if (c_perf >= max_random) and (c_steps < max_random_step):
                all_best_curric += [{'perf': c_perf,
                                     'steps': c_steps,
                                     'name': curric,
                                     'time': np.round(c_steps/max_random_step, 4),
                                     'color': plt.gca().lines[k].get_color()}]

    logger.info(' Best curricula found')
    for abc in sorted(all_best_curric, key=lambda d: d['perf'], reverse=True):
        logger.info('\t\t'.join([str(b) for a, b in abc.items() if a != 'color']))

    if not flag:  # no better point found -- use max curric value
        print('No better point detected')
        max_curric = max_curric
        max_curric_step = max_curric_step
        max_curric_name = max_curric_name
    else:
        pass
        # sorted_curric = sorted(all_best_curric, key=lambda d: d['time'], reverse=False)
        # close_curric = float(sorted_curric[0]['perf'])
        # close_curric_step = int(sorted_curric[0]['steps'])
        # close_curric_name = sorted_curric[0]['name']

    logger.info(f' --> Maximum Random:  {max_random} @ {max_random_step}')
    # logger.info(f' --> Closest CURRICULA ({close_curric_name}): {close_curric} @ {close_curric_step/max_random_step}')
    logger.info(f' --> Maximum CURRIC ({max_curric_name}): {max_curric} @ {max_curric_step/max_random_step}')

    # =============== PLOT =================== #
    sns.despine()
    plt.ylabel('Accuracy (%)')
    plt.xlabel('Training Steps')
    plt.xlim([0, max(plotted_steps) + 100])

    if args.dataset_name in ['pawsx']:
        # plt.title('PAWS-X')
        plt.ylabel('PAWS-X\nAccuracy (%)')
        plt.ylim([76, 88])
        plt.xlim([0, 15000])
        plt.yticks(np.arange(76, 89, 2))

    elif args.dataset_name in ['xnli']:
        plt.ylabel('XNLI\nAccuracy (%)')
        plt.ylim([64, 76])
        plt.yticks(np.arange(64, 77, 2))
        # plt.yticks(np.arange(66, 77, 2))
        # plt.title(args.dataset_name.upper())
        plt.xlim([0, 100000])
        plt.legend(loc='upper center', fontsize=12, ncol=3, bbox_to_anchor=(0.5, 1.3))

    elif args.dataset_name == 'mldoc':
        plt.ylabel('MLDoc\nAccuracy (%)')
        # plt.title('MLDoc')
        plt.ylim([70, 88])
        plt.yticks(np.arange(70, 89, 3))
        plt.xlim([0, 1400])

    else:
        plt.ylabel('XCOPA\nAccuracy (%)')
        plt.ylim([52, 64])
        plt.xlim([0, 17500])
        plt.yticks(np.arange(52, 65, 2))

    ax = plt.gca()
    ax.xaxis.grid()
    ax.xaxis.set_major_formatter(matplotlib.ticker.FuncFormatter(lambda x, pos: '{:,.0f}'.format(x / 1000) + 'K'))

    plot_file = f"../plots/{args.dataset_name}_smoothed.png"
    logger.info(f"Saving plot in {plot_file}")
    fig.tight_layout()
    fig.savefig(plot_file, bbox_inches="tight")
    fig.savefig(plot_file.replace('.png', '.pdf'), bbox_inches="tight")

def main(args):
    scores = get_scores(args)
    plot_curves(args, scores)

if __name__ == '__main__':
    logging.basicConfig(
        format='%(asctime)s - %(levelname)s - %(name)s - %(message)s',
        datefmt='%d/%m/%Y %H:%M:%S',
        level=logging.INFO
    )

    parser = argparse.ArgumentParser()
    parser.add_argument('--curricula', nargs='*', help='Curricula to test',
                        default=[#'annealing',
                                 #'annealing-bias',
                                 'cross-review',
                                 #'competence',
                                 'competence-bias',
                                 #'length',
                                 #'rarity',
                                 #'ppl',
                                 'random'])
    parser.add_argument('--model_dir', type=str)
    parser.add_argument('--model_name', type=str, default='xlm-roberta-base')
    parser.add_argument('--dataset_name', type=str)
    parser.add_argument('--steps', type=int, help='baseline best # steps', nargs='*')
    parser.add_argument('--seeds', type=int, nargs='*', default=['123', '456', '789'], help='Seeds to test')
    args = parser.parse_args()

    if args.model_dir.endswith('/'):
        args.model_dir = '/'.join(args.model_dir.split('/')[:-1])

    main(args)


"""
Given a string, are all characters unique? True/False
"""

def is_unique_char(s):
    seen = set()
    for char in s:
        if char in seen:
            return False
        seen.add(char)
    return True

print(is_unique_char("Peter"))


import dateparser
import logging
import datetime

from django.template.loader import render_to_string
from django.core.mail import send_mail
from django.conf import settings
from django.contrib.auth import get_user_model

from notifhain.event.models import Room, Slot, Artist, DancefloorEvent
from notifhain.event.publisher import PublishToRR

logger = logging.getLogger('scrapy')

class DjangoPipeline(object):

    def item_to_model(self, item):
        model_class = getattr(item, 'django_model')
        if not model_class:
            raise TypeError("Item is not a `DjangoItem` or is misconfigured")

        return item.instance

    def get_or_create(self, model):
        model_class = type(model)
        created = False

        # Normally, we would use `get_or_create`. However, `get_or_create` would
        # match all properties of an object (i.e. create a new object
        # anytime it changed) rather than update an existing object.
        #
        # Instead, we do the two steps separately
        try:
            # We have no unique identifier at the moment; use the url for now.
            obj = model_class.objects.get(url=model.url)
        except model_class.DoesNotExist:
            created = True
            obj = model  # DjangoItem created a model for us.

        return (obj, created)

    def update_model(self, django_model, item, commit=True):
        pk = django_model.pk

        # item_dict = model_to_dict(item)
        item_dict = item.__dict__
        for (key, value) in item_dict.items():
            setattr(django_model, key, value)

        setattr(django_model, 'pk', pk)

        if commit:
            django_model.save()

        return django_model

    class Meta:
        abstract = True

class ProgramPipeline(DjangoPipeline):
    def process_item(self, item, spider):
        try:
            item_model = self.item_to_model(item)
            item_model.month = dateparser.parse(item["name"], "%Y-%m")
        except TypeError:
            return item

        model, created = self.get_or_create(item_model)
        self.update_model(model, item_model)
        logger.info("Program %s %s" % (item_model.name, created and 'created' or 'updated'))

        return item

class EventPipeline(DjangoPipeline):
    def process_item(self, item, spider):
        try:
            item_model = self.item_to_model(item)
            item_model.event_date = dateparser.parse(item["date_string"])
        except TypeError:
            return item

        model, created = self.get_or_create(item_model)
        # reset all state values
        # TODO should be handled differently, maybe a separte state model would be good
        item_model.is_completed = model.is_completed
        item_model.has_timetable = model.has_timetable
        item_model.is_notification_send = model.is_notification_send
        item_model.is_posted_to_rr = model.is_posted_to_rr
        item_model.timetable_updated = model.timetable_updated
        item_model.custom_appendix = model.custom_appendix
        self.update_model(model, item_model)
        logger.info("Event %s %s" % (item_model.name, created and 'created' or 'updated'))

        return item

class EventDetailsPipeline(DjangoPipeline):
    def process_item(self, event_details_item, spider):
        try:
            item_model = self.item_to_model(event_details_item)
            item_model.event_date = dateparser.parse(
                "%s %s" % (event_details_item["date_string"],
                event_details_item["time_string"]),
                settings={'RETURN_AS_TIMEZONE_AWARE': True}
            )
        except TypeError:
            return event_details_item

        event_details, created = self.get_or_create(item_model)
        self.update_model(event_details, item_model)
        logger.info("EventDetail %s %s" % (item_model.name, created and 'created' or 'updated'))

        # delete all existing objects
        Slot.objects.filter(event_details=event_details).delete()
        for room_item in event_details_item["rooms"]:
            room, created = Room.objects.get_or_create(name=room_item["name"])
            for slot_item in room_item["slots"]:
                self.process_slot(slot_item, room, event_details, spider)
        event = event_details.event
        event.is_completed = event_details_item["is_completed"]
        event.has_timetable = event_details_item["has_timetable"]
        if not event.is_completed and datetime.datetime.now().date() > event.event_date:
            event.is_completed = True
        if event.is_completed and not event.timetable_updated:
            event.timetable_updated = datetime.datetime.now()
        event.save()

        return event_details_item

    def process_slot(self, slot_item, room, event_details, spider):
        try:
            item_model = self.item_to_model(slot_item)
        except TypeError:
            return slot_item
        item_model.room = room
        item_model.event_details = event_details
        # add artists to slot
        item_model.save()
        for artist in slot_item["artists"]:
            artist, created = Artist.objects.get_or_create(name=artist)
            item_model.artists.add(artist)
        return slot_item

    def close_spider(self, spider):
        if spider.send_email:
            today = datetime.date.today()
            next_monday = today + datetime.timedelta(days=-today.weekday(), weeks=1)
            events = DancefloorEvent.objects.filter(has_timetable=True, is_notification_send=False, event_details__event_date__lte=next_monday)
            for event in events:
                logger.info("send_timetable_email: " + event.event_details.name)
                msg_plain = render_to_string('event-timetable-online.html', {'event': event})
                send_emails_to = get_user_model().objects.all().values_list('email', flat=True)
                send_mail(
                    'Timetable online: %s %s' % (event.name, event.event_date),
                    msg_plain,
                    settings.DEFAULT_FROM_EMAIL,
                    send_emails_to,
                    fail_silently=False,
                )
                msg_plain = render_to_string('klubnacht-tt-rr.html', {'event': event})
                send_mail(
                    event.get_title(),
                    msg_plain,
                    settings.DEFAULT_FROM_EMAIL,
                    send_emails_to,
                    fail_silently=False,
                )
                event.is_notification_send = True
                event.save()
        if spider.publish_to_rr:
            # post possible new klubnacht timetable to RR
            publisher = PublishToRR()
            publisher.publish(do_submit=True)


# https://leetcode.com/problems/reverse-bits/

class Solution(object):
    def reverseBits(self, n):
        """
        :type n: int
        :rtype: int
        """
        num = 0
        for x in range(0, 32):
            num += (n & 1) * (1 << (31 -x) )
            n >>= 1
        return num


class FiniteStateTransducer :
    def __init__(self, states, inputs, outputs, transitions, initial_state, final_states) :
        self.states = states
        self.inputs = inputs
        self.outputs = outputs
        self.transitions = transitions
        self.initial_state = initial_state
        self.final_states = final_states

    def __str__(self) :
        return "FiniteStateTransducer(\n\
            states={}\n\
            inputs={}\n\
            outputs={}\n\
            transitions={}\n\
            initial_state={}\n\
            final_states={})".format(self.states, self.inputs, self.outputs, self.transitions, self.initial_state, self.final_states)

    def add_state(self, state) :
        if state not in self.states :
            self.states.append(state)

    def remove_state(self, state) :
        if state not in self.states :
            raise ValueError("Le state {} n'existe pas".format(state))
        else :
            self.states.remove(state)

    def add_input(self, input) :
        if input not in self.inputs :
            self.inputs.append(input)

    def remove_input(self, input) :
        if input not in self.inputs :
            raise ValueError("L'input {} n'existe pas".format(input))
        else :
            self.inputs.remove(input)

    def add_output(self, output) :
        if output not in self.outputs :
            self.outputs.append(output)

    def remove_output(self, output) :
        if output not in self.outputs :
            raise ValueError("L'output {} n'existe pas".format(output))
        else :
            self.outputs.remove(output)

    def add_transition(self, transition) :
        #transition should be in this format {'init_state': 'q0', 'input': 'a', 'output': '0', 'next_state': 'q1'}
        if not 'init_state' in transition or not 'input' in transition or not 'output' in transition or not 'next_state' in transition :
            raise ValueError("La transition doit être de la forme {'init_state': 'q0', 'input': 'a', 'output': '0', 'next_state': 'q1'}")

        init_state = transition['init_state']
        input = transition['input']
        output = transition['output']
        next_state = transition['next_state']

        if init_state not in self.states :
            raise ValueError("Le state {} n'existe pas".format(transition['init_state']))
        elif input not in self.inputs :
            raise ValueError("L'input {} n'existe pas".format(transition['input']))
        elif output not in self.outputs :
            raise ValueError("L'output {} n'existe pas".format(transition['output']))
        elif next_state not in self.states :
            raise ValueError("Le state {} n'existe pas".format(transition['next_state']))
        else :
            if init_state not in self.transitions : #check if a transition from this state does not already exist
                self.transitions[init_state] = {input: {'output': output, 'next_state': next_state}}
                return
            if input not in self.transitions[init_state] : #check if a transition from this state with this input does not already exist
                self.transitions[init_state][input] = {'output': output, 'next_state': next_state}
                return
            else :
                raise ValueError("Une transition existe déjà depuis le state {} avec l'input {}".format(init_state, input))

    def remove_transition(self, transition) :
        #transition should be in this format {'init_state': 'q0', 'input': 'a', 'output': '0', 'next_state': 'q1'}
        if not 'init_state' in transition or not 'input' in transition or not 'output' in transition or not 'next_state' in transition :
            raise ValueError("La transition doit être de la forme {'init_state': 'q0', 'input': 'a', 'output': '0', 'next_state': 'q1'}")

        init_state = transition['init_state']
        input = transition['input']
        output = transition['output']
        next_state = transition['next_state']

        if init_state not in self.transitions :
            raise ValueError("Aucune transition existe depuis le state {}".format(init_state))
        if input not in self.transitions[init_state] :
            raise ValueError("Aucune transition existe depuis le state {} avec l'input {}".format(init_state, input))
        else :
            del self.transitions[init_state][input]

    def change_initial_state(self, state) :
        if state not in self.states :
            raise ValueError("Le state {} n'existe pas".format(state))
        else :
            self.initial_state = state

    def add_final_state(self, state) :
        if state not in self.states :
            raise ValueError("Le state {} n'existe pas".format(state))
        else :
            self.final_states.append(state)

    def remove_final_state(self, state) :
        if state not in self.states :
            raise ValueError("Le state {} n'existe pas".format(state))
        elif state not in self.final_states :
            raise ValueError("Le state {} n'est pas un état final".format(state))
        else :
            self.final_states.remove(state)

    def get_current_inputs(self, state) :
        inputs = []
        for input in self.inputs :
            if input in self.transitions[state] :
                inputs.append(input)
        return inputs

    def is_final_state(self, state) :
        return state in self.final_states


#!/usr/bin/env python

import json
import requests
import sys
import subprocess
import argparse

VERSION='1.06'
def show_version(): print(VERSION)

class Nagios:
    ok          = (0, 'OK')
    warning     = (1, 'WARNING')
    critical    = (2, 'CRITICAL')
    unknown     = (3, 'UNKNOWN')

nagios = Nagios()

def nagiosExit(exit_code,msg=None):
    """Exit script with a str() message and an integer 'nagios_code', which is a sys.exit level."""
    if msg:
        print(exit_code[0],exit_code[1] + " - " + str(msg))
    sys.exit(exit_code[0])

def uri_request(uri, expected_response_format=None, arg0=None, arg1=None, headers_only=False):
    try:
        if headers_only == True:  request = requests.head(uri)
        else: request = requests.get(uri)

        if request.status_code > 200:
            nagiosExit(nagios.critical, str("Status code: {0} :: {1}".format(request.status_code, uri)))
        else:
            if expected_response_format == 'JSON':
                try:
                    json_response = json.loads(request.text)
                except ValueError:
                    nagiosExit(nagios.critical, str("Could not decode valid JSON at URI: {0}".format(uri)))
                check_json_response(json_response, check_json_key=arg0, check_json_value=arg1)
            else:
                text_response = str(request.content) #be careful on strings that could look like other types
                check_text_response(text_response, arg0)

    except requests.ConnectionError : nagiosExit(nagios.critical,str("Error loading :: {0}".format(uri)))
    except requests.Timeout : nagiosExit(nagios.critical,str("Timed out :: {0}".format(uri)))
    except requests.HTTPError : nagiosExit(nagios.critical,str("Invalid HTTP response :: {0}".format(uri)))
    except requests.TooManyRedirects: nagiosExit(nagios.critical,str("Too many redirects :: {0}".format(uri)))

def check_json_response(json_response,check_json_key,check_json_value):
    """ check a json key/value pair against a HTTP response.
    match returns nagiosExit(0), otherwise nagiosExit(1) is returned.
    """
    try:
        if json_response[check_json_key] != check_json_value:
            returnValue = "Expected '{0}:{1}' ; Received '{2}'".format(check_json_key, check_json_value, json_response[check_json_key])
            nagiosExit(nagios.critical, str(returnValue))
        else:
            nagiosExit(nagios.ok)
    except KeyError:
        ''' key could not be looked up in the response data from the URI '''
        nagiosExit(nagios.critical, str("KeyError :: Failed to find JSON key: {0}").format(check_json_value))

def check_text_response(text_response,expected_response_text):
    """ Simply do an equality comparison between two objects.  Caution, may do 'hilarious' things on binary data. """
    if str(text_response) != str(expected_response_text):
        returnValue = "Expected {0} ; Received: {1}".format(expected_response_text, text_response)
        nagiosExit(nagios.critical,str(returnValue))
    else:
        nagiosExit(nagios.ok)

if __name__ == "__main__":

    parser = argparse.ArgumentParser(description=str("A Nagios-ready python script for comparing data retrieved from an HTTP source.\n ./check_http_response.py --host 'https://example.org/status' --json 'status' 'ok'"))
    parser.add_argument('-v', '--version', action="store_true", help='Show script version and exit')
    parser.add_argument('--server', '--host', help="specify a target host", type=str)
    parser.add_argument('--headers_only', help="retrieve only the headers", action='store_true', default=False)

    group = parser.add_mutually_exclusive_group()
    group.add_argument('--json', nargs=2, help="compares against a JSON key/value pair from a URI", type=str)
    group.add_argument('--text', nargs=1, help="compares against a plain text response from a URI")

    args = parser.parse_args()

    if args.version:
        show_version()
    if args.json:
        uri_request(uri=args.server, expected_response_format='JSON', arg0=args.json[0], arg1=args.json[1],
                headers_only=args.headers_only)
    if args.text:
        uri_request(uri=args.server, expected_response_format='text', arg0=str(args.text[0]),
                headers_only=args.headers_only)
    if not args.version or args.json or args.text:
        parser.print_help()
        sys.exit(0)


from rest_framework import serializers

from api.user.models.Department import Department
from api.user.models.Teacher import Teacher
from api.user.models.User import User
from api.user.serializers.User import UserListSerializer

class UserMinSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = ['identification_number', 'name', 'last_name']

class DepartmentSerializer(serializers.ModelSerializer):
    class Meta:
        model = Department
        fields = ['id', 'number', 'name']

class TeacherListSerializer(serializers.ModelSerializer):
    person = UserListSerializer()
    department = DepartmentSerializer()

    class Meta:
        model = Teacher
        fields = ['id','number', 'person', 'department']

class TeacherSerializer(serializers.ModelSerializer):

    class Meta:
        model = Teacher
        fields = ['number', 'person', 'department']


import pytest
import cv2
from plantcv.plantcv import rgb2gray_cmyk

def test_rgb2gray_cmyk(test_data):
    """Test for PlantCV."""
    # Read in test data
    img = cv2.imread(test_data.small_rgb_img)
    gray_img = rgb2gray_cmyk(rgb_img=img, channel="c")
    # Assert that the output image has the dimensions of the input image but is only a single channel
    assert img.shape[:2] == gray_img.shape

def test_rgb2gray_cmyk_bad_channel(test_data):
    """Test for PlantCV."""
    # Read in test data
    img = cv2.imread(test_data.small_rgb_img)
    with pytest.raises(RuntimeError):
        # Channel S is not in CMYK
        _ = rgb2gray_cmyk(rgb_img=img, channel="s")


n = int(input())
rank = list(map(int, input().split()))

ans = [0] * n

for i in range(n):
    cnt = ans[:i].count(0)
    ans[i] = rank[i] + cnt + 1
    for j in range(i):
        if ans[j] >= ans[i]:
            ans[j] += 1

print(*ans)


import skimage
import numpy as np
import matplotlib.pyplot as plt
import pywt
from PIL import Image, ImageCms
import cv2

# Perceptual image hash based on the work of
#  Vadlamudi, Lokanadham Naidu and Vaddella, Rama and Devara, Vasumathi

def sift_dwt_hash(image_path):
    # In this step, the input RGB color image () is resized to  pixels using bi-cubic interpolation
    img = Image.open(image_path).convert("RGB")
    img = img.resize((512,512),Image.BICUBIC)
    img = np.array(img)

    # Convert to Lab
    img = cv2.cvtColor(img,cv2.COLOR_BGR2LAB)

    # # Gaussian low pas filter
    img = np.array(img)
    kernel = np.ones((5,5),np.float32)/25
    img = cv2.filter2D(img,-1,kernel)

    L,A,B=cv2.split(img)

    # # # Get keypoints from the L dimension and select the n best keypoints measured in SIFT algorithm as the local contrast
    sift = cv2.xfeatures2d.SIFT_create(nfeatures=16)
    key_points, des1 = sift.detectAndCompute(L,None)

    # Get kernel of P*P around keypoints
    rois = []
    P = 64
    for kp in key_points:
        y = int(key_points[0].pt[1])
        x = int(key_points[0].pt[0])
        up = int(y - (P/2))
        low = int(y + (P/2))
        left = int(x - (P/2))
        right = int(x + (P/2))
        cropped_img = L[up:low, left:right]

        rois.append(cropped_img)

    # Get DWT representation of the rois
    dwt_representations = []
    level = 2
    for roi in rois:
        dwt_res = pywt.wavedec2(roi,'db1', level = level)
        cA = dwt_res[0]
        dwt_representations.append(cA)
    len(dwt_representations)
    # print(dwt_representations[0].shape)

    # reshape the DWT representation
    Q = len(dwt_representations) * (P / 2**level)
    R = (P/2**level)
    dwt_representations[0].shape
    qr_matrix = dwt_representations[0]
    i = 0
    for dwt in dwt_representations[1:]:
            qr_matrix = np.concatenate((qr_matrix,dwt), axis = 0)

    # # # Get the row wise averages
    row_wise_averages = []
    for row in qr_matrix:
        row_wise_averages.append(np.mean(row))
    row_wise_averages

    # EXPERIMENT: subtract minimum value
    minimum = min(row_wise_averages)
    placeholder = []
    for element in row_wise_averages:
        element = element - minimum
        placeholder.append(element)
    row_wise_averages = placeholder

    # TODO: GET THE RIGHT RANDOM PERMUTATION
    # row_wise_averages = np.random.permutation(row_wise_averages)

    # MAX average the list
    row_wise_averages  = [float(i)/max(row_wise_averages) for i in row_wise_averages]

    # Convert to bit hash
    hash_result = []
    for i in row_wise_averages:
        if i > 0.5:
            hash_result.append(1)
        else:
            hash_result.append(0)
    hash_string = ''
    for hash_element in hash_result:
        hash_string += str(hash_element)
    # return string
    return hash_string


import re
from urllib import robotparser
from urllib.parse import urljoin, urlparse
import requests

USER_AGENT = "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/76.0.3809.132 Safari/537.36"

def download(url, num_retries=2, user_agent=USER_AGENT, proxies=None):
    print('Downloading:', url)
    headers = {'User-Agent': user_agent}
    try:
        resp = requests.get(url, headers=headers, proxies=proxies)
        html = resp.text
        if resp.status_code >= 400:
            print('Download error:', resp.text)
            html = None
            if num_retries and 500 <= resp.status_code < 600:
                # recursively retry 5xx HTTP errors
                return download(url, num_retries - 1)
    except requests.exceptions.RequestException as e:
        print('Download error:', e)
        html = None
    return html

def get_robots_parser(robots_url):
    " Return the robots parser object using the robots_url "
    rp = robotparser.RobotFileParser()
    rp.set_url(robots_url)
    rp.read()
    return rp

def get_links(html):
    webpage_regex = re.compile("""<a[^>]+href=["'](.*?)["']""", re.IGNORECASE)
    return webpage_regex.findall(html)

def jsonify(list1, list2):
    return {k:v for k,v in list(zip(list1, list2))}