import re
from datetime import datetime
from time import sleep

import pygame
import requests

url = r"https://www.amazon.co.jp/dp/B07XV8VSZT/ref=sr_1_1?__mk_ja_JP=%E3%82%AB%E3%82%BF%E3%82%AB%E3%83%8A&dchild=1&keywords=%E3%83%AA%E3%83%B3%E3%82%B0%E3%83%95%E3%82%A3%E3%83%83%E3%83%88&qid=1589075747&sr=8-1"
# url = "https://www.amazon.co.jp/%E4%BB%BB%E5%A4%A9%E5%A0%82-%E3%81%82%E3%81%A4%E3%81%BE%E3%82%8C-%E3%81%A9%E3%81%86%E3%81%B6%E3%81%A4%E3%81%AE%E6%A3%AE-Switch/dp/B084HPGQ9W/ref=zg_bs_videogames_1?_encoding=UTF8&psc=1&refRID=5XJYC1V5V679EFG15X21"
music = r'D:\Desktop\T\he Phantom of the Opera.MP3'
flag = False

def getHTMLText(url):
    try:
        kv = {'user-agent': 'Mozilla/5.0'}
        r = requests.get(url, timeout=30, headers=kv)
        # print("get请求状态码 = ", r.status_code)
        r.raise_for_status()
        r.encoding = 'utf-8'
        return r.text
    except:
        print("get请求失败！")

def check(html):
    global flag
    try:
        result = re.findall(r'からお求めいただけます', html)
        if len(result) != 1:
            play_music(music)
            flag = True
            # print("!=1")
        else:
            flag = False
            # print("==1")
        # print("length = ", len(result))
        print_results()
    except:
        pass

def play_music(file):
    pygame.mixer.init()
    pygame.mixer.music.load(file)
    pygame.mixer.music.play()
    sleep(30)
    pygame.mixer.music.stop()

def print_results():
    global flag
    dt = datetime.now()
    template = "{0:^4}.{1:^2}.{2:^2}\t{3:^2}:{4:^2}:{5:^2}\t{6:^5}"
    print(template.format(dt.year, dt.month, dt.day,
                          dt.hour, dt.minute, dt.second, flag))

def main():
    html = getHTMLText(url)
    while(True):
        check(html)
        sleep(60)

if __name__ == "__main__":
    main()


import argparse
import subprocess
import re
import json
from pathlib import Path
from sys import stderr
from jinja2 import Environment, FileSystemLoader, select_autoescape
from bs4 import BeautifulSoup

regex = r"^FROM .*"

def make_bold(match_obj):
    if match_obj.group(1) is not None:
        return " **" + match_obj.group(1) + "** "

def tool_info_extractor(soup, tool, script_args, is_version_in_json=False):
    """Parse tool's name and command to get version info.
    Run extracted command in docker container
    Returns List

    Args:
        soup (BeautifulSoup): BeautifulSoup object with toolset xml
        tool (str): Toolname in toolset xml
        is_version_in_json (bool): If version needs to parsed as json

    Returns:
        list: Returns List(dict) with 'name' and 'version'
    """
    out = []
    for command in soup.find_all(tool):
        cmd = command.find('command-to-check-version').text.split(" ")
        bash_cmd = ['docker', 'run', script_args.image, *cmd]
        process = subprocess.Popen(bash_cmd, stdout=subprocess.PIPE, stderr=subprocess.DEVNULL)
        output, error = process.communicate()
        if not error:
            if not is_version_in_json:
                version = re.sub(r"([\w\-]+:) ", make_bold, output.decode())
            else:
                version = json.loads(output.decode())
            out.append({
                'name': command.find('name').text,
                'version': version})
        else:
            out.append({
                'name': command.find('name').text,
                'version': "Not present or error"})
    return out

def main():
    parser = argparse.ArgumentParser(
        description='''Creates changelog file based on jinja2 template. Extracts versions from docker image, using xml description. Parses BASE IMAGE from Dockerfile''')

    parser.add_argument('--image', type=str, required=True,
                        help='an image ID or an image name')

    parser.add_argument('--outpath', type=str, required=True,
                        help='Path for generated changelog')
    parser.add_argument('--dockerfile', type=str, required=True,
                        help='path to dockerfile')
    parser.add_argument('--toolstotestfile', type=str, required=True,
                        help='path to the xml file with tools for extracting info')
    parser.add_argument('--outputtemplatefile', type=str, required=True,
                        help='path to Junja2 template file for rendering and createtin well-formated changelog')
    parser.add_argument('--mode', type=str, default='append', choices=['append', 'create'], required=False,
                        help='either create new changelog file or append to existing one')
    args = parser.parse_args()

    TOOLSET_FILE = Path(args.toolstotestfile).resolve()
    OUTPUT_FILE = Path(args.outpath).resolve()
    OUTPUTTEMPLATE_FILE = Path(args.outputtemplatefile).resolve().name
    OUTPUTTEMPLATE_DIR = Path(args.outputtemplatefile).resolve().parent
    DOCKER_FILE = Path(args.dockerfile).resolve()
    context = {}  # the dict to be sent for being rendered in the template
    context['BASE_IMAGE'] = "NOT DEFINED"

    env = Environment(
        loader=FileSystemLoader(OUTPUTTEMPLATE_DIR),
        autoescape=select_autoescape()
    )

    template = env.get_template(OUTPUTTEMPLATE_FILE)

    with open(DOCKER_FILE, "r") as fp:
        # base image info parser
        text = fp.read()
        from_image = re.findall('FROM (.*)', text)
        if from_image:
            context['BASE_IMAGE'] = from_image[0]

    with open(TOOLSET_FILE, 'r') as fp:
        soup = BeautifulSoup(fp, "xml")

    context['APT_TOOLS'] = tool_info_extractor(soup, 'apt-tool', args)
    context['PIP_TOOLS'] = tool_info_extractor(soup, 'python-pip-tool', args)
    context['AZURE_CLI_TOOLS'] = tool_info_extractor(
        soup, 'azure-cli-tool', args, is_version_in_json=True)

    if from_image:
        context['BASE_IMAGE'] = from_image[0]

    output = template.render(context)

    if args.mode == 'create':
        mode = 'w'
    else:
        mode = 'a'
    with open(OUTPUT_FILE, mode) as fp:
        fp.write(output)

if __name__ == "__main__":
    main()


from django.core.exceptions import ValidationError
from django.core.validators import MinLengthValidator
from django.db import models

from football_news_app.core.model_mixins import StrFromFieldsMixin

from football_news_app.core.validators import validate_file_less_than_7mb
from football_news_app.teams.models import Team

class Match(StrFromFieldsMixin, models.Model):
    str_fields = ('pk', 'photo',)
    MAX_LEAGUE_NAME_LENGTH = 30
    MIN_LEAGUE_NAME_LENGTH = 2
    MAX_PLACE_NAME_LENGTH = 30
    MIN_PLACE_NAME_LENGTH = 2
    MAX_LEAGUE_STAGE_LENGTH = 30

    home_team = models.ForeignKey(
        Team,
        on_delete=models.RESTRICT,
        related_name='%(class)s_home_team',
    )

    guest_team = models.ForeignKey(
        Team,
        on_delete=models.RESTRICT,
        related_name='%(class)s_guest_team',
    )

    photo = models.ImageField(
        upload_to='matches-photos/',
        null=False,
        blank=True,
        validators=(validate_file_less_than_7mb,),
    )

    league = models.CharField(
        max_length=MAX_LEAGUE_NAME_LENGTH,
        validators=(
            MinLengthValidator(MIN_LEAGUE_NAME_LENGTH),
        ),
        null=True,
        blank=True
    )

    match_date = models.DateField(
        blank=True,
        null=False,
    )

    match_location = models.CharField(
        max_length=MAX_PLACE_NAME_LENGTH,
        validators=(
            MinLengthValidator(MIN_PLACE_NAME_LENGTH),
        ),
        null=True,
        blank=True
    )

    league_stage = models.CharField(
        max_length=MAX_LEAGUE_STAGE_LENGTH,
        blank=False,
        null=False,
    )

    def clean(self):
        if self.home_team == self.guest_team:
            raise ValidationError('Home team and Guest team should be different')

    def __str__(self):
        return f"{self.home_team} vs {self.guest_team}"


import requests

def get_weather(city):
    url = f"https://api.example.com/weather?city={city}"
    response = requests.get(url)
    if response.status_code == 200:
        return response.json()
    else:
        return None

def generate_weather_report(city):
    weather_data = get_weather(city)
    if weather_data:
        temperature = weather_data.get("temperature")
        condition = weather_data.get("condition")
        return f"The weather in {city} is {condition} with a temperature of {temperature}°C."
    else:
        return f"Could not fetch weather data for {city}."


# -*- coding: utf-8 -*-
__author__ = 'Matheus Becatini'
__version__ = '0.1.0'

import os
import json

NAME = 'Artigos'

if (os.path.exists('data.json')):
    with open('data.json') as json_file:
        data = json.load(json_file)
else:
    data={}
    data[NAME]=[]

title = 'O titulo é tal 3333'
text = 'Dia da República é uma data histórica que comemora a instituição do sistema republicano[1] de governo em um determinado país ou região. Em alguns países, é conhecido como Dia Nacional ou Dia da Proclamação, ou por algum outro nome.'
url = 'https://wikipedia.readthedocs.io/en/latest/'

data[NAME].append({
    'title': title,
    'content': text,
    'url': url
})

with open('data.json', 'w') as outfile:
    json.dump(data, outfile, indent=4, ensure_ascii=False)


import json

from opentelemetry import trace as trace_api
from opentelemetry.exporter.zipkin.encoder import (
    _SCOPE_NAME_KEY,
    _SCOPE_VERSION_KEY,
    NAME_KEY,
    VERSION_KEY,
)
from opentelemetry.exporter.zipkin.json.v2 import JsonV2Encoder
from opentelemetry.exporter.zipkin.node_endpoint import NodeEndpoint
from opentelemetry.sdk import trace
from opentelemetry.test.spantestutil import (
    get_span_with_dropped_attributes_events_links,
)
from opentelemetry.trace import SpanKind, TraceFlags

from .common_tests import (  # pylint: disable=import-error
    TEST_SERVICE_NAME,
    CommonEncoderTestCases,
)

# pylint: disable=protected-access
class TestV2JsonEncoder(CommonEncoderTestCases.CommonJsonEncoderTest):
    @staticmethod
    def get_encoder(*args, **kwargs) -> JsonV2Encoder:
        return JsonV2Encoder(*args, **kwargs)

    def test_encode(self):
        local_endpoint = {"serviceName": TEST_SERVICE_NAME}
        span_kind = JsonV2Encoder.SPAN_KIND_MAP[SpanKind.INTERNAL]

        otel_spans = self.get_exhaustive_otel_span_list()
        trace_id = JsonV2Encoder._encode_trace_id(
            otel_spans[0].context.trace_id
        )

        expected_output = [
            {
                "traceId": trace_id,
                "id": JsonV2Encoder._encode_span_id(
                    otel_spans[0].context.span_id
                ),
                "name": otel_spans[0].name,
                "timestamp": otel_spans[0].start_time // 10**3,
                "duration": (otel_spans[0].end_time // 10**3)
                - (otel_spans[0].start_time // 10**3),
                "localEndpoint": local_endpoint,
                "kind": span_kind,
                "tags": {
                    "key_bool": "false",
                    "key_string": "hello_world",
                    "key_float": "111.22",
                    "otel.status_code": "OK",
                },
                "annotations": [
                    {
                        "timestamp": otel_spans[0].events[0].timestamp
                        // 10**3,
                        "value": json.dumps(
                            {
                                "event0": {
                                    "annotation_bool": True,
                                    "annotation_string": "annotation_test",
                                    "key_float": 0.3,
                                }
                            },
                            sort_keys=True,
                        ),
                    }
                ],
                "debug": True,
                "parentId": JsonV2Encoder._encode_span_id(
                    otel_spans[0].parent.span_id
                ),
            },
            {
                "traceId": trace_id,
                "id": JsonV2Encoder._encode_span_id(
                    otel_spans[1].context.span_id
                ),
                "name": otel_spans[1].name,
                "timestamp": otel_spans[1].start_time // 10**3,
                "duration": (otel_spans[1].end_time // 10**3)
                - (otel_spans[1].start_time // 10**3),
                "localEndpoint": local_endpoint,
                "kind": span_kind,
                "tags": {
                    "key_resource": "some_resource",
                    "otel.status_code": "ERROR",
                    "error": "Example description",
                },
            },
            {
                "traceId": trace_id,
                "id": JsonV2Encoder._encode_span_id(
                    otel_spans[2].context.span_id
                ),
                "name": otel_spans[2].name,
                "timestamp": otel_spans[2].start_time // 10**3,
                "duration": (otel_spans[2].end_time // 10**3)
                - (otel_spans[2].start_time // 10**3),
                "localEndpoint": local_endpoint,
                "kind": span_kind,
                "tags": {
                    "key_string": "hello_world",
                    "key_resource": "some_resource",
                },
            },
            {
                "traceId": trace_id,
                "id": JsonV2Encoder._encode_span_id(
                    otel_spans[3].context.span_id
                ),
                "name": otel_spans[3].name,
                "timestamp": otel_spans[3].start_time // 10**3,
                "duration": (otel_spans[3].end_time // 10**3)
                - (otel_spans[3].start_time // 10**3),
                "localEndpoint": local_endpoint,
                "kind": span_kind,
                "tags": {
                    NAME_KEY: "name",
                    VERSION_KEY: "version",
                    _SCOPE_NAME_KEY: "name",
                    _SCOPE_VERSION_KEY: "version",
                },
            },
        ]

        self.assert_equal_encoded_spans(
            json.dumps(expected_output),
            JsonV2Encoder().serialize(otel_spans, NodeEndpoint()),
        )

    def test_encode_id_zero_padding(self):
        trace_id = 0x0E0C63257DE34C926F9EFCD03927272E
        span_id = 0x04BF92DEEFC58C92
        parent_id = 0x0AAAAAAAAAAAAAAA
        start_time = 683647322 * 10**9  # in ns
        duration = 50 * 10**6
        end_time = start_time + duration

        otel_span = trace._Span(
            name=TEST_SERVICE_NAME,
            context=trace_api.SpanContext(
                trace_id,
                span_id,
                is_remote=False,
                trace_flags=TraceFlags(TraceFlags.SAMPLED),
            ),
            parent=trace_api.SpanContext(trace_id, parent_id, is_remote=False),
            resource=trace.Resource({}),
        )
        otel_span.start(start_time=start_time)
        otel_span.end(end_time=end_time)

        expected_output = [
            {
                "traceId": format(trace_id, "032x"),
                "id": format(span_id, "016x"),
                "name": TEST_SERVICE_NAME,
                "timestamp": JsonV2Encoder._nsec_to_usec_round(start_time),
                "duration": JsonV2Encoder._nsec_to_usec_round(duration),
                "localEndpoint": {"serviceName": TEST_SERVICE_NAME},
                "kind": JsonV2Encoder.SPAN_KIND_MAP[SpanKind.INTERNAL],
                "debug": True,
                "parentId": format(parent_id, "016x"),
            }
        ]

        self.assert_equal_encoded_spans(
            json.dumps(expected_output),
            JsonV2Encoder().serialize([otel_span], NodeEndpoint()),
        )

    def _test_encode_max_tag_length(self, max_tag_value_length: int):
        otel_span, expected_tag_output = self.get_data_for_max_tag_length_test(
            max_tag_value_length
        )
        service_name = otel_span.name

        expected_output = [
            {
                "traceId": JsonV2Encoder._encode_trace_id(
                    otel_span.context.trace_id
                ),
                "id": JsonV2Encoder._encode_span_id(otel_span.context.span_id),
                "name": service_name,
                "timestamp": JsonV2Encoder._nsec_to_usec_round(
                    otel_span.start_time
                ),
                "duration": JsonV2Encoder._nsec_to_usec_round(
                    otel_span.end_time - otel_span.start_time
                ),
                "localEndpoint": {"serviceName": service_name},
                "kind": JsonV2Encoder.SPAN_KIND_MAP[SpanKind.INTERNAL],
                "tags": expected_tag_output,
                "debug": True,
            }
        ]

        self.assert_equal_encoded_spans(
            json.dumps(expected_output),
            JsonV2Encoder(max_tag_value_length).serialize(
                [otel_span], NodeEndpoint()
            ),
        )

    def test_dropped_span_attributes(self):
        otel_span = get_span_with_dropped_attributes_events_links()
        tags = JsonV2Encoder()._encode_span(otel_span, "test")["tags"]

        self.assertEqual("1", tags["otel.dropped_links_count"])
        self.assertEqual("2", tags["otel.dropped_attributes_count"])
        self.assertEqual("3", tags["otel.dropped_events_count"])


import tkinter as tk
from tkinter import font, messagebox
import math

numPlayers = 1
player = 'p1'
p1 = 'X'
p2 = 'O'
stop_game = False
computer = 'O'
gameMode = "norm"

namedTitle = ""
namedOpponent = ""

copiedBoard = [['', '', ''], ['', '', ''], ['', '', '']]
bestMoveR = ''
bestMoveC = ''

# TicTacToeBoard stuff

class TicTacToeBoard(tk.Tk):
    def __init__(self, titleName = "Tic-Tac-Toe Game"):
        super().__init__()
        #namedTitle = titleName
        self.title(titleName)
        self.geometry("750x750")
        self.resizable(0,0)
        self.configure(bg="#3498db")  # Set the background color to a shade of blue
        self.player_turn = 'X'  # Initialize the first player's turn as 'X'
        self.game_state = [['', '', ''], ['', '', ''], ['', '', '']]  # Initialize the game state
        self._create_board_grid()
        """
        still needs code to use the opponent parameter
        """
        self._create_menu()  # Create the menu

    def _create_board_grid(self):
        color = "#ECF0F1"
        for row in range(3):
            self.rowconfigure(row, weight=1, minsize=150)
            for col in range(3):
                self.columnconfigure(col, weight=1, minsize=150)

                # adds different colors to different squares
                if row < 1:
                    if col < 1:
                        color = "#B1B4B5"
                    elif col < 2:
                        color = "#ECF0F1"
                    else:
                        color = "#B1B4B5"
                elif row < 2:
                    if col < 1:
                        color = "#ECF0F1"
                    elif col < 2:
                        color = "#B1B4B5"
                    else:
                        color = "#ECF0F1"
                else:
                    if col < 1:
                        color = "#B1B4B5"
                    elif col < 2:
                        color = "#ECF0F1"
                    else:
                        color = "#B1B4B5"

                frame = tk.Frame(
                    master=self,
                    relief=tk.RAISED,
                    borderwidth=1,
                    bg= color  # Set the background color of the squares to a light gray
                )
                frame.grid(row=row, column=col, padx=5, pady=5, sticky="nsew")

                button = tk.Button(
                    master=frame,
                    text="",
                    font=font.Font(size=36, weight="bold"),
                    fg="#2c3e50",  # Set the text color to a dark gray
                    bg=color  # Set the background color of the buttons to match the squares
                )
                button.pack(fill=tk.BOTH, expand=True)

                # Bind a callback function (click_button) to the button click event
                button.bind("<Button-1>", lambda event, row=row, col=col: self.click_button(event, row, col))
    def get_title(self):
        return namedTitle

    def set_title(self, newName):
        self.title(newName)
        namedTitle = newName
        self.reset_board(newName)

    def get_game_state(self, r, c):
        return self.game_state[r][c]

    def set_game_state(self, r, c, value):
        self.game_state[r][c] = value

    def check_for_win(self, player):
        for row in range(3):
            if all(self.game_state[row][col] == player for col in range(3)):
                return True

        for col in range(3):
            if all(self.game_state[row][col] == player for row in range(3)):
                return True

        if all(self.game_state[i][i] == player for i in range(3)) or all(self.game_state[i][2 - i] == player for i in range(3)):
            return True

        return False

    def check_for_tie(self):
        return all(self.game_state[row][col] != '' for row in range(3) for col in range(3))

    def display_message(self, message):
        messagebox.showinfo("Game Over", message)

    def reset_board(self, titleName = namedTitle):
        # Reset the game board and state
        self.player_turn = 'X'
        self.game_state = [['', '', ''], ['', '', ''], ['', '', '']]
        for child in self.winfo_children():
            if isinstance(child, tk.Frame):
                for button in child.winfo_children():
                    button.config(text="")
        self.destroy()
        if titleName.startswith("Normal Game"):
            app = TicTacToeBoard(titleName)
        #elif titleName.startswith("Game in a Game"):
            #app = BigTicTacToeBoard(titleName)
        else:
            name = self.get_title()
            app = TicTacToeBoard(name)
        app.mainloop()

    def _create_menu(self):
        menu_bar = tk.Menu(master=self, tearoff="off")
        self.config(menu=menu_bar)
        file_menu = tk.Menu(master=menu_bar, tearoff="off")
        file_menu.add_command(
            label="Play Again",
            command=self.reset_board
        )
        file_menu.add_separator()
        file_menu.add_command(label="Exit", command=quit)

        game_modes = tk.Menu(master=menu_bar, tearoff="off")
        one_player = tk.Menu(master=game_modes, tearoff="off")
        two_players = tk.Menu(master=game_modes, tearoff="off")
        normal_bot = tk.Menu(master=one_player, tearoff="off")
        game_modes.add_cascade(label="1 Player", menu=one_player)
        game_modes.add_cascade(label="2 Players", menu=two_players)

        two_players.add_command(
            # Two Players (Normal Game)
            #TicTacToeBoard.set_title(self, "Normal Game - Two Players"),
            label="Normal Game",
            #command=self.reset_board
            command = lambda: TicTacToeBoard.set_title(self, "Normal Game - Two Players")
        )
        """two_players.add_command(
            # Two Players (Game in a Game)
            #TicTacToeBoard.set_title(self, "Game in a Game - Two Players"),
            label="Game in a Game",
            #command=self.reset_board
            command = lambda: TicTacToeBoard.set_title(self, "Game in a Game - Two Players")
        )"""
        one_player.add_cascade(label="Normal Bot", menu=normal_bot)
        normal_bot.add_command(
            # Single Player (Normal Game - Normal Bot)
            #TicTacToeBoard.set_title(self, "Normal Game - Normal Bot"),
            label="Normal Game",
            #command=self.reset_board
            command = lambda: TicTacToeBoard.set_title(self, "Normal Game - Normal Bot")
        )
        """normal_bot.add_command(
            # Single Player (Game in a Game - Normal Bot)
            #TicTacToeBoard.set_title(self, "Game in a Game - Normal Bot"),
            label="Game in a Game",
            #command=self.reset_board
            command = lambda: TicTacToeBoard.set_title(self, "Game in a Game - Normal Bot")
        )"""
        one_player.add_command(
            #TicTacToeBoard.set_title(self, "Normal Game - Impossible Bot"),
            # Single Player (Impossible Bot)
            label="Impossible Bot",
            #command=self.reset_board
            command = lambda: TicTacToeBoard.set_title(self, "Normal Game - Impossible Bot")
        )

        menu_bar.add_cascade(label="File", menu=file_menu)
        menu_bar.add_cascade(label="Game Modes", menu=game_modes)

    def click_button(self, event, row, col):
        button = event.widget
        if button.cget("text") == "" and not self.check_for_win('X') and not self.check_for_win('O') and not self.check_for_tie():
            button.config(text=self.player_turn)
            self.game_state[row][col] = self.player_turn

            if self.check_for_win(self.player_turn):
                self.display_message(f"{self.player_turn} wins!")
            elif self.check_for_tie():
                self.display_message("It's a tie!")

            self.player_turn = 'O' if self.player_turn == 'X' else 'X'

# impossible Bot Stuff

class impBot():
	def copyBoard():
		for r in copiedBoard:
			for c in copiedBoard:
				copiedBoard[r][c] = TicTacToeBoard.getGameState(r,c)

	def spaceAvailable(r, c):
		if TicTacToeBoard.getGameState(r,c) == '':
			return True
		else:
			return False

	def get_possible_moves():
		impBot.copyBoard()
		for r in copiedBoard:
			for c in copiedBoard:
				if copiedBoard[r][c] == '':
					copiedBoard[r][c] = computer
					score = impBot.minimax(copiedBoard, False)
					copiedBoard[r][c] = ''
					if score > bestScore:
						bestScore = score
				else:
					copiedBoard[r][c] = ''

	def impBotMove():

		bestScore = -800
		r = 0
		c = 0
		for r in copiedBoard:
			for c in copiedBoard:
				if copiedBoard[r][c] == '':
					copiedBoard[r][c] = computer
					score = impBot.minimax(copiedBoard, False)
					copiedBoard[r][c] = ''
					if score > bestScore:
						bestScore = score
						bestMoveR = r
						bestMoveC = c
		TicTacToeBoard.set_game_state(bestMoveR, bestMoveC, computer)
		return

	def minimax(copiedBoard, isMaximizing):
		if impBot.checkWhichMarkWon(computer):
			return 1
		elif impBot.checkWhichMarkWon(p1):
			return -1
		elif impBot.checkDraw():
			return 0

		if isMaximizing:
			bestScore = -800
			for r in copiedBoard:
				for c in copiedBoard:
					if copiedBoard[r][c] == '':
						copiedBoard[r][c] = computer
						score = impBot.minimax(copiedBoard, False)
						copiedBoard[r][c] = ''
						if score > bestScore:
							bestScore = score
			return bestScore
		else:
			bestScore = 800
			for r in copiedBoard:
				for c in copiedBoard:
					if copiedBoard[r][c] == '':
						copiedBoard[r][c] = p1
						score = impBot.minimax(copiedBoard, True)
						copiedBoard[r][c] = ''
						if score < bestScore:
							bestScore = score
			return bestScore

	def checkWhichMarkWon(mark):
		if (copiedBoard[0][0] == copiedBoard[0][1] and copiedBoard[0][0] == copiedBoard[0][2] and copiedBoard[0][0] == mark):
			return True
		elif (copiedBoard[1][0] == copiedBoard[1][1] and copiedBoard[1][0] == copiedBoard[1][2] and copiedBoard[1][0] == mark):
			return True
		elif (copiedBoard[2][0] == copiedBoard[2][1] and copiedBoard[2][0] == copiedBoard[2][2] and copiedBoard[2][0] == mark):
			return True
		elif (copiedBoard[0][0] == copiedBoard[1][0] and copiedBoard[0][0] == copiedBoard[2][0] and copiedBoard[0][0] == mark):
			return True
		elif (copiedBoard[0][1] == copiedBoard[1][1] and copiedBoard[0][1] == copiedBoard[2][1] and copiedBoard[0][1] == mark):
			return True
		elif (copiedBoard[0][2] == copiedBoard[1][2] and copiedBoard[0][2] == copiedBoard[2][2] and copiedBoard[0][2] == mark):
			return True
		elif (copiedBoard[0][0] == copiedBoard[1][1] and copiedBoard[0][0] == copiedBoard[2][2] and copiedBoard[0][0] == mark):
			return True
		elif (copiedBoard[2][0] == copiedBoard[1][1] and copiedBoard[2][0] == copiedBoard[0][2] and copiedBoard[2][0] == mark):
			return True
		else:
			return False

	def checkDraw():
		for r in copiedBoard:
			for c in copiedBoard:
				if copiedBoard[r][c] == '':
					return False
			return True

		# check_if_tie()
		# if norm_check_if_win() == False:
		#     tie = messagebox.showinfo("tie","its tie")
		#     return tie
	def norm_check_if_win():
		global stop_game
		states = [
			[0, 0, 0],
			[0, 0, 0],
			[0, 0, 0]
		]

		for i in range(3):
			if states[i][0] == states[i][1] == states[i][2] !=0:
				stop_game = True

				#winner = messagebox.showinfo("Winner", states[i][0] + " Won")
				# disableAllButton()
				break

		#for j in range(3):
			elif states [0][i] == states[1][i] == states[2][i] != 0:
				stop_game = True

				#winner = messagebox.showinfo("Winner", states[0][i]+ " Won!")
				break

			elif states[0][0] == states[1][1] == states[2][2] !=0:
				stop_game = True

				#winner = messagebox.showinfo("Winner", states[0][0]+ " Won!")
				break

			elif states[0][2] == states[1][1] == states[2][0] !=0:
				stop_game = True

				#winner = messagebox.showinfo("Winner" , states[0][2]+ " Won!")
				break

			elif states[0][0] and states[0][1] and states[0][2] and states[1][0] and states[1][1] and states[1][2] and states[2][0] and states[2][1] and states[2][2] != 0:
				stop_game = True

				#winner = messagebox.showinfo("tie", "Tie")

	def getPlayer():
		return player

	def switchPlayer():
		if numPlayers == 1:
			if impBot.getPlayer() == p1:
				player = computer
			elif impBot.getPlayer() == computer:
				player = p1
		else:
			if impBot.getPlayer() == p1:
				player = p2
			elif impBot.getPlayer() == computer:
				player = p2

# main

def main():
    """Create the game's board and run its main loop."""
    """#Button
    b = [
        [0,0,0],
        [0,0,0],
        [0,0,0]]

    #text for buttons
    states = [
        [0,0,0],
        [0,0,0],
        [0,0,0]]"""

    if gameMode == "norm":
        #Button
        b = [
            [0,0,0],
            [0,0,0],
            [0,0,0]]

        #text for buttons
        states = [
            [0,0,0],
            [0,0,0],
            [0,0,0]]

    elif gameMode == "gng":
        #Button
        b = [
            [[0,0,0], [0,0,0], [0,0,0]],
            [[0,0,0], [0,0,0], [0,0,0]],
            [[0,0,0], [0,0,0], [0,0,0]]]

        #text for buttons
        states = [
            [[0,0,0], [0,0,0], [0,0,0]],
            [[0,0,0], [0,0,0], [0,0,0]],
            [[0,0,0], [0,0,0], [0,0,0]]]

    impBot.getPlayer()
    impBot.norm_check_if_win()

    if gameMode == "norm":
        #normal game starter
        board = TicTacToeBoard()
        board.mainloop()
    #elif gameMode == "gng":
        #game in game starter
        #board = BigTicTacToeBoard()
        #board.mainloop()

    #game in game starter
    #board = BigTicTacToeBoard()
    board.mainloop()

if __name__ == "__main__":
    main()


# -*- coding: utf-8 -*-
# -------------------------------------------------------------------------------
# Name:		tb_nuovo_progetto.py
# Author:	  Tarquini E.
# Created:	 21-02-2018
# -------------------------------------------------------------------------------

import csv
import datetime
import os
import shutil
import sqlite3
import sys
import webbrowser
import zipfile

from qgis.core import *
from qgis.gui import *
from qgis.PyQt import QtGui, uic
from qgis.PyQt.QtCore import *
from qgis.PyQt.QtGui import *
from qgis.PyQt.QtWidgets import *
from qgis.utils import *
from .utils import save_map_image

FORM_CLASS, _ = uic.loadUiType(os.path.join(
    os.path.dirname(__file__), 'tb_nuovo_progetto.ui'))

class nuovo_progetto(QDialog, FORM_CLASS):

    def __init__(self, iface, parent=None):
        """Constructor."""
        self.iface = iface
        super().__init__(parent)
        self.setupUi(self)
        self.plugin_dir = os.path.dirname(__file__)

    def nuovo(self):
        self.help_button.clicked.connect(lambda: webbrowser.open(
            'https://www.youtube.com/watch?v=TcaljLE5TCk&t=57s&list=PLM5qQOkOkzgWH2VogqeQIDybylmE4P1TQ&index=2'))
        dir_svg_input = os.path.join(self.plugin_dir, "img", "svg")
        dir_svg_output = self.plugin_dir.split("python")[0] + "svg"
        tabella_controllo = os.path.join(self.plugin_dir, "comuni.csv")
        pacchetto = os.path.join(self.plugin_dir, "data", "progetto_MS.zip")

        dizio_comuni = {}
        dict_comuni = {}

        with open(tabella_controllo, 'r') as csvfile:
            csvreader = csv.reader(csvfile, delimiter=';')
            for row in csvreader:
                cod_istat = str(row[2])
                nome_com = row[3]
                cod_com = row[4]
                nome_comune = cod_istat + "_" + cod_com
                dict_comuni[cod_istat] = nome_comune
                dizio_comuni[nome_com] = cod_istat

        data_meta = datetime.datetime.now().strftime(r"%d/%m/%Y")
        data_dato = datetime.datetime.now().strftime(r"%d/%m/%Y")

        self.dir_output.clear()
        self.comune.clear()
        self.cod_istat.clear()
        self.professionista.clear()
        self.email_prof.clear()
        self.sito_prof.clear()
        self.ufficio.clear()
        self.propretario.clear()
        self.email_prop.clear()
        self.sito_prop.clear()
        self.contatto.clear()
        self.email_cont.clear()
        self.sito_cont.clear()
        self.scala_nom.clear()
        self.accuratezza.clear()
        self.lineage.clear()
        self.descriz.clear()

        self.button_box.setEnabled(False)
        self.comune.addItems(sorted(dizio_comuni.keys()))
        self.comune.model().item(0).setEnabled(False)
        self.comune.currentIndexChanged.connect(lambda: self.update_cod_istat(
            dizio_comuni, str(self.comune.currentText()), self.cod_istat))
        self.scala_nom.textEdited.connect(
            lambda: self.update_num(self.scala_nom, 0, 100000))
        self.comune.currentIndexChanged.connect(self.disableButton)
        self.professionista.textChanged.connect(self.disableButton)
        self.email_prof.textChanged.connect(self.disableButton)
        self.sito_prof.textChanged.connect(self.disableButton)
        self.ufficio.textChanged.connect(self.disableButton)
        self.propretario.textChanged.connect(self.disableButton)
        self.email_prop.textChanged.connect(self.disableButton)
        self.sito_prop.textChanged.connect(self.disableButton)
        self.contatto.textChanged.connect(self.disableButton)
        self.sito_cont.textChanged.connect(self.disableButton)
        self.email_cont.textChanged.connect(self.disableButton)
        self.scala_nom.textChanged.connect(self.disableButton)
        self.accuratezza.textChanged.connect(self.disableButton)
        self.lineage.textChanged.connect(self.disableButton)
        self.descriz.textChanged.connect(self.disableButton)
        self.dir_output.textChanged.connect(self.disableButton)

        # Sample data for testing purposes
        # TODO: disable
        if False:
            d = QTemporaryDir()
            d.setAutoRemove(False)
            self.dir_output.setText(d.path())
            self.comune.setCurrentText('Luserna San Giovanni')
            self.cod_istat.setText('001139')
            self.professionista.setText('itopen')
            self.email_prof.setText('some text')
            self.sito_prof.setText('some text')
            self.ufficio.setText('some text')
            self.propretario.setText('some text')
            self.email_prop.setText('some text')
            self.sito_prop.setText('some text')
            self.contatto.setText('some text')
            self.email_cont.setText('some text')
            self.sito_cont.setText('some text')
            self.scala_nom.setText('50000')
            self.accuratezza.setText('some text')
            self.lineage.setText('some text')
            self.descriz.setText('some text')

        self.show()
        self.adjustSize()
        result = self.exec_()

        if result:

            dir_out = self.dir_output.text()
            if os.path.isdir(dir_out):
                try:
                    comune = str(self.comune.currentText())
                    cod_istat = self.cod_istat.text()
                    professionista = self.professionista.text()
                    email_prof = self.email_prof.text()
                    sito_prof = self.sito_prof.text()
                    ufficio = self.ufficio.text()
                    propretario = self.propretario.text()
                    email_prop = self.email_prop.text()
                    sito_prop = self.sito_prop.text()
                    contatto = self.contatto.text()
                    email_cont = self.email_cont.text()
                    sito_cont = self.sito_cont.text()
                    scala_nom = self.scala_nom.text()
                    accuratezza = self.accuratezza.text()
                    lineage = self.lineage.toPlainText()
                    descriz = self.descriz.toPlainText()

                    if not os.path.exists(dir_svg_output):
                        shutil.copytree(dir_svg_input, dir_svg_output)
                    else:
                        src_files = os.listdir(dir_svg_input)
                        for file_name in src_files:
                            full_file_name = os.path.join(
                                dir_svg_input, file_name)
                            if os.path.isfile(full_file_name):
                                shutil.copy(full_file_name, dir_svg_output)

                    zip_ref = zipfile.ZipFile(pacchetto, 'r')
                    zip_ref.extractall(dir_out)
                    zip_ref.close()
                    for x, y in list(dict_comuni.items()):
                        if x == cod_istat:
                            comune_nome = (y[6:]).replace("_", " ")
                            path_comune = os.path.join(dir_out, y)
                            os.rename(os.path.join(
                                dir_out, "progetto_MS"), path_comune)

                    project = QgsProject.instance()
                    project.read(os.path.join(path_comune, "progetto_MS.qgs"))

                    layer_limiti_comunali = QgsProject.instance(
                    ).mapLayersByName("Limiti comunali")[0]
                    req = QgsFeatureRequest()
                    req.setFilterExpression('"cod_istat" = \'%s\'' % cod_istat)
                    selection = layer_limiti_comunali.getFeatures(req)
                    layer_limiti_comunali.selectByIds(
                        [k.id() for k in selection])

                    layer_comune_progetto = QgsProject.instance(
                    ).mapLayersByName("Comune del progetto")[0]
                    selected_features = layer_limiti_comunali.selectedFeatures()

                    features = []
                    for i in selected_features:
                        features.append(i)

                    layer_comune_progetto.startEditing()
                    data_provider = layer_comune_progetto.dataProvider()
                    data_provider.addFeatures(features)
                    layer_comune_progetto.commitChanges()

                    features = layer_comune_progetto.getFeatures()
                    for feat in features:
                        attrs = feat.attributes()
                        codice_regio = attrs[1]
                        codice_prov = attrs[2]
                        codice_com = attrs[3]
                        nome = attrs[4]
                        regione = attrs[7]
                        provincia = attrs[6]

                    layer_limiti_comunali.removeSelection()

                    layer_limiti_comunali.setSubsetString(
                        "cod_regio='" + codice_regio + "'")

                    logo_regio_in = os.path.join(
                        self.plugin_dir, "img", "logo_regio", codice_regio + ".png").replace('\\', '/')
                    logo_regio_out = os.path.join(
                        path_comune, "progetto", "loghi", "logo_regio.png").replace('\\', '/')
                    shutil.copyfile(logo_regio_in, logo_regio_out)

                    mainPath = QgsProject.instance().homePath()
                    canvas = self.iface.mapCanvas()

                    # QgsMessageLog.logMessage(
                    #     'Canvas WKT %s' % canvas.extent().asWktPolygon())
                    # QgsMessageLog.logMessage(
                    #     'layer_limiti_comunali WKT %s' % layer_limiti_comunali.extent().asWktPolygon())

                    imageFilename = os.path.join(
                        mainPath, "progetto", "loghi", "mappa_reg.png")
                    save_map_image(
                        imageFilename, layer_limiti_comunali, canvas)

                    extent = layer_comune_progetto.dataProvider().extent()
                    canvas.setExtent(extent)

                    # QgsMessageLog.logMessage(
                    #     'Canvas WKT %s' % canvas.extent().asWktPolygon())
                    # QgsMessageLog.logMessage(
                    #     'layer_comune_progetto data provider WKT %s' % extent.asWktPolygon())

                    layout_manager = QgsProject.instance().layoutManager()
                    layouts = layout_manager.printLayouts()

                    for layout in layouts:
                        map_item = layout.itemById('mappa_0')
                        map_item.zoomToExtent(canvas.extent())
                        map_item_2 = layout.itemById(
                            'regio_title')
                        map_item_2.setText("Regione " + regione)
                        map_item_3 = layout.itemById(
                            'com_title')
                        map_item_3.setText("Comune di " + nome)
                        map_item_4 = layout.itemById('logo')
                        map_item_4.refreshPicture()
                        map_item_5 = layout.itemById('mappa_1')
                        map_item_5.refreshPicture()

                    self.indice_tab_execute(data_meta, regione, codice_regio, provincia,
                                            codice_prov, nome, codice_com, professionista, ufficio, propretario)
                    self.metadati_tab_execute(codice_prov, codice_com, professionista, email_prof, sito_prof, data_meta, ufficio, propretario,
                                              email_prop, sito_prop, data_dato, descriz, contatto, email_cont, sito_cont, scala_nom, extent, accuratezza, lineage)

                    # Save the project!
                    project.write(os.path.join(path_comune, "progetto_MS.qgs"))

                    QMessageBox.information(
                        None, self.tr("Notice"), self.tr("The project has been created successfully."))

                except Exception as z:
                    # raise z
                    QMessageBox.critical(
                        None, 'ERROR!', 'Error:\n"' + str(z) + '"')
                    if os.path.exists(os.path.join(dir_out, "progetto_MS")):
                        shutil.rmtree(os.path.join(dir_out, "progetto_MS"))

            else:
                QMessageBox.warning(
                    self.iface.mainWindow(), self.tr("WARNING!"), self.tr("The selected directory does not exist!"))

    def disableButton(self):
        check_campi = [self.professionista.text(), self.email_prof.text(), self.sito_prof.text(), self.propretario.text(), self.ufficio.text(), self.email_prop.text(), self.sito_prop.text(), self.contatto.text(
        ), self.email_cont.text(), self.sito_cont.text(), self.scala_nom.text(), self.dir_output.text(), self.accuratezza.text(), self.lineage.toPlainText(), self.descriz.toPlainText(), str(self.comune.currentText())]
        check_value = []

        for x in check_campi:
            if len(x) > 0:
                value_campi = 1
                check_value.append(value_campi)
            else:
                value_campi = 0
                check_value.append(value_campi)

        campi = sum(check_value)
        if campi > 15:
            self.button_box.setEnabled(True)
        else:
            self.button_box.setEnabled(False)

    def update_cod_istat(self, dizionario, nome_comune_sel, campo):
        for chiave, valore in list(dizionario.items()):
            if chiave == nome_comune_sel:
                campo.setText(valore)

    def update_num(self, value, n1, n2):
        try:
            valore = int(value.text())
            if valore not in list(range(n1, n2)):
                value.setText('')
        except:
            value.setText('')

    def indice_tab_execute(self, data_meta, regione, codice_regio, provincia, codice_prov, nome, codice_com, professionista, ufficio, propretario):
        orig_gdb = QgsProject.instance().readPath(
            os.path.join("db", "indagini.sqlite"))
        conn = sqlite3.connect(orig_gdb)
        sql = """ATTACH '""" + orig_gdb + """' AS A;"""
        conn.execute(sql)
        conn.execute("""INSERT INTO 'indice'(data_in,regione,cod_reg,provincia,cod_prov,comune,cod_com,soggetto,ufficio,responsabile,ID_MZS) VALUES ('""" + data_meta + """', '""" + regione + """', '""" + codice_regio + """',
			'""" + self.changeWord(provincia) + """', '""" + codice_prov + """', '""" + self.changeWord(nome) + """', '""" + codice_com + """', '""" + self.changeWord(professionista) + """', '""" + self.changeWord(ufficio) + """',
			'""" + self.changeWord(propretario) + """', '""" + codice_prov + codice_com + """');""")
        conn.commit()
        conn.close()

    def metadati_tab_execute(self, codice_prov, codice_com, professionista, email_prof, sito_prof, data_meta, ufficio, propretario, email_prop, sito_prop, data_dato, descriz, contatto, email_cont, sito_cont, scala_nom, extent, accuratezza, lineage):
        orig_gdb = QgsProject.instance().readPath(
            os.path.join("db", "indagini.sqlite"))
        conn = sqlite3.connect(orig_gdb)
        sql = """ATTACH '""" + orig_gdb + """' AS A;"""
        conn.execute(sql)
        conn.execute("""INSERT INTO 'metadati'("id_metadato", "liv_gerarchico", "resp_metadato_nome", "resp_metadato_email", "resp_metadato_sito", "data_metadato", "srs_dati", "proprieta_dato_nome", "proprieta_dato_email", "proprieta_dato_sito",
			"data_dato", "ruolo", "desc_dato", "formato", "tipo_dato", "contatto_dato_nome", "contatto_dato_email", "contatto_dato_sito", "keywords", "keywords_inspire", "limitazione", "vincoli_accesso", "vincoli_fruibilita", "vincoli_sicurezza",
			"scala", "categoria_iso", "estensione_ovest", "estensione_est", "estensione_sud", "estensione_nord", "precisione", "genealogia")
			VALUES ('""" + codice_prov + codice_com + """M1', 'series','""" + self.changeWord(professionista) + """', '""" + self.changeWord(email_prof) + """', '""" + self.changeWord(sito_prof) + """', '""" + self.changeWord(data_meta) + """',
			32633,'""" + self.changeWord(ufficio) + """ """ + self.changeWord(propretario) + """', '""" + self.changeWord(email_prop) + """', '""" + self.changeWord(sito_prop) + """', '""" + self.changeWord(data_dato) + """', 'owner',
			'""" + self.changeWord(descriz) + """', 'mapDigital','vector','""" + self.changeWord(contatto) + """', '""" + self.changeWord(email_cont) + """', '""" + self.changeWord(sito_cont) + """', '(Microzonazione Sismica, Pericolosita Sismica)',
			'(Zone a rischio naturale, Geologia)','nessuna limitazione','nessuno','nessuno','nessuno','""" + self.changeWord(scala_nom) + """', 'geoscientificInformation',  '""" + str(extent.xMinimum()) + """', '""" + str(extent.xMaximum()) + """',
            '""" + str(extent.yMinimum()) + """', '""" + str(extent.yMaximum()) + """', '""" + self.changeWord(accuratezza) + """', '""" + self.changeWord(lineage) + """');""")
        conn.commit()
        conn.close()

    def changeWord(self, word):
        for letter in word:
            if letter == "'":
                word = word.replace(letter, "''")
        return word

    def tr(self, message):
        return QCoreApplication.translate('nuovo_progetto', message)


import logging
from findQA.data_access_services.TesterDAO import TesterDAO
from findQA.data_access_services.TesterSQLDAO import TesterSQLDAO

class TesterAService(object):
    """
        Application service designed to retrieve tester data
    """

    @staticmethod
    def get_testers(countries=None, devices=None):
        """
            retrieving tester records based on given countries and devices
            @param countries: a list of country codes or None if use all countries
            @type countries: list or None
            @param devices: a list of devices' descriptions or None if use all devices
            @type devices: list or None
            @rtype: tuple
        """
        assert isinstance(countries, list) or countries is None, type(countries)
        assert isinstance(devices, list) or devices is None, type(list)
        assert countries is None or len(countries) > 0
        assert devices is None or len(devices) > 0

        if countries:
            for country in countries:
                if len(country) > 2:
                    TesterAService.__LOGGER.warning("invalid country code {0}".format(country))
                    return

        return TesterDAO.get_testers_sorted_by_bugs_count(
            countries,
            devices,
        )

    __LOGGER = logging.getLogger(__name__)
    """ logger for the current class """


import pandas as pd
import numpy as np
import torch
from torch import nn
from torch.utils.data import Dataset, random_split, DataLoader
from torch.nn.functional import mse_loss
from torch.optim import Adam, SGD

epochs = 100
_traits_map_df = pd.read_csv('.\\data\\traits_map.csv')
traits_map = dict(zip(_traits_map_df.iloc[:, 0].values, _traits_map_df.iloc[:, 1].values))
# print(traits_map)

class FungusMoisture(nn.Module):
    def __init__(self):
        super(FungusMoisture, self).__init__()
        layers = [nn.Linear(1, 32), nn.ELU(), nn.Linear(32, 256), nn.ELU(), nn.Linear(256, 1024), nn.ELU(),
                  nn.Linear(1024, 1024), nn.ELU(), nn.Linear(1024, 256), nn.ELU(), nn.Linear(256, 32), nn.ELU(),
                  nn.Linear(32, 1), nn.ELU()]
        self.learner = nn.Sequential(*layers)

    def forward(self, x):
        return self.learner(x)

    def save(self, name):
        torch.save(self.state_dict(), f'.\\data\\er_wp_map\\{name}.txt')

    def load(self, name):
        self.load_state_dict(torch.load(f'.\\data\\er_wp_map\\{name}.txt'))
        self.eval()

class DataSet(Dataset):
    def __init__(self, x, y):
        assert len(x) == len(y)
        self.x = x
        self.y = y

    def __getitem__(self, idx):
        return self.x.iloc[idx], self.y.iloc[idx]

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

class Fungi:
    def __init__(self):
        global traits_map

        er_temp = pd.read_csv('.\\data\\er_temp.csv')
        er_temp_slope = torch.tensor(er_temp.loc[:, 'slope'].values)
        er_temp_inter = torch.tensor(er_temp.loc[:, 'intercept'].values)
        # ranking =

        self.er_temp_alpha = er_temp_slope / torch.log(torch.tensor(10.))
        self.er_temp_beta = torch.exp(er_temp_inter / torch.log(torch.tensor(10.)))

        self.colors = torch.rand(34, 3, 1, 1, device='cuda:0')
        self.er_moisture_df = pd.read_csv('.\\data\\raw\\fungal_biogeography\\fungi_data\\Fungi_moisture_curves.csv')

        trait_df = pd.read_csv('.\\data\\raw\\Fungal_trait_data.csv')
        self.ranking = torch.tensor(trait_df.loc[:, 'ranking'].values, device='cuda:0')

        groups = self.er_moisture_df.groupby('species').groups
        self.max_er_moisture = torch.cat([torch.max(torch.tensor(self.er_moisture_df.iloc[groups[traits_map[i]], 2].values)).reshape(1,) for i in range(34)], dim=0).reshape(34,1)

        self.niche = torch.tensor(trait_df.loc[:, 'water.niche.width'].values)

        # comment this part out in the first time running
        # groups = self.er_moisture_df.groupby('species').groups
        # for i in range(34):
        #     survived = torch.tensor(self.er_moisture_df.iloc[groups[traits_map[i]], 2].values,
        #                             device='cuda:0').ge(self.max_er_moisture[i].cuda()/2)
        #     niche = torch.masked_select(torch.tensor(self.er_moisture_df.iloc[groups[traits_map[i]], 1].values, device='cuda:0'), survived)
        #     self.niche.append(torch.tensor([torch.max(niche), torch.min(niche)]).reshape(2, 1))
        #
        # self.niche = torch.cat(self.niche, dim=0)

    def fitting(self, idxes):
        global traits_map
        groups = self.er_moisture_df.groupby('species').groups
        # print(groups)
        for idx in idxes:
            i = groups[traits_map[idx]]
            specie = self.er_moisture_df.iloc[i, 1:]
            X, Y = specie.iloc[:, 0], specie.iloc[:, 1]

            data = DataSet(X, Y)
            train, test = random_split(data, [450, 58])
            network = FungusMoisture()
            network.cuda()
            optim = Adam(network.parameters(), lr=0.001)
            for j in range(epochs):
                for k, (x, y) in enumerate(DataLoader(train, batch_size=10)):
                    # print(k)
                    # print(x.reshape(10,1), y.reshape(10,1))
                    predict = network(x.reshape(x.shape[0], 1).float().cuda())
                    # print(predict)
                    optim.zero_grad()
                    loss = torch.sum((predict - y.reshape(x.shape[0], 1).cuda()) ** 2)
                    # print(loss)
                    loss.backward()
                    optim.step()
            network.save(idx)

    def read_fitted(self, idxes):
        models = []
        for idx in idxes:
            network = FungusMoisture()
            network.load(idx)
            network.cuda()
            models.append(network)
        return models

    def sampling(self, num):
        idxes = np.random.choice(np.arange(34), num)
        # print(idxes)
        return self.er_temp_alpha[idxes], self.er_temp_beta[idxes], self.max_er_moisture[idxes],  \
               self.read_fitted(idxes), self.colors[idxes], self.niche[idxes], self.ranking[idxes]


import csv
from delfic.entities.company import Company

__author__ = 'scorpio'

class CsvLoader:
    def __init__(self):
        self.fieldOrdinals = []
        self.setup_field_ordinals()

    def load_company_file(self, path):
        with open(path) as csv_file:
            self.read_company_file(csv_file)

    def read_company_file(self, csv_file):
        csv.register_dialect('norm', delimiter=',', quoting=csv.QUOTE_MINIMAL)
        csv_file.seek(0)
        reader = csv.reader(csv_file, 'norm')
        reader.next()
        reader.next()
        companies = []
        for rowDef in reader:
            cur_comp = CompanyCsvLine()
            set = True
            try:
                i = 0
                for val in rowDef:
                    val_stp = val.strip()
                    if val_stp != "NULL":
                        if i > 13:
                            setattr(cur_comp, self.fieldOrdinals[13], val_stp)
                        else:
                            setattr(cur_comp, self.fieldOrdinals[i], val_stp)
                    i += 1
            except Exception as ex1:
                print(ex1.message)
                set = False
            if set:
                try:
                    new_comp = Company(cur_comp.reg_no, cur_comp.name, cur_comp.turnover, cur_comp.post_code)
                    companies.append(new_comp)
                except Exception as ex:
                    print(ex.message)
                    pass
        return companies

    def setup_field_ordinals(self):
        self.fieldOrdinals = [
            "reg_no",
            "name",
            "turnover",
            "Profit",
            "Employees",
            "SIC",
            "AddressLine1",
            "AddressLine2",
            "AddressLine3",
            "AddressLine4",
            "AddressLine5",
            "Town",
            "County",
            "post_code"
        ]

class CompanyCsvLine:
    def __init__(self):
        self.post_code = None
        self.turnover = None
        self.name = None
        self.reg_no = None


# coding: utf-8

import pandas as pd
import random as rd
import os

def data():

    file_name = 'labs/data/public/sdgs/targets.csv'

    if (os.path.exists(file_name)):

        items = pd.read_csv(file_name,encoding="utf-8")

        indices = []
        targets = []

        indices = items['index']
        targets =  items['target']

        if (len(targets) > 0):

            number_of_targets = len(targets)

            if (number_of_targets == len(indices)):

                last_index = number_of_targets - 1

                selected_index = ""
                selected_target = ""

                if (last_index == 0):

                    selected_index = indices[0]
                    selected_targets = targets[0]

                else:

                    i = rd.randint(0, last_index)

                    selected_index = indices[i]
                    selected_target = targets[i]

            if (len(selected_index) and len(selected_target) > 0):
                return [selected_index, selected_target]

    return []

def message():

    d = data()

    if (len(d) == 2):

        index = ""
        target = ""

        index = d[0]
        target = d[1]

        if (len(index) > 0 and len(target) > 0):

            message = index + " : "
            message = message + target
            message = message + " "
            message = message + " #SDGs"
            message = message + " #国連"
            message = message + " #持続可能な開発目標"
            message = message + " #17の目標"
            message = message + " #169のターゲット"

            return message

    return ""


class TCP_segment():
    def __init__(self):
        self.source_port = 0
        self.destination_port = 0
        self.sequence_number = 0
        self.acknowledgment_number = 0
        self.urg = 0
        self.ack = 0
        self.psh = 0
        self.rst = 0
        self.syn = 0
        self.fin = 0
        self.data = ''

    def with_source_port(self, value):
        self.source_port = value
        return self

    def with_destination_port(self, value):
        self.destination_port = value
        return self

    def with_sequence_number(self, value):
        self.sequence_number = value
        return self

    def with_acknowledgment_number(self, value):
        self.acknowledgment_number = value
        return self

    def with_urg(self, value):
        self.urg = value
        return self

    def with_ack(self, value):
        self.ack = value
        return self

    def with_psh(self, value):
        self.psh = value
        return self

    def with_rst(self, value):
        self.rst = value
        return self

    def with_syn(self, value):
        self.syn = value
        return self

    def with_fin(self, value):
        self.fin = value
        return self

    def with_data(self, value):
        self.data = value
        return self

    def get_string(self):
        array = '{0:016b}'.format(self.source_port) \
                + '{0:016b}'.format(self.destination_port) \
                + '{0:032b}'.format(self.sequence_number) \
                + '{0:032b}'.format(self.acknowledgment_number) \
                + '0' * (4 + 6) \
                + str(int(self.urg)) \
                + str(int(self.ack)) \
                + str(int(self.psh)) \
                + str(int(self.rst)) \
                + str(int(self.syn)) \
                + str(int(self.fin)) \
                + '0' * (16 + 16 + 16) \
                + to_bits(self.data)

        return array

    def __str__(self):
        return self.get_string()

    @staticmethod
    def from_string(_string):
        obj = TCP_segment()

        return obj \
            .with_source_port(int(_string[0:16], 2)) \
            .with_destination_port(int(_string[16:32], 2)) \
            .with_sequence_number(int(_string[32:64], 2)) \
            .with_acknowledgment_number(int(_string[64:96], 2)) \
            .with_urg(bool(_string[106])) \
            .with_ack(bool(_string[107])) \
            .with_psh(bool(_string[108])) \
            .with_rst(bool(_string[109])) \
            .with_syn(bool(_string[110])) \
            .with_fin(bool(_string[111])) \
            .with_data(from_bits(_string[160:]))

def to_bits(s):
    result = ''
    for c in s:
        bits = bin(ord(c))[2:]
        result += '00000000'[len(bits):] + bits
    return result

def from_bits(bits):
    chars = []
    for b in range(int(len(bits) / 8)):
        byte = bits[b * 8:(b + 1) * 8]
        chars.append(chr(int(''.join([str(bit) for bit in byte]), 2)))
    return ''.join(chars)

# mes = 'success'
# bits = to_bits(mes)
# print(bits)
# print(from_bits(bits))


import tkinter as tk
from tkinter import messagebox

window = tk.Tk();
window.title("Egzamono Uzduotis :)")
window.resizable(False, False)
label = tk.Label(text = "Iveskite du zodzius", width=30)
label.pack();
text = tk.StringVar()
entry = tk.Entry(width = 30, textvariable=text)
entry.pack();

def message():
   messagebox.showinfo("Du zodziai", "Du zodziai: " + text.get())

control = tk.Frame()
ok = tk.Button(text="Ok", master=control, width=5, command = message)
ok.pack(pady=2, padx=30, side = tk.RIGHT)
cncl = tk.Button(text="Cancel", master=control, width=5, command=window.destroy)
cncl.pack(pady=2, padx=30, side = tk.LEFT)

control.pack()

window.mainloop();


from selenium.common.exceptions import NoSuchElementException
from selenium.common.exceptions import NoAlertPresentException
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from .locators import BasePageLocators
import math

class BasePage():

    def go_to_login_page(self):
        link = self.browser.find_element(*BasePageLocators.LOGIN_LINK)
        link.click()

    def go_to_basket_page(self):
        link = self.browser.find_element(*BasePageLocators.BASKET_ON_PAGE)
        link.click()

    def should_not_be_product_in_a_basket(self):
        assert self.is_not_element_present(*BasePageLocators.STUFF_IN_BASKET), "Product is presented in basket"

    def should_be_text_about_empty_basket(self):
        assert self.is_element_present(*BasePageLocators.TEXT_ABOUT_EMPTY_BASKET), "Text about empty basket is not presented in basket"
        "Success message is not presented"
        #сообщение о добавлении отсутсвует
#переход в корзину

    def should_be_login_link(self):
        assert self.is_element_present(*BasePageLocators.LOGIN_LINK), "Login link is not presented"

    def should_be_authorized_user(self):
        assert self.is_element_present(*BasePageLocators.USER_ICON), "User icon is not presented," \
                                                                 " probably unauthorised user"

    def __init__(self, browser, url, timeout=10):
        #Внутри конструктора сохраняем эти данные как аттрибуты нашего класса
        self.browser = browser
        self.url = url
        self.browser.implicitly_wait(timeout)

    def open(self):
        #добавим еще один метод, который открывает нужную страницу в браузере
        self.browser.get(self.url)

    def is_element_present(self, how, what):
        try:
            self.browser.find_element(how, what)
        except NoSuchElementException:
            return False
        return True

    def solve_quiz_and_get_code(self):
        alert = self.browser.switch_to.alert
        x = alert.text.split(" ")[2]
        answer = str(math.log(abs((12 * math.sin(float(x))))))
        alert.send_keys(answer)
        alert.accept()
        try:
            alert = self.browser.switch_to.alert
            print("Your code: {}".format(alert.text))
            alert.accept()
        except NoAlertPresentException:
            print("No second alert presented")

    def is_not_element_present(self, how, what, timeout=4):
        try:
            WebDriverWait(self.browser, timeout).until(EC.presence_of_element_located((how, what)))
        except TimeoutException:
            return True

        return False

    def is_disappeared(self, how, what, timeout=4):
        try:
            WebDriverWait(self.browser, timeout, 1, TimeoutException).\
            until_not(EC.presence_of_element_located((how, what)))
        except TimeoutException:
            return False

        return True


# screen
ASPECT_RATIO = 4/3
SCR_H = 960
SCR_W = int(ASPECT_RATIO * SCR_H)
SCR_W2 = SCR_W // 2
SCR_H2= SCR_H // 2
SCR_SIZE = (SCR_W, SCR_H)

# start menu
START_MENU_SHOW = 1
START_MENU_WAIT = 0
START_MENU_HIDE = -1
START_MENU_ANIMATION_TIME = 1500

# upgrade_menu
UPGRADE_MENU_ANIMATION_TIME = 350

# game
ROOM_RADIUS = int(7/6 * SCR_H)
DIST_BETWEEN_ROOMS = int(3.05 * SCR_H)
TRANSPORTATION_TIME = 600
MU = 0.00064


import numpy as np
import math

msg = input("Enter Message : ")
n = len(msg)
key = input(f"Enter key of size 3*3 : " )

def encrypt(msg , key ):
   keyA = np.array( [ ord(x) % 65 for x in key ] )
   keyA = np.reshape( keyA , (3,3) )
   print(keyA)
   msgA = [ ord(x) % 65 for x in msg ]
   i=n
   while(i<(math.ceil(n/3)*3)):
    msgA.append(23)
    i+=1
   msgA = np.array(msgA)
   msgA = np.reshape(msgA, (math.ceil(n/3),3) )
   print(msgA)

   encryptedMsgA = np.dot( msgA,keyA ) %26
   print(encryptedMsgA)
   encryptedMsg = ""
   for i in encryptedMsgA:
        for j in range(3):
            encryptedMsg += chr( i[j] + 65 )
   return encryptedMsg

def egcd(a,b):
    t1,t2 = 0,1
    while(b != 0):
        q, r = a // b , a % b
        t = t1 - q*t2
        a,b , t1,t2 = b,r , t2,t
    return a , t1

def modinv(a, m):
   gcd, x = egcd(m, a)
   if gcd != 1:
       return None
   else:
       return x % m

def decrypt( msg , key ):
   keyA = np.array( [ ord(x) % 65 for x in key ] )
   keyA = np.reshape( keyA , (3,3) )

   msgA = np.array( [ ord(x) % 65 for x in msg ] )
   msgA = np.reshape(msgA, (math.ceil(n/3),3) )

   detInv = modinv( np.linalg.det(keyA) , 26 )
   keyInvA = np.linalg.inv(keyA) * np.linalg.det(keyA)

   keyInvA = np.round( ((keyInvA % 26 )* detInv)%26 )
   decA = np.dot(msgA,keyInvA ) % 26
   decA=(np.rint(decA)).astype(int)
   print(decA)
   dec = ""
   for i in decA:
        for j in range(3):
            if(i[j]!=23):
                dec += chr( i[j] + 65 )

   return dec

eMsg = encrypt(msg, key)
print( eMsg )

dMsg = decrypt(eMsg, key)
print(dMsg)


import scrapy

from ..items import ShubitrageItem
class NikeSpider(scrapy.Spider):
    name = "Nike"
    allowed_domains = ["Nike.com", "stockx.com"]

    sku = input('Enter SKU - ')

    start_urls = [f"https://www.nike.com/w?q={sku}"]

    def parse(self, response):
        shoe_name = response.css('div.product-card__title::text').get()
        shoe_category = response.css('div.product-card__subtitle::text').get()

        selling_price = response.css('div.is--current-price::text').get()

        try:
            original_price = response.css('div.is--striked-out::text').get()
        except AttributeError:
            original_price = None

        try:
            best_seller = response.css('div.product-card__messaging.accent--color::text').get()
        except AttributeError:
            best_seller = None

        items = ShubitrageItem()

        items['sku'] = NikeSpider.sku
        items['Nike_category'] = shoe_category
        items['Nike_name'] = shoe_name
        items['Nike_selling_price'] = selling_price
        items['Nike_original_price'] = original_price
        items['Nike_status'] = best_seller

        stockx_url = f'https://stockx.com/search?s={NikeSpider.sku}'

        yield scrapy.Request(stockx_url, callback=self.parse_stockx, cb_kwargs={'items':items})

    def parse_stockx(self, response, items):
        main = response.css('div.css-xzkzsa')
        for search in main:
            stockx_name = search.css('p.chakra-text.css-3lpefb::text').extract()
            stockx_status = search.css('p.chakra-text.css-jsq4f::text').extract()
            stockx_price = search.css('p.chakra-text.css-nsvdd9::text').extract()

            items['stockx_price'] = stockx_price
            items['stockx_name'] = stockx_name
            items['stockx_status'] = stockx_status

        yield items


# WebPushNotification.py
import time

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

chrome_options = Options()
chrome_options.add_argument("--disable-notifications")
driver = webdriver.Chrome()
driver.maximize_window()
driver.get("https://www.homedepot.com/")

time.sleep(2)
driver.close()


'''
 Crie um programa em python que leia o arquivo sequence.fasta (disponível no moodle), e retorne uma lista de tuplas (header,sequência), onde header é o cabeçalho da sequência (linha iniciada por “>”) e a sequência é aquela composto por nucleotídeos (a, c, t, g)
'''

#lendo um arquivo .fasta
filename = "sequence.fasta"

#colocando o arquivo em uma lista
with open(filename) as fp:
    arquivo = fp.readlines()

#Separando as informações do arquivo em duas listas
for i in arquivo :

    lista1 = arquivo[::2] #lista de nomes
    lista2 = arquivo[1::2]#lista de sequência

#convertendo a lista1 em string para tirar os ">"
lista1_string = ' '.join(lista1)
lista1_string = lista1_string.replace('>', '')

#convertendo a lista2 em string para tirar os "\n"
lista2_string = ' '.join(lista2)
lista2_string = lista2_string.replace('\n', '')

#convertendo de string para lista
lista1 = lista1_string.split()
lista2 = lista2_string.split()

#convertendo para uma lista de tuplas
lista = list(zip(lista1, lista2)) #criando uma lista de tuplas

#formatando a saida
for nome, seq in lista:
    print("(" +nome+" , " +seq+")" )


"""Tests for BrowserTimeframePlugin."""
from __future__ import unicode_literals

import numpy as np
import pandas as pd

from timesketch.lib.analyzers import browser_timeframe
from timesketch.lib.testlib import BaseTest

class TestBrowserTimeframePlugin(BaseTest):
    """Tests the functionality of the analyzer."""

    def test_get_list_of_consecutive_sequences(self):
        """Test the get_list_of_consecutive_sequences function."""
        hours = [0, 1, 2, 3, 9, 10, 11, 12, 13, 14]
        runs = browser_timeframe.get_list_of_consecutive_sequences(hours)

        self.assertEqual(len(runs), 2)

        first_run = runs[0]
        self.assertEqual(first_run[0], 0)
        self.assertEqual(first_run[1], 3)

        second_run = runs[1]
        self.assertEqual(second_run[0], 9)
        self.assertEqual(second_run[1], 14)

        hours = [0, 2, 3, 9, 10, 12, 14]
        runs = browser_timeframe.get_list_of_consecutive_sequences(hours)
        self.assertEqual(len(runs), 5)

    def test_fix_gap_in_list(self):
        """Test the fix_gap_in_list function."""
        hours = [0, 6, 10, 11, 13, 14]
        fixed_hours = browser_timeframe.fix_gap_in_list(hours)

        self.assertEqual(fixed_hours, [0, 10, 11, 12, 13, 14])

    def test_get_active_hours(self):
        """Test get_active_hours function."""
        date_array = np.random.randn(500)
        hours = [
            np.repeat(0, 80),
            np.repeat(1, 50),
            np.repeat(4, 10),
            np.repeat(7, 8),
            np.repeat(12, 12),
            np.repeat(18, 40),
            np.repeat(19, 50),
            np.repeat(20, 10),
            np.repeat(21, 90),
            np.repeat(22, 50),
            np.repeat(23, 100),
        ]

        data_frame = pd.DataFrame(
            {"hour": np.concatenate(hours), "datetime": date_array}
        )

        expected_hours = [0, 1, 18, 19, 20, 21, 22, 23]
        active_hours, _, _ = browser_timeframe.get_active_hours(data_frame)
        self.assertEqual(active_hours, expected_hours)


from __future__ import unicode_literals
import os
import logbook
import sys

import trollius as asyncio
from trollius import From, subprocess, Return
from trollius.executor import TimeoutError
from trollius.py33_exceptions import ProcessLookupError

from pyshark.tshark.tshark import get_tshark_path, get_tshark_display_filter_flag
from pyshark.tshark.tshark_xml import packet_from_xml_packet, psml_structure_from_xml

class TSharkCrashException(Exception):
    pass

class UnknownEncyptionStandardException(Exception):
    pass

class Capture(object):
    """
    Base class for packet captures.
    """
    DEFAULT_BATCH_SIZE = 2 ** 16
    SUMMARIES_BATCH_SIZE = 64
    DEFAULT_LOG_LEVEL = logbook.CRITICAL
    SUPPORTED_ENCRYPTION_STANDARDS = ['wep', 'wpa-pwk', 'wpa-pwd', 'wpa-psk']

    def __init__(self, display_filter=None, only_summaries=False, eventloop=None,
                 decryption_key=None, encryption_type='wpa-pwd', output_file=None,
                 decode_as=None, tshark_path=None, override_prefs=None):
        self._packets = []
        self.current_packet = 0
        self.display_filter = display_filter
        self.only_summaries = only_summaries
        self.output_file = output_file
        self.running_processes = set()
        self.loaded = False
        self.decode_as = decode_as
        self.log = logbook.Logger(self.__class__.__name__, level=self.DEFAULT_LOG_LEVEL)
        self.tshark_path = tshark_path
        self.override_prefs = override_prefs
        self.debug = False

        self.eventloop = eventloop
        if self.eventloop is None:
            self.setup_eventloop()
        if encryption_type and encryption_type.lower() in self.SUPPORTED_ENCRYPTION_STANDARDS:
            self.encryption = (decryption_key, encryption_type.lower())
        else:
            raise UnknownEncyptionStandardException("Only the following standards are supported: %s."
                                                    % ', '.join(self.SUPPORTED_ENCRYPTION_STANDARDS))

    def __getitem__(self, item):
        """
        Gets the packet in the given index.

        :param item: packet index
        :return: Packet object.
        """
        return self._packets[item]

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

    def next(self):
        return self.next_packet()

    # Allows for child classes to call next() from super() without 2to3 "fixing"
    # the call
    def next_packet(self):
        if self.current_packet >= len(self._packets):
            raise StopIteration()
        cur_packet = self._packets[self.current_packet]
        self.current_packet += 1
        return cur_packet

    def clear(self):
        """
        Empties the capture of any saved packets.
        """
        self._packets = []
        self.current_packet = 0

    def reset(self):
        """
        Starts iterating packets from the first one.
        """
        self.current_packet = 0

    def load_packets(self, packet_count=0, timeout=None):
        """
        Reads the packets from the source (cap, interface, etc.) and adds it to the internal list.
        If 0 as the packet_count is given, reads forever

        :param packet_count: The amount of packets to add to the packet list (0 to read forever)
        :param timeout: If given, automatically stops after a given amount of time.
        """
        initial_packet_amount = len(self._packets)
        def keep_packet(pkt):
            self._packets.append(pkt)

            if packet_count != 0 and len(self._packets) - initial_packet_amount >= packet_count:
                raise Return()

        try:
            self.apply_on_packets(keep_packet, timeout=timeout)
            self.loaded = True
        except TimeoutError:
            pass

    def set_debug(self):
        """
        Sets the capture to debug mode.
        """
        self.log.level = logbook.DEBUG
        self.debug = True

    def setup_eventloop(self):
        """
        Sets up a new eventloop as the current one according to the OS.
        """
        if os.name == 'nt':
            self.eventloop = asyncio.ProactorEventLoop()
            if sys.version_info <= (3, 0):
                # FIXME: There appears to be a bug in the 2.7 version of trollius, wherein the selector retrieves an
                # object of value 0 and attempts to look for it in the weakref set, which raises an exception.
                # This hack sidesteps this issue, but does not solve it. If a proper fix is found, apply it!
                self.eventloop._selector._stopped_serving = set()
        else:
            self.eventloop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.eventloop)

    @staticmethod
    def _extract_tag_from_data(data, tag_name=b'packet'):
        """
        Gets data containing a (part of) tshark xml.
        If the given tag is found in it, returns the tag data and the remaining data.
        Otherwise returns None and the same data.

        :param data: string of a partial tshark xml.
        :return: a tuple of (tag, data). tag will be None if none is found.
        """
        opening_tag = b'<' + tag_name + b'>'
        closing_tag = opening_tag.replace(b'<', b'</')
        tag_end = data.find(closing_tag)
        if tag_end != -1:
            tag_end += len(closing_tag)
            tag_start = data.find(opening_tag)
            return data[tag_start:tag_end], data[tag_end:]
        return None, data

    def _packets_from_tshark_sync(self, packet_count=None, existing_process=None):
        """
        Returns a generator of packets.
        This is the sync version of packets_from_tshark. It wait for the completion of each coroutine and
         reimplements reading packets in a sync way, yielding each packet as it arrives.

        :param packet_count: If given, stops after this amount of packets is captured.
        """
        # NOTE: This has code duplication with the async version, think about how to solve this
        tshark_process = existing_process or self.eventloop.run_until_complete(self._get_tshark_process())
        psml_structure, data = self.eventloop.run_until_complete(self._get_psml_struct(tshark_process.stdout))
        packets_captured = 0

        data = b''
        try:
            while True:
                try:
                    packet, data = self.eventloop.run_until_complete(
                        self._get_packet_from_stream(tshark_process.stdout, data, psml_structure=psml_structure))
                except EOFError:
                    self.log.debug('EOF reached (sync)')
                    break
                if packet:
                    packets_captured += 1
                    yield packet
                if packet_count and packets_captured >= packet_count:
                    break
        finally:
            self._cleanup_subprocess(tshark_process)

    def apply_on_packets(self, callback, timeout=None):
        """
        Runs through all packets and calls the given callback (a function) with each one as it is read.
        If the capture is infinite (i.e. a live capture), it will run forever, otherwise it will complete after all
        packets have been read.

        Example usage:
        def print_callback(pkt):
            print pkt
        capture.apply_on_packets(print_callback)

        If a timeout is given, raises a Timeout error if not complete before the timeout (in seconds)
        """
        coro = self.packets_from_tshark(callback)
        if timeout is not None:
            coro = asyncio.wait_for(coro, timeout)
        return self.eventloop.run_until_complete(coro)

    @asyncio.coroutine
    def packets_from_tshark(self, packet_callback, packet_count=None):
        """
        A coroutine which creates a tshark process, runs the given callback on each packet that is received from it and
        closes the process when it is done.

        Do not use directly. Can be used in order to insert packets into your own eventloop.
        """
        tshark_process = yield From(self._get_tshark_process(packet_count=packet_count))
        try:
            yield From(self._go_through_packets_from_fd(tshark_process.stdout, packet_callback,
                                                        packet_count=packet_count))
        finally:
            self._cleanup_subprocess(tshark_process)

    @asyncio.coroutine
    def _go_through_packets_from_fd(self, fd, packet_callback, packet_count=None):
        """
        A coroutine which goes through a stream and calls a given callback for each XML packet seen in it.
        """
        packets_captured = 0
        self.log.debug('Starting to go through packets')

        psml_struct, data = yield From(self._get_psml_struct(fd))

        while True:
            try:
                packet, data = yield From(self._get_packet_from_stream(fd, data, psml_structure=psml_struct))
            except EOFError:
                self.log.debug('EOF reached')
                break

            if packet:
                packets_captured += 1
                packet_callback(packet)

            if packet_count and packets_captured >= packet_count:
                break

    @asyncio.coroutine
    def _get_psml_struct(self, fd):
        """
        Gets the current PSML (packet summary xml) structure in a tuple ((None, leftover_data)),
        only if the capture is configured to return it, else returns (None, leftover_data).

        A coroutine.
        """
        data = b''
        psml_struct = None

        if self.only_summaries:
            # If summaries are read, we need the psdml structure which appears on top of the file.
            while not psml_struct:
                new_data = yield From(fd.read(self.SUMMARIES_BATCH_SIZE))
                data += new_data
                psml_struct, data = self._extract_tag_from_data(data, b'structure')
                if psml_struct:
                    psml_struct = psml_structure_from_xml(psml_struct)
                elif not new_data:
                    raise Return(None, data)
            raise Return(psml_struct, data)
        else:
            raise Return(None, data)

    @asyncio.coroutine
    def _get_packet_from_stream(self, stream, existing_data, psml_structure=None):
        """
        A coroutine which returns a single packet if it can be read from the given StreamReader.
        :return a tuple of (packet, remaining_data). The packet will be None if there was not enough XML data to create
        a packet. remaining_data is the leftover data which was not enough to create a packet from.
        :raises EOFError if EOF was reached.
        """
        #yield each packet in existing_data
        #Maybe there is already a packet in our buffer
        packet, existing_data = self._extract_tag_from_data(existing_data)

        if packet:
            packet = packet_from_xml_packet(packet, psml_structure=psml_structure)
            raise Return(packet, existing_data)

        new_data = yield From(stream.read(self.DEFAULT_BATCH_SIZE))
        existing_data += new_data

        if not new_data:
            # Reached EOF
            raise EOFError()
        raise Return(None, existing_data)

    @asyncio.coroutine
    def _get_tshark_process(self, packet_count=None, stdin=None):
        """
        Returns a new tshark process with previously-set parameters.
        """
        xml_type = 'psml' if self.only_summaries else 'pdml'
        parameters = [get_tshark_path(self.tshark_path), '-l', '-n', '-T', xml_type] + self.get_parameters(packet_count=packet_count)

        self.log.debug('Creating TShark subprocess with parameters: ' + ' '.join(parameters))

        # Ignore stderr output unless in debug mode (sent to console)
        output = None if self.debug else open(os.devnull, "w")
        tshark_process = yield From(asyncio.create_subprocess_exec(*parameters,
                                                                    stdout=subprocess.PIPE,
                                                                    stderr=output,
                                                                    stdin=stdin))
        self.log.debug('TShark subprocess created')

        if tshark_process.returncode is not None and tshark_process.returncode != 0:
            raise TSharkCrashException(
                'TShark seems to have crashed. Try updating it. (command ran: "%s")' % ' '.join(parameters))
        self.running_processes.add(tshark_process)
        raise Return(tshark_process)

    def _cleanup_subprocess(self, process):
        """
        Kill the given process and properly closes any pipes connected to it.
        """
        if process.returncode is None:
            try:
                process.kill()
            except ProcessLookupError:
                pass
            except OSError:
                if os.name != 'nt':
                    raise
        elif process.returncode > 0:
            raise TSharkCrashException('TShark seems to have crashed (retcode: %d). Try rerunning in debug mode [ capture_obj.set_debug() ] or try updating tshark.' % process.returncode)

    def close(self):
        for process in self.running_processes:
            self._cleanup_subprocess(process)

    def __del__(self):
        self.close()

    def get_parameters(self, packet_count=None):
        """
        Returns the special tshark parameters to be used according to the configuration of this class.
        """
        params = []
        if self.display_filter:
            params += [get_tshark_display_filter_flag(self.tshark_path), self.display_filter]
        if packet_count:
            params += ['-c', str(packet_count)]
        if all(self.encryption):
            params += ['-o', 'wlan.enable_decryption:TRUE', '-o', 'uat:80211_keys:"' + self.encryption[1] + '","' +
                                                                  self.encryption[0] + '"']
        if self.override_prefs:
            for preference_name, preference_value in self.override_prefs.items():
                if all(self.encryption) and preference_name in ('wlan.enable_decryption', 'uat:80211_keys'):
                    continue  # skip if override preferences also given via --encryption options
                params += ['-o', '{0}:{1}'.format(preference_name, preference_value)]

        if self.output_file:
            params += ['-w', self.output_file]

        if self.decode_as:
            for criterion, decode_as_proto in self.decode_as.items():
                params += ['-d', ','.join([criterion.strip(), decode_as_proto.strip()])]
        return params

    def __iter__(self):
        if self.loaded:
            return iter(self._packets)
        else:
            return self._packets_from_tshark_sync()

    def __repr__(self):
        return '<%s (%d packets)>' % (self.__class__.__name__, len(self._packets))


#Time Series Predictions
#https://www.youtube.com/watch?v=D9y6dcy0xK8
#https://www.machinelearningplus.com/time-series/arima-model-time-series-forecasting-python/
#https://www.machinelearningplus.com/time-series/time-series-analysis-python/
#https://www.datacamp.com/community/tutorials/time-series-analysis-tutorial
#https://otexts.com/fpp2/stochastic-and-deterministic-trends.html

import pandas as pd
from pandas import datetime
import matplotlib.pyplot as plt
import numpy as np
from statsmodels.tsa.stattools import acf
from statsmodels.tsa.seasonal import seasonal_decompose
from statsmodels.graphics.tsaplots import plot_acf, plot_pacf
from statsmodels.tsa.ar_model import AR
from sklearn.metrics import mean_squared_error
from pandas import DataFrame
from statsmodels.tsa.arima_model import ARIMA
import itertools
import warnings

def parser(x): return datetime.strptime (x, '%Y-%m-%d')

def turn_list():
    for pred in fc:
        forecasted.append(pred)
    test_n = test.values
    for val in test_n:
        for idk in val:
            actual.append(idk)
    print('')
    print('Forecasted Values')
    print(forecasted)
    print('Actual values')
    print(actual)

#Errors
def forecast_accuracy(forecast, actual):
    mape = np.mean(np.abs(list(np.array(forecast) - np.array(actual)))/np.abs(actual))  # MAPE
    me = np.mean(list(np.array(forecast) - np.array(actual)))             # ME
    mae = np.mean(np.abs(list(np.array(forecast) - np.array(actual))))    # MAE
    mpe = np.mean((list(np.array(forecast) - np.array(actual)))/np.array(actual))   # MPE
    rmse = np.mean(list(np.array(list(np.array(forecast) - np.array(actual)))**2))**.5  # RMSE
    corr = np.corrcoef(forecast, actual)[0,1]   # corr
#    mins = np.amin(np.hstack([forecast[:,None],
#                              actual[:,None]]), axis=1)
#    maxs = np.amax(np.hstack([forecast[:,None],
#                              actual[:,None]]), axis=1)
#    minmax = 1 - np.mean(mins/maxs)             # minmax
#    acf1 = acf(pd.Series(list(np.array(forecast)-np.array(test)), index=test.index))[1]                      # ACF1
    return({'mape':mape, 'me':me, 'mae': mae,
            'mpe': mpe, 'rmse':rmse,'corr':corr})

#('https://raw.githubusercontent.com/selva86/datasets/master/wwwusage.csv', names=['value'], header=0)
#('/users/Juan Riofrio/Downloads/daily-min-temperatures.csv', index_col = 0,parse_dates = [0], date_parser = parser,converters={'Daily minimum temperatures':float})
#Plot sales
t_file = pd.read_csv('https://raw.githubusercontent.com/selva86/datasets/master/wwwusage.csv', names=['value'], header=0)

r_min =0
train_r=85
test_r=15
size_d=train_r+test_r+r_min

#Dividing data
sales = t_file[r_min:size_d]
train = sales[0:train_r] #28 data as train data
test = sales[train_r:(train_r+test_r)]   #8 data as test data
predictionsAR = []
predictionsARIMA = []
forecasted= []
actual = []

#print(sales.head())
#print(sales.tail())
#print(sales.values)
#print(sales.size)
print(sales.describe().transpose())

plt.figure(figsize=(12,5), dpi=100)
plt.plot(sales)
plt.title('Sales per Date(month-year)')
plt.xlabel('Date')
plt.ylabel('Sales')
plt.show()

decomp = seasonal_decompose(sales, freq = 25)
decomp.plot()
plt.show()

#Autocorrelation - Partial Autocorrelation
plot_acf(sales)
plt.title('Sales Autocorrelation')
plt.show()

plot_pacf(sales, title = 'Sales Partial Autocorrelation', lags=50)
plt.show()

#Integrated - Converting to Stationary - Differencing
sales_diff = sales.diff(periods=1) #Integrated of order 1
sales_diff = sales_diff[1:]

sales_diff.plot()
plt.title('Sales(Integrated of order 1)')
plt.xlabel('Dates')
plt.show()

#Autocorrelation - Partial Autocorrelation DIFF
plot_acf(sales_diff)
plt.title('Diff_Sales Autocorrelation')
plt.show()

plot_pacf(sales_diff, title='Diff_Sales Partial Autocorrelation', lags=50, method='ywm')
plt.show()

#AutoRegressive Model
model_ar = AR(train)    #freq = 'D'
model_ar_fit = model_ar.fit()
predictionsAR = model_ar_fit.predict(start=train_r, end = size_d)

plt.plot(test, label = 'Real data')
plt.plot(predictionsAR, color = 'red', label ='AR prediction')
plt.title('Predictions AR')
plt.ylabel('Sales')
plt.legend()
plt.show()

#ARIMA model(AutoRegresive Integrated Moving Average)
#Parameters for ARIMA (p,d,q)
#p = periods taken for autoregressive model
#d = Integrated order, difference
#q = periods in moving average model
#AIC = Akaike Information Criteria (the less the better)

model_arimaX = ARIMA (sales, order = (3,2,1)) #freq = 'D'
model_arimaX_fit = model_arimaX.fit(disp = 0)
model_arimaX_fit.plot_predict(dynamic=False)
plt.show()

#ARIMA parameters (found the correct one)
#p=d=q=range(0,5)
#aux = None
#pdq = list(itertools.product(p,d,q))
#warnings.filterwarnings('ignore')

#for param in pdq:
#   try:
#      model_arima = ARIMA (train, order = param)
#      model_arima_fit = model_arima.fit(disp = 0)
#      if aux is None:
#         aux = [param, model_arima_fit.aic]
#      if model_arima_fit.aic < aux[1]:
#         aux = [param, model_arima_fit.aic]
#      print(aux)
#   except:
#      continue
#print(aux) #aic less the better

#model_arima = ARIMA(train, order = aux[0])    #Train with the best p,d,q
model_arima = ARIMA(train, order = (3,2,1))    #freq = 'D'
model_arima_fit = model_arima.fit(disp = 0)
fc, se , conf = model_arima_fit.forecast(test_r, alpha=0.05) #95%conf
print(fc)
print(test)
print(test)
turn_list()
x=forecast_accuracy(forecasted, actual)
print('')
print(x)
fc_series = pd.Series(fc, index=test.index)
lower_series = pd.Series(conf[:, 0])
upper_series = pd.Series(conf[:, 1])

# Plot
print(model_arima_fit.summary())
plt.figure(figsize=(12,5), dpi=100)
plt.plot(train, label='training')
plt.plot(test, label='actual')
plt.plot(fc_series, label='forecast')
print(fc_series.subtract(test))
plt.fill_between(test.index, lower_series, upper_series, color='k', alpha=.15)
plt.title('Forecast vs Actuals')
plt.legend(loc='upper left', fontsize=8)
plt.show()

predictionsARIMA = model_arima_fit.forecast(steps=test_r)[0]
prediction_serie = pd.Series(predictionsARIMA, index=test.index)
plt.plot(test, label = 'Real data')
plt.plot(prediction_serie, color = 'red', label = 'ARIMA prediction')
plt.title('Predictions ARIMA')
plt.ylabel('Sales')
plt.legend()
plt.show()

# plot residual errors
residuals = DataFrame(model_arima_fit.resid)
residuals.plot()
plt.title('Residual Errors')
plt.show()
residuals.plot(kind='kde')
plt.title('Density Plot of Residual Errors')
plt.show()
print('Residual Errors description')
print(residuals.describe().transpose())

#import statsmodels.tsa.statespace.mlemodel.MLEResults.plot_diagnostics
#model_arima_fit.plot_diagnostics(figsize=(15,12))
#plt.show()

# Forecast
n_periods = 24
n_start=train_r+test_r
prediction_arima = ARIMA(sales, order = (3,2,1))    #freq = 'D'
prediction_arima_fit = prediction_arima.fit(disp = 0)
fc, se , confint = prediction_arima_fit.forecast(n_periods, alpha=0.05) #95%conf
index_of_fc = np.arange(n_start, n_start+n_periods)

# make series for plotting purpose
fc_series = pd.Series(fc, index=index_of_fc)
print('------------------------------------------------------------------------')
print('')
print('Forecasted values')
print(fc_series)
print(prediction_arima_fit.summary())
lower_series = pd.Series(confint[:, 0], index=index_of_fc)
upper_series = pd.Series(confint[:, 1], index=index_of_fc)

# Plot
plt.figure(figsize=(12,5), dpi=100)
plt.plot(sales)
plt.plot(fc_series, color='darkgreen')
plt.fill_between(lower_series.index,
                 lower_series,
                 upper_series,
                 color='k', alpha=.15)

plt.title("Final Forecast of WWW Usage")
plt.show()


from django_filters.rest_framework import FilterSet

from automate.models import Project

class RepositoryFilter(FilterSet):
    """Repository Filterset Class."""

    class Meta:
        """Metaclass for Repository Filterset Class."""

        model = Project
        # fmt: off
        fields = [
            "owner",
            "name",
            "slug",
            "primary_repo_owner",
            "primary_repo_name",
            "primary_repo_token",
            "primary_repo_type",
            "primary_repo_project_name",
            "secondary_repo_owner",
            "secondary_repo_name",
            "secondary_repo_token",
            "secondary_repo_type",
            "secondary_repo_project_name",
        ]