# -*- coding: utf-8 -*-

import json
import urllib
from django.contrib import auth
from django.http import HttpResponse, HttpResponseRedirect, Http404
from django.template import RequestContext
from django.shortcuts import render_to_response
from django.conf import settings

from common import utils, page
from www.misc import qiniu_client
from www.misc.decorators import staff_required, common_ajax_response, verify_permission

from www.question.interface import TopicBase

@verify_permission('')
def topic(request, template_name='admin/topic.html'):
    from www.question.models import Topic
    states = [{'name': x[1], 'value': x[0]} for x in Topic.state_choices]
    return render_to_response(template_name, locals(), context_instance=RequestContext(request))

def format_topic(objs, num):
    data = []

    for x in objs:
        num += 1
        data.append({
            'num': num,
            'topic_id': x.id,
            'name': x.name,
            'domain': x.domain,
            'parent_id': x.parent_topic.id if x.parent_topic else '',
            'parent_name': x.parent_topic.name if x.parent_topic else '',
            'child_count': x.child_count,
            'follower_count': x.follower_count,
            'question_count': x.question_count,
            'level': x.level,
            'img': x.get_img(),
            'des': x.des,
            'sort': x.sort_num,
            'is_show': x.is_show,
            'state': x.state,
            'create_time': str(x.create_time)
        })

    return data

@verify_permission('query_topic')
def search(request):
    topic_name = request.POST.get('topic_name')
    page_index = int(request.POST.get('page_index', 1))

    data = []

    if topic_name:
        objs = TopicBase().get_topic_by_name(topic_name)
        objs = [objs] if objs else []
    else:
        objs = TopicBase().get_all_topics()

    page_objs = page.Cpt(objs, count=10, page=page_index).info

    num = 10 * (page_index - 1)
    data = format_topic(page_objs[0], num)

    return HttpResponse(
        json.dumps({'data': data, 'page_count': page_objs[4], 'total_count': page_objs[5]}),
        mimetype='application/json'
    )

@verify_permission('query_topic')
def get_topics_by_name(request):
    topic_name = request.REQUEST.get('topic_name')

    result = []

    topics = TopicBase().get_topics_by_name(topic_name)

    if topics:
        for x in topics:
            result.append([x.id, x.name, None, x.name])

    return HttpResponse(json.dumps(result), mimetype='application/json')

@verify_permission('query_topic')
def get_topic_by_id(request):
    data = ""

    topic_id = request.REQUEST.get('topic_id')

    obj = TopicBase().get_topic_by_id_or_domain(topic_id, False)

    if obj:
        data = format_topic([obj], 1)[0]

    return HttpResponse(json.dumps(data), mimetype='application/json')

@verify_permission('modify_topic')
def modify_topic(request):
    topic_id = request.REQUEST.get('topic_id')
    name = request.REQUEST.get('name')
    domain = request.REQUEST.get('domain')
    des = request.REQUEST.get('des')
    state = request.REQUEST.get('state')
    sort = request.REQUEST.get('sort')
    parent_topic_id = request.REQUEST.get('parent_id')

    tb = TopicBase()
    obj = tb.get_topic_by_id_or_domain(topic_id, False)
    img_name = obj.img

    img = request.FILES.get('img')
    if img:
        flag, img_name = qiniu_client.upload_img(img, img_type='topic')
        img_name = '%s/%s' % (settings.IMG0_DOMAIN, img_name)

    code, msg = tb.modify_topic(topic_id, name, domain, des, img_name, state, parent_topic_id, sort)

    if code == 0:
        url = "/admin/topic?#modify/%s" % (topic_id)
    else:
        url = "/admin/topic?%s#modify/%s" % (msg, topic_id)

    return HttpResponseRedirect(url)

@verify_permission('add_topic')
def add_topic(request):
    name = request.REQUEST.get('name')
    domain = request.REQUEST.get('domain')
    des = request.REQUEST.get('des')
    state = request.REQUEST.get('state')
    sort = request.REQUEST.get('sort')
    parent_topic_id = request.REQUEST.get('parent_id')

    tb = TopicBase()
    img_name = ''

    img = request.FILES.get('img')
    if img:
        flag, img_name = qiniu_client.upload_img(img, img_type='topic')
        img_name = '%s/%s' % (settings.IMG0_DOMAIN, img_name)

    flag, msg = tb.create_topic(name, domain, parent_topic_id, img_name, des)

    if flag == 0:
        url = "/admin/topic?#modify/%s" % (msg)
    else:
        url = "/admin/topic?%s" % (msg)

    return HttpResponseRedirect(url)


# script to find best results of mnist evaluation based on accuracy, same accuracy is not taken care of
import numpy as np

# opening file
with open('log.txt') as file:
    # reading all lines from file, skipping first 2 lines
    lines = file.readlines()[2:]
    # closing file
    file.close()

    # declaring list scores
    scores = []

    # appending characters until first space (accuracy) to scores list
    [scores.append(line.split(' ')[0]) for line in lines]

    # finding index of highest value using numpy
    idx = np.argmax(np.array(scores))

    # printing entire line of best accuracy
    print(lines[idx])


# -*- coding: utf-8 -*-
from django.db import models
from django.conf import settings

from .base import BaseModel
from .user_group import UserGroup

class Event(BaseModel):
    TYPE_1, TYPE_2 = xrange(2)
    SOURCE_GROUP, SOURCE_INDIVIDUAL = xrange(2)

    EVENT_TYPES = (
        (TYPE_1, 'Collecting'),
        (TYPE_2, 'Spent')
    )

    SOURCE_TYPES =(
        (SOURCE_GROUP, 'Group'),
        (SOURCE_INDIVIDUAL, 'Individual')
    )

    group = models.ForeignKey(
        UserGroup,
        on_delete=models.CASCADE,
        related_name="events"
    )
    event_type = models.SmallIntegerField(
        choices=EVENT_TYPES)

    amount = models.DecimalField(default=0.0, max_digits=10, decimal_places=2)
    description = models.TextField(default=None)
    source_money = models.SmallIntegerField(choices=SOURCE_TYPES, default=SOURCE_GROUP)
    member_join = models.TextField(null=True)

    def collecting_money(self):
        from .transaction import Transaction
        if self.event_type == self.TYPE_1:
            for user in self.group.members.filter(id__in=self.member_join_list):
                Transaction.create_user_paid_transaction(
                    user=user,
                    amount=self.amount,
                    description=u"<@%s> đóng tiền vào quỹ '%s' cho event '%s'" %(user.userprofile.slack_id, self.group.name, self.description),
                    group=self.group,
                    paid_group=True,
                    event_id=self.id
                )
        if self.event_type == self.TYPE_2:
            if self.source_money == self.SOURCE_GROUP:
                Transaction.create_group_paid_transaction(
                    amount=self.amount,
                    description=u"<@%s> trả tiền cho event '%s'" %(self.group.name, self.description),
                    group=self.group,
                    event=self
                )
            if self.source_money == self.SOURCE_INDIVIDUAL:
                for user in self.group.members.filter(id__in=self.member_join_list):
                    Transaction.create_user_paid_transaction(
                        user=user,
                        amount=self.amount,
                        description=u"<@%s> trả tiền cho event '%s' của '%s'" %(user.userprofile.slack_id, self.description, self.group.name),
                        group=self.group,
                        paid_group=False,
                        event_id=self.id
                    )

    @property
    def event_complete_status(self):
        from .transaction import Transaction
        if self.transactions.filter(status=Transaction.PENDING).count() > 0:
            return False
        return True

    @property
    def member_join_list(self):
        return [int(member) for member in self.member_join.split(",")]


import cv2
import numpy as np

cap = cv2.VideoCapture(0) #取得視訊鏡頭的畫面

#不同顏色的筆
pen_color_HSV = [[86, 121, 205, 111, 245, 255],
                [46, 78, 172, 71, 255, 255],
                [22, 70, 214, 31, 255, 255]
                ]

#不同顏色的筆對應的筆尖
pen_color_BGR = [[255, 0, 0],
                [0, 255, 0],
                [0, 255, 255]
                ]

#記錄每個筆畫過的位置和顏色 [x, y, color_ID]
draw_points = []

def find_pen(img):
    hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV)

    #用迴圈跑每個顏色
    for i in range(len(pen_color_HSV)):
        #最大和最小值
        lower = np.array(pen_color_HSV[i][:3])
        upper = np.array(pen_color_HSV[i][3:6])

        mask = cv2.inRange(hsv, lower, upper)

        #過濾顏色
        result = cv2.bitwise_and(img, img, mask = mask)
        pen_x, pen_y = find_contour(mask)
        cv2.circle(img_contour, (pen_x, pen_y), 10, pen_color_BGR[i], cv2.FILLED)

        #先判斷是否有偵測到輪廓
        if(pen_y != -1):
            draw_points.append([pen_x, pen_y, i])

    # cv2.imshow("result", result)

def find_contour(img):
    #檢測輪廓
    contours, hierarchy = cv2.findContours(img, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_NONE)
    x, y, w, h = -1, -1, -1, -1
    for cnt in contours:
        cv2.drawContours(img_contour, cnt, -1, (0,0,0), 4) #描邊
        #畫外切正方形
        area = cv2.contourArea(cnt)
        if(area > 500):
            peri = cv2.arcLength(cnt, True)
            vertices = cv2.approxPolyDP(cnt, peri * 0.02, True) #頂點
            x, y, w, h = cv2.boundingRect(vertices) #把每個圖形用方形匡起來 左上x座標、左上y座標、寬度、高度
    return x+w//2, y

#用筆畫圖
def draw(draw_points):
    for point in draw_points:
        cv2.circle(img_contour, (point[0], point[1]), 10, pen_color_BGR[point[2]], cv2.FILLED)

#顯示影片
while(True):
    ret, frame = cap.read() #回傳兩個變數(有無成功取得下一幀->bool + 下一幀的圖片)

    if ret:
        img_contour = frame.copy()
        find_pen(frame)
        draw(draw_points)
        cv2.imshow("contour", img_contour)
    else:
        break

    if cv2.waitKey(1) == ord("q"): #若輸入q則結束影片
        break


# Seq2Seq model with attention
import torch
import torch.nn as nn
import torch.nn.functional as F
import random
from copy import copy

def init_weights(m):
    for name, param in m.named_parameters():
        if 'weight' in name:
            nn.init.normal_(param.data, mean=0, std=0.01)
        else:
            nn.init.constant_(param.data, 0)

def count_parameters(model):
    return sum(p.numel() for p in model.parameters() if p.requires_grad)

def train_an_epoch(model, iterator, optimizer, criterion, clip, device, scheduler, tf_ratio=1.):
    model.train()
    epoch_loss = 0
    for i, batch in enumerate(iterator):
        src = batch[0].float().to(device)
        trg = copy(batch[0]).float().to(device)

        optimizer.zero_grad()
        output = model(src, trg, tf_ratio).permute(1, 0, 2)

        loss = criterion(output, trg)
        loss.backward()
        torch.nn.utils.clip_grad_norm_(model.parameters(), clip)
        optimizer.step()
        scheduler.step()
        epoch_loss += loss.item()

    return epoch_loss / len(iterator)

def evaluate(model, iterator, criterion, device):
    model.eval()
    epoch_loss = 0
    with torch.no_grad():
        for i, batch in enumerate(iterator):
            src = batch[0].float().to(device)
            trg = copy(batch[0]).float().to(device)
            output = model(src, trg, 0).permute(1, 0, 2) #turn off teacher forcing
            loss = criterion(output, trg)
            epoch_loss += loss.item()
    return epoch_loss / len(iterator)

def epoch_time(start_time, end_time):
    elapsed_time = end_time - start_time
    elapsed_mins = int(elapsed_time / 60)
    elapsed_secs = int(elapsed_time - (elapsed_mins * 60))
    return elapsed_mins, elapsed_secs

class Encoder(nn.Module):
    def __init__(self, num_layers=2, input_dim=10, emb_dim=64, enc_hid_dim=128, dec_hid_dim=128, dropout=0.5):
        super().__init__()
        self.embedding = nn.Linear(input_dim, emb_dim)
        self.norm = nn.LayerNorm(emb_dim)
        self.rnn = nn.GRU(emb_dim, enc_hid_dim, bidirectional = True, batch_first = True, num_layers=num_layers)
        self.dropout = nn.Dropout(dropout)
        self.fc = nn.Linear(enc_hid_dim * 2, dec_hid_dim)

    def forward(self, src):
        embedded = self.dropout(self.embedding(src))
        embedded = self.norm(embedded)
        #embedded = [batch size, n_time_steps, emb dim]
        outputs, hidden = self.rnn(embedded)
        #outputs = [batch size, n_time_steps, hid dim * num directions]
        #hidden = [n layers * num directions, batch size, hid dim]
        hidden = torch.tanh(self.fc(torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim = 1)))
        #hidden is stacked [forward_1, backward_1, forward_2, backward_2, ...]
        #outputs are always from the last layer
        #hidden = [batch size, dec hid dim]
        return outputs, hidden

class Attention(nn.Module):
    def __init__(self, enc_hid_dim, dec_hid_dim):
        super().__init__()
        self.norm = nn.LayerNorm((enc_hid_dim * 2) + dec_hid_dim)
        self.attn = nn.Linear((enc_hid_dim * 2) + dec_hid_dim, dec_hid_dim)
        self.v = nn.Linear(dec_hid_dim, 1, bias = False)

    def forward(self, hidden, encoder_outputs):
        #hidden = [batch size, dec hid dim]
        #encoder_outputs = [batch size, src len, enc hid dim * 2]
        src_len = encoder_outputs.shape[1]

        #repeat decoder hidden state src_len times
        hidden = hidden.unsqueeze(1).repeat(1, src_len, 1)
        #hidden = [batch size, src len, dec hid dim]
        #encoder_outputs = [batch size, src len, enc hid dim * 2]
        energy = torch.tanh(self.attn(self.norm(torch.cat((hidden, encoder_outputs), dim = 2))))
        #energy = [batch size, src len, dec hid dim]
        attention = self.v(energy).squeeze(2)
        #attention= [batch size, src len]
        return F.softmax(attention, dim=1)

class Decoder(nn.Module):
    def __init__(self, attention, num_layer=1, output_dim=10, emb_dim=64, enc_hid_dim=128, dec_hid_dim=128, dropout=0.5):
        super().__init__()

        self.output_dim = output_dim
        self.attention = attention

        self.embedding = nn.Linear(output_dim, emb_dim)
        self.norm = nn.LayerNorm(emb_dim)
        self.rnn = nn.GRU((enc_hid_dim * 2) + emb_dim, dec_hid_dim, num_layers=num_layer)
        self.fc_out = nn.Linear((enc_hid_dim * 2) + dec_hid_dim + emb_dim, output_dim)
        self.dropout = nn.Dropout(dropout)

    def forward(self, input, hidden, encoder_outputs, dec_hid=None):
        #input = [batch size, n_features]
        #hidden = [batch size, dec hid dim]
        #encoder_outputs = [batch size, n_time_steps, enc hid dim * 2]
        input = input.unsqueeze(1)
        #input = [batch size, 1, n_features]
        embedded = self.dropout(self.embedding(input)).permute(1, 0, 2)
        embedded = self.norm(embedded)
        #embedded = [1, batch_size, emb dim]
        a = self.attention(hidden, encoder_outputs)
        #a = [batch size, src len]
        a = a.unsqueeze(1)
        #a = [batch size, 1, src len]

        weighted = torch.bmm(a, encoder_outputs)
        #weighted = [batch size, 1, enc hid dim * 2]
        weighted = weighted.permute(1, 0, 2)
        #weighted = [1, batch size, enc hid dim * 2]
        rnn_input = torch.cat((embedded, weighted), dim = 2)

        #rnn_input = [1, batch size, (enc hid dim * 2) + emb dim]
        if dec_hid == None:
            output, dec_hid = self.rnn(rnn_input)
        else:
            output, dec_hid = self.rnn(rnn_input, dec_hid)

        embedded = embedded.squeeze(0)
        output = output.squeeze(0)
        weighted = weighted.squeeze(0)
        prediction = self.fc_out(torch.cat((output, weighted, embedded), dim = 1))
        #prediction = [batch size, output dim]
        return prediction, dec_hid

class Seq2Seq(nn.Module):
    def __init__(self, encoder, decoder, device):
        super().__init__()
        self.encoder = encoder
        self.decoder = decoder
        self.device = device

    def forward(self, src, trg, teacher_forcing_ratio = 0.5):
        #teacher_forcing_ratio is probability to use teacher forcing
        #e.g. if teacher_forcing_ratio is 0.75 we use teacher forcing 75% of the time
        batch_size = src.shape[0]
        trg_len = trg.shape[1]
        trg_vocab_size = self.decoder.output_dim

        #tensor to store decoder outputs
        outputs = torch.zeros(trg_len, batch_size, trg_vocab_size).to(self.device)

        #encoder_outputs is all hidden states of the input sequence, back and forwards
        #hidden is the final forward and backward hidden states, passed through a linear layer
        encoder_outputs, hidden = self.encoder(src)

        #first input to the decoder (start token = [0, ..., 0])
        input = torch.zeros_like(trg[:, 0, :]).to(self.device)
        dec_hid = None
        for t in range(0, trg_len-1):
            #insert input token embedding, previous hidden state and all encoder hidden states
            #receive output tensor (predictions) and new hidden state
            output, dec_hid = self.decoder(input, hidden, encoder_outputs, dec_hid)

            #place predictions in a tensor holding predictions for each token
            outputs[t] = output
            hidden = dec_hid[-1, ...]
            #decide if we are going to use teacher forcing or not
            teacher_force = random.random() < teacher_forcing_ratio
            #if teacher forcing, use actual next token as next input
            #if not, use predicted token
            input = trg[:, t, :] if teacher_force else output

        return outputs


import tkinter
from PIL import Image
import time
import pygame
# Ссылка на гугл диск, на котором файл с музыкой. Он не прошла по размеру на github. https://drive.google.com/drive/folders/1RzTOtOH4LLt6UE6C6TCYG-0Quf38lkTE
pygame.init()
pygame.mixer.music.load("music.wav")
pygame.mixer.music.play(-1)

def game():
    code_symbols = []
    for i in range(10):
        code_symbols.append(i)
    alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
    for i in alphabet:
        code_symbols.append(i)

    middle = 9

    def block(k):
        from random import randint
        interval = k * middle
        summa = 0
        result = ''
        while summa <= interval:
            summa = 0
            result = ''
            for i in range(k):
                a = randint(0, 35)
                summa += a
                result += str(code_symbols[a])
        return result

    def clicked():
        lbl = tkinter.Label(window, text="Успешно! Ваш код: " + block(5) + '-' + block(4) + '-' + block(4),
                            font=("Arial Bold", 25),
                            bg='Gray')
        lbl.grid(column=0, row=0)

    window = tkinter.Tk()
    window.title("Добро пожаловать в генерацию кода")

    window.geometry('1313x833')

    window.image = tkinter.PhotoImage(file='gta.png')
    bg_gta = tkinter.Label(window, image=window.image)
    bg_gta.grid(column=0, row=0)

    btn_1 = tkinter.Button(window, text="Сгенерировать код", font=("Arial Bold", 15), bg='Gray', command=clicked)
    btn_1.grid(column=0, row=0)
    window.mainloop()

def animation(count, k):
    global anim
    global frames
    im2 = im[count]

    gif_label.configure(image=im2)
    count += 1
    k += 1
    time.sleep(0.5)
    if count == frames:
        count = 0
    if k == frames + 1:
        root.destroy()
        game()
    anim = root.after(50, lambda: animation(count, k))

root = tkinter.Tk()
root.title('Мы начинаем!')
file = "10.gif"
root.geometry('627x627')
info = Image.open(file)
frames = info.n_frames  # gives total number of frames that gif contains

# creating list of PhotoImage objects for each frames
im = [tkinter.PhotoImage(file=file, format=f"gif -index {i}") for i in range(frames)]

count = 0
k = 0
anim = None

gif_label = tkinter.Label(root, image="")
gif_label.pack()

btn_2 = tkinter.Button(root, text="СТАРТ", font=("Arial Bold", 15), command=lambda: animation(count, k))
btn_2.pack()

root.mainloop()


from random import random

import numpy
from copy import deepcopy

from texttable import Texttable

class Ant:
    def __init__(self, size):
        self._size = size
        self._representation = [[] for i in range(size * 2)]
        self._graph = [self._representation]
        self._freeSpots = size - 1

    def getFreeSpotsCount(self):
        return self._freeSpots

    def getRepresentation(self):
        return self._representation

    def getGraph(self):
        return self._graph[:]

    def setRepresentation(self, newRepresentation):
        if len(self._representation[-1]) > len(newRepresentation[-1]):
            self.decreaseFreeSpots()
        self._representation = deepcopy(newRepresentation)

    def decreaseFreeSpots(self):
        self._freeSpots -= 1

    def nextPossibilities(self):
        possibilities = []
        for i in range(self._size * 2 * (self._freeSpots)):
            newPossibility = deepcopy(self._representation)
            for row in range(self._size * 2):
                possibleNumbers = [i for i in range(1, self._size + 1)]
                for elem in self._representation[row]:
                    possibleNumbers.remove(elem)

                # if row >= self._size and newPossibility[row - self._size][-1] in possibleNumbers:
                #     possibleNumbers.remove(newPossibility[row - self._size][-1])

                choice = numpy.random.choice(possibleNumbers)
                newPossibility[row].append(choice)
                possibleNumbers.remove(choice)
            possibilities.append(newPossibility)
        return possibilities

    def move(self, q0, trace, alpha, beta):
        nextPossibilities = self.nextPossibilities()
        distances = []
        if len(nextPossibilities) == 0:
            return False

        auxAnt = Ant(self._size)
        for position in nextPossibilities:
            auxAnt.setRepresentation(position)
            distances.append([position, auxAnt.fitness() - self.fitness()])

        for i in range(len(distances)):
            index = [0, False]
            while index[0] < len(trace) or index[1]:
                if trace[index[0]] == distances[i][0]:
                    index[1] = True
                index[0] += 1
            if index[1]:
                distances[i][1] = (distances[i][1] ** beta) * (trace(index[0]) ** alpha)

        if numpy.random.random() < q0:
            distances = min(distances, key=lambda elem:elem[1])
            self.setRepresentation(distances[0])
            self._graph.append(self._representation)
        else:
            suma = 0
            for elem in distances:
                suma += elem[1]
            if suma == 0:
                choice = numpy.random.randint(0, len(distances))
                self.setRepresentation(distances[choice][0])
                self._graph.append(self._representation)
                return
            distances = [[distances[i][0], distances[i][1] / suma] for i in range(len(distances))]

            for i in range(len(distances)):
                sum = 0
                for j in range(i+1):
                    sum += distances[j][1]
                distances[i][1] = sum

            choice = numpy.random.random()
            i = 0
            while choice > distances[i][1]:
                i += 1
            self.setRepresentation(distances[i][0])
            self._graph.append(self._representation)
        return True

    def __str__(self):
        table = Texttable()
        for i in range(self._size):
           row = []
           for j in range(len(self._representation[i])):
              row.append((self._representation[i][j], self._representation[i + self._size][j]))
           table.add_row(row)
        return table.draw()

    def fitness(self):
        fitness = 0
        for i in range(self._size):
            for j in range(len(self._representation[i])):
                if self._representation[i][j] == self._representation[i + self._size][j]:
                    fitness += 1
                if i < len(self._representation[i]) and self._representation[j][i] == self._representation[j + self._size][i]:
                    fitness += 1

        for i in range(self._size - 1):
            for j in range(i + 1, self._size):
                fitness += numpy.count_nonzero(
                    numpy.equal(self._representation[i + self._size], self._representation[j + self._size]))
                fitness += numpy.count_nonzero(numpy.equal(self._representation[i], self._representation[j]))

        for i in range(len(self._representation[-1]) - 1):
            column11 = [self._representation[j][i] for j in range(self._size)]
            column12 = [self._representation[j + self._size][i] for j in range(self._size)]
            for j in range(i + 1, len(self._representation[i])):
                column21 = [self._representation[k][j] for k in range(self._size)]
                column22 = [self._representation[k + self._size][j] for k in range(self._size)]

                fitness += numpy.count_nonzero(numpy.equal(column11, column21))
                fitness += numpy.count_nonzero(numpy.equal(column12, column22))

        return fitness


from tkinter import *
#tkinter module GUI application
fruits=["dragon fruits","Apple","banana","grapes","pine apple","papaya"]
win=Tk()
win.title("Demo GUI 1")
win.geometry("400x400")
li=Listbox(win,foreground="blue",bg="tomato")
index=1
for fruit in fruits:
    li.insert(index,fruit+str(index))
    index=index+1
li.pack(side=RIGHT)
win.mainloop()


from tkinter import *
import sqlite3
from PIL import ImageTk, Image
from backend import Database
import requests

database=Database("books.db")

class Window(object):

    def __init__(self,window):
        self.window=window
        self.window.title("Bookstore")
        self.window.configure(bg='#856ff8')

        #Title input
        self.title=StringVar()
        self.l1=Label(text="Title")
        self.l1.grid(row=0,column=0)
        self.e1=Entry(window,textvariable=self.title)
        self.e1.grid(row=0,column=1)

        #Author input
        self.author=StringVar()
        self.l2=Label(text="Author")
        self.l2.grid(row=0,column=2)
        self.e2=Entry(window,textvariable=self.author)
        self.e2.grid(row=0,column=3)

        #Year input
        self.year=StringVar()
        self.l3=Label(text="Year")
        self.l3.grid(row=1,column=0)
        self.e3=Entry(window,textvariable=self.year)
        self.e3.grid(row=1,column=1)

        #Genre input
        self.genre=StringVar()
        self.l4=Label(text="Genre")
        self.l4.grid(row=1,column=2)
        self.e4=Entry(window,textvariable=self.genre)
        self.e4.grid(row=1,column=3)

        #Rate input
        self.rate=StringVar()
        self.l5=Label(text="Rating")
        self.l5.grid(row=2,column=0)
        self.e5=Entry(window,textvariable=self.rate)
        self.e5.grid(row=2,column=1)

        #ISBN input
        self.isbn=StringVar()
        self.l6=Label(text="ISBN")
        self.l6.grid(row=2,column=2)
        self.e6=Entry(window,textvariable=self.isbn)
        self.e6.grid(row=2,column=3)

        #URL input
        self.img_url=StringVar()
        self.l7=Label(text="Image Url")
        self.l7.grid(row=3,column=1)
        self.e7=Entry(window,textvariable=self.img_url)
        self.e7.grid(row=3,column=2)

        self.list1=Listbox(window,width=75)
        self.list1.grid(row=0,column=5,rowspan=6)

        sb1=Scrollbar(window)
        sb1.grid(row=0,column=6,rowspan=6)

        self.list1.configure(yscrollcommand=sb1.set)
        sb1.configure(command=self.list1.yview)
        self.list1.bind('<<ListboxSelect>>',self.CurSelect)

        #Search Button
        b1=Button(text ="Search Entry", width=15,foreground="red",command=self.search)
        b1.grid(row=4,column=1)

        #Add Button
        b2=Button(text ="Add Entry", width=15,command=self.add)
        b2.grid(row=4,column=3)

        #Update Button
        b3=Button(text ="Update Entry", width=15,command=self.update)
        b3.grid(row=5,column=1)

        #Delete Button
        b4=Button(text ="Delete Entry", width=15,command=self.delete)
        b4.grid(row=5,column=3)

        b5=Button(text ="Close", width=15,command=window.destroy)
        b5.grid(row=5,column=2)

    def view(self):
        for row in database.view():
            self.list1.insert(END,row)

    def search(self):
        self.list1.delete(0,END)
        for row in database.search(title.get(),author.get(),year.get(),genre.get(),rate.get(),isbn.get()):
            self.list1.insert(END,row)

    def CurSelect(self,e):
        if self.list1.size()!=0:
            global selected_tuple
            global img

            #this one will get the index and to be used for deleting an item
            index=list1.curselection()[0]
            self.selected_tuple=self.list1.get(index)
            value=self.list1.get(self.list1.curselection())

            #This part will create the image box on the side and it will display the image that belongs to the book
            self.img_url1=value[len(value)-1]
            self.img = Image.open(requests.get(img_url1, stream=True).raw)
            self.img = img.resize((170,170), Image.ANTIALIAS)
            self.img = ImageTk.PhotoImage(img)
            self.l8=Label(image=img)
            self.l8.grid(row=0,column=7,rowspan=5)

            #this part will bring selected item to the entrees
            self.e1.delete(0,END)
            self.e1.insert(END,self.selected_tuple[1])

            self.e2.delete(0,END)
            self.e2.insert(END,self.selected_tuple[2])

            self.e3.delete(0,END)
            self.e3.insert(END,self.selected_tuple[3])

            self.e4.delete(0,END)
            self.e4.insert(END,self.selected_tuple[4])

            self.e5.delete(0,END)
            self.e5.insert(END,self.selected_tuple[5])

            self.e6.delete(0,END)
            self.e6.insert(END,self.selected_tuple[6])

            self.e7.delete(0,END)
            self.e7.insert(END, self.selected_tuple[7])

    def delete(self):
        database.delete(self.selected_tuple[0])
        self.list1.delete(0,END)
        view()

    def add(self):
        database.insert(self.title.get(),self.author.get(),self.year.get(),self.genre.get(),self.rate.get(),self.isbn.get(),self.img_url.get())

        self.e1.delete(0,END)
        self.e2.delete(0,END)
        self.e3.delete(0,END)
        self.e4.delete(0,END)
        self.e5.delete(0,END)
        self.e6.delete(0,END)
        self.e7.delete(0,END)

        self.list1.delete(0,END)
        self.view()

    def update(self):
        database.update(self.selected_tuple[0],self.title.get(),self.author.get(),self.year.get(),self.genre.get(),self.rate.get(),self.isbn.get(),self.img_url.get())
        self.list1.delete(0,END)
        view()

window= Tk()
win=Window(window)
win.view()
window.mainloop()


import asyncio
import importlib
import re
from contextlib import closing, suppress
from uvloop import install
from pyrogram import filters, idle
from pyrogram.types import InlineKeyboardButton, InlineKeyboardMarkup, Message
from Yukinon.menu import *
from Yukinon import *
from Yukinon.plugins import ALL_MODULES
from Yukinon.utils import paginate_modules
from lang import get_command
from Yukinon.utils.lang import *
from Yukinon.utils.commands import *
from Yukinon.mongo.rulesdb import *
from Yukinon.utils.start import *
from Yukinon.mongo.usersdb import *
from Yukinon.mongo.restart import *
from Yukinon.mongo.chatsdb import *
from Yukinon.plugins.fsub import ForceSub
import random

loop = asyncio.get_event_loop()
flood = {}
START_COMMAND = get_command("START_COMMAND")
HELP_COMMAND = get_command("HELP_COMMAND")
HELPABLE = {}

async def start_bot():
    global HELPABLE
    for module in ALL_MODULES:
        imported_module = importlib.import_module("Yukinon.plugins." + module)
        if (
            hasattr(imported_module, "__MODULE__")
            and imported_module.__MODULE__
        ):
            imported_module.__MODULE__ = imported_module.__MODULE__
            if (
                hasattr(imported_module, "__HELP__")
                and imported_module.__HELP__
            ):
                HELPABLE[
                    imported_module.__MODULE__.replace(" ", "_").lower()
                ] = imported_module
    all_module = ""
    j = 1
    for i in ALL_MODULES:
        all_module = "•≫ Successfully imported:{:<15}.py".format(i)
        print(all_module)
    restart_data = await clean_restart_stage()
    try:
        if restart_data:
            await app.edit_message_text(
                restart_data["chat_id"],
                restart_data["message_id"],
                "**Restarted Successfully**",
            )

        else:
            await app.send_message(LOG_GROUP_ID, "Yukinon Robot started!")
    except Exception as e:
        print(e)
    #print(f"{all_module}")
    print("""
 _____________________________________________
|                                             |
|          Deployed Successfully              |
|      (C) 2021-2022 by @TechZBots            |
|_____________________________________________|

    """)
    await idle()

    await aiohttpsession.close()
    await app.stop()
    for task in asyncio.all_tasks():
        task.cancel()

home_keyboard_pm = InlineKeyboardMarkup(
    [
        [
            InlineKeyboardButton(
                text=" ➕ Add Me To Your Group ➕ ",
                url=f"http://t.me/{BOT_USERNAME}?startgroup=new",
            )
        ],
        [
           InlineKeyboardButton(
                text=" ℹ About", callback_data="_about"
            ),
            InlineKeyboardButton(
                text="🌍 languages ", callback_data="_langs"
            ),
        ],
        [
            InlineKeyboardButton(
                text="📮 How To Use Me", callback_data="bot_commands"
            ),
        ],
        [
            InlineKeyboardButton(
                text="🌐 My Website",
                url=f"https://szrosebot.ml",
            ),
            InlineKeyboardButton(
                text="🔰News Channel",
                url=f"https://t.me/szroseupdates",
            )
        ],
    ]
)

keyboard = InlineKeyboardMarkup(
    [
        [
            InlineKeyboardButton(
                text="📚 Commands & help",
                url=f"t.me/{BOT_USERNAME}?start=help",
            )
        ]
    ]
)

IMG = ["https://telegra.ph/file/c8f5c1dd990ca9a3d8516.jpg",
       "https://telegra.ph/file/77cc3154b752ce822fd52.jpg",
       "https://telegra.ph/file/e72fb0b6a7fba177cf4c7.jpg",
       "https://telegra.ph/file/8738a478904238e367939.jpg",
       "https://telegra.ph/file/68d7830ba72820f44bda0.jpg"
]

@app.on_message(filters.command(START_COMMAND))
@language
async def start(client, message: Message, _):
    FSub = await ForceSub(bot, message)
    if FSub == 400:
        return
    chat_id = message.chat.id
    if message.sender_chat:
        return
    if message.chat.type != "private":
        await message.reply(
            _["main2"], reply_markup=keyboard)
        return await add_served_chat(message.chat.id)
    if len(message.text.split()) > 1:
        name = (message.text.split(None, 1)[1]).lower()
        if name.startswith("rules"):
                await get_private_rules(app, message, name)
                return
        elif "_" in name:
            module = name.split("_", 1)[1]
            text = (_["main6"].format({HELPABLE[module].__MODULE__}
                + HELPABLE[module].__HELP__)
            )
            await message.reply(text, disable_web_page_preview=True)
        elif name == "help":
            text, keyb = await help_parser(message.from_user.first_name)
            await message.reply(
                _["main5"],
                reply_markup=keyb,
                disable_web_page_preview=True,
            )
        elif name == "connections":
            await message.reply("Run /connections to view or disconnect from groups!")
    else:
        served_chats = len(await get_served_chats())
        served_chats = []
        chats = await get_served_chats()
        for chat in chats:
           served_chats.append(int(chat["chat_id"]))
        served_users = len(await get_served_users())
        served_users = []
        users = await get_served_users()
        for user in users:
          served_users.append(int(user["bot_users"]))
        await message.reply(f"""
[👋]({random.choice(IMG)}) Hey there {message.from_user.mention},

   My name is Yukinon, an  advanced telegram Group management Bot For helpYou Protect Your Groups & Suit For All Your Needs.
I currently manage about `{len(served_chats)}` groups.I have over `{len(served_users)}` users

⚒ Send Me /help For Get Commands.
👨💻Dᴇᴠᴇʟᴏᴘᴇʀ : @supunma
""",
            reply_markup=home_keyboard_pm,
        )
        return await add_served_user(message.from_user.id)

@app.on_message(filters.command(HELP_COMMAND))
@language
async def help_command(client, message: Message, _):
    FSub = await ForceSub(bot, message)
    if FSub == 400:
        return
    if message.chat.type != "private":
        if len(message.command) >= 2:
            name = (message.text.split(None, 1)[1]).replace(" ", "_").lower()
            if str(name) in HELPABLE:
                key = InlineKeyboardMarkup(
                    [
                        [
                            InlineKeyboardButton(
                                text=_["main3"],
                                url=f"t.me/{BOT_USERNAME}?start=help_{name}",
                            )
                        ],
                    ]
                )
                await message.reply(
                    _["main4"],
                    reply_markup=key,
                )
            else:
                await message.reply(
                    _["main2"], reply_markup=keyboard
                )
        else:
            await message.reply(
                _["main2"], reply_markup=keyboard
            )
    else:
        if len(message.command) >= 2:
            name = (message.text.split(None, 1)[1]).replace(" ", "_").lower()
            if str(name) in HELPABLE:
                text = (_["main6"].format({HELPABLE[name].__MODULE__}
                + HELPABLE[name].__HELP__)
                )
                if hasattr(HELPABLE[name], "__helpbtns__"):
                       button = (HELPABLE[name].__helpbtns__) + [[InlineKeyboardButton("« Back", callback_data="bot_commands")]]
                if not hasattr(HELPABLE[name], "__helpbtns__"): button = [[InlineKeyboardButton("« Back", callback_data="bot_commands")]]
                await message.reply(text,
                           reply_markup=InlineKeyboardMarkup(button),
                           disable_web_page_preview=True)
            else:
                text, help_keyboard = await help_parser(
                    message.from_user.first_name
                )
                await message.reply(
                    _["main5"],
                    reply_markup=help_keyboard,
                    disable_web_page_preview=True,
                )
        else:
            text, help_keyboard = await help_parser(
                message.from_user.first_name
            )
            await message.reply(
                text, reply_markup=help_keyboard, disable_web_page_preview=True
            )
    return

@app.on_callback_query(filters.regex("startcq"))
@languageCB
async def startcq(client,CallbackQuery, _):
    served_chats = len(await get_served_chats())
    served_chats = []
    chats = await get_served_chats()
    for chat in chats:
        served_chats.append(int(chat["chat_id"]))
    served_users = len(await get_served_users())
    served_users = []
    users = await get_served_users()
    for user in users:
        served_users.append(int(user["bot_users"]))
    await CallbackQuery.message.edit(
            text=f"""
👋 Hey there {CallbackQuery.from_user.mention},

   My name is Yukinon ,an  advanced telegram Group management Bot For help
You Protect Your Groups & Suit For All Your Needs.
I currently manage about `{len(served_chats)}` groups.I have over `{len(served_users)}` users

 ⚒ Send Me /help For Get Commands.
👨💻Dᴇᴠᴇʟᴏᴘᴇʀ : @supunma
""",
            disable_web_page_preview=True,
            reply_markup=home_keyboard_pm)

async def help_parser(name, keyboard=None):
    if not keyboard:
        keyboard = InlineKeyboardMarkup(paginate_modules(0, HELPABLE, "help"))
    return (
"""
**Welcome to help menu**
I'm a group management bot with some useful features.
You can choose an option below, by clicking a button.
If you have any bugs or questions on how to use me,
have a look at my [Docs](https://szsupunma.gitbook.io/rose-bot/), or head to @szteambots.
**All commands can be used with the following: / **""",
        keyboard,
    )

@app.on_callback_query(filters.regex("bot_commands"))
@languageCB
async def commands_callbacc(client,CallbackQuery, _):
    text ,keyboard = await help_parser(CallbackQuery.from_user.mention)
    await app.send_message(
        CallbackQuery.message.chat.id,
        text=_["main5"],
        reply_markup=keyboard,
        disable_web_page_preview=True,
    )
    await CallbackQuery.message.delete()

@app.on_callback_query(filters.regex(r"help_(.*?)"))
@languageCB
async def help_button(client, query, _):
    home_match = re.match(r"help_home\((.+?)\)", query.data)
    mod_match = re.match(r"help_module\((.+?)\)", query.data)
    prev_match = re.match(r"help_prev\((.+?)\)", query.data)
    next_match = re.match(r"help_next\((.+?)\)", query.data)
    back_match = re.match(r"help_back", query.data)
    create_match = re.match(r"help_create", query.data)
    top_text = _["main5"]
    if mod_match:
        module = (mod_match.group(1)).replace(" ", "_")
        text = (
            "{} **{}**:\n".format(
                "Here is the help for", HELPABLE[module].__MODULE__
            )
            + HELPABLE[module].__HELP__
            + "\n👨💻Dᴇᴠᴇʟᴏᴘᴇʀ : @supunma"
        )
        if hasattr(HELPABLE[module], "__helpbtns__"):
                       button = (HELPABLE[module].__helpbtns__) + [[InlineKeyboardButton("« Back", callback_data="bot_commands")]]
        if not hasattr(HELPABLE[module], "__helpbtns__"): button = [[InlineKeyboardButton("« Back", callback_data="bot_commands")]]
        await query.message.edit(
            text=text,
            reply_markup=InlineKeyboardMarkup(button),
            disable_web_page_preview=True,
        )
        await query.answer(f"Here is the help for {module}",show_alert=True)
    elif home_match:
        await app.send_message(
            query.from_user.id,
            text= _["main2"],
            reply_markup=home_keyboard_pm,
        )
        await query.message.delete()
    elif prev_match:
        curr_page = int(prev_match.group(1))
        await query.message.edit(
            text=top_text,
            reply_markup=InlineKeyboardMarkup(
                paginate_modules(curr_page - 1, HELPABLE, "help")
            ),
            disable_web_page_preview=True,
        )

    elif next_match:
        next_page = int(next_match.group(1))
        await query.message.edit(
            text=top_text,
            reply_markup=InlineKeyboardMarkup(
                paginate_modules(next_page + 1, HELPABLE, "help")
            ),
            disable_web_page_preview=True,
        )

    elif back_match:
        await query.message.edit(
            text=top_text,
            reply_markup=InlineKeyboardMarkup(
                paginate_modules(0, HELPABLE, "help")
            ),
            disable_web_page_preview=True,
        )

    elif create_match:
        text, keyboard = await help_parser(query)
        await query.message.edit(
            text=text,
            reply_markup=keyboard,
            disable_web_page_preview=True,
        )

    return await client.answer_callback_query(query.id)

if __name__ == "__main__":
    install()
    with closing(loop):
        with suppress(asyncio.exceptions.CancelledError):
            loop.run_until_complete(start_bot())
        loop.run_until_complete(asyncio.sleep(3.0))


"""
Classes containing different occlusion models (e.g. estimators for shadows, sky view factor etc.)
"""
import hylite
import matplotlib.pyplot as plt
import numpy as np

from hylite.correct import get_hull_corrected
from hylite.multiprocessing import parallel_chunks

def estimate_path_radiance(image, depth, thresh=1):
    """
    Apply the dark object subtraction (DOS) method to estimate path radiance in the provided image.

    Args:
        image: the hyperspectral image (HyImage instance) to estimate path radiance for.
        depth: A 2-D (width,height) numpy array of pixel depths in meters. This can be easily computed using
               a HyScene instance.
        thresh: the percentile threshold to use when selecting dark pixels. Default is 1%.

    Returns:
        A tuple containing:

            - spectra = a numpy array containing the estimated path radiance spectra (in radiance per meter of depth).
            - path = a HyImage instance containing the estimated path radiance per pixel (computed by multiplying
                  the spectra by the depth).
    """

    # identify dark pixels
    r = np.nanmean(image.data, axis=-1)  # calculate mean brightness

    assert r.shape == depth.shape, "Error: depth array and HSI have different shapes: %s != %s" % (
    str(r.shape), str(depth.shape))

    r[r == 0] = np.nan  # remove background / true zeros as this can bias the percentile clip
    r[np.logical_not(np.isfinite(depth))] = np.nan  # remove areas without depth info
    r[depth == 0] = np.nan  # remove areas without depth info

    # extract dark pixels and get median
    thresh = np.nanpercentile(r, thresh)  # threshold for darkest pixels
    darkref = image.data[r <= thresh, :]
    darkdepth = depth[r <= thresh]  # corresponding depths

    # compute path radiance estimate
    S = darkref / darkdepth[..., None]  # compute estimated path-radiance per meter
    S = np.nanpercentile(S, 50, axis=0)  # take median of all estimates

    # compute per pixel path radiance
    P = image.copy(data=False)
    P.data = depth[..., None] * S[None, None, :]

    return S, P

def correct_path_absorption(data, band_range=(0, -1), thresh=99, atabs = 1126., vb=True):
    """
    Fit and remove a known atmospheric water feature to remove atmospheric path absorbtions from reflectance spectra.
    See  Lorenz et al., 2018 for more details.

    Reference:
    https://doi.org/10.3390/rs10020176

    Args:
        image: a hyperspectral image to correct
        band_range: a range of bands to do this over. Default is (0,-1), which applies the correction to all bands.
        thresh: the percentile to apply when identifying the smallest absorbtion in any range based on hull corrected
                spectra. Lower values will remove more absorption (potentially including features of interest).
        atabs: wavelength position at which a known control feature is situated that defines the intensity of correction
                - for atmospheric effects, this is set to default to 1126 nm
        vb: True if a progress bar should be created during hull correction steps.

    Returns:
        a HyData instance containing the corrected spectra.
    """
    assert isinstance(atabs, float), "Absorption wavelength must be float"
    # subset dataset
    out = data.export_bands(band_range)
    nanmask = np.logical_not(np.isfinite(out.data))
    out.data[nanmask] = 0  # replace nans with 0

    # get depth of water feature at 1126 nm for all pixels
    atm_depth = (out.get_band(atabs - 50.) + out.get_band(atabs + 50.)) / 2 - out.get_band(atabs)

    # kick out data points with over-/undersaturated spectra
    atm_temp = atm_depth.copy()
    atm_temp[np.logical_or(np.nanmax(out.data, axis=-1) >= 1, np.nanmax(out.data, axis=-1) <= 0)] = 0
    # extract pixels that are affected most by the features
    highratio = out.data[atm_temp > np.percentile(atm_temp, 90)]
    # hull correct those
    hull = get_hull_corrected(hylite.HyData(highratio), vb=vb)
    # extract the always consistent absorptions
    hull_max = np.nanpercentile(hull.data, thresh, axis=0)

    vmin = hull_max[out.get_band_index(atabs)]
    # apply adjustment and return
    if out.is_image():
        nmin = -atm_depth[..., None]
        out.data -= ((hull_max[None, None, :] - vmin) * (-nmin) / (1 - vmin) + nmin)
    else:
        nmin = -atm_depth[..., None]
        out.data -= ((hull_max[None, :] - vmin) * (-nmin) / (1 - vmin) + nmin)
    out.data[nanmask] = np.nan  # add nans back in
    out.data = np.clip(out.data, 0, 1)

    return out


import logging
import sys

from tracker import LogawareMixin, getenv_or_fail
from tracker.fetch.online import JsonEndpointFetcher
from tracker.metadata.retriever import LiftMetadataRetriever
from tracker.metadata.store import LiftMetadataDatabaseRecorder

class LiftMetadataInserter(LogawareMixin):
    def __init__(self, lift_metadata_retriever: LiftMetadataRetriever, database_client: LiftMetadataDatabaseRecorder):
        super().__init__()
        self.lift_metadata_retriever = lift_metadata_retriever
        self.database_client = database_client

    def insert(self):
        lift_metadata = []
        for page in range(1, 13):
            lift_metadata.extend(self.lift_metadata_retriever.lift_metadata(page))
        self._log.debug(f'recording lift state snapshot {lift_metadata}')
        self.database_client.record_all(lift_metadata)

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG, format="%(asctime)s %(levelname)s %(message)s", stream=sys.stdout)
    recorder = LiftMetadataDatabaseRecorder(getenv_or_fail('MONGODB_PASS'))
    recorder.purge_data()
    snapshot_taker = LiftMetadataInserter(
        LiftMetadataRetriever(JsonEndpointFetcher.lift_metadata_fetcher(getenv_or_fail('DOLOMITI_BEARER'))),
        recorder
    )
    snapshot_taker.insert()


import linecache
import math
import os

# numpy and revise it with numpy

# multiple sets of 100 test cases

# cosine similarity

# 100 test cases for sum squared errors
# 100 test cases for Average
# small standard deviation -> good prediction

# smaller mean -> the better -> (mean = better prediction)

# transpose matrix to get the same functionality
# transpose matrix ->
FILESIZE = 24983
NUMJOKES = 100
FILENAME = "jester-data-1.csv"
FILENAMENNC = "nearestNeighborsC.csv"
FILENAMENNIB = "nearestNeighborsIB.csv"

def main():
    print("Collaborative Average - User 500, Joke 50: " + str(collaborativeAverage(3, 3)))
    print("Item Based Average - User 500, Joke 500: " + str(itemBasedAverage(3, 3)))
    print("Collaborative Weighted Sum - User 500, Joke 50: " + str(collaborativeWeightedSum(3, 3)))
    print("Item Based Weighted Sum - User 500, Joke 50: " + str(itemBasedWeightedSum(3, 3)))
    print("Collaborative Adjusted Weighted Sum - User 500, Joke 50: " + str(collaborativeAdjustedWeightedSum(3, 3)))
    print("Item Based Adjusted Weighted Sum - User 500, Joke 50: " + str(itemBasedAdjustedWeightedSum(3, 3)))
#    print("Nearest Neighbors Collaborative Average - User 500, Joke 50, N 24982: " + str(nearestNeighborsCollaborativeAverage(499, 49, 24982)))

#    print("Nearest Neighbors Collaborative Weighted Sum - User 500, Joke 50, N 24982: " + str(nearestNeighborsCollaborativeWeightedSum(499, 49, 24982)))

#    print("Nearest Neighbors Collaborative Adjusted Weighted Sum - User 500, Joke 50, N 24982: " + str(nearestNeighborsCollaborativeAdjustedWeightedSum(499, 49, 24982)))

#    print("Nearest Neighbors Item Based Average: " + str(nearestNeighborsItemBasedAverage(499, 49, 99)))

#    print("Nearest Neighbors Item Based Weighted Sum: " + str(nearestNeighborsItemBasedWeightedSum(499, 49, 99)))
#    print("Item Based Adjusted Weighted Sum - User 500, Joke 50: " + str(itemBasedAdjustedWeightedSum(3, 3)))
#    print("Nearest Neighbors Item Based Adjusted Weighted Sum: " + str(nearestNeighborsItemBasedAdjustedWeightedSum(499, 49, 99)))
#    print("Collaborative Pearson Correlation - User 24983, User 24982: " + str(collaborativePearsonCorrelation(FILESIZE - 1, FILESIZE - 2)))
#    print("Item Based Pearson Correlation - Joke 99, Joke 100: " + str(itemBasedPearsonCorrelation(98, 99)))
#    print("--------------------------------------------Test Cases ^^^-------------------------------------------------------------------")
#    print("Collaborative Average - User 1, Joke 1: " + str(collaborativeAverage(0, 0)))
#    print("Item based Average - User 1, Joke 1: " + str(itemBasedAverage(0, 0)))
#    print("Collaborative Pearson Correlation - User 1, User 2: " + str(collaborativePearsonCorrelation(0, 1)))
#    print("Item Based Pearson Correlation - Joke 1, Joke 2: " + str(itemBasedPearsonCorrelation(3, 3)))
#    print("Collaborative Weighted Sum - User 1, Joke 1: " + str(collaborativeWeightedSum(0,0)))
#    print("Collaborative Adjusted Weighted Sum - User 1, Joke 1: " + str(collaborativeAdjustedWeightedSum(0,0)))
#    print("Item Based Weighted Sum - User 1, Joke 1: " + str(itemBasedWeightedSum(3,3)))
#    print("Item Based Adjusted Weighted Sum - User 1, Joke 1: " + str(itemBasedAdjustedWeightedSum(0, 0)))
#    print("Nearest Neighbors Collaborative Average - User 500, Joke 50, N 5: " + str(nearestNeighborsCollaborativeAverage(499, 49, 24982)))
#    print("Nearest Neighbors Item Based Average: " + str(nearestNeighborsItemBasedWeightedSum(499, 49, 99)))

# given the user number and joke number, find all joke ratings at joke number except at row of user
def collaborativeAverage(userNumber, itemNumber, fileName = FILENAME, fileSize = FILESIZE):
    currentUser = 0
    count = 0
    total = 0
    for i in range(0, fileSize):
        if currentUser != userNumber:
            info = linecache.getline(fileName, i + 1).split(",")
            rating = float(info[itemNumber + 1])
            if rating != 99:
                total += rating
                count += 1
        currentUser += 1
    return total/count

def collaborativeWeightedSum(userNumber, itemNumber, fileName = FILENAME, fileSize = FILESIZE): # need to add appropriate params
    normalizationSum = 0
    compSum = 0
    for i in range(0, fileSize):
        if i != userNumber:
            info = linecache.getline(fileName, i + 1).split(",")
            utilityUserI = float(info[itemNumber + 1])
            if utilityUserI != 99:
                similarity = collaborativePearsonCorrelation(userNumber, i, fileName)
                #print(similarity)
                normalizationSum += abs(similarity)
                compSum += (similarity * utilityUserI)

    return compSum/normalizationSum

def collaborativeAdjustedWeightedSum(userNumber, itemNumber, fileName = FILENAME, fileSize = FILESIZE):
    normalizationSum = 0
    compSum = 0
    for i in range(0, fileSize):
        if i != userNumber:
            info = linecache.getline(fileName, i + 1).split(",")
            utilityUserI = float(info[itemNumber + 1])
            if utilityUserI != 99:
                similarity = collaborativePearsonCorrelation(userNumber, i, fileName)
                #print(similarity)
                normalizationSum += abs(similarity)
                compSum += (similarity * (utilityUserI - itemBasedAverage(i, -1, fileName)))

    return (itemBasedAverage(userNumber, -1, fileName) + (compSum/normalizationSum))

def collaborativePearsonCorrelation(user1Number, user2Number, fileName = FILENAME):
    sumNumerator = 0
    sumDenominatorUser1 = 0
    sumDenominatorUser2 = 0
    user1 = linecache.getline(fileName, user1Number + 1).split(",") # linecache indices start with 1
    user2 = linecache.getline(fileName, user2Number + 1).split(",")
    avgUser1 = itemBasedAverage(user1Number, -1, fileName) # -1 to ensure that it does not skip any joke
    avgUser2 = itemBasedAverage(user2Number, -1, fileName)
    #print(avgUser1, avgUser2)
    for i in range(1, len(user1)):
        utilityUser1 = float(user1[i])
        utilityUser2 = float(user2[i])
        if not (utilityUser1 == 99 or utilityUser2 == 99):
            compUser1 = utilityUser1 - avgUser1
            compUser2 = utilityUser2 - avgUser2
            sumNumerator += compUser1 * compUser2
            sumDenominatorUser1 += compUser1 ** 2
            sumDenominatorUser2 += compUser2 ** 2

    return sumNumerator / math.sqrt(sumDenominatorUser1 * sumDenominatorUser2)

def itemBasedAverage(userNumber, itemNumber, fileName = FILENAME):
    total = 0
    count = 0
    line = linecache.getline(fileName, userNumber + 1)
    info = line.split(",")
    for i in range(1, len(info)):
        if i != itemNumber + 1:
            rating = float(info[i])
            if rating != 99:
                total += rating
                count += 1
    return total/(count)

def itemBasedWeightedSum(userNumber, itemNumber, fileName = FILENAME, fileSize = FILESIZE):
    normalizationSum = 0
    compSum = 0
    info = linecache.getline(fileName, userNumber + 1).split(",")
    for i in range(1, len(info)):
        if i != itemNumber + 1:
            utilityItemI = float(info[i])
            if utilityItemI != 99:
                similarity = itemBasedPearsonCorrelation(itemNumber, i - 1, fileName, fileSize)
                #print(similarity)
                normalizationSum += abs(similarity)
                compSum += (similarity * utilityItemI)

    return compSum/normalizationSum

def itemBasedAdjustedWeightedSum(userNumber, itemNumber, fileName = FILENAME, fileSize = FILESIZE):
    normalizationSum = 0
    compSum = 0
    info = linecache.getline(fileName, userNumber + 1).split(",")
    for i in range(1, len(info)):
        if i != itemNumber + 1:
            utilityItemI = float(info[i])
            if utilityItemI != 99:
                similarity = itemBasedPearsonCorrelation(itemNumber, i - 1, fileName, fileSize)
                normalizationSum += abs(similarity)
                compSum += (similarity * (utilityItemI - collaborativeAverage(-1, i - 1, fileName, fileSize)))

    return (collaborativeAverage(-1, itemNumber) + (compSum/normalizationSum))

def itemBasedPearsonCorrelation(item1Number, item2Number, fileName = FILENAME, fileSize = FILESIZE):
    sumNumerator = 0
    sumDenominatorItem1 = 0
    sumDenominatorItem2 = 0
    avgItem1 = collaborativeAverage(-1, item1Number, fileName, fileSize) # -1 to ensure that it does not skip any user by
    avgItem2 = collaborativeAverage(-1, item2Number, fileName, fileSize)
    for i in range(0, fileSize):
        line = linecache.getline(fileName, i + 1).split(",");
        utilityItem1 = float(line[item1Number + 1])
        utilityItem2 = float(line[item2Number + 1])
        if not (utilityItem1 == 99 or utilityItem2 == 99): # if either user did not rate the joke, do not calculate

            compItem1 = utilityItem1 - avgItem1
            compItem2 = utilityItem2 - avgItem2
            sumNumerator += compItem1 * compItem2
            sumDenominatorItem1 += compItem1 ** 2
            sumDenominatorItem2 += compItem2 ** 2

    return sumNumerator / math.sqrt(sumDenominatorItem1 * sumDenominatorItem2)

def getNearestNeighborsCollaborative(userNumber, n):
    nearestNeighbors = [[-2, -1] for i in range(n)]
    for i in range(0, FILESIZE):
        if i != userNumber:
            info = linecache.getline(FILENAME, i + 1).split(",")
            similarity = collaborativePearsonCorrelation(userNumber, i)
            if similarity > nearestNeighbors[0][0]:
                #print("Before assigning")
                #print(nearestNeighbors)
                nearestNeighbors[0][0] = similarity
                #print("After assigning")
                #print(nearestNeighbors)
                nearestNeighbors[0][1] = i
                #print("Before sorted: ")
                #print(nearestNeighbors)
                nearestNeighbors = sorted(nearestNeighbors, key=lambda x: x[0])
                #print("After sorted: ")
                #print(nearestNeighbors)

    file = open(FILENAMENNC, 'w')
    for j in range(0, n):
        file.write(linecache.getline(FILENAME, nearestNeighbors[j][1] + 1))
    file.write(linecache.getline(FILENAME, userNumber + 1))

def getNearestNeighborsItemBased(itemNumber, n):
    nearestNeighbors = [[-2, -1] for i in range(n)]
    for i in range(0, NUMJOKES):
        if i != itemNumber:
            similarity = itemBasedPearsonCorrelation(itemNumber, i);
            if similarity > nearestNeighbors[0][0]:
                nearestNeighbors[0][0] = similarity
                nearestNeighbors[0][1] = i
                nearestNeighbors = sorted(nearestNeighbors, key=lambda x: x[0])

    file = open(FILENAMENNIB, 'w')
    for i in range(0, FILESIZE):
        line = linecache.getline(FILENAME, i+1).rstrip()
        info = line.split(',')

        count = NUMJOKES - (info[1:]).count(str(99))
        lineOut = ""
        for j in range(0, n):
            lineOut += info[nearestNeighbors[j][1]] + ","
        lineOut += info[itemNumber]
        lineOut = str(count) + "," + lineOut + "\n"
        file.write(lineOut)

def nearestNeighborsCollaborativeAverage(userNumber, itemNumber, n):
    getNearestNeighborsCollaborative(userNumber, n)
    average = collaborativeAverage(n, itemNumber, FILENAMENNC, n + 1)
    deleteFile(FILENAMENNC)
    return average

def nearestNeighborsCollaborativeWeightedSum(userNumber, itemNumber, n):
    getNearestNeighborsCollaborative(userNumber, n)
    weightedSum = collaborativeWeightedSum(n, itemNumber, FILENAMENNC, n + 1)
    deleteFile(FILENAMENNC)
    return weightedSum

def nearestNeighborsCollaborativeAdjustedWeightedSum(userNumber, itemNumber, n):
    getNearestNeighborsCollaborative(userNumber, n)
    adjustedWeightedSum = collaborativeAdjustedWeightedSum(n, itemNumber, FILENAMENNC, n + 1)
    deleteFile(FILENAMENNC)
    return adjustedWeightedSum

def nearestNeighborsItemBasedAverage(userNumber, itemNumber, n):
    getNearestNeighborsItemBased(itemNumber, n)
    average = itemBasedAverage(userNumber, n, FILENAMENNIB)
    deleteFile(FILENAMENNIB)
    return average

def nearestNeighborsItemBasedWeightedSum(userNumber, itemNumber, n):
    getNearestNeighborsItemBased(itemNumber, n)
    weightedSum = itemBasedWeightedSum(userNumber, n, FILENAMENNIB)
    deleteFile(FILENAMENNIB)
    return weightedSum

def nearestNeighborsItemBasedAdjustedWeightedSum(userNumber, itemNumber, n):
    getNearestNeighborsItemBased(itemNumber, n)
    adjustedWeightedSum = itemBasedAdjustedWeightedSum(userNumber, n, FILENAMENNIB, FILESIZE)
    deleteFile(FILENAMENNIB)
    return adjustedWeightedSum

def deleteFile(fileName):
    try:
        os.remove(fileName)
    except:
        pass

if __name__ == "__main__":
    main()


"""
Example

Description: Showcasing the use of Example Images from 'Images.py'
"""
from IMAGES import *
import pygame,sys
pygame.init()

w,h = (1920,1080)
win = pygame.display.set_mode([w,h])

img1 = Rock((255,255,255),(0,0))
img2 = Testing((255,255,255),(0,0))
while True:
    for e in pygame.event.get():
        if e.type == pygame.QUIT:
            sys.exit()

    win.fill((125,125,125))
    win.blit(img1.img,(0,0))
    win.blit(img2.img,(0,0))

    pygame.display.flip()


import sys
import os
import argparse

from pypiscout.SCout_Logger import Logger as sc
import gprof2dot    # pylint: disable=unused-import
                    # Rationale: Not directly used, but later we do a sys-call wich needs the library. This is needed to inform the user to install the package.

sys.path.append("../")
# pylint: disable=wrong-import-position
# Rationale: This module needs to access modules that are above them in the folder structure.

from Emma.shared_libs.stringConstants import *                           # pylint: disable=unused-wildcard-import,wildcard-import
import Emma.shared_libs.emma_helper
import genDoc._genCallGraphs
import genDoc._genUmlDiagrams

def ParseArguments():
    """
    Argument parser
    :return: argparse object containing the parsed options
    """
    parser = argparse.ArgumentParser(
        prog="Emma - Call graph generator",
        description="Script to generate call graphs that can be used in the documentation or to examine the run of Emma and the Emma Visualiser.",
        formatter_class=argparse.ArgumentDefaultsHelpFormatter
    )
    parser.add_argument(
        "--graphviz_bin_folder",
        help=r"The bin subfolder of the Graphviz software. Example: c:\Program Files (x86)\Graphviz2.38\bin",
        required=False
    )
    parser.add_argument(
        "--verbose",
        help="Prints out more info during run.",
        default=False
    )
    parser.add_argument(
        "--no_graphs",
        help="Do not update graphs (UML + call graph)",
        action="store_true",
        default=False
    )
    return parser.parse_args()

def main(arguments):
    """
    Main function.
    :param arguments: Processed command line arguments.
    :return: None
    """
    sc(invVerbosity=-1, actionWarning=lambda: sys.exit(-10), actionError=lambda: sys.exit(-10))

    sc().header("Generating the Readme documents", symbol="/")

    # Give a hint on python sys-call
    sc().info("A `python` system call is going to happen. If any errors occur please check the following first:")
    if sys.platform == "win32":
        sc().info("Windows OS detected. Make sure `python` refers to the Python3 version targeted for this application (-> dependencies; e.g. WSL comes with its own Python).\n")
    else:
        sc().info("Make sure `python` refers to a Python 3 installation.\n")

    # Store original path variables
    pathOldValue = os.environ["PATH"]
    if not("Graphviz" in os.environ["PATH"] or "graphviz" in os.environ["PATH"]):
        if arguments.graphviz_bin_folder is not None:
            graphvizBinAbspath = os.path.abspath(arguments.graphviz_bin_folder)
            # Add to path
            os.environ["PATH"] += (graphvizBinAbspath + ";")
        else:
            sc().error("The \"graphviz_bin_folder\" was not found in PATH nor was given in the argument --graphviz_bin_folder")

    try:
        outPath = os.path.abspath(Emma.shared_libs.emma_helper.joinPath("..", README_CALL_GRAPH_AND_UML_PATH))
        if not os.path.isdir(outPath):
            sc().info("The folder \"" + outPath + "\" was created because it did not exist...")
            os.makedirs(README_CALL_GRAPH_AND_UML_PATH)

        if not arguments.no_graphs:
            # pylint: disable=protected-access
            # Rationale: These modules are private so that the users will not use them directly. They are meant to be used trough this script.
            genDoc._genCallGraphs.main(arguments)
            genDoc._genUmlDiagrams.main()

        sc().info("Storing Emma readme as a .html file...")
        markdownFilePath = r"../doc/readme-emma.md"
        Emma.shared_libs.emma_helper.convertMarkdownFileToHtmlFile(Emma.shared_libs.emma_helper.joinPath(os.path.dirname(__file__), markdownFilePath), (os.path.splitext(markdownFilePath)[0] + ".html"))
        sc().info("Done.\n")

        sc().info("Storing Emma Visualiser readme as a .html file...")
        markdownFilePath = r"../doc/readme-vis.md"
        Emma.shared_libs.emma_helper.convertMarkdownFileToHtmlFile(Emma.shared_libs.emma_helper.joinPath(os.path.dirname(__file__), markdownFilePath), (os.path.splitext(markdownFilePath)[0] + ".html"))
        sc().info("Done.\n")

        sc().info("Storing Emma contribution as a .html file...")
        markdownFilePath = r"../doc/contribution.md"
        Emma.shared_libs.emma_helper.convertMarkdownFileToHtmlFile(Emma.shared_libs.emma_helper.joinPath(os.path.dirname(__file__), markdownFilePath), (os.path.splitext(markdownFilePath)[0] + ".html"))
        sc().info("Done.\n")

        sc().info("Storing the test_project readme as a .html file...")
        markdownFilePath = r"../doc/test_project/readme.md"
        Emma.shared_libs.emma_helper.convertMarkdownFileToHtmlFile(Emma.shared_libs.emma_helper.joinPath(os.path.dirname(__file__), markdownFilePath), (os.path.splitext(markdownFilePath)[0] + ".html"))
        sc().info("Done.\n")

        sc().info("Storing the top level README as a .html file...")
        # Change the working directory; otherwise we get errors about the relative image import paths in emma_helper.changePictureLinksToEmbeddingInHtmlData()
        os.chdir("..")
        markdownFilePath = r"../README.md"
        Emma.shared_libs.emma_helper.convertMarkdownFileToHtmlFile(Emma.shared_libs.emma_helper.joinPath(os.path.dirname(__file__), markdownFilePath), (os.path.splitext(markdownFilePath)[0] + ".html"))
        sc().info("Done.")
        os.chdir("doc")     # Change working directory back

    except Exception as exception:  # pylint: disable=broad-except
                                    # Rationale: We are not trying to catch a specific exception type here.
                                    # The purpose of this is, that the PATH environment variable will be set back in case of an error.
        sc().error("An exception was caught:", exception)

    # Get back initial path config
    os.environ["PATH"] = pathOldValue

if __name__ == "__main__":
    main(ParseArguments())


import typed_args as ta
from typing import List, Callable

@ta.argument_parser()
class Args(ta.TypedArgs):
    """
    Process some integers.
    """

    integers: List[int] = ta.add_argument(
        metavar='N', type=int, nargs='+',
        # help='an integer for the accumulator'
    )
    """
    an integer for the accumulator
    """

    accumulate: Callable[[List[int]], int] = ta.add_argument(
        '--sum',
        action='store_const',
        const=sum, default=max,
        help='sum the integers (default: find the max)'
    )

args = Args.parse_args()
print(args.accumulate(args.integers))


turn = ''
shown_turn = ''
winner= ''
check_if_win = False
check_if_tie = False
board = ["-", "-", "-",
         "-", "-", "-",
         "-", "-", "-"]

def Play_game():

    while check_if_win == False or check_if_tie == False:
        check_trun = False
        print_board = board[0] + " | " + board[1] + " | " + board[2] +"\n"+\
                      board[3] + " | " + board[4] + " | " + board[5] +"\n"+\
                      board[6] + " | " + board[7] + " | " + board[8]

        print(print_board)

        Check_Winner()
        check_tie()

        if shown_turn == 'X' or 'O' and shown_turn != '' and check_if_win == False:
            print("It's " + shown_turn+ " turn")

        if winner == 'X' or 'O' and check_if_win == True:
            print("Yay " + winner + " won.")
            break
        elif check_if_tie == True:
            print("Tie :(")
            break

        Player = input("Enter a number between 1 to 9")

        while Player not in ["1","2","3","4","5","6","7","8","9"]:
                Player= input("only numbers between 1 to 9")

        while check_trun ==False:
            if board[int(Player) -1 ] == '-':
                check_trun = True
                board[int(Player) - 1] = Switch_Turn(turn)
            else:
                print("Used Space try again")
                break

def Switch_Turn(turn1):
    global turn
    global shown_turn
    if turn1 == 'X':
        turn = 'O'
        shown_turn = 'X'
        return 'O'
    else:
        turn = 'X'
        shown_turn = 'O'
        return 'X'

def Check_Winner():
    global winner
    global check_if_win
    #Rows --
    if board[0] == board[1] == board[2] != "-":
        winner = board[0]
        check_if_win = True
        return
    elif board[3] == board[4] == board[5] != "-":
        winner= board[3]
        check_if_win = True
        return
    elif board[6] == board[7] == board[8] != "-":
        winner = board[6]
        check_if_win = True
        return
    #Col --
    if board[0] == board[3] == board[6] != "-":
        winner = board[0]
        check_if_win = True
        return
    elif board[1] == board[4] == board[7] != "-":
        winner = board[1]
        check_if_win = True
        return
    elif board[2] == board[5] == board[8] != "-":
        winner = board[2]
        check_if_win = True
        return
    #digno --
    if board[0] == board[4] == board[8] != "-":
        winner = board[0]
        check_if_win = True
        return
    elif board[2] == board[4] == board[6] != "-":
        winner = board[2]
        check_if_win = True
        return
    else:
        return

def check_tie():
    global check_if_tie
    for i in board:
        if i == '-':
            return

    check_if_tie = True

Play_game()


#Задать список из N элементов, заполненных числами из [-N, N]. Найти произведение элементов
#на указанных позициях. Позиции хранятся в списке positions - создайте этот список
# (например:positions = [1, 3, 6]).

# 1 вариант
n = int(input("Введите число n:"))
positions = [1, 3, 6]
x = max(positions)
y = int(len(positions))
my_str = []

for i in range(-n, n+1):
    my_str.append(i)

total = int(1)
if len(my_str) < x:
    print(f'Необходимо ввести значение больше ')
else:
    for i in range(1, y+1):
        total *= my_str[positions[i-1]]
print(total)

# 2 вариант

def new_spisok(n, n1, n2, n3):
    res = []
    poz = [n1,n2,n3]
    result = 1
    for i in range(-n, n+1):
        res.append(i)
    maxindex = len(res)-1
    minindex = len(res)
    for n in poz:
        if n > maxindex or n < -minindex:
            return print("Неверное указали значения индекса")
        result *= res[n]
    return print (f'В списке {res}, произведение значений с индексами  {n1},{n2},{n3} составляет {result}')

number = int(input("Введите число n:"))
poz1 = int(input("Введите индекс первого числа:"))
poz2 = int(input("Введите индекс первого числа:"))
poz3 = int(input("Введите индекс первого числа:"))

new_spisok(number, poz1, poz2, poz3)


import sys
import ctypes

def popcount(N):
    if sys.platform.startswith('linux'):
        libc = ctypes.cdll.LoadLibrary('libc.so.6')
        return libc.__sched_cpucount(ctypes.sizeof(ctypes.c_long), (ctypes.c_long * 1)(N))
    elif sys.platform == 'darwin':
        libc = ctypes.cdll.LoadLibrary('libSystem.dylib')
        return libc.__popcountdi2(N)
    else:
        assert(False)

S = input()
N = len(S)
ans = N
for state in range(1 << N):
    cand = 0
    used = [False] * N
    for i in range(N):
        if state >> i & 1:
            for j in range(N):
                if S[j] == "o":
                    used[(i + j) % N] = True
    if sum(used) == N:
        ans = min(ans, popcount(state))

print(ans)


from main import speak, sing
import unittest

class TestMain(unittest.TestCase):

    def test_speak(self):
        INP = EXP ='OK'
        OUT = speak(INP)
        assert OUT == EXP, 'It must speak exactly what I asked'

    def test_sing(self):
        INP = EXP = 'Lala land'
        OUT = sing(INP)
        assert OUT == EXP, 'It must sing exactly what I asked'

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


import csv
from pylab import *
import sys

if len(sys.argv) != 4:
    print('Error, ejecucion: python estadisticas.py <topico> <fecha_ini(yyyy-mm-dd)> <fecha_fin(yyyy-mm-dd)>')
    print('Para omitir un parametro dejar el valor \'\'')
    exit()

topico = str(sys.argv[1])   #str(input("ingrese topico: "))
date_ini = str(sys.argv[2])   #str(input("fecha de inicio (yyyy-mm-dd): "))
date_fin = str(sys.argv[3])   #str(input("fecha de fin (yyyy-mm-dd): "))

fecha_ini = int(date_ini.replace("-", "")+'000000')
fecha_fin = int(date_fin.replace("-", "")+'235959')

data_csv = open('tweets_nyctsubway.csv', 'r', encoding='latin1')
data = csv.reader(data_csv, delimiter=';', quotechar='\"')

comp = []
neg = []
neu = []
pos = []

a = 0
for row in data:

    if a == 0:
        a += 1
        continue

    tweet_date = int(row[2])

    if topico != '' and (fecha_fin == '235959' or fecha_ini == "000000"):
        if topico == row[1]:
            comp.append(float(row[3]))
            neg.append(float(row[4]))
            neu.append(float(row[5]))
            pos.append(float(row[6]))

    elif topico != '' and fecha_fin != '235959' and fecha_ini != "000000":
        if topico == row[1] and tweet_date <= fecha_fin and tweet_date >= fecha_ini:
            comp.append(float(row[3]))
            neg.append(float(row[4]))
            neu.append(float(row[5]))
            pos.append(float(row[6]))

    elif topico == '' and fecha_fin != '235959' and fecha_ini != "000000":
        if tweet_date <= fecha_fin and tweet_date >= fecha_ini:
            comp.append(float(row[3]))
            neg.append(float(row[4]))
            neu.append(float(row[5]))
            pos.append(float(row[6]))

if len(pos) == 0:
    print("No hay datos para los parametros usados.")
    exit()
else:
    print('Analizando', len(pos), 'tweets...')
    print('-> Positividad', sum(pos)/len(pos))
    print('-> Negatividad', sum(neg)/len(neg))
    print('-> Polaridad', sum(comp)/len(comp))

tot_pos = sum(pos)
tot_neg = sum(neg)
tot_neu = sum(neu)

ax = axes([0, 0, 0.9, 0.9])
labels = 'Positivos ', 'Negativos', 'Neutros'
fracs = [tot_pos, tot_neg, tot_neu]
pie(fracs, labels=labels, autopct='%10.0f%%', shadow=True)
legend()
title('Estadisticas de tweets', bbox={'facecolor': '0.8', 'pad': 5})
show()


from turtle import Turtle, Screen
import random

screen = Screen()
screen.setup(width=500, height=400)
colors = ["red", "orange", "yellow", "green", "blue", "purple"]
user_bet = ""
while user_bet not in colors:
    user_bet = screen.textinput(title="Make your bet", prompt="Which turtle will win the race? Enter a color: ")

is_race_on = False
turtles = []

y = -100
for i in range(0, 6):
    new_turtle = Turtle(shape="turtle")
    new_turtle.pu()
    new_turtle.color(colors[i])
    new_turtle.goto(x=-235, y=y)
    turtles.append(new_turtle)
    y += 40

if user_bet:
    is_race_on = True

while is_race_on:
    for turtle in turtles:
        if turtle.xcor() > 230:
            is_race_on = False
            winning_color = turtle.pencolor()
            if winning_color == user_bet:
                print("You have won!")
            else:
                print("You have lost.")
            print(f"The {winning_color} color turtle is the winner!")
        else:
            rand_distance = random.randint(0, 10)
            turtle.forward(rand_distance)

screen.exitonclick()


#!/usr/bin/python3
"""Returns the number of lines of a text file"""

def read_lines(filename="", nb_lines=0):
    """Reads a text file and return the number of lines"""
    lines = 0
    with open(filename) as a_file:
        i = len(list(a_file))
        if nb_lines >= i or nb_lines <= 0:
            nb_lines = i
        a_file.seek(0, 0)
        for l in range(nb_lines):
            print(a_file.readline(), end="")


import unittest
import mock

from hpOneView.connection import connection
from hpOneView.resources.networking.sas_logical_interconnects import SasLogicalInterconnects
from hpOneView.resources.resource import ResourceClient

class SasLogicalInterconnectsTest(unittest.TestCase):
    def setUp(self):
        self.host = '127.0.0.1'
        self.connection = connection(self.host)
        self._client = SasLogicalInterconnects(self.connection)

    @mock.patch.object(ResourceClient, 'get_all')
    def test_get_all_called_once(self, mock_get_all):
        filter = 'name=TestName'
        sort = 'name:ascending'

        self._client.get_all(2, 500, filter, sort)

        mock_get_all.assert_called_once_with(count=500, fields='name=TestName', filter='name:ascending', query='',
                                             sort='', start=2, view='')

    @mock.patch.object(ResourceClient, 'get_all')
    def test_get_all_called_once_with_default(self, mock_get_all):
        self._client.get_all()
        mock_get_all.assert_called_once_with(count=-1, fields='', filter='', query='', sort='', start=0, view='')

    @mock.patch.object(ResourceClient, 'get')
    def test_get_by_id_called_once(self, mock_get):
        logical_interconnect_id = "f0a0a113-ec97-41b4-83ce-d7c92b900e7c"
        self._client.get(logical_interconnect_id)
        mock_get.assert_called_once_with(logical_interconnect_id)

    @mock.patch.object(ResourceClient, 'get')
    def test_get_by_uri_called_once(self, mock_get):
        logical_interconnect_uri = "/rest/sas-logical-interconnects/f0a0a113-ec97-41b4-83ce-d7c92b900e7c"
        self._client.get(logical_interconnect_uri)
        mock_get.assert_called_once_with(logical_interconnect_uri)

    @mock.patch.object(ResourceClient, 'get_by')
    def test_get_by_called_once(self, mock_get):
        self._client.get_by("name", "value")
        mock_get.assert_called_once_with("name", "value")

    @mock.patch.object(ResourceClient, 'create')
    def test_replace_drive_enclosure_called_once(self, mock_create):
        drive_replacement = {
            "oldSerialNumber": "SN1100",
            "newSerialNumber": "SN1101"
        }
        self._client.replace_drive_enclosure(drive_replacement, "ad28cf21-8b15-4f92-bdcf-51cb2042db32")

        mock_create.assert_called_once_with(
            drive_replacement.copy(),
            '/rest/sas-logical-interconnects/ad28cf21-8b15-4f92-bdcf-51cb2042db32/replaceDriveEnclosure')

    @mock.patch.object(ResourceClient, 'update')
    def test_update_compliance_all_called_once(self, mock_update):
        compliance_uris = {
            "uris": [
                "/rest/sas-logical-interconnects/ad28cf21-8b15-4f92-bdcf-51cb2042db32"
            ]}

        self._client.update_compliance_all(compliance_uris)

        mock_update.assert_called_once_with(compliance_uris.copy(),
                                            '/rest/sas-logical-interconnects/compliance',
                                            timeout=-1)

    @mock.patch.object(ResourceClient, 'update_with_zero_body')
    def test_update_compliance_by_uri(self, mock_update_with_zero_body):
        logical_interconnect_uri = '/rest/sas-logical-interconnects/ad28cf21-8b15-4f92-bdcf-51cb2042db32'
        self._client.update_compliance(logical_interconnect_uri)

        mock_update_with_zero_body.assert_called_once_with(
            '/rest/sas-logical-interconnects/ad28cf21-8b15-4f92-bdcf-51cb2042db32/compliance', timeout=-1)

    @mock.patch.object(ResourceClient, 'update_with_zero_body')
    def test_update_compliance_by_id(self, mock_update_with_zero_body):
        mock_update_with_zero_body.return_value = {}
        logical_interconnect_id = 'ad28cf21-8b15-4f92-bdcf-51cb2042db32'

        self._client.update_compliance(logical_interconnect_id)

        mock_update_with_zero_body.assert_called_once_with(
            '/rest/sas-logical-interconnects/ad28cf21-8b15-4f92-bdcf-51cb2042db32/compliance', timeout=-1)

    @mock.patch.object(ResourceClient, 'update_with_zero_body')
    def test_update_configuration_by_uri(self, mock_update_with_zero_body):
        logical_interconnect_uri = '/rest/sas-logical-interconnects/ad28cf21-8b15-4f92-bdcf-51cb2042db32'

        self._client.update_configuration(logical_interconnect_uri)

        mock_update_with_zero_body.assert_called_once_with(
            '/rest/sas-logical-interconnects/ad28cf21-8b15-4f92-bdcf-51cb2042db32/configuration')

    @mock.patch.object(ResourceClient, 'update_with_zero_body')
    def test_update_configuration_by_id(self, mock_update_with_zero_body):
        logical_interconnect_id = 'ad28cf21-8b15-4f92-bdcf-51cb2042db32'

        self._client.update_configuration(logical_interconnect_id)

        mock_update_with_zero_body.assert_called_once_with(
            '/rest/sas-logical-interconnects/ad28cf21-8b15-4f92-bdcf-51cb2042db32/configuration')

    @mock.patch.object(ResourceClient, 'get')
    def test_get_firmware(self, mock_get):
        logical_interconnect_id = '3518be0e-17c1-4189-8f81-83f3724f6155'

        logical_interconnect_uri = "/rest/sas-logical-interconnects/" + logical_interconnect_id

        expected_uri = logical_interconnect_uri + "/firmware"

        self._client.get_firmware(logical_interconnect_id)
        mock_get.assert_called_once_with(expected_uri)

    @mock.patch.object(ResourceClient, 'update')
    def test_update_firmware(self, mock_update):
        logical_interconnect_id = '3518be0e-17c1-4189-8f81-83f3724f6155'

        fake_firmware = dict(
            command="Update",
            sppUri="/rest/firmware-drivers/Service_0Pack_0for_0ProLiant"
        )

        logical_interconnect_uri = "/rest/sas-logical-interconnects/" + logical_interconnect_id

        expected_uri = logical_interconnect_uri + "/firmware"

        self._client.update_firmware(fake_firmware, logical_interconnect_id)
        mock_update.assert_called_once_with(fake_firmware, expected_uri)


class Player:
    def __init__(self, name, id, pos, switch, order, sub, sub_id, status, team):
        self.name = name
        self.id = id
        self.pos = pos
        self.switch = switch
        self.order = order

        self.sub = sub
        self.sub_id = sub_id
        self.status = status # 'available', 'entered', 'removed'
        self.team = team
        self.pbp_name = None


from django.shortcuts import render, redirect
from .models import *
from hashlib import sha1
from django.http import JsonResponse, HttpResponseRedirect
from . import user_decorator
from df_goods.models import *

def register(request):
    return render(request, 'df_user/register.html')

def register_handle(request):
    # 接受用户输入
    post = request.POST
    uname = post.get('user_name')
    upwd = post.get('pwd')
    upwd2 = post.get('cpwd')
    uemail = post.get('email')
    # 判断两次密码是否一次
    if upwd != upwd2:
        return redirect('/user/register/')
    # 密码加密
    s1 = sha1()
    s1.update(upwd.encode("utf8"))
    upwd3 = s1.hexdigest()

    # 创建对象
    user = UserInfo()
    user.uname = uname
    user.upwd = upwd3
    user.uemail = uemail
    user.save()
    # 注册成功，转到登录页面
    context = {'title': '用户登录', 'uname': uname, 'page_name': 1}
    return render(request, 'df_user/login.html', context)

def register_exist(request):
    uname = request.GET.get('uname')
    print(uname)
    count = UserInfo.objects.filter(uname=uname).count()
    print(count)
    return JsonResponse({'count': count})

def login(request):
    uname = request.COOKIES.get('uname', '')
    context = {'title': '用户登录', 'error_name': 0, 'error_pwd': 0, "uname": uname, 'page_name': 1}
    return render(request, 'df_user/login.html', context)

def login_handle(request):
    # 接受请求信息
    post = request.POST
    uname = post.get('username')
    upwd = post.get('pwd')
    remember_name = post.get('remember_name', 0)
    # 根据用户名查询对象
    users = UserInfo.objects.filter(uname=uname) # []
    print(uname)
    # 判断：如果未查到则用户名错，如果查到则判断密码是否正确，正确则转到用户中心
    if len(users) == 1:
        s1 = sha1()
        s1.update(upwd.encode("utf8"))
        if s1.hexdigest() == users[0].upwd:
            url = request.COOKIES.get('url', '/')
            red = HttpResponseRedirect(url)
            # 记住用户名
            if remember_name != 0:
                red.set_cookie('uname', uname)
            else:
                red.set_cookie('uname', '', max_age=-1)  # max_age过期时间
            request.session['user_id'] = users[0].id
            request.session['user_name'] = uname
            return red
        else:
            context = {'title': '用户登录', 'error_name': 0, 'error_pwd': 1, 'uname': uname, 'upwd': upwd, 'page_name': 1}
            return render(request, 'df_user/login.html', context)
    else:
        context = {'title': '用户登录', 'error_name': 1, 'error_pwd': 0, 'uname': uname, 'upwd': upwd, 'page_name': 1}
        return render(request, 'df_user/login.html', context)

def logout(request):
    request.session.clear()
    return HttpResponseRedirect('/')

@user_decorator.login
def info(request):
    user_email = UserInfo.objects.get(id=request.session['user_id']).uemail
    # 最近浏览
    goods_ids = request.COOKIES.get('goods_ids', '')
    goods_ids1 = goods_ids.split(',')
    goods_list = []
    for goods_id in goods_ids1:
        goods_list.append(GoodsInfo.objects.get(id=int(goods_id)))

    context = {'title': '用户中心',
               'user_email': user_email,
               'user_name': request.session['user_name'],
               'page_name': 1,
               'goods_list': goods_list,
               }
    return render(request, 'df_user/user_center_info.html', context)

@user_decorator.login
def order(request):
    context = {'title': '订单中心', 'page_name': 1}
    return render(request, 'df_user/user_center_order.html', context)

@user_decorator.login
def site(request):
    user = UserInfo.objects.get(id=request.session['user_id'])
    print(user.id)
    if request.method == 'POST':
        post = request.POST
        user.urece = post.get('urece')
        user.uaddress = post.get('uaddress')
        user.uzip = post.get('uzip')
        user.uphone = post.get('uphone')
        user.save()
    context = {'title': '收货地址', 'user': user, 'page_name': 1}
    return render(request, 'df_user/user_center_site.html', context)


"""Holds environmental variables, sets up custom logger."""

import logging
import os

log = logging.getLogger(name="log")

# declare environment constants
COSMOSDB_CONNECTION_STRING: str = os.environ["COSMOSDB_CONNECTION_STRING"]
COSMOSDB_DATABASE_ID: str = os.environ["COSMOSDB_DATABASE_ID"]
COSMOSDB_CONTAINER_ID: str = os.environ["COSMOSDB_CONTAINER_ID"]
BLOB_SERVICE_CONNECTION_STRING: str = os.environ["BLOB_CONNECTION_STRING"]
BLOB_CONTAINER_NAME: str = os.environ["BLOB_CONTAINER_NAME"]

def logger(
    logging_format: str = "%(levelname)s, %(name)s.%(funcName)s: %(message)s",
    level: int = logging.INFO,
) -> None:
    """
    Sets up custom logger.

    Parameters:
        format (str, optional): Logging format. Defaults to "%(name)s%(funcName)s: %(message)s".
        level (int, optional): Logging level. Defaults to logging.INFO.

    Returns:
        None
    """
    log.debug(msg="Setting up custom logger.")

    log.setLevel(level=level)

    handler = logging.StreamHandler(stream=None)

    formatter = logging.Formatter(fmt=logging_format)
    handler.setFormatter(fmt=formatter)

    if log.hasHandlers():
        log.handlers.clear()

    log.addHandler(handler)


from Game    import Game
from Player  import Player
from Players import Players

print('::::: PROBLEM 1 :::::')

player_1     = Player( 1 , "Kirat Boli"   , [5,30,25,10,15,1,9,5]  )
player_2     = Player( 2 , "N.S Nodhi"    , [10,40,20,5,10,1,4,10] )
player_3     = Player( 3 , "R Rumrah"     , [20,30,15,5,5,1,4,20]  )
player_4     = Player( 4 , "Shashi Henra" , [30,25,5,0,5,1,4,30]   )

players_list = [player_1,player_2,player_3,player_4]

players      = Players(players_list,"Lengaburu")

problem_1    = Game(players,40,24)

problem_1.runGame()
problem_1.printGameSummary()

print('::::: PROBLEM 2 :::::')

player_1_1     = Player( 1 , "Kirat Boli"   , [5,10,25,10,25,1,14,10]  )
player_2_1     = Player( 2 , "N.S Nodhi"    , [5,15,15,10,20,1,19,15]  )
player_1_2     = Player( 3 , "DB Vellyers"  , [5,10,25,10,25,1,14,10]  )
player_2_2     = Player( 4 , "H Mamla"      , [10,15,15,10,20,1,19,15] )

players_list_1 = [player_1_1,player_2_1]
players_list_2 = [player_1_2,player_2_2]

players_1 = Players(players_list_1,"Lengaburu")
players_2 = Players(players_list_2,"Enchai")

problem_2_1 = Game(players_1,999,12)
problem_2_1.runGame(False)

problem_2_2 = Game(players_2,problem_2_1.players.team_score,12)
problem_2_2.runGame()
problem_2_2.printGameSummary()


from typing import Optional
import torch
from torch import nn
from config import dt_config
from block import TransformerBlock

class DecisionTransformer(nn.Module):
    def __init__(self,
                 cfg: dt_config,
                 state_dim: int,
                 action_dim: int) -> None:
        super().__init__()

        self.embedding_dropout = nn.Dropout(cfg.embedding_dropout)
        self.embedding_norm = nn.LayerNorm(cfg.embedding_dim)

        self.final_norm = nn.LayerNorm(cfg.embedding_dim)
        self.positional_encoding = nn.Embedding(cfg.episode_length + cfg.sequence_length,
                                           cfg.embedding_dim)
        self.state_embedding = nn.Linear(state_dim, cfg.embedding_dim)
        self.action_embedding = nn.Linear(action_dim, cfg.embedding_dim)
        self.return_embedding = nn.Linear(1, cfg.embedding_dim)

        self.blocks = nn.ModuleList([
            TransformerBlock(3 * cfg.sequence_length,
                             cfg.embedding_dim,
                             cfg.num_heads,
                             cfg.attention_dropout,
                             cfg.residual_dropout) for _ in range(cfg.num_layers)
        ])

        self.embedding_dim = cfg.embedding_dim
        self.sequence_length = cfg.sequence_length
        self.state_dim = state_dim
        self.action_dim = action_dim
        self.episode_length = cfg.episode_length
        self.max_action = cfg.max_action

        self.action_head = nn.Sequential(
            nn.Linear(self.embedding_dim, self.action_dim),
            nn.Tanh()
        )

        self.apply(self.reset_weights)

    @staticmethod
    def reset_weights(m: nn.Module):
        if isinstance(m, (nn.Linear, nn.Embedding)):
            nn.init.normal_(m.weight, mean=0.0, std=0.02)

            if isinstance(m, nn.Linear) and m.bias is not None:
                nn.init.zeros_(m.bias)

        if isinstance(m, nn.LayerNorm):
            nn.init.zeros_(m.bias)
            nn.init.ones_(m.weight)

    def forward(self,
                states: torch.Tensor,
                actions: torch.Tensor,
                mc_returns: torch.Tensor,
                time_steps: torch.Tensor,
                key_padding_mask: Optional[torch.Tensor] = None) -> torch.Tensor:
        batch_size, sequence_length = states.shape[0], states.shape[1]

        pos_encoding = self.positional_encoding(time_steps)
        state_embedding = self.state_embedding(states) + pos_encoding
        action_embedding = self.action_embedding(actions) + pos_encoding
        returns_embedding = self.return_embedding(mc_returns.unsqueeze(-1)) + pos_encoding

        sequence = torch.stack((
            returns_embedding, state_embedding, action_embedding
        ), dim=1).permute(0, 2, 1, 3).reshape(batch_size, 3 * sequence_length, self.embedding_dim)

        if key_padding_mask is not None:
            key_padding_mask = torch.stack((
                key_padding_mask, key_padding_mask, key_padding_mask
            ), dim=1).permute(0, 2, 1).reshape(batch_size, 3 * sequence_length)

        out = self.embedding_dropout(self.embedding_norm(sequence))

        for block in self.blocks:
            out = block(out, padding_mask=key_padding_mask)

        out = self.final_norm(out)
        return self.action_head(out[:, 1::3]) * self.max_action


from os import mkdir, getcwd
from os.path import join,exists

def new_file(file_name, data):
    """
    create new file
    """
    with open(file_name, 'w', encoding='utf-8') as file:
        file.write(data)

def new_static_dir(project_name):
    """
    root_dir/static
    """
    static_path = join(getcwd(), project_name, 'static')
    if exists(static_path):
        return
    mkdir(static_path)

def new_static_readme(project_name):
    """
    root_dir/static/README.md
    """
    content = [
        f'# {project_name} Docs',
        '\n',
        ' 文件存放文件夹',
        ' - 若是算法模型，可将数据和算法模型下载到此文件夹',
        ' - 若是容器服务，此文件夹为容器映射文件夹，做持久化使用'
    ]
    readme_file = join(getcwd(), project_name, 'static', 'README.md')
    data = '\n'.join(content)
    new_file(readme_file, data)

def new_static(project_name):
    """
    Export static
    """
    new_static_dir(project_name)
    new_static_readme(project_name)