"""A handler for the HTTP/2 protocol"""

import asyncio
from asyncio import Task
import functools
from typing import (
    Awaitable,
    Callable,
    List,
    MutableMapping,
    Optional,
    Tuple,
    cast
)

import h2.connection
import h2.events
import h2.settings

from .types import (
    HttpRequest,
    HttpRequestBody,
    HttpResponse,
    HttpResponseConnection,
    HttpResponseBody,
    HttpDisconnect,
    HttpRequests,
    HttpResponses
)

from .http_protocol import HttpProtocol
from .asyncio_events import ResetEvent

class H2Protocol(HttpProtocol):
    """An HTTP/2 protocol handler"""

    READ_NUM_BYTES = 4096

    def __init__(
            self,
            reader: asyncio.StreamReader,
            writer: asyncio.StreamWriter
    ) -> None:
        """Initialise an HTTP/2 protocol

        Args:
            reader (asyncio.StreamReader): The reader
            writer (asyncio.StreamWriter): The writer
        """
        super().__init__(reader, writer)
        self.h2_state = h2.connection.H2Connection()
        self.window_update_event: MutableMapping[int, ResetEvent] = {}
        self.initialized = False
        self.responses: asyncio.Queue = asyncio.Queue()
        self.response_task: Optional[asyncio.Task] = None
        self.pending: List[Task] = []
        self.on_close: Optional[Callable[[], Awaitable[None]]] = None
        self.h2_events: List[h2.events.Event] = []

    async def send(
            self,
            message: HttpRequests
    ) -> None:
        message_type: str = message['type']

        if message_type == 'http.request':
            await self._send_request(cast(HttpRequest, message))
        elif message_type == 'http.request.body':
            await self._send_request_body(cast(HttpRequestBody, message))
        elif message_type == 'http.disconnect':
            if self.on_close:
                await self.on_close()
        else:
            raise RuntimeError(f'unknown request type: {message_type}')

    async def receive(self) -> HttpResponses:
        return await self.responses.get()

    async def _send_request(
            self,
            message: HttpRequest
    ) -> None:
        # Start sending the request.
        if not self.initialized:
            self._initiate_connection()

        stream_id = await self._send_headers(
            message['scheme'],
            message['host'],
            message['path'],
            message['method'],
            message.get('headers', [])
        )
        self.window_update_event[stream_id] = ResetEvent()
        http_response_connection: HttpResponseConnection = {
            'type': 'http.response.connection',
            'http_version': 'h2',
            'stream_id': stream_id
        }
        await self.responses.put(http_response_connection)

        body = message['body']
        more_body = message['more_body']

        if body is not None:
            await self._send_request_data(stream_id, body, more_body)
        else:
            await self._end_stream(stream_id)

        self.response_task = asyncio.create_task(self._receive_response())
        self.on_close = functools.partial(
            self._response_closed, stream_id=stream_id
        )

    async def _send_request_body(
            self,
            message: HttpRequestBody
    ) -> None:
        assert message['stream_id'] is not None, "stream_id required for http/2"
        await self._send_request_data(
            message['stream_id'],
            message['body'],
            message.get('more_body', False)
        )

    def _create_task(self, coroutine) -> Task:
        task = asyncio.create_task(coroutine)
        self.pending.append(task)
        task.add_done_callback(self._reap_task)
        return task

    def _reap_task(self, task: Task):
        self.pending.remove(task)

    def _initiate_connection(self) -> None:
        self.h2_state.local_settings = h2.settings.Settings(
            client=True,
            initial_values={
                h2.settings.SettingCodes.ENABLE_PUSH: 0,
                h2.settings.SettingCodes.MAX_CONCURRENT_STREAMS: 100,
                h2.settings.SettingCodes.MAX_HEADER_LIST_SIZE: 65536,
            },
        )

        del self.h2_state.local_settings[
            h2.settings.SettingCodes.ENABLE_CONNECT_PROTOCOL
        ]

        self.h2_state.initiate_connection()
        self.h2_state.increment_flow_control_window(2 ** 24)
        data_to_send = self.h2_state.data_to_send()
        self.writer.write(data_to_send)
        self.initialized = True

    async def _send_headers(
            self,
            scheme: str,
            host: str,
            path: str,
            method: str,
            headers: List[Tuple[bytes, bytes]]
    ) -> int:
        stream_id = self.h2_state.get_next_available_stream_id()
        headers = [
            (b":method", method.encode("ascii")),
            (b":authority", host.encode("ascii")),
            (b":scheme", scheme.encode("ascii")),
            (b":path", path.encode("ascii")),
        ] + [
            (name, value)
            for name, value in headers
            if name not in (b'host', b'transfer-encoding')
        ]

        self.h2_state.send_headers(stream_id, headers)
        data_to_send = self.h2_state.data_to_send()
        self.writer.write(data_to_send)
        await self.writer.drain()

        return stream_id

    async def _send_request_data(
            self,
            stream_id: int,
            body: bytes,
            more_body: bool
    ) -> None:
        await self._send_data(stream_id, body, more_body)

    async def _send_data(
            self,
            stream_id: int,
            data: bytes,
            more_body: bool
    ) -> None:
        while data:
            window_size = self.h2_state.local_flow_control_window(stream_id)
            chunk_size = min(
                len(data),
                window_size,
                self.h2_state.max_outbound_frame_size
            )
            if chunk_size == 0:
                await self.window_update_event[stream_id].wait()
            else:
                chunk, data = data[:chunk_size], data[chunk_size:]
                self.h2_state.send_data(
                    stream_id,
                    chunk,
                    end_stream=not more_body
                )
                data_to_send = self.h2_state.data_to_send()
                self.writer.write(data_to_send)
                await self.writer.drain()

    async def _end_stream(self, stream_id: int) -> None:
        self.h2_state.end_stream(stream_id)
        data_to_send = self.h2_state.data_to_send()
        self.writer.write(data_to_send)
        await self.writer.drain()

    async def _receive_response(self) -> None:

        event: Optional[h2.events.Event] = None
        while not isinstance(event, h2.events.ResponseReceived):
            event = await self._receive_event()

        status_code = 200
        headers: List[Tuple[bytes, bytes]] = []
        for name, value in event.headers:
            if name == b":status":
                status_code = int(value)
            elif not name.startswith(b":"):
                headers.append((name, value))

        http_response: HttpResponse = {
            'type': 'http.response',
            'acgi': {
                'version': "1.0"
            },
            'http_version': '2',
            'status_code': status_code,
            'headers': headers,
            'more_body': event.stream_ended is None,
            'stream_id': event.stream_id

        }
        await self.responses.put(http_response)

        is_connected = True
        while is_connected:
            event = await self._receive_event()
            if isinstance(event, h2.events.DataReceived):
                self.h2_state.acknowledge_received_data(
                    event.flow_controlled_length, event.stream_id
                )
                http_response_body: HttpResponseBody = {
                    'type': 'http.response.body',
                    'body': event.data,
                    'more_body': event.stream_ended is None,
                    'stream_id': event.stream_id
                }
                await self.responses.put(http_response_body)
            elif isinstance(event, (h2.events.StreamEnded, h2.events.StreamReset)):
                http_disconnect: HttpDisconnect = {
                    'type': 'http.disconnect',
                    'stream_id': event.stream_id
                }
                await self.responses.put(http_disconnect)
                is_connected = False

    async def _receive_event(self) -> h2.events.Event:
        while not self.h2_events:
            data = await self.reader.read(self.READ_NUM_BYTES)
            events = self.h2_state.receive_data(data)
            for event in events:
                if isinstance(event, h2.events.WindowUpdated):
                    if event.stream_id == 0:
                        for update_event in self.window_update_event.values():
                            update_event.set()
                    else:
                        self.window_update_event[event.stream_id].set()

                self.h2_events.append(event)

            data_to_send = self.h2_state.data_to_send()
            self.writer.write(data_to_send)
            await self.writer.drain()

        return self.h2_events.pop(0)

    async def _response_closed(self, stream_id: int) -> None:
        del self.window_update_event[stream_id]

        # Drain responses to allow the socket to close cleanly.
        if self.response_task is not None:
            await self.response_task
            while self.responses.qsize():
                await self.responses.get()

        for task in self.pending:
            if not task.done():
                try:
                    task.cancel()
                    await task
                except asyncio.CancelledError:
                    pass

        self.writer.close()
        await self.writer.wait_closed()


# -*- coding: utf-8 -*-
from setuptools import setup, find_packages
import os

HERE = os.path.abspath(os.path.dirname(__file__))
README = open(os.path.join(HERE, 'README.rst')).read()
CHANGELOG = open(os.path.join(HERE, 'CHANGELOG.rst')).read()

VERSION = '0.0.1'

setup(name='trelloapi',
      version=VERSION,
      description="autogenerated trello API client for python",
      long_description=README + '\n\n' + CHANGELOG,
      classifiers=[
          'Programming Language :: Python :: 3.4',
          'Development Status :: 4 - Beta',
          'License :: OSI Approved :: GNU Lesser General Public License v3 (LGPLv3)'
      ],
      keywords='trello api client:q',
      author='Roberto Abdelkader Martínez Pérez',
      author_email='robertomartinezp@gmail.com',
      url='https://github.com/nilp0inter/trelloapi',
      license='LGPLv3',
      packages=find_packages(exclude=["tests", "docs"]),
      include_package_data=True,
      zip_safe=False,
      install_requires=[
          'PyYAML==3.11',
      ],
      entry_points={
      })


from flask import Flask

PORT = 8000
MESSAGE = "Welcome to SimpliLearn!!!\n DevOps Practioner Certification- Docker Jenkins CI/CD Pipeline\n"

app = Flask(__name__)

@app.route("/")
def root():
    result = MESSAGE.encode("utf-8")
    return result

if __name__ == "__main__":
    app.run(debug=True, host="0.0.0.0", port=PORT)


from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.models import User
from django.urls import reverse_lazy
from django.http import HttpResponse, response
from django.views.generic import ListView, CreateView, UpdateView, DeleteView
from .models import Task, Preferences
from .forms import NewTaskForm

class index(LoginRequiredMixin, ListView):
    model = Task
    template_name = 'tdl/index.html'
    context_object_name = 'tasks'
    paginate_by = 3

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.order_by('pk')

@login_required
def show_hide(request, show):
    user = request.user.pk
    preferences = get_object_or_404(Preferences, user=user)
    preferences.show_all = (show == "t")
    preferences.save()
    return HttpResponse(preferences.show_all)

@login_required
def show_hide_getval(request):
    user = request.user
    preferences, _ = Preferences.objects.get_or_create(
        user=user, defaults={'user': user, 'show_all': False})
    return HttpResponse(preferences.show_all)

class new_task(LoginRequiredMixin, CreateView):
    model = Task
    form_class = NewTaskForm
    template_name = 'tdl/new_task.html'
    context_object_name = 'form'

    def form_valid(self, form):
        task = form.save(commit=False)
        task.issued_by = self.request.user
        task.save()
        return redirect('tdl:index')

class task_edit(LoginRequiredMixin, UpdateView):
    model = Task
    form_class = NewTaskForm
    template_name = 'tdl/edit.html'
    context_object_name = 'form'
    pk_url_kwarg = 'task_id'
    success_url = reverse_lazy('tdl:index')

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(issued_by=self.request.user)

class task_delete(LoginRequiredMixin, DeleteView):
    model = Task
    success_url = reverse_lazy('tdl:index')
    pk_url_kwarg = 'task_id'
    template_name = 'tdl/delete_confirm.html'
    context_object_name = 'task'

    def get_queryset(self):
        queryset = super().get_queryset()
        return queryset.filter(issued_by=self.request.user)

@login_required
def task_done(request, task_id):
    task = get_object_or_404(Task, pk=task_id)
    task.done = True
    task.done_by = request.user
    task.save()
    tasks = Task.objects.all()
    return redirect('tdl:index')

@login_required
def task_undone(request, task_id):
    task = get_object_or_404(Task, pk=task_id, issued_by=request.user)
    task.done = False
    task.save()
    tasks = Task.objects.all()
    return redirect('tdl:index')


# 建立留存函数(里面默认data数据中有day/user_id两个字段数据，day为日期、user_id为用户id)

# 导入数据包
import pandas as pd
import numpy as np
from datetime import timedelta

# 建立n日留存率计算函数
def cal_retention(data, n):  # n为n日留存
    user = []
    date = pd.Series(data.day.unique()).sort_values()[:-n]  # 时间截取至最后一天的前n天
    retention_rates = []
    for i in date:
        new_user = set(data[data.day == i].user_id.unique()) - set(user)  # 识别新用户，本案例中设初始用户量为零
        user.extend(new_user)  # 将新用户加入用户群中
        # 第n天留存情况
        user_nday = data[data.day == i + timedelta(n)].user_id.unique()  # 第n天登录的用户情况
        a = 0
        for user_id in user_nday:
            if user_id in new_user:
                a += 1
        retention_rate = a / len(new_user)  # 计算该天第n日留存率
        retention_rates.append(retention_rate)  # 汇总n日留存数据
    data_retention = pd.Series(retention_rates, index=date)
    return data_retention

taobaoappDf = pd.read_excel('d:/WJ/数据准备/登录日志2.xlsx')
print(taobaoappDf)
taobaoappDf[['user_id', 'day']] = taobaoappDf[['PHONE_NUMBER', 'ACTIVE_TIME']]
data_retention = cal_retention(taobaoappDf, 3)  # 求用户的3日留存情况
print(data_retention)

运营/用户留存率/留存率.py


from Speechmanager.speech_manager import speech as sp
import Speechmanager.analizer as al
from Speechmanager.TTS import tts
from Commander.commander import commander
import urllib2
from validcommands import commands as co

#body of mainloop
def mainloop():
    if internet_on():
        #activate system commandset
        co.activatesystemcommandset()
        command = sp.gstt()
        if command:
            command = al.analize(command)
            if command:
                #print(command)
                status=commander.main(command)
                if(status==-1):
                     return -1;
            else:
                mainloop()
        else:
            tts.say('Check settings again')
            print('Check settings again')

    else:
        raise Exception('check internet connection and try again')

#function for checking net connectivity
def internet_on():
    try:
        urllib2.urlopen('http://216.58.192.142', timeout=1)
        return True
    except urllib2.URLError as err:
        return False

#starting mainloop
mainloop()


from torch import Tensor
from torch_geometric.data import Data

import torch
import torch_geometric.utils as tu
from torch_scatter import scatter_add

def degree(edge_index: Tensor, direction='out', num_nodes=None, edge_weight=None):
    """calulcates the degree of each node in the graph

    Args:
        edge_index (Tensor): tensor edge_index encoding the graph structure
        direction (str, optional): either calculate 'in'-degree or 'out'-degree. Defaults to 'out'.
        num_nodes (int, optional): number of nodes. Defaults to None.
        edge_weight (Tensor, optional): weight of edges. Defaults to None.

    Raises:
        AssertionError: raised if unsupported direction is passed

    Returns:
        Tensor: node degree
    """
    row, col = edge_index[0], edge_index[1]

    if num_nodes is None:
        num_nodes = edge_index.max() + 1

    if edge_weight is None:
        edge_weight = torch.ones(
            (edge_index.size(1), ),
            device=edge_index.device)

    if direction == 'out':
        return scatter_add(edge_weight, row, dim=0, dim_size=num_nodes)

    elif direction == 'in':
        return scatter_add(edge_weight, col, dim=0, dim_size=num_nodes)

    else:
        raise AssertionError

def get_k_hop_diversity(data: Data, k=1, kind='diversity'):
    """returns k-hop-diversity of each node in the grap

    Args:
        data (Data): pytorch-geometric data object representing graph
        k (int, optional): k specifying k-hop neighborhood. Defaults to 1.
        kind (str, optional): either return 'purity' or 'diversity'. Defaults to 'diversity'.

    Raises:
        AssertionError: raised if unsurported kind is passed

    Returns:
        Tensor: divsierty of purity
    """
    n_nodes = data.y.size(0)
    diversity = torch.zeros_like(data.y)

    if kind == 'purity':
        diversity = diversity.float()

    for n in range(n_nodes):
        k_hop_nodes, _, _, _ = tu.k_hop_subgraph(n, k, data.edge_index)
        if kind == 'diversity':
            div = len(data.y[k_hop_nodes].unique())
        elif kind == 'purity':
            y_center = data.y[n]
            y_hop = data.y[k_hop_nodes]
            div = (y_hop == y_center.item()).float().mean()

        else:
            raise AssertionError

        diversity[n] = div

    return diversity


import sublime
import sublime_plugin

from ..cli import CLI, InvalidContext
from ..settings import find_flow_settings
from ..util import debounce, wait_for_load
from ..view import rowcol_to_region, display_unknown_error

class FlowCoverageListener(sublime_plugin.EventListener):
    def on_selection_modified_async(self, view):
        self.view = view
        sublime.set_timeout_async(
            lambda: self.run_coverage(view)
        )

    @wait_for_load
    @debounce
    def run_coverage(self, view):
        settings = find_flow_settings(view.window().project_data())
        if not settings.get('show_coverage'):
            return

        result = None
        try:
            result = CLI(view).coverage()
        except InvalidContext:
            view.erase_regions('flow_error')
            view.erase_regions('flow_uncovered')
        except Exception as e:
            display_unknown_error(self.view, e)

        if not result:
            return

        regions = []

        for line in result['expressions']['uncovered_locs']:
            start = line['start']
            end = line['end']
            row = int(start['line']) - 1
            col = int(start['column']) - 1
            endrow = int(end['line']) - 1
            endcol = int(end['column'])
            regions.append(
                rowcol_to_region(view, row, col, endcol, endrow)
            )

        view.add_regions(
            'flow_uncovered', regions, 'comment', '',
            sublime.DRAW_STIPPLED_UNDERLINE +
            sublime.DRAW_NO_FILL +
            sublime.DRAW_NO_OUTLINE
        )

        uncovered_count = result['expressions']['uncovered_count']
        covered_count_text = 'Flow coverage: {} line{} uncovered'.format(
            uncovered_count, '' if uncovered_count is 1 else 's'
        )
        view.set_status('flow_coverage', covered_count_text)


#Author: Dhwani Patel
#This is first program of implementing neural network with 3 neurons having its 4 inputs
#inputs here are outputs from other neurons
#Converting p1.py code in formal python code
inputs = [1,2,3,2.5]
weights = [[0.2,0.8,-0.5,1.0], [0.5, -0.91, 0.26, -0.5], [-0.26, -0.27, 0.17, 0.87]]
baises = [2,3,0.5]

layer_outputs = [] #output of the current layer
for neuron_weight, neuron_bais in zip(weights, baises):
    neuron_output = 0
    for n_input, weight in zip(inputs, neuron_weight):
        neuron_output += n_input*weight
    neuron_output+=bias
    layer_outputs.append(neuron_output)

print(layer_outputs)


###########################################
## XML CORUPUS READER
###########################################
"""
this script is used to read the scraped data.
it also provides methods to get basic descriptive statistics.
"""

from nltk.corpus.reader.api import CorpusReader, CategorizedCorpusReader
from nltk import sent_tokenize, wordpunct_tokenize, pos_tag, FreqDist
from bs4 import BeautifulSoup

import time
import codecs
import os

class XMLCorpusReader(CategorizedCorpusReader, CorpusReader):
    CAT_PATTERN = r".*(?=(\/(?<=\/)[^\/]*\.xml))"
    DOC_PATTERN = r"[\w ]+/[\w ]+/.+\.xml"

    def __init__(self, root, fileids=DOC_PATTERN, encoding="utf8", **kwargs):
        """
        Initialize the corpus reader. Categorization arguments (``cat_pattern``, ``cat_map``, and ``cat_file``)
        are passed to the ``CategorizedCorpusReader`` constructor. The remaining arguments are passed to the
        ``CorpusReader`` constructor.
        """

        # add default category pattern if not passed into the class
        if not any(key.startswith("cat_") for key in kwargs.keys()):
            kwargs["cat_pattern"] = self.CAT_PATTERN

        # initialize the NLTK corpus reader objects
        CorpusReader.__init__(self, root, fileids, encoding)
        CategorizedCorpusReader.__init__(self, kwargs)

    def resolve(self, fileids=None, categories=None):
        """
        Returns a list of fieleids or categories depending on what is passed to each internal corups reader
        function.
        """

        if fileids is not None and categories is not None:
            raise ValueError("Specify fileids or categories, not both")

        if categories is not None:
            return self.fileids(categories)
        return fileids

    def docs(self, fileids=None, categories=None):
        """
        Returns the complete text of an XML document, closing the document after done reading it and yielding
        it in a memory safe fashion.
        """

        # resolve the fileids and the categories
        fileids = self.resolve(fileids, categories)

        # create a generator loading one document into memory at a time
        for path, encoding in self.abspaths(fileids, include_encoding=True):
            with codecs.open(path, "r", encoding=encoding) as f:
                yield f.read()

    def sizes(self, fileids=None, categories=None):
        """
        Returns a list of tuples, the fileid and size on disk of the file.
        This function is used to detect oddly large files in the corpus.
        """

        # resolve the fileids and the categories
        fileids = self.resolve(fileids, categories)

        # create a generator, getting every path and computing filesize
        for path in self.abspaths(fileids):
            yield os.path.getsize(path)

    def paras(self, fileids=None, categories=None):
        """
        Parses the paragraphs from XML
        """

        for doc in self.docs(fileids, categories):
            soup = BeautifulSoup(doc, "lxml")
            for paragraph in soup.findAll("paragraph"):
                yield paragraph.text
            soup.decompose()

    def sents(self, fileids=None, categories=None):
        """
        Uses the built in sentence tokenizer of nltk to extract sentences from the paragraphs.
        """

        for paragraph in self.paras(fileids, categories):
            for sentence in sent_tokenize(paragraph):
                yield sentence

    def words(self, fileids=None, categories=None):
        """
        Uses the built in word tokenizer of nltk to extract tokens from the sentences.
        """

        for sentence in self.sents(fileids, categories):
            for token in wordpunct_tokenize(sentence):
                yield token

    def tokenize(self, fileids=None, categories=None):
        """
        Segments, tokenizes, and tags a document in the corpus
        """

        for paragraph in self.paras(fileids=fileids):
            yield [
                pos_tag(wordpunct_tokenize(sent)) for sent in sent_tokenize(paragraph)
            ]

    def describe(self, fileids=None, categories=None):
        """
        Performs a single pass of the corpus and returns a dictionary with a variety of metrics
        concernig the state of the corpus.
        """

        started = time.time()

        # structures to perform counting.
        counts = FreqDist()
        tokens = FreqDist()

        # perform single pass over paragraphs, tokenize and count
        for para in self.paras(fileids, categories):
            counts["paras"] += 1

            for sent in sent_tokenize(para):
                counts["sents"] += 1

                for word in wordpunct_tokenize(sent):
                    counts["words"] += 1
                    tokens[word] += 1

        # compute the number of files and categories in the corpus
        n_fileids = len(self.resolve(fileids, categories) or self.fileids())
        n_topics = len(self.categories(self.resolve(fileids, categories)))

        # return data structure with information
        return {
            "files": n_fileids,
            "topics": n_topics,
            "paras": counts["paras"],
            "sents": counts["sents"],
            "words": counts["words"],
            "vocab": len(tokens),
            "lexdiv": float(counts["words"]) / float(len(tokens)),
            "ppdoc": float(counts["paras"]) / float(n_fileids),
            "sppar": float(counts["sents"]) / float(counts["paras"]),
            "secs": time.time() - started,
        }


from django.views.generic.detail import DetailView
import pdb
from django.views.generic import ListView
from django_filters.views import FilterView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.views.generic.base import TemplateView

from django.contrib.messages.views import SuccessMessageMixin
from django.shortcuts import render, redirect
from django.urls import reverse

from .models import *
from .forms import PokemonForm, UpdatePokemonForm
from .filters import PokemonFilter

class HomeView(TemplateView):
    template_name = "pokedex/home.html"

    def get_context_data(self, **kwargs):
        context = super(HomeView, self).get_context_data(**kwargs)
        pokemon = Pokemon.objects.filter(name__in=["Bulbasaur", "Charmander", "Squirtle"])
        context["pokemon"] = pokemon
        return context

class PokemonListView(FilterView):
    model = Pokemon
    paginate_by = 25
    filterset_class = PokemonFilter
    template_name = "pokedex/pokemon_list.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['filter'] = PokemonFilter(self.request.GET, queryset=self.get_queryset())
        query = self.request.GET.copy()
        if 'page' in query:
            del query['page']
        context['queries'] = query
        return context

class PokemonDetailView(DetailView):
    model = Pokemon

    def get_context_data(self, **kwargs):
        context = super(PokemonDetailView, self).get_context_data(**kwargs)
        double_damage_list = []
        half_damage_list = []
        no_damage_list = []
        quadruple_damage_list = []
        quarter_damage_list = []

        first_stage = []
        second_stage = []
        third_stage = []

        qs = Pokemon.objects.filter(name=self.object)

        for item in qs:
            before_pokemon = Pokemon.objects.filter(pokedex_id=item.pokedex_id-1)
            after_pokemon = Pokemon.objects.filter(pokedex_id=item.pokedex_id+1)
            qs_type = item.types.all()
            evolution_id = item.evolution_id

        evolution_list = Pokemon.objects.filter(evolution_id=evolution_id)

        for pokemon in evolution_list:
            if pokemon.evolution_order == 1:
                first_stage.append(Pokemon.objects.filter(name=pokemon))
            elif pokemon.evolution_order == 2:
                second_stage.append(Pokemon.objects.filter(name=pokemon))
            else:
                third_stage.append(Pokemon.objects.filter(name=pokemon))

        for item in qs_type:
            double_damage_list += item.double_damage_from.split(',')
            if item.half_damage_from != "":
                half_damage_list += item.half_damage_from.split(',')
            if item.no_damage_from != "":
                no_damage_list += item.no_damage_from.split(',')

        final_dd_list = double_damage_list.copy()
        final_hd_list = half_damage_list.copy()

        #Logic for computing type effectiveness
        for item in double_damage_list:
            if item in half_damage_list or item in no_damage_list:
                final_dd_list.remove(item)
            if final_dd_list.count(item) == 2:
                quadruple_damage_list.append(item)
                final_dd_list.remove(item)

        for item in half_damage_list:
            if item in double_damage_list or item in no_damage_list:
                final_hd_list.remove(item)
            if final_hd_list.count(item) == 2:
                quarter_damage_list.append(item)
                final_hd_list.remove(item)

        for item in quadruple_damage_list:
            if item in final_dd_list:
                final_dd_list.remove(item)

        for item in quarter_damage_list:
            if item in final_hd_list:
                final_hd_list.remove(item)

        context['before_pokemon'] = before_pokemon
        context['after_pokemon'] = after_pokemon
        context['double_damage_list'] = final_dd_list
        context['quadruple_damage_list'] = quadruple_damage_list
        context['half_damage_list'] = final_hd_list
        context['quarter_damage_list'] = quarter_damage_list
        context['no_damage_list'] = no_damage_list
        context['first_stage'] = first_stage
        context['second_stage'] = second_stage
        context['third_stage'] = third_stage

        return context

class PokemonCreateView(SuccessMessageMixin, CreateView):
    template_name = "pokedex/forms.html"
    form_class = PokemonForm
    success_message = "%(name)s has been added to the Pokedex."

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        evolve_pokemon_list = Pokemon.objects.all().filter(evolution_order__lt=3)
        devolve_pokemon_list = Pokemon.objects.all().filter(evolution_order__gt=1)
        context['evolve_pokemon_list'] = evolve_pokemon_list
        context['devolve_pokemon_list'] = devolve_pokemon_list
        context['form_header'] = "Create New Pokemon"
        return context

    def form_valid(self, form, *args, **kwargs):
        pokedex_id = Pokemon.objects.all().latest('pokedex_id').pokedex_id + 1
        next_evolution_id = Pokemon.objects.all().latest('evolution_id').evolution_id + 1

        if self.request.POST.get("evolve_devolve_new") == "new":
            form.instance.evolution_id = next_evolution_id
            form.instance.evolution_order = 1

        elif self.request.POST.get("evolve_devolve_new") == "evolve":
            selected_pokemon = Pokemon.objects.filter(name=self.request.POST.get(
                                'select_pokemon_evolve')).first()
            evolution_id = selected_pokemon.evolution_id
            form.instance.evolution_id = evolution_id
            form.instance.evolution_order = selected_pokemon.evolution_order + 1

        elif self.request.POST.get("evolve_devolve_new") == "devolve":
            selected_pokemon = Pokemon.objects.filter(name=self.request.POST.get(
                                'select_pokemon_devolve')).first()
            evolution_id = selected_pokemon.evolution_id
            form.instance.evolution_id = evolution_id
            form.instance.evolution_order = selected_pokemon.evolution_order - 1

        form.instance.pokedex_id = pokedex_id
        valid_form = super(PokemonCreateView, self).form_valid(form, *args, **kwargs)
        return valid_form

class PokemonUpdateView(SuccessMessageMixin, UpdateView):
    model = Pokemon
    form_class = UpdatePokemonForm
    template_name = "pokedex/forms.html"
    success_message = "%(name)s has been updated."

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        evolve_pokemon_list = Pokemon.objects.all().filter(evolution_order__lt=3)
        devolve_pokemon_list = Pokemon.objects.all().filter(evolution_order__gt=1)
        qs = Pokemon.objects.filter(name=self.object)
        evolution_order = qs.first().evolution_order
        devolution_pokemon = Pokemon.objects.all().filter(evolution_id=qs.first().evolution_id,
                            evolution_order = evolution_order-1).first()

        image_url = qs.first().image_url

        if devolution_pokemon is None:
            devolution_pokemon = context['object']

        context['form_header'] = "Edit Pokemon"
        context['evolve_pokemon_list'] = evolve_pokemon_list
        context['devolve_pokemon_list'] = devolve_pokemon_list
        context['evolution_order'] = evolution_order
        context['image_url'] = image_url
        context['default_pokemon'] = devolution_pokemon

        return context

    def form_valid(self, form, *args, **kwargs):
        if self.request.POST.get("evolve_devolve_new") == "evolve":
            selected_pokemon = Pokemon.objects.filter(name=self.request.POST.get(
                                'select_pokemon_evolve')).first()
            evolution_id = selected_pokemon.evolution_id
            form.instance.evolution_id = evolution_id
            form.instance.evolution_order = selected_pokemon.evolution_order + 1

        elif self.request.POST.get("evolve_devolve_new") == "devolve":
            selected_pokemon = Pokemon.objects.filter(name=self.request.POST.get(
                                'select_pokemon_devolve')).first()
            evolution_id = selected_pokemon.evolution_id
            form.instance.evolution_id = evolution_id
            form.instance.evolution_order = selected_pokemon.evolution_order - 1

        valid_form = super(PokemonUpdateView, self).form_valid(form, *args, **kwargs)
        return valid_form

class PokemonDeleteView(SuccessMessageMixin, DeleteView):
    model = Pokemon
    success_message = "%(name)s has been deleted from the Pokedex."

    def get_success_url(self):
        return reverse("pokemon_list")


from math import inf

def print_array(array):
    for row in array:
        print(row)

def diff(A, B):
    return 1 if A != B else 0

# https://en.wikipedia.org/wiki/Levenshtein_distance
def levenshtein_dist(seq1, seq2, return_d=False):
    n, m = len(seq1) + 1, len(seq2) + 1
    D = [[0] * m for _ in range(n)]

    # rows init
    for i in range(n):
        D[i][0] = i

    # cols init
    for j in range(m):
        D[0][j] = j

    # D
    for i in range(1, n):
        for j in range(1, m):
            cost = diff(seq1[i - 1], seq2[j - 1])  # edit cost (zero based -> i - 1)
            D[i][j] = min(
                D[i][j - 1] + 1,  # insert
                D[i - 1][j] + 1,  # del
                D[i - 1][j - 1] + cost  # edit
            )

    if return_d:
        return D[n - 1][m - 1], D

    return D[n - 1][m - 1]

def levenshtein_dist_rec(seq1, seq2, i=None, j=None):
    n, m = len(seq1) + 1, len(seq2) + 1
    D = [[inf] * m for _ in range(n)]

    if i is None:
        i, j = n - 1, m - 1

    if D[i][j] == inf:
        if i == 0:  # min(i, j) == 0 -> D[i, j] = max(i, j)
            D[i][j] = j
        elif j == 0:
            D[i][j] = i
        else:
            ins = levenshtein_dist_rec(seq1, seq2, i, j - 1) + 1
            del_ = levenshtein_dist_rec(seq1, seq2, i - 1, j) + 1
            edit = levenshtein_dist_rec(seq1, seq2, i - 1, j - 1) + diff(seq1[i - 1], seq2[j - 1])

            D[i][j] = min(ins, del_, edit)

    return D[i][j]

def backtrack_edit(D, seq1, seq2):
    n, m = len(D) - 1, len(D[0]) - 1
    seq1_align = []
    seq2_align = []

    i, j = n, m
    while i > 0 or j > 0:
        if D[i][j] == D[i - 1][j] + 1:
            seq1_align.append(seq1[i - 1])
            seq2_align.append("-")

            i = i - 1
        elif D[i][j] == D[i][j - 1] + 1:
            seq1_align.append("-")
            seq2_align.append(seq2[j - 1])

            j = j - 1
        else:
            seq1_align.append(seq1[i - 1])
            seq2_align.append(seq2[j - 1])

            i, j = i - 1, j - 1

    return "".join(reversed(seq1_align)), "".join(reversed(seq2_align))

def main():
    seq1, seq2 = input(), input()

    dist, D = levenshtein_dist(seq1, seq2, True)
    ans1, ans2 = backtrack_edit(D, seq1, seq2)

    print(ans1)
    print(ans2)

if __name__ == "__main__":
    main()


import ee
import streamlit as st
import geemap.foliumap as geemap

def app():

    st.title("Change layer opacity")

    col1, _, col2, _ = st.columns([1, 0.3, 2, 2])

    with col1:
        layer = st.selectbox("Select a layer", ["SRTM DEM", "Landsat", "US Census"])

    with col2:
        opacity = st.slider(
            "Opacity", min_value=0.0, max_value=1.0, value=0.8, step=0.05
        )

    Map = geemap.Map()

    # Add Earth Engine dataset
    dem = ee.Image("USGS/SRTMGL1_003")
    landsat7 = ee.Image("LE7_TOA_5YEAR/1999_2003").select(
        ["B1", "B2", "B3", "B4", "B5", "B7"]
    )
    states = ee.FeatureCollection("TIGER/2018/States")

    # Set visualization parameters.
    dem_vis = {
        "min": 0,
        "max": 4000,
        "palette": ["006633", "E5FFCC", "662A00", "D8D8D8", "F5F5F5"],
    }

    landsat7_vis = {"bands": ["B4", "B3", "B2"], "min": 20, "max": 200, "gamma": 2.0}

    layer = layer.strip()
    if layer == "SRTM DEM":
        Map.addLayer(dem, dem_vis, "SRTM DEM", True, opacity)
    elif layer == "Landsat":
        Map.addLayer(landsat7, landsat7_vis, "Landsat", True, opacity)
    elif layer == "US Census":
        Map.addLayer(states, {}, "US Census", True, opacity)

    Map.to_streamlit()


from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from celery.schedules import crontab
from celery.schedules import timedelta

os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings")
app = Celery("config")
app.config_from_object("django.conf:settings", namespace="CELERY")
app.autodiscover_tasks()

@app.task(bind=True)
def debug_task(self):
    print(f'Request: {self.request!r}')

app.conf.beat_schedule = {
    "jobinja_scrap_task": {
        "task": "post.tasks.jobinja_scrap",
        "schedule": timedelta(minutes=30),
    },
    "jobvision_scrap_task": {
        "task": "post.tasks.jobvision_scrap",
        "schedule": timedelta(minutes=30),
    },
    "e_estekhdam_scrap_task": {
        "task": "post.tasks.e_estekhdam_scrap",
        "schedule": timedelta(minutes=30),
    },
    "update_database_task": {
        "task": "post.tasks.update_database",
        "schedule": crontab(hour=0, minute=0),
    },
}


import cv2
import imutils
import numpy as np
def running_average(bg_img, image, aweight):
    if bg_img is None:
        bg_img = image.copy().astype("float")
    else:
        cv2.accumulateWeighted(image, bg_img, aweight)
    return bg_img
def get_contours(bg_img, image, threshold=10):
    diff = cv2.absdiff(bg_img.astype("uint8"), image)    # abs diff betn img and bg
    _, th = cv2.threshold(diff, threshold, 255, cv2.THRESH_BINARY)
    cnts,_ = cv2.findContours(th.copy(), cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    if len(cnts) == 0:
        return None
    else:
        max_cnt = max(cnts, key=cv2.contourArea)
        return th, max_cnt
class VideoCamera(object):
    def __init__(self):
       #capturing video
       self.video = cv2.VideoCapture(0)
       self.top = 250
       self.bottom = 480
       self.left = 640
       self.right = 400
       self.t=5
       self.draw_color = (0, 255, 0)
       self.pointer_color = (255, 0, 0)
       self.erase = False
       self.bg_img = None
       self.canvas = None
       self.num_frames = 0
       self.take_average = True
       self.draw = True
       self.er = False
    def close(self):
        #releasing camera
        self.video.release()

    def get_frame(self,aweight,take_average):
        ret, frame = self.video.read()
        top = self.top
        bottom = self.bottom
        right = self.right
        left = self.left
        bg_img = self.bg_img
        num_frames = self.num_frames
        if ret:
        # wait for 1ms to key press
            #key = cv2.waitKey(1) & 0xFF
            frame = imutils.resize(frame, width=700)
        # flip to remove mirror effect
            frame = cv2.flip(frame, 1)
                # clone it to not mess with real frame
            clone = frame.copy()
            h, w = frame.shape[:2]
                # take roi, to send it onto contour/average extraction
            roi = frame[top:bottom, right:left]
                # roi to grayscale
            gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
                # add GaussianBlur to eliminate some noise
            gray = cv2.GaussianBlur(gray, (7, 7), 0)
            if num_frames<100 and take_average==True:
                # perform running average
                bg_img = running_average(bg_img, gray, aweight)
                # put frame number on frame
                cv2.putText(clone, str(num_frames), (100, 100),
                                       cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 5)
                num_frames+=1
            else:
                cv2.putText(clone, "done with the average", (100, 100),
                                       cv2.FONT_HERSHEY_SIMPLEX, 0.5, (0, 0, 255), 5)
            cv2.rectangle(clone, (left, top), (right, bottom), (0, 255, 0), 2)
            ret, jpeg = cv2.imencode('.jpg', clone)
            bytes_clone = jpeg.tobytes()
            self.bg_img = bg_img
            self.num_frames = num_frames
            return num_frames,bg_img,bytes_clone

    def write(self):
        ret, frame = self.video.read()
        draw_this_run = np.zeros((525,700,3))
        top = self.top
        bottom = self.bottom
        right = self.right
        left = self.left
        t = self.t
        canvas = self.canvas
        draw_color = self.draw_color
        pointer_color = self.pointer_color
        erase = self.draw
        bg_img = self.bg_img
        er = self.er
        if ret:
        # wait for 1ms to key press
            key = cv2.waitKey(1) & 0xFF
            frame = imutils.resize(frame, width=700)
        # flip to remove mirror effect
            frame = cv2.flip(frame, 1)
                # clone it to not mess with real frame
            clone = frame.copy()
            h, w = frame.shape[:2]
                # take roi, to send it onto contour/average extraction
            roi = frame[top:bottom, right:left]
                # roi to grayscale
            gray = cv2.cvtColor(roi, cv2.COLOR_BGR2GRAY)
                # add GaussianBlur to eliminate some noise
            gray = cv2.GaussianBlur(gray, (7, 7), 0)
                # take our segmented hand
            hand = get_contours(bg_img, gray)
            take_average=False
            if hand is not None:

                # #if pressed x, erase
                # if chr(key) == "x":
                #     draw_color = (255, 255, 255)
                #     pointer_color = (0, 0, 255)
                #     erase = True
                # if chr(key) == "c":
                #     draw_color = (0, 255, 0)
                #     pointer_color = (255, 0, 0)
                #     erase = False
                # #idle
                # if chr(key) == "z":
                #     erase = None
                #     pointer_color = (0, 0, 0)
                # # restart system
                # if chr(key) == "r":
                #     take_average=True
                #     canvas = None
                # if chr(key) == "e":
                #     canvas = None
                #     drawn = np.zeros(drawn.shape)+255
                thresholded, segmented = hand
                cv2.drawContours(clone, [segmented+(right,top)], -1, (0, 0, 255))
                tshape = thresholded.shape
                sshape = segmented.shape
                new_segmented = segmented.reshape(sshape[0], sshape[-1])
                m = new_segmented.min(axis=0)
                if type(canvas) == type(None):
                    canvas = np.zeros((tshape[0], tshape[1], 3))+255
                c = np.zeros(canvas.shape, dtype=np.uint8)
                cv2.circle(c, (m[0], m[1]), t-2, pointer_color, -3)
                cv2.circle(clone, (right+m[0], top+m[1]), t, pointer_color, -3)

                if er==True:
                    cv2.circle(canvas, (m[0], m[1]), t+2, (255,255,255), -3)
                    erimg=cv2.circle(canvas.copy(), (m[0], m[1]), t+2, (0, 0, 0), -3)
                    cv2.circle(c, (m[0], m[1]), t+2, (0, 0, 255), -3)
                    e = cv2.erode(erimg, (3, 3), iterations=5)
                    drawn = cv2.resize(e, (clone.shape[1], clone.shape[0]))
                    c = cv2.resize(c, (clone.shape[1], clone.shape[0]))
                    drawn_new = drawn+c
                    draw_this_run = drawn_new.copy()
                    #cv2.imshow("Drawing", drawn+c)
                    erimg=cv2.circle(canvas.copy(), (m[0], m[1]), t+2, (255, 255, 255), -3)
                    cv2.circle(c, (m[0], m[1]), t+2, (0, 0, 255), -3)
                    e = cv2.erode(erimg, (3, 3), iterations=5)
                    drawn = cv2.resize(e, (clone.shape[1], clone.shape[0]))
                    self.drawn = drawn
                elif erase==True:
                    cv2.circle(canvas, (m[0], m[1]), t-2, draw_color, -3)
                    canvas_shape = canvas.shape
                    clone_shape = clone.shape
                    eshape = (clone_shape[0]/canvas_shape[0], clone_shape[1]/canvas_shape[1])
                    m[0] = int(eshape[1]*m[0])
                    m[1] = int(eshape[0]*m[1])
                    e = cv2.erode(canvas, (3, 3), iterations=5)
                    drawn = cv2.resize(e, (clone.shape[1], clone.shape[0]))
                    c = cv2.resize(c, (clone.shape[1], clone.shape[0]))
                    drawn_new = drawn+c
                    x = drawn_new.copy()
                    cv2.circle(x, (m[0], m[1]), t, pointer_color, -3)
                    draw_this_run = x.copy()
                    self.drawn = drawn
                    #cv2.imshow("Drawing", drawn+c)
                elif erase == False:
                    drawn = self.drawn
                    canvas_shape = canvas.shape
                    clone_shape = clone.shape
                    eshape = (clone_shape[0]/canvas_shape[0], clone_shape[1]/canvas_shape[1])
                    m[0] = int(eshape[1]*m[0])
                    m[1] = int(eshape[0]*m[1])
                    drawn = cv2.resize(drawn, (clone.shape[1], clone.shape[0]))
                    dc = drawn.copy()
                    cv2.circle(dc, (m[0], m[1]), t, pointer_color, -3)
                    draw_this_run = dc.copy()
                #cv2.imshow("Drawing",draw_this_run)
                #print("shape:",clone.shape)
        cv2.rectangle(clone, (left, top), (right, bottom), (0, 255, 0), 2)
        cv2.imshow("Feed", clone)
        ret, jpeg = cv2.imencode('.jpg', draw_this_run)
        bytes_clone = jpeg.tobytes()
        self.canvas = canvas
        return canvas,bytes_clone


from .lightsMode import LightsMode

class RainbowKeyMode(LightsMode):
    def __init__(self, numLights):
        super().__init__(numLights)
        self.color=[(255,0,0), (255, 127,0), (255,255,0), (0,255,0), (0,0,255), (46,43,95), (139,0,255)]

    def processEvent(self, event):
        message, deltatme = event
        state = message[0]
        key = message[1]
        intensity = message[2]
        if (state == LightsMode.DOWN):
            self.pixels.fill(self.pickColor(key))

    def pickColor(self, key):
        note = key % len(self.color)
        return self.color[note]


# import the necessary packages

import time
import cv2
from multipledispatch.conflict import super_signature

from land_mark import LandMark
from head_pose import HeadPose
from heatmap import HeatMap

def set_resolution_1080(cap):
    cap.set(3, 1920)  # Pixel horizontal
    cap.set(4, 1080)  # Pixel vertical

def set_resolution_900(cap):
    cap.set(3, 1600)  # Pixel horizontal
    cap.set(4, 900)  # Pixel vertical

def set_resolution_720(cap):
    cap.set(3, 1280)  # Pixel horizontal
    cap.set(4, 720)  # Pixel vertical

def set_resolution_480(cap):
    cap.set(3, 640)  # Pixel horizontal
    cap.set(4, 480)  # Pixel vertical

def video_stream():

    # construct the argument parse and parse the arguments
    # ap = argparse.ArgumentParser()
    # ap.add_argument("-p", "--shape-predictor", required=True,
    #	help="path to facial landmark predictor")
    # ap.add_argument("-r", "--picamera", type=int, default=-1,
    #	help="whether or not the Raspberry Pi camera should be used")
    # args = vars(ap.parse_args())

    # initialize the video stream and allow the cammera sensor to warmup
    global sup_esq, sup_dir, inf_esq, inf_dir, vitrine_larg_altu, divisao_colum_row, comecar_leitura_unica

    sup_esq = (330,10);
    sup_dir = (-330,10);
    inf_esq = (330,-170);
    inf_dir = (-330,-170);
    vitrine_larg_altu = None;
    comecar_leitura_unica = False;

    print("[INFO] Preparando a câmera...")
    cap = cv2.VideoCapture(1)

    set_resolution_480(cap)

    time.sleep(1.0)

    land_mark = LandMark();
    head_pose = HeadPose(cv2);
    heatmap_global = HeatMap("Global");
    heatmap_usuario = HeatMap("Instantaneo");

    # Loop de frames do video
    while True:
        # Captura o frame
        ret, frame = cap.read()

        key = cv2.waitKey(100) & 0xFF
        # if the `q` key was pressed, break from the loop
        if key == ord("q"):
            break;
        if key == ord("s"):
            heatmap_global.salve_map();
            heatmap_usuario.salve_map();
            print("[INFO] HeatMap salvo!!");

        if key == ord("r"):
            heatmap_usuario.reset_map();
            # heatmap_global.reset_map()
            print("[INFO] HeatMap resetaqdo!!");

        if key == ord("b"):
            comecar_leitura_unica = True;
            print("[INFO] Leitura de usuário começado!!");
        if key == ord("e"):
            comecar_leitura_unica = False;
            print("[INFO] Leitura de usuário parado!!");

        if (head_pose.vitrine_points != None):
            if key == ord("7"):
                sup_esq = head_pose.vitrine_points;
                print("[INFO] Ponto superior esquerdo capturado!!");
            if key == ord("9"):
                sup_dir = head_pose.vitrine_points;
                print("[INFO] Ponto superior direito capturado!!");
            if key == ord("1"):
                inf_esq = head_pose.vitrine_points;
                print("[INFO] Ponto inferor esquerdo capturado!!");
            if key == ord("3"):
                inf_dir = head_pose.vitrine_points;
                print("[INFO] Ponto inferior direito capturado!!");

        if key == ord("5"):
            sup_esq = None;
            sup_dir = None;
            inf_esq = None;
            inf_dir = None;
            vitrine_larg_altu = None;
            print("[INFO] Calibração resetada!!");

        if key == ord("p"):
            print("[INFO] Sup Esquerda:");
            print(sup_esq)
            print("[INFO] Sup Direita:");
            print(sup_dir)
            print("[INFO] Inf Esquerda:");
            print(inf_esq)
            print("[INFO] Inf Direita:");
            print(inf_dir)
            print("[INFO] Largura ; Altura:");
            print(vitrine_larg_altu)

        if key == ord("c"):
            if ( sup_esq != None and sup_dir != None and inf_esq != None and inf_dir != None):
                vitrine_larg_altu = calibrar_vitrine(sup_esq, sup_dir, inf_esq, inf_dir);
                divisao_colum_row = [0 , 0]
                divisao_colum_row[0] = int(vitrine_larg_altu[0] / heatmap_global.width);
                divisao_colum_row[1] = int(vitrine_larg_altu[1] / heatmap_global.higth);
                print("[INFO] Calibração feita!!");

        if (None is frame):
            print("[ERROR] FALHA NA CAPTURA DO VIDEO!!")
            print("[ERROR] TENTANDO NOVAMENTE")
            continue

        frame = cv2.flip(frame, 1)

        gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        land_mark.set_frame(gray);
        head_pose.set_frame(gray);

        mapa = land_mark.get_land_mark();

        primeiro_elemento = True;

        if (mapa.__len__() != 0):  # Encontrou alguns rostos

            # for face in land_mark.shape:  # Loop pelos rostos encontrados
            for face in mapa:  # Loop pelos rostos encontrados
                for (x, y) in face:
                    cv2.circle(frame, (int(x), int(y)), 2, (0, 0, 255), -1)

                points = head_pose.get_line_points(face);

                if( points == None ):
                    continue;

                cv2.arrowedLine(frame, points[0], points[1], (255, 0, 0), 2)

                # Adicionar regra de tempo para saber a partir de quanto tempo começa a contar
                if ( head_pose.vitrine_points != None):

                    if ( sup_esq != None and vitrine_larg_altu != None):
                        coordenada_heat = global2heat(sup_esq, head_pose.vitrine_points);
                        heatmap_global.incrementa(coordenada_heat)

                        if ( primeiro_elemento and comecar_leitura_unica ):
                            primeiro_elemento = False;
                            heatmap_usuario.incrementa(coordenada_heat);
        else:
            heatmap_usuario.reset_map();

        # show the frame
        cv2.imshow("Frame", frame)

    heatmap_global.salve_map()
    heatmap_usuario.salve_map()

    cv2.destroyAllWindows();
    cap.release()

    return

def calibrar_vitrine(sup_esq, sup_dir, inf_esq, inf_dir):

    largura = abs(sup_esq[0]) + abs(sup_dir[0]);
    altura = abs(sup_esq[1]) + abs(inf_esq[1]);

    return (abs(largura), abs(altura))

def global2heat(ponto_zero, vitrine_points):
    global divisao_colum_row, sup_esq, sup_dir, inf_esq, inf_dir;
    pontos_heat = [-1, -1];

    if( vitrine_points[0] < ponto_zero[0] ):
        pontos_heat[0] = int(abs(ponto_zero[0] - vitrine_points[0]) / divisao_colum_row[0]);

    if( vitrine_points[1] < ponto_zero[1] ):
        pontos_heat[1] = int(abs(ponto_zero[1] - vitrine_points[1]) / divisao_colum_row[1]);

    # pontos_heat[1] = 7;

    return pontos_heat

if __name__ == "__main__":

    video_stream()

    exit()


from flask_restful import Resource
from utils import file_processor, database_processor
from flask_restful import reqparse

class GetCourtStatus(Resource):
    def get(self):
        parser = reqparse.RequestParser()
        parser.add_argument('date', required=True,
                            help="date cannot be blank!")
        args = parser.parse_args()
        QUERY_SELECT_COURT_STATUS_DATE = file_processor.read_sql_file(
            "sql/select_court_status_date.sql")
        sql_court_status = QUERY_SELECT_COURT_STATUS_DATE.format(args['date'])
        court_status = database_processor.fetch_data_in_database(
            sql_court_status)
        column = ['court_id', 'court_no', 'court_status_name',
                  'court_surface', 'court_type']
        items = [dict(zip(column, row)) for row in court_status]
        return items


from flask import abort
from flask_login import current_user
from app.models.model_turnament import Tournament

def privilege_required(view_function):
    def check_user_wrapper(tournament_id):
        if not current_user.is_authenticated:
            abort(401)
        tournament = Tournament.query.get(tournament_id)
        print(tournament.id, current_user.id)
        if tournament.owner.id == current_user.id:
            return view_function(tournament_id)
        else:
            abort(401)
    return check_user_wrapper


from datetime import datetime
from app.utils.constants import DATE_FORMAT, TIME_FORMAT

def datetimeCreator(dateString):
    formats = ["%d/%m/%Y", "%m/%d/%Y", "%Y/%m/%d", "%d/%m/%y", "%m/%d/%y",
               "%d-%m-%Y", "%m-%d-%Y", "%Y-%m-%d", "%d-%m-%y", "%m-%d-%y", TIME_FORMAT]
    separators = [' ', ', ']

    if not isinstance(dateString, str):
        return False

    for dateFormat in formats:
        try:
            return datetime.strptime(dateString, dateFormat)
        except ValueError:
            for separator in separators:
                if dateFormat != TIME_FORMAT:
                    try:
                        return datetime.strptime(dateString, dateFormat + separator + TIME_FORMAT)
                    except ValueError:
                        pass

    return False

def convertDatetime(dateString, outputFormat):
    dateObj = datetimeCreator(dateString)
    if not dateObj or (dateObj.year == 1900 and outputFormat == DATE_FORMAT):
        return None
    try:
        return dateObj.strftime(outputFormat)
    except ValueError:
        return None

if __name__ == "__main__":
    print(convertDatetime('10/11/22 22:00:00', DATE_FORMAT))
    print(convertDatetime('22:00:00', TIME_FORMAT))
    print(convertDatetime('22:00', TIME_FORMAT))
    print(convertDatetime('22:00:00', DATE_FORMAT))
    print(convertDatetime('10-11-2020', DATE_FORMAT))


from comtypes.hresult import MAKE_HRESULT, E_FAIL, E_INVALIDARG, E_OUTOFMEMORY, E_NOTIMPL, \
     E_UNEXPECTED, SEVERITY_ERROR, SEVERITY_SUCCESS, FACILITY_WIN32

E_HANDLE = 2147942406
E_ACCESSDENIED = 2147942405
ERROR_FILE_NOT_FOUND = 2

SYN_OK = 0
SYN_FALSE = 0
SYN_TRUE = 1

SYNE_HANDLE = E_HANDLE
SYNE_FAIL = E_FAIL
SYNE_INVALIDARG = E_INVALIDARG
SYNE_OUTOFMEMORY = E_OUTOFMEMORY
SYNE_ACCESSDENIED = E_ACCESSDENIED
SYNE_NOTIMPL = E_NOTIMPL
SYNE_SEQUENCE = E_UNEXPECTED

SYNE_NOTFOUND = MAKE_HRESULT(SEVERITY_ERROR, FACILITY_WIN32, ERROR_FILE_NOT_FOUND)
SYNE_SYNTPENH_NOTFOUND = MAKE_HRESULT(SEVERITY_SUCCESS, FACILITY_WIN32, ERROR_FILE_NOT_FOUND)


# coding: utf-8
from __future__ import unicode_literals

import re

from .common import InfoExtractor
from ..compat import compat_urllib_parse_urlparse
from ..utils import (
    dict_get,
    ExtractorError,
    HEADRequest,
    int_or_none,
    qualities,
    remove_end,
    unified_strdate,
)

class CanalplusIE(InfoExtractor):
    IE_DESC = 'canalplus.fr, piwiplus.fr and d8.tv'
    _VALID_URL = r'''(?x)
                        https?://
                            (?:
                                (?:
                                    (?:(?:www|m)\.)?canalplus\.fr|
                                    (?:www\.)?piwiplus\.fr|
                                    (?:www\.)?d8\.tv|
                                    (?:www\.)?c8\.fr|
                                    (?:www\.)?d17\.tv|
                                    (?:(?:football|www)\.)?cstar\.fr|
                                    (?:www\.)?itele\.fr
                                )/(?:(?:[^/]+/)*(?P<display_id>[^/?#&]+))?(?:\?.*\bvid=(?P<vid>\d+))?|
                                player\.canalplus\.fr/#/(?P<id>\d+)
                            )

                    '''
    _VIDEO_INFO_TEMPLATE = 'http://service.canal-plus.com/video/rest/getVideosLiees/%s/%s?format=json'
    _SITE_ID_MAP = {
        'canalplus': 'cplus',
        'piwiplus': 'teletoon',
        'd8': 'd8',
        'c8': 'd8',
        'd17': 'd17',
        'cstar': 'd17',
        'itele': 'itele',
    }

    _TESTS = [{
        'url': 'http://www.canalplus.fr/c-emissions/pid1830-c-zapping.html?vid=1192814',
        'info_dict': {
            'id': '1405510',
            'display_id': 'pid1830-c-zapping',
            'ext': 'mp4',
            'title': 'Zapping - 02/07/2016',
            'description': 'Le meilleur de toutes les chaînes, tous les jours',
            'upload_date': '20160702',
        },
    }, {
        'url': 'http://www.piwiplus.fr/videos-piwi/pid1405-le-labyrinthe-boing-super-ranger.html?vid=1108190',
        'info_dict': {
            'id': '1108190',
            'display_id': 'pid1405-le-labyrinthe-boing-super-ranger',
            'ext': 'mp4',
            'title': 'BOING SUPER RANGER - Ep : Le labyrinthe',
            'description': 'md5:4cea7a37153be42c1ba2c1d3064376ff',
            'upload_date': '20140724',
        },
        'skip': 'Only works from France',
    }, {
        'url': 'http://www.c8.fr/c8-divertissement/ms-touche-pas-a-mon-poste/pid6318-videos-integrales.html',
        'md5': '4b47b12b4ee43002626b97fad8fb1de5',
        'info_dict': {
            'id': '1420213',
            'display_id': 'pid6318-videos-integrales',
            'ext': 'mp4',
            'title': 'TPMP ! Même le matin - Les 35H de Baba - 14/10/2016',
            'description': 'md5:f96736c1b0ffaa96fd5b9e60ad871799',
            'upload_date': '20161014',
        },
        'skip': 'Only works from France',
    }, {
        'url': 'http://www.itele.fr/chroniques/invite-michael-darmon/rachida-dati-nicolas-sarkozy-est-le-plus-en-phase-avec-les-inquietudes-des-francais-171510',
        'info_dict': {
            'id': '1420176',
            'display_id': 'rachida-dati-nicolas-sarkozy-est-le-plus-en-phase-avec-les-inquietudes-des-francais-171510',
            'ext': 'mp4',
            'title': 'L\'invité de Michaël Darmon du 14/10/2016 - ',
            'description': 'Chaque matin du lundi au vendredi, Michaël Darmon reçoit un invité politique à 8h25.',
            'upload_date': '20161014',
        },
    }, {
        'url': 'http://football.cstar.fr/cstar-minisite-foot/pid7566-feminines-videos.html?vid=1416769',
        'info_dict': {
            'id': '1416769',
            'display_id': 'pid7566-feminines-videos',
            'ext': 'mp4',
            'title': 'France - Albanie : les temps forts de la soirée - 20/09/2016',
            'description': 'md5:c3f30f2aaac294c1c969b3294de6904e',
            'upload_date': '20160921',
        },
        'params': {
            'skip_download': True,
        },
    }, {
        'url': 'http://m.canalplus.fr/?vid=1398231',
        'only_matching': True,
    }, {
        'url': 'http://www.d17.tv/emissions/pid8303-lolywood.html?vid=1397061',
        'only_matching': True,
    }]

    def _real_extract(self, url):
        mobj = re.match(self._VALID_URL, url)

        site_id = self._SITE_ID_MAP[compat_urllib_parse_urlparse(url).netloc.rsplit('.', 2)[-2]]

        # Beware, some subclasses do not define an id group
        display_id = remove_end(dict_get(mobj.groupdict(), ('display_id', 'id', 'vid')), '.html')

        webpage = self._download_webpage(url, display_id)
        video_id = self._search_regex(
            [r'<canal:player[^>]+?videoId=(["\'])(?P<id>\d+)',
             r'id=["\']canal_video_player(?P<id>\d+)',
             r'data-video=["\'](?P<id>\d+)'],
            webpage, 'video id', default=mobj.group('vid'), group='id')

        info_url = self._VIDEO_INFO_TEMPLATE % (site_id, video_id)
        video_data = self._download_json(info_url, video_id, 'Downloading video JSON')

        if isinstance(video_data, list):
            video_data = [video for video in video_data if video.get('ID') == video_id][0]
        media = video_data['MEDIA']
        infos = video_data['INFOS']

        preference = qualities(['MOBILE', 'BAS_DEBIT', 'HAUT_DEBIT', 'HD'])

        fmt_url = next(iter(media.get('VIDEOS')))
        if '/geo' in fmt_url.lower():
            response = self._request_webpage(
                HEADRequest(fmt_url), video_id,
                'Checking if the video is georestricted')
            if '/blocage' in response.geturl():
                raise ExtractorError(
                    'The video is not available in your country',
                    expected=True)

        formats = []
        for format_id, format_url in media['VIDEOS'].items():
            if not format_url:
                continue
            if format_id == 'HLS':
                formats.extend(self._extract_m3u8_formats(
                    format_url, video_id, 'mp4', 'm3u8_native', m3u8_id=format_id, fatal=False))
            elif format_id == 'HDS':
                formats.extend(self._extract_f4m_formats(
                    format_url + '?hdcore=2.11.3', video_id, f4m_id=format_id, fatal=False))
            else:
                formats.append({
                    # the secret extracted ya function in http://player.canalplus.fr/common/js/canalPlayer.js
                    'url': format_url + '?secret=pqzerjlsmdkjfoiuerhsdlfknaes',
                    'format_id': format_id,
                    'preference': preference(format_id),
                })
        self._sort_formats(formats)

        thumbnails = [{
            'id': image_id,
            'url': image_url,
        } for image_id, image_url in media.get('images', {}).items()]

        titrage = infos['TITRAGE']

        return {
            'id': video_id,
            'display_id': display_id,
            'title': '%s - %s' % (titrage['TITRE'],
                                  titrage['SOUS_TITRE']),
            'upload_date': unified_strdate(infos.get('PUBLICATION', {}).get('DATE')),
            'thumbnails': thumbnails,
            'description': infos.get('DESCRIPTION'),
            'duration': int_or_none(infos.get('DURATION')),
            'view_count': int_or_none(infos.get('NB_VUES')),
            'like_count': int_or_none(infos.get('NB_LIKES')),
            'comment_count': int_or_none(infos.get('NB_COMMENTS')),
            'formats': formats,
        }


import re
from utils import utils

class rules(object):

    # Check for Cross Site Request Forgery
    # https://github.com/ethicalhack3r/wordpress_plugin_security_testing_cheat_sheet#cross-site-request-forgery-csrf
    @staticmethod
    def csrf(code):
        blacklist = [r'wp_nonce_field\(\S*\)', r'wp_nonce_url\(\S*\)',
                     r'wp_verify_nonce\(\S*\)', r'check_admin_referer\(\S*\)']
        vulns = []
        for bl in blacklist:
            for idx, cd in enumerate(code):
                pattern = re.findall(bl, cd, re.I)
                if pattern != []:
                    vulns.append({"line": idx, "match": pattern[0] })
                    utils.printLine(idx, "Cross-Site Request Forgery", pattern[0])
        return vulns

    # Check for Open Redirect
    # https://github.com/ethicalhack3r/wordpress_plugin_security_testing_cheat_sheet#open-redirect
    @staticmethod
    def ope(code):
        vulns = []
        for idx, cd in enumerate(code):
            pattern = re.findall(r"wp_redirect\(\S*\)", cd, re.I)
            if pattern != []:
                vulns.append({"line": idx, "match": pattern[0] })
                utils.printLine(idx, "Open Redirect", pattern[0])
        return vulns

    # Check for PHP Code Execution
    # https://github.com/ethicalhack3r/wordpress_plugin_security_testing_cheat_sheet#php-code-execution
    @staticmethod
    def pce(code):
        blacklist = [r'eval\(\S*\)', r'assert\(\S*\)', r'preg_replace\(\S*\)']
        vulns = []
        for bl in blacklist:
            for idx, cd in enumerate(code):
                pattern = re.findall(bl, cd, re.I)
                if pattern != []:
                    vulns.append({"line": idx, "match": pattern[0] })
                    utils.printLine(idx, "PHP Code Execution", pattern[0])
        return vulns

    # Check for Command Execution
    # https://github.com/ethicalhack3r/wordpress_plugin_security_testing_cheat_sheet#command-execution
    @staticmethod
    def com(code):
        blacklist = [r'system\(\S*\)', r'exec\(\S*\)',
                     r'passthru\(\S*\)', r'shell_exec\(\S*\)']
        vulns = []
        for bl in blacklist:
            for idx, cd in enumerate(code):
                pattern = re.findall(bl, cd, re.I)
                if pattern != []:
                    vulns.append({"line": idx, "match": pattern[0] })
                    utils.printLine(idx, "Command Execution", pattern[0])
        return vulns

    # Check for Authorization Hole
    # https://github.com/ethicalhack3r/wordpress_plugin_security_testing_cheat_sheet#authorisation
    @staticmethod
    def auth(code):
        blacklist = [r'is_admin\(\S*\)', r'is_user_admin\(\S*\)']
        vulns = []
        for bl in blacklist:
            for idx, cd in enumerate(code):
                pattern = re.findall(bl, cd, re.I)
                if pattern != []:
                    vulns.append({"line": idx, "match": pattern[0] })
                    utils.printLine(idx, "Authorization Hole", pattern[0])
        return vulns

    # Check for PHP Object Injection
    @staticmethod
    def php(code):
        vulns = []
        for idx, cd in enumerate(code):
            pattern = re.findall(r"unserialize\(\S*\)", cd, re.I)
            if pattern != []:
                vulns.append({"line": idx, "match": pattern[0] })
                utils.printLine(idx, "PHP Object Injection", pattern[0])
        return vulns

    # Check for File Inclusion
    # https://github.com/ethicalhack3r/wordpress_plugin_security_testing_cheat_sheet#file-inclusion
    @staticmethod
    def fin(code):
        blacklist = [r'include\(\S*\)', r'require\(\S*\)',
                     r'include_once\(\S*\)', r'require_once\(\S*\)', r'fread\(\S*\)']
        vulns = []
        for bl in blacklist:
            for idx, cd in enumerate(code):
                pattern = re.findall(bl, cd, re.I)
                if pattern != []:
                    vulns.append({"line": idx, "match": pattern[0] })
                    utils.printLine(idx, "File Inclusion", pattern[0])
        return vulns

    # Check for File Download
    # https://github.com/ethicalhack3r/wordpress_plugin_security_testing_cheat_sheet#file-download
    @staticmethod
    def fid(code):
        blacklist = [r'file\(\S*\)', r'readfile\(\S*\)',
                     r'file_get_contents\(\S*\)']
        vulns = []
        for bl in blacklist:
            for idx, cd in enumerate(code):
                pattern = re.findall(bl, cd, re.I)
                if pattern != []:
                    vulns.append({"line": idx, "match": pattern[0] })
                    utils.printLine(idx, "File Download", pattern[0])
        return vulns

    # Check for Sql Injection
    # https://github.com/ethicalhack3r/wordpress_plugin_security_testing_cheat_sheet#sql-injection
    @staticmethod
    def sql(code):
        blacklist = [r'\$wpdb->query\(\S*\)', r'\$wpdb->get_var\(\S*\)', r'\$wpdb->get_row\(\S*\)', r'\$wpdb->get_col\(\S*\)',
                     r'\$wpdb->get_results\(\S*\)', r'\$wpdb->replace\(\S*\)', r'esc_sql\(\S*\)', r'escape\(\S*\)', r'esc_like\(\S*\)',
                     r'like_escape\(\S*\)']
        vulns = []
        for bl in blacklist:
            for idx, cd in enumerate(code):
                pattern = re.findall(bl, cd, re.I)
                if pattern != []:
                    vulns.append({"line": idx, "match": pattern[0] })
                    utils.printLine(idx, "Sql Injection", pattern[0])
        return vulns

    # Check for Cross-Site Scripting
    # https://github.com/ethicalhack3r/wordpress_plugin_security_testing_cheat_sheet#cross-site-scripting-xss-tips
    @staticmethod
    def xss(code):
        blacklist = [r'\$_GET\[\S*\]', r'\$_POST\[\S*\]', r'\$_REQUEST\[\S*\]', r'\$_SERVER\[\S*\]', r'\$_COOKIE\[\S*\]',
                     r'add_query_arg\(\S*\)', r'remove_query_arg\(\S*\)']
        vulns = []
        for bl in blacklist:
            for idx, cd in enumerate(code):
                pattern = re.findall(bl, cd, re.I)
                if pattern != []:
                    vulns.append({"line": idx, "match": pattern[0] })
                    utils.printLine(idx, "Cross-Site Scripting", pattern[0])
        return vulns


# type: ignore

import discord
from discord.ext import commands

import emoji
import re
from typing import Union, Optional

class Emote(commands.Converter):
    async def convert(self, ctx: discord.Interaction, argument: Optional[str]) -> Union[str, discord.Emoji, Exception]:
        try:
            server_emote = await ServerEmote().convert(ctx, argument)
        except commands.BadArgument:
            found = emoji.get_emoji_regexp().search(argument)
            if found:
                return argument
            else:
                raise commands.BadArgument(f"Emote {argument} not found")
        else:
            return server_emote

class ServerEmote(commands.Converter):
    async def convert(self, ctx: discord.Interaction, argument: str) -> Union[discord.Emoji, Exception]:
        match = re.match(r'<a?:[a-zA-Z0-9\_]{1,32}:([0-9]{15,20})>$', argument)
        result = None
        bot = ctx._client
        guild = ctx.guild

        if match is None:
            if guild:
                result = discord.utils.get(guild.emojis, name=argument)

            if result is None:
                result = discord.utils.get(bot.emojis, name=argument)
        else:
            emoji_id = int(match.group(1))

            result = bot.get_emoji(emoji_id)

        if result is None:
            raise commands.EmojiNotFound(argument)

        return result


# 测试数据
# 3 2
# 11 12 20

# 测试数据2
# 5 4
# 1001 0042 0165 1999 0605

# 输入
lenList, lenNum = map(int, input().split(' '))

# 将每个数都转成 元组:按位存储的字符
myList = list(map(tuple,input().split(' ')))

# 按照从数字最低位到最高位, 统计词频
wei = lenNum - 1
while  wei >= 0:
    # 统计词频字典
    mydict = {}
    for i in range(lenList):
        key = myList[i][wei]
        mydict[key] = mydict.get(key,0) + 1

    # 找字频最多的最小数字
    maxValue = max(mydict.values())
    outputKey = 10
    for key, value in mydict.items():
        if value == maxValue:
            if int(key) < outputKey:
                outputKey = int(key)
    print(outputKey)
    wei = wei - 1


import pytest
from selenium import webdriver
from selenium.webdriver.chrome.options import Options

def pytest_addoption(parser):
    parser.addoption("--browser", action="store", default="chrome")
    parser.addoption("--language", action="store", default="ru")

def get_language_local_chrome(request):
    local = request.config.getoption("--language")
    options = Options()
    options.add_experimental_option('prefs', {'intl.accept_languages': local})
    return options

def get_language_local_firefox(request):
    local = request.config.getoption("--language")
    fp = webdriver.FirefoxProfile()
    fp.set_preference("intl.accept_languages", local)
    return fp

def change_browser(request):
    browser_name = request.config.getoption("--browser")
    if browser_name == "chrome":
        br = webdriver.Chrome(options=get_language_local_chrome(request))
    elif browser_name == "firefox":
        br = webdriver.Firefox(firefox_profile=get_language_local_firefox(request))
    else:
        raise ValueError("Unrecognized browser {}".format(browser_name))
    return br

@pytest.fixture(scope="function")
def browser(request):
    print("\nstart chrome browser for test..")
    browser = change_browser(request)
    yield browser
    print("\nquit browser..")
    browser.quit()


__author__ = 'Adam Stelmack'
__version__ = '2.1.8'
__date__ = 'May 17 2010'

#Basic imports
from ctypes import *
import sys
import random
from dbconnect import dbconnect
#Phidget specific imports
from Phidgets.PhidgetException import *
from Phidgets.Events.Events import *
from Phidgets.Devices.InterfaceKit import *

connect = dbconnect()

#Create an interfacekit object
try:
    interfaceKit = InterfaceKit()
except RuntimeError as e:
    print("Runtime Exception: %s" % e.details)
    print("Exiting....")
    exit(1)

#Event Handler Callback Functions
def inferfaceKitAttached(e):
    attached = e.device
    print("InterfaceKit %i Attached!" % (attached.getSerialNum()))

def interfaceKitDetached(e):
    detached = e.device
    print("InterfaceKit %i Detached!" % (detached.getSerialNum()))

def interfaceKitError(e):
    source = e.device
    print("InterfaceKit %i: Phidget Error %i: %s" % (source.getSerialNum(), e.eCode, e.description))

def interfaceKitInputChanged(e):
    source = e.device

    #WATER MONITORS ON INPUTS 0-5
    if e.index < 6:
        if e.state:
            #LOG TO DATABASE
            connect.insert_gallon(e.index + 301)
            print("logging one gallon to the database...")

    #DOOR/WINDOW MONITORS ON INPUTS 6-15
    else:
        if e.state:
            #LOG TO DATABASE: close
            connect.door_close(e.index + 201 - 6)
            print("Door/Window %i is closed." % (e.index - 5))

        else:
            #LOG TO DATABASE: open
            connect.door_open(e.index + 201 - 6)
            print("Door/Window %i is open." % (e.index - 5))

    #print("InterfaceKit %i: Input %i: %s" % (source.getSerialNum(), e.index, e.state))

def interfaceKitSensorChanged(e):
    source = e.device
    print("InterfaceKit %i: Sensor %i: %i" % (source.getSerialNum(), e.index, e.value))

def interfaceKitOutputChanged(e):
    source = e.device
    print("InterfaceKit %i: Output %i: %s" % (source.getSerialNum(), e.index, e.state))

#Main Program Code
try:
    interfaceKit.setOnAttachHandler(inferfaceKitAttached)
    interfaceKit.setOnDetachHandler(interfaceKitDetached)
    interfaceKit.setOnErrorhandler(interfaceKitError)
    interfaceKit.setOnInputChangeHandler(interfaceKitInputChanged)

except PhidgetException as e:
    print("Phidget Exception %i: %s" % (e.code, e.details))
    print("Exiting....")
    exit(1)

print("Opening phidget object....")

try:
    interfaceKit.openPhidget()
except PhidgetException as e:
    print("Phidget Exception %i: %s" % (e.code, e.details))
    print("Exiting....")
    exit(1)

print("Waiting for attach....")

try:
    interfaceKit.waitForAttach(86400000) # wait a day
except PhidgetException as e:
    print("Phidget Exception %i: %s" % (e.code, e.details))
    try:
        interfaceKit.closePhidget()
    except PhidgetException as e:
        print("Phidget Exception %i: %s" % (e.code, e.details))
        print("Exiting....")
        exit(1)
    print("Exiting....")
    exit(1)

chr = sys.stdin.read(1)

print("Closing...")

try:
    interfaceKit.closePhidget()
except PhidgetException as e:
    print("Phidget Exception %i: %s" % (e.code, e.details))
    print("Exiting....")
    exit(1)

print("Done.")
exit(0)


def create(values = None):
  # "therapyRecommendation": {
  #   "therapyName": []
  #   "therapySensitivity": ...
  # }
  record = {
    "calledBy": None,
    "test": None,
    "value": None,
    "units": None,
    "result": None,
    "threshold": None,
    "component": None,
    "interpretation": None,
    "therapyRecommendation": None,
  }
  if values!=None:
    record.update(values)
  return record


import os
import shlex
import textwrap

from typing import Optional, List, Dict, Union, Any, Sequence

# Convenience shorter names:
from buildbot.plugins import steps, util
from buildbot.process.properties import Property

from .commons import line  # utility functions and stuff

class ToolkitEnvironmentShellCommand(steps.ShellCommand):
    """Shell command step within a toolkit activated environment"""

    # The path to the file to source to activate the CLIP OS toolkit
    # environment (path relative from the repo root):
    SOURCE_ME_FILE = "toolkit/activate"

    def __init__(self,
                 command: Union[str, Sequence[Union[str, Property, util.Interpolate]]],
                 *args: Any, **kwargs: Any
                ) -> None:
        if isinstance(command, str):
            super().__init__(
                command=["/usr/bin/env", "bash", "-c",
                         "source {sourceme}\n\n{command}".format(
                             sourceme=shlex.quote(self.SOURCE_ME_FILE),
                             command=command,
                         )],
                *args,
                **kwargs,
            )
        elif isinstance(command, (list, tuple)):
            super().__init__(
                command=["/usr/bin/env", "bash", "-c",
                         'source {sourceme}; exec "$0" "$@"'.format(
                             sourceme=shlex.quote(self.SOURCE_ME_FILE),
                         )] + list(command),
                *args,
                **kwargs,
            )
        else:
            raise TypeError("command is not of expected type")

# vim: set ft=python ts=4 sts=4 sw=4 et tw=79:


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

# Build C Progam
script_c = open("steal_flag.c").read()
fix_c = script_c.replace("127.0.0.1",sys.argv[1])
f = open("steal.c", "w")
f.write(fix_c)
f.close()
os.system("gcc steal.c -o steal")


def contains(a_min, a_max, b_min, b_max):
    a_in_b = a_min >= b_min and a_max <= b_max
    b_in_a = b_min >= a_min and b_max <= a_max
    return a_in_b or b_in_a

def overlaps(a_min, a_max, b_min, b_max):
    return a_min <= b_max and b_min <= a_max

if __name__ == "__main__":
    with open("data.in", "r") as f:
        pairs = [
            [int(n) for r in pair.split(",") for n in r.split("-")]
            for pair in f.read().splitlines()
        ]

    # Part 1
    print(sum(contains(*pair) for pair in pairs))

    # Part 2
    print(sum(overlaps(*pair) for pair in pairs))


#!/usr/bin/env python

import argparse
import rclpy
import numpy as np
from rclpy.node import Node
from robot_chase.common import *

from geometry_msgs.msg import Twist
from geometry_msgs.msg import PoseStamped
from std_msgs.msg import String

class Stat(Node):

    def __init__(self, args):
        super().__init__('stat')
        self._started = False
        self._start_time = None
        self._ended = False
        self._end_time = None

        self._stat_subscriber = self.create_subscription(PoseStamped, '/stat', self.stat_callback, 5)

        self.get_logger().info('Stat init finished')

    def stat_callback(self, msg):
        if not self._started and msg.pose.position.x == 1:
            self._started = True
            self._start_time = rclpy.time.Time.from_msg(msg.header.stamp)
            self.get_logger().info('Game started at ' + str(self._start_time))

        if not self._ended and msg.pose.position.y == 1:
            self._ended = True
            self._end_time = rclpy.time.Time.from_msg(msg.header.stamp)
            self.get_logger().info('Game ended at ' + str(self._end_time))
            self.get_logger().info('Game finished in ' + str((self._end_time.nanoseconds - self._start_time.nanoseconds) / 1000000000) + ' seconds')

def run(args):
    rclpy.init()
    stat_node = Stat(args)

    rclpy.spin(stat_node)

    stat_node.destroy_node()
    rclpy.shutdown()

def main():
    parser = argparse.ArgumentParser(description='Statistics node')
    args, unknown = parser.parse_known_args()
    run(args)

if __name__ == '__main__':
    main()


import sys
import os
import subprocess

VALUE_SEPARATOR = '|:|'
SECRET_SEPARATOR = '|,|'
SECRET_PREFIX = os.getenv('SECRET_PREFIX')
SECRET_STRING = os.getenv('DRONE_SECRETS')
DB_SECRET_DIFF_CHECK = int(os.getenv('DB_SECRET_DIFF_CHECK', 0))
SQLITE_DATABASE_PATH = os.getenv('SQLITE_DATABASE_PATH')
SQLITE_ENABLED = os.path.isfile(SQLITE_DATABASE_PATH)

def log_line(message):
  print('[drone/globalize] ' + message)

def create_secret(name, data = '', pull_request = 0, pull_request_push = 0):
  return {
    'name': name,
    'data': data,
    'pull_request': pull_request,
    'pull_request_push': pull_request_push
  }

def parse_secrets():
  secrets = []
  secret_splitted = [
    string for string in SECRET_STRING.split(SECRET_SEPARATOR) if string != ""
  ]

  if len(secret_splitted) > 0:
    for secret in secret_splitted:
      parts = secret.split(VALUE_SEPARATOR)

      secrets.append(create_secret(
        SECRET_PREFIX + parts[0],
        parts[1],
        parts[2] if len(parts) > 2 else 0,
        parts[3] if len(parts) > 3 else 0
      ))

  return secrets

def update_secret_state_sqlite(orgs, secrets, state):
  table = 'orgsecrets'
  columns = [
    'secret_namespace',
    'secret_name',
    'secret_data',
    'secret_pull_request',
    'secret_pull_request_push'
  ]

  sqlite_proc = subprocess.run(
    [ 'sqlite3', '-separator', VALUE_SEPARATOR, '-readonly', SQLITE_DATABASE_PATH ],
    input='SELECT ' + (','.join(columns)) + ' FROM ' + table,
    encoding='ascii',
    stdout=subprocess.PIPE
  )

  org_secrets = sqlite_proc.stdout.splitlines()

  # Detect updates and additions
  for org in orgs:
    for secret in secrets:
      secret_item = { 'org': org, 'secret': secret }
      secret_str = VALUE_SEPARATOR.join([ org, secret['name'] ])
      secret_exists = False

      # Check if secret needs and update
      for org_secret in org_secrets:
        if org_secret.startswith(secret_str) == True:
          secret_exists = True
          secret_str_detail = VALUE_SEPARATOR.join([
            org,
            secret['name'],
            secret['data'],
            str(secret['pull_request']),
            str(secret['pull_request_push'])
          ])

          if secret_str_detail != org_secret:
            state['update'].append(secret_item)

          break

      if secret_exists == False:
        state['add'].append(secret_item)

  return org_secrets

def update_secret_state_cli(orgs, secrets, state):
  process = subprocess.run(
    [
      'drone',
      'orgsecret',
      'ls',
      '--format={{ .Namespace }}' + VALUE_SEPARATOR + '{{ .Name }}'
    ],
    stdout=subprocess.PIPE,
    encoding='ascii'
  )

  org_secrets = process.stdout.splitlines()

  # Detect updates and additions
  for org in orgs:
    for secret in secrets:
      org_secret_item = org + ':' + secret['name']
      secret_item = { 'org': org, 'secret': secret }

      if org_secret_item in org_secrets:
        state['update'].append(secret_item)

      if org_secret_item not in org_secrets:
        state['add'].append(secret_item)

  return org_secrets

def get_secret_state(orgs, secrets):
  state = { 'add': [], 'update': [], 'rm': [] }

  if SQLITE_ENABLED == True and DB_SECRET_DIFF_CHECK == 1:
    org_secrets = update_secret_state_sqlite(orgs, secrets, state)
  else:
    org_secrets = update_secret_state_cli(orgs, secrets, state)

  # Detect deletetions
  for org_secret in org_secrets:
    org_secret_namespace = org_secret.split(':')[0]
    org_secret_name = org_secret.split(':')[1]

    if org_secret_name.startswith(SECRET_PREFIX):
      mark_as_removed = True

      for secret in secrets:
        if secret['name'] == org_secret_name:
          mark_as_removed = False
          break

      if (mark_as_removed):
        state['rm'].append({
          'org': org_secret_namespace,
          'secret': create_secret(org_secret_name)
        })

  return state

def drone_secret_action(action, org, secret):
  cmd = [ 'drone', 'orgsecret', action, org, secret['name'] ]

  if action != 'rm':
    cmd.append(secret['data'])
    cmd.append('--allow-pull-request=' + str(secret['pull_request']))
    cmd.append('--allow-push-on-pull-request=' + str(secret['pull_request_push']))

  subprocess.run(cmd, stdout=subprocess.DEVNULL)

def apply_secret_state(state, action, message = ''):
  for item in state[action]:
    secret = item['secret']
    org = item['org']

    log_line(message.format(secret['name'], org))
    drone_secret_action(action, org, secret)

def state_is_empty(state):
  addCount = len(state['add'])
  updateCount = len(state['update'])
  rmCount = len(state['rm'])

  return addCount == 0 and updateCount == 0 and rmCount == 0

def main():
  state = get_secret_state(sys.argv[1:], parse_secrets())

  if state_is_empty(state):
    log_line('No changes detected!')
  else:
    apply_secret_state(state, 'add', 'Add secret "{0}" to "{1}"')
    apply_secret_state(state, 'update', 'Update secret "{0}" in "{1}"')
    apply_secret_state(state, 'rm', 'Remove secret "{0}" from "{1}"')

if __name__ == "__main__":
  main()


""" 5) Altere o programa anterior para conter mais três variáveis, com o preço unitário da fruta,
verdura e legume. Estas variáveis devem armazenar números e não strings. Depois, mostre o
preço de cada produto após o nome (nome ao lado do preço, por exemplo: “Maça: 10”) """

fruta = 'morango'
verdura = 'alface'
legume = 'beringela'

fruta_preco = 5.50
verdura_preco = 4.40
legume_preco = 3.30

print(f'Aqui estão os nomes de uma fruta, uma verdura e um legume: \n{fruta} - {fruta_preco}\n{verdura} - {verdura_preco}\n{legume} - {legume_preco}')


'''
@Description: Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321
Example 2:

Input: -123
Output: -321
Example 3:

Input: 120
Output: 21
Note:
Assume we are dealing with an environment which could only store integers
within the 32-bit signed integer range: [−231,  231 − 1].
For the purpose of this problem,
assume that your function returns 0 when the reversed integer overflows.

@Author: cshi
@Date: 2019-01-14 10:01:37
@LastEditTime: 2019-01-14 10:36:05
@LastEditors: your name
'''

class Solution:
    # 主题思想其实是一个 pop 和 push 的过程——反转类题目都是
    def reverse(self, x):
        """
        :type x: int
        :rtype: int
        """
        x_abs = abs(x)
        x_re = 0
        while x_abs > 0:
            x_re = (x_abs % 10) + x_re * 10
            x_abs = x_abs // 10

        if x_re > 2**31:
            return 0
        elif x > 0:
            return x_re
        else:
            return x_re * -1

soulution = Solution()
y = soulution.reverse(1534236469)
print(y)


import tensorflow.compat.v1 as tf
tf.disable_v2_behavior()
import numpy as np

def fc_layer(input_tensor, name, n_output_units, activation_fn=None):
    with tf.variable_scope(name):
        input_shape = input_tensor.get_shape().as_list()[1:]
        n_input_units = np.prod(input_shape)
        if len(input_shape) > 1:
            input_tensor = tf.reshape(input_tensor, shape=(-1, n_input_units))

        weights_shape = [n_input_units, n_output_units]
        weights = tf.get_variable(name='_weights', shape=weights_shape)
        print(weights)
        biases = tf.get_variable(name='biases', initializer=tf.zeros(shape=[n_output_units]))
        print(biases)

        layer = tf.matmul(input_tensor, weights)
        print(layer)
        layer = tf.nn.bias_add(layer, biases, name='net_pre-activation')
        print(layer)
        if activation_fn is None:
            return layer
        layer = activation_fn(layer, name='activation')
        print(layer)
        return layer


import unittest

from money import Money
from portfolio import Portfolio

class TestMoney(unittest.TestCase):
    def testNegativeAmountThrowsException(self):
        with self.assertRaises(ValueError):
            Money(-5, "USD")

    def testMultiplicationinDollars(self):
        fiveDollars = Money(5, "USD")
        fifteenDollars = Money(15, "USD")
        self.assertEqual(fifteenDollars, fiveDollars.times(3))

    def testMultiplicationInEuros(self):
        tenEuros = Money(10, "EUR")
        twohundretfiftyEuros = Money(250, "EUR")
        self.assertEqual(twohundretfiftyEuros, tenEuros.times(25))

    def testDivision(self):
        originalMoney = Money(4002, "KRW")
        actualMoneyAfterDivision = originalMoney.divide(4)
        expectedMOneyAfterDivision = Money(1000.5, "KRW")
        self.assertEqual(expectedMOneyAfterDivision, actualMoneyAfterDivision)

    def testAddition(self):
        fiveDollars = Money(5, "USD")
        tenDollars = Money(10, "USD")
        fifteenDollars = Money(15, "USD")
        portfolio = Portfolio()
        portfolio.add(fiveDollars, tenDollars)
        self.assertEqual(fifteenDollars, portfolio.evaluate("USD"))

    def testRemove(self):
        fiveDollars = Money(5, "USD")
        tenDollars = Money(10, "USD")
        fifteenDollars = Money(15, "USD")
        portfolio = Portfolio()
        portfolio.add(fiveDollars, tenDollars, fifteenDollars)
        portfolio.remove(fifteenDollars)
        self.assertEqual(fifteenDollars, portfolio.evaluate("USD"))

    def testRemoveNonPortfolioItemRaisesException(self):
        fiveDollars = Money(5, "USD")
        tenDollars = Money(10, "USD")
        fifteenDollars = Money(15, "USD")
        portfolio = Portfolio()
        portfolio.add(fiveDollars, tenDollars)
        with self.assertRaises(ValueError):
            portfolio.remove(fifteenDollars)

    def testAdditionDollarsandEuros(self):
        fiveDollars = Money(5, "USD")
        tenEuros = Money(10, "EUR")
        portfolio = Portfolio()
        portfolio.add(fiveDollars, tenEuros)
        expectedValue = Money(17, "USD")
        actualValue = portfolio.evaluate("USD")
        self.assertEqual(
            expectedValue, actualValue, "%s != %s" % (expectedValue, actualValue)
        )

    def testAdditionDollarsAndWons(self):
        oneDollar = Money(1, "USD")
        elevenHundretWon = Money(1100, "KRW")
        portfolio = Portfolio()
        portfolio.add(oneDollar, elevenHundretWon)
        expectedValue = Money(2200, "KRW")
        actualValue = portfolio.evaluate("KRW")
        self.assertEqual(
            expectedValue, actualValue, "%s != %s" % (expectedValue, actualValue)
        )

    def testAdditionDollarEurWon(self):
        twoDollars = Money(2, "USD")
        elevenHundretWon = Money(1100, "KRW")
        hundretEUR = Money(100, "EUR")
        portfolio = Portfolio()
        portfolio.add(twoDollars, elevenHundretWon, hundretEUR)
        expectedValue = Money(137700, "KRW")
        actualValue = portfolio.evaluate("KRW")
        self.assertEqual(
            expectedValue, actualValue, "%s != %s" % (expectedValue, actualValue)
        )

if __name__ == "__main__":
    unittest.main()


import requests
import json
import os
import sys
import argparse
from .common import *
from .tokens import *

def main():
    # Get the options from the commandline
    parser = argparse.ArgumentParser(allow_abbrev=False)
    parser.description = "Fedcloud Server Resource Status (FSRS) - A took to obtain the usage of resources from a OpenStack server that is integrated in Fedcloud. FSS is able to use EGI-AAI to authenticate in the target site"
    parser.add_argument('-q', "--quiet", dest = "quiet", action="store_true", help="Mutes any debug information", default=False)
    parser.add_argument('-i', "--open-id-url", dest = "openid_url", help="OpenID URL", default="https://aai.egi.eu/oidc/token")
    parser.add_argument('-b', "--bearer-token", dest = "bearer_token", help="Bearer token (if provided, the app ignores the use refresh token)", default=None)
    parser.add_argument("-r", "--refresh-token", dest = "refresh_token" , help="Refresh token from AAI", default=os.environ.get('OS_REFRESH_TOKEN'))
    parser.add_argument("-a", "--os-auth-url", dest = "auth_url" , help="Auth URL (e.g. https://localhost:5000/v3)", default=os.environ.get('OS_AUTH_URL'))
    parser.add_argument("-p", "--os-project", dest = "project", required=True, help="Project ID or NAME to scope authorization", default=os.environ.get('OS_PROJECT_ID'))
    parser.add_argument("-t", "--timeout", dest="timeout", help="Timeout in seconds for http requests (default: 5)", default=5)
    args = parser.parse_args()

    if args.quiet:
        setVerbose(False)
    else:
        setVerbose(1)

    # Obtain a token from the AAI
    if args.bearer_token is None:
        openIDToken = OpenIDToken(
            BearerToken(
                args.refresh_token,
                args.openid_url),
            args.auth_url)
    else:
        p_debug("Using bearer token provided by the user")
        openIDToken = OpenIDToken(
            Token.fromTokenString(args.bearer_token, datetime.now() + timedelta(seconds = 30), None),
            args.auth_url)

    if openIDToken.get() == False:
        sys.exit(r_error("Could not get a new OpenID token", 0))

    # Get the projects in the site and obtain the ID of the project to which we want to scope the authorization
    project_id = None
    projects = requests.get("{}/auth/projects".format(args.auth_url), headers = { "X-Auth-Token" : openIDToken.getToken()} )
    if projects.status_code == 200:
        projects = projects.json()
        for p in projects["projects"]:
            if (p["id"] == args.project) or (p["name"] == args.project):
                project_id = p["id"]
                break
    else:
        r_error("Failed to retrieve projects: {}".format(projects.status_code))

    if project_id is None:
        sys.exit(r_error("Project {} not found (or you do not have permissions on that project)".format(args.project)))

    # Get a token for the user in the project
    authToken = AuthTokenToken(openIDToken, args.auth_url, {"project": { "id" : project_id } })
    if not authToken.get():
        sys.exit(r_error("Failed to get a valid token", 1))

    # We need the token in the headers
    token = authToken.getToken()

    # Retrieve the endpoints for the project (we need the endpoint for "nova")
    body = authToken.getBody()
    if body is None:
        sys.exit(r_error("could not get body from the token", 1))
    if "token" not in body:
        sys.exit(r_error("could not get information about the token obtained", 1))
    if "catalog" not in body["token"]:
        sys.exit(r_error("could not get information about the catalog obtained", 1))
    catalog = body["token"]["catalog"]
    if len(catalog) == 0:
        sys.exit(r_error("the catalog had no endpoint available", 1))

    nova_ep = None
    for service in catalog:
        if service["type"] == "compute":
            for endpoint in service["endpoints"]:
                if endpoint["interface"] == "public":
                    nova_ep = endpoint["url"]
                    break
            break

    if nova_ep is None:
        sys.exit(r_error("could not find nova endpoint", 1))

    # Get the list of IDs of the servers in the project
    r = requests.get(nova_ep + "/servers", headers = {'X-Auth-Token': token })
    if r.status_code != 200:
        sys.exit(r_error("could not get servers", 1))

    servers = r.json()
    server_ids = []
    for server in servers["servers"]:
        server_ids.append(server["id"])

    # Finally, retrieve the details of the servers (we'll retrieve the details using API version 2.48, which is better parsed)
    server_info = {}
    for id in server_ids:
        r = requests.get("{}/servers/{}/diagnostics".format(nova_ep, id), headers = {'X-Auth-Token': token, "X-OpenStack-Nova-API-Version": "2.48" })
        if r.status_code != 200:
            r_error("could not get diagnostics for server {}".format(id))
        else:
            server_info[id] = r.json()

    print(json.dumps(server_info, indent=4))