#################################################################################################
# Visual object tracking in panoramic video
# Master thesis at Brno University of Technology - Faculty of Information Technology
# Author:       Vít Ambrož (xambro15@stud.fit.vutbr.cz)
# Supervisor:   Doc. Ing. Martin Čadík, Ph.D.
# Module:       tracker_360_default.py
# Description:  Default tracking using DaSiamRPN tracker
#################################################################################################
# --------------------------------------------------------
# DaSiamRPN (https://github.com/foolwood/DaSiamRPN)
# Licensed under The MIT License
# Written by Qiang Wang (wangqiang2015 at ia.ac.cn)
# --------------------------------------------------------

import sys
import cv2
import torch
import numpy as np
from os.path import realpath, dirname, join

from net import SiamRPNBIG
from run_SiamRPN import SiamRPN_init, SiamRPN_track
from utils import get_axis_aligned_bbox, cxy_wh_2_rect, rect_2_cxy_wh

# custom modules to improve equirectangular tracking
from boundingbox import BoundingBox
from parser import Parser

class Tracker360Default:
    """Default tracking using DaSiamRPN tracker"""
    def __init__(self, video_path: str, groundtruth_path: str = None, save_result_path: str = None):
        self.video_path = video_path
        self.groundtruth_path = groundtruth_path
        if save_result_path:
            self.save_result_path = save_result_path
        else:
            self.save_result_path = "tmp-result-DaSiamRPN.txt"

        self.net = None

        self.video = None
        self.video_width = None
        self.video_height = None
        self.frame = None
        self.tracker = None
        self.bbox = None
        self.gt_bounding_boxes = []
        self.result_bounding_boxes = []

        # enable parsing/creating methods
        self.parser = Parser()

        # constants for sizes and positions of opencv circles, rectangles and texts
        self.RECTANGLE_BORDER_PX = 3
        self.FONT_SCALE = 0.75
        self.FONT_WEIGHT = 1
        self.TEXT_ROW1_POS = (30,30)
        self.TEXT_ROW2_POS = (30,60)
        self.TEXT_ROW3_POS = (30,90)
        self.TEXT_ROW4_POS = (30,120)

        self.WINDOW_NAME = "Tracker-DaSiamRPN"

    def _drawBoundingBox(self, videoWidth, point1, point2, boundingBox, color, thickness):
        """Method for drawing rectangle according to points"""
        if (boundingBox.is_on_border()):
            # draw two rectangles around the region of interest
            rightBorderPoint = (videoWidth - 1, point2[1])
            cv2.rectangle(self.frame, point1, rightBorderPoint, color, thickness)

            leftBorderPoint = (0, point1[1])
            cv2.rectangle(self.frame, leftBorderPoint, point2, color, thickness)
        else:
            # draw a rectangle around the region of interest
            cv2.rectangle(self.frame, point1, point2, color, thickness)

    def _checkBoundsOfPoint(self, point):
        """Checks if given point is in interval [0,self.width] and [0,self.height] with x overflow"""
        # horizontal could overflow in equirectangular
        x = point[0]
        y = point[1]
        if x < 0:
            x = self.video_width + x - 1
        elif x > self.video_width - 1:
            x = x - self.video_width - 1

        # vertical
        if y < 0:
            y = 0
        elif y > self.video_height - 1:
            y = self.video_height - 1

        point = (x,y)
        return point

    def _saveResults(self):
        """Method for saving result bounding boxes to .txt file"""
        # creating string result data
        resultData = self.parser.createAnnotations(self.result_bounding_boxes)
        # saving file on drive
        self.parser.saveDataToFile(self.save_result_path, resultData)
        print("File '" + self.save_result_path + "' has been successfully created with total " + str(len(self.result_bounding_boxes)) + " computed frames.")

    def run_video_default(self):
        """Method for start DaSiamRPN tracking without any modifications"""
        ########## 1) Video Checking ##########
        # Read video
        self.video = cv2.VideoCapture(self.video_path)
        # Exit if video not opened.
        if not self.video.isOpened():
            print("Could not open video")
            print(help)
            sys.exit(-1)

        # Read first frame.
        ok, self.frame = self.video.read()
        if not ok:
            print("Error - Could not read a video file")
            sys.exit(-1)

        # save video width/height to global variables
        self.video_width = int(self.video.get(cv2.CAP_PROP_FRAME_WIDTH))
        self.video_height = int(self.video.get(cv2.CAP_PROP_FRAME_HEIGHT))

        ########## 2) Load pretrained model ##########
        # load net
        print("Loading pretrained model SiamRPNBIG.model...")
        self.net = SiamRPNBIG()
        self.net.load_state_dict(torch.load(join(realpath(dirname(__file__)), 'SiamRPNBIG.model')))
        self.net.eval().cuda()

        ########## 3) Setup opencv2 window ##########
        # resize window (lets define max width is 1600px)
        if self.video_width < 1600:
            cv2.namedWindow(self.WINDOW_NAME)
        else:
            cv2.namedWindow(self.WINDOW_NAME, cv2.WINDOW_NORMAL | cv2.WINDOW_KEEPRATIO)
            whRatio = self.video_width / self.video_height
            if whRatio == 2:
                # pure equirectangular 2:1
                cv2.resizeWindow(self.WINDOW_NAME, 1600, 800)
            else:
                # default 16:9
                cv2.resizeWindow(self.WINDOW_NAME, 1600, 900)

            scaleFactor = self.video_width / 1600
            self.RECTANGLE_BORDER_PX = int(self.RECTANGLE_BORDER_PX * scaleFactor)
            self.FONT_SCALE = self.FONT_SCALE * scaleFactor
            self.FONT_WEIGHT = int(self.FONT_WEIGHT * scaleFactor) + 1
            self.TEXT_ROW1_POS = (int(self.TEXT_ROW1_POS[0] * scaleFactor), int(self.TEXT_ROW1_POS[1] * scaleFactor))
            self.TEXT_ROW2_POS = (int(self.TEXT_ROW2_POS[0] * scaleFactor), int(self.TEXT_ROW2_POS[1] * scaleFactor))
            self.TEXT_ROW3_POS = (int(self.TEXT_ROW3_POS[0] * scaleFactor), int(self.TEXT_ROW3_POS[1] * scaleFactor))
            self.TEXT_ROW4_POS = (int(self.TEXT_ROW4_POS[0] * scaleFactor), int(self.TEXT_ROW4_POS[1] * scaleFactor))

        # use copy of frame to be shown in window
        frame_disp = self.frame.copy()

        ########## 4) Initialation of bounding box ##########
        # Set up initial bounding box
        self.bbox = None
        self.result_bounding_boxes = []
        self.gt_bounding_boxes = []
        if self.groundtruth_path:
            # use first bounding box from given groundtruth
            self.gt_bounding_boxes = self.parser.parseGivenDataFile(self.groundtruth_path, self.video_width)

            if len(self.gt_bounding_boxes) > 0:
                bb1 = self.gt_bounding_boxes[0]
                if bb1.is_annotated:
                    self.bbox = (bb1.get_point1_x(), bb1.get_point1_y(), bb1.get_width(), bb1.get_height())
                    self.result_bounding_boxes.append(bb1)
                else:
                    print("Error - Invalid first frame annotation from file: '" + self.groundtruth_path + "'")
                    sys.exit(-1)
        else:
            # using opencv2 select ROI
            cv2.putText(frame_disp, 'Select target ROI and press ENTER', self.TEXT_ROW1_POS, cv2.FONT_HERSHEY_SIMPLEX, self.FONT_SCALE, (0, 200, 250), self.FONT_WEIGHT)

            x, y, w, h = cv2.selectROI(self.WINDOW_NAME, frame_disp, False)
            self.bbox = [x, y, w, h]

            # save it to result list
            p1 = (int(self.bbox[0]), int(self.bbox[1]))
            p2 = (int(self.bbox[0] + self.bbox[2]), int(self.bbox[1] + self.bbox[3]))
            # new instance of bounding box
            bb1 = BoundingBox(p1, p2, self.video_width)
            bb1.is_annotated = True
            self.result_bounding_boxes.append(bb1)

        if not(self.bbox) or self.bbox == (0,0,0,0):
            print("Error - Invalid first frame annotation")
            sys.exit(-1)

        ########## 5) Tracking process ##########
        # prints just basic guide and info
        print("--------------------------------------------------------------------")
        print("DaSiamRPN default tracking process has started...")
        print("Tracker  : DaSiamRPN")
        print("Frame #1 : " + str(self.bbox))
        print("Press 'Esc' or 'Q' key to exit")
        print("--------------------------------------------------------------------")

        # initialize tracker with first frame and bounding box
        ([cx, cy], [w, h]) = rect_2_cxy_wh(self.bbox)
        target_pos, target_sz = np.array([int(cx), int(cy)]), np.array([int(w), int(h)])
        state = SiamRPN_init(self.frame, target_pos, target_sz, self.net)

        # display first frame
        cv2.imshow(self.WINDOW_NAME, frame_disp)

        # if you want to have the FPS according to the video then uncomment this code
        # fps = cap.get(cv2.CAP_PROP_FPS)
        videoFPS = 30
        # calculate the interval between frame
        interval = int(1000/videoFPS)

        while True:
            # Read a new frame
            ok, self.frame = self.video.read()
            if not ok:
                break

            # Start timer
            timer = cv2.getTickCount()

            # Get tracked bbox
            state = SiamRPN_track(state, self.frame)  # track
            res = cxy_wh_2_rect(state['target_pos'], state['target_sz'])
            res = [int(l) for l in res]
            self.bbox = res

            # Calculate Frames per second (FPS)
            fps = cv2.getTickFrequency() / (cv2.getTickCount() - timer)

            # draw bounding box
            if res[0] and res[1] and res[2] and res[3]:
                # Tracking success
                p1 = (res[0], res[1])
                p2 = (res[0] + res[2], res[1] + res[3])

                p1 = self._checkBoundsOfPoint(p1)
                p2 = self._checkBoundsOfPoint(p2)

                # new instance of bounding box
                bb = BoundingBox(p1, p2, self.video_width)
                bb.is_annotated = True
                self.result_bounding_boxes.append(bb)

                # draw bounding box to original frame
                self._drawBoundingBox(self.video_width, p1, p2, bb, (0, 255, 0), self.RECTANGLE_BORDER_PX)
            else:
                # tracking failure
                cv2.putText(self.frame, "Tracking failure detected", self.TEXT_ROW4_POS, cv2.FONT_HERSHEY_SIMPLEX, self.FONT_SCALE, (0, 0, 255), self.FONT_WEIGHT)

                # new instance of bounding box
                bb = BoundingBox(None, None, self.video_width)
                bb.is_annotated = False
                self.result_bounding_boxes.append(bb)

            # Display tracker type on frame
            cv2.putText(self.frame, "DaSiamRPN Tracker", self.TEXT_ROW1_POS, cv2.FONT_HERSHEY_SIMPLEX, self.FONT_SCALE, (0, 200, 250), self.FONT_WEIGHT)
            # Display FPS on frame
            cv2.putText(self.frame, "Video   FPS : " + str(videoFPS), self.TEXT_ROW2_POS, cv2.FONT_HERSHEY_SIMPLEX, self.FONT_SCALE, (0, 250, 0), self.FONT_WEIGHT)
            cv2.putText(self.frame, "Tracker FPS : " + str(int(fps)), self.TEXT_ROW3_POS, cv2.FONT_HERSHEY_SIMPLEX, self.FONT_SCALE, (0, 250, 0), self.FONT_WEIGHT)
            # Display result
            cv2.imshow(self.WINDOW_NAME, self.frame)

            # waitKey time computing
            # time in ms
            time = int(1000 * (cv2.getTickCount() - timer) / cv2.getTickFrequency())

            waitMiliseconds = 1
            if (time >= interval):
                waitMiliseconds = 1
            else:
                waitMiliseconds = interval - time

            k = cv2.waitKey(waitMiliseconds) & 0xff
            # Exit if 'Esc' or 'q' key is pressed
            if k == 27 or k == ord("q"):
                break

        # always save tracker result
        self._saveResults()

        self.video.release()
        cv2.destroyAllWindows()


first = int(input())
answer = []
mx = 0
if first == 1:  # edge case 주의!
    print(4)
    answer = [1, 1, 0, 1]
    print(*answer, sep=" ")
else:
    for second in range(1, first):  # first > 1인 경우
        arr = [first, second]  # 정답 저장 배열
        temp = [first, second]  # 값 계산 위한 임시 배열
        nex = temp[0] - temp[1]
        while nex >= 0:
            arr.append(nex)
            temp[0] = temp[1]
            temp[1] = nex
            nex = temp[0] - temp[1]
        if len(arr) > mx:  # 최대길이 갱신시
            mx = len(arr)
            answer = arr[:]  # 정답 저장
    print(mx)
    print(*answer, sep=" ")


# Data
dict = {"country": ["Brazil", "Russia", "India", "China", "South Africa"],
       "capital": ["Brasilia", "Moscow", "New Dehli", "Beijing", "Pretoria"],
       "area": [8.516, 17.10, 3.286, 9.597, 1.221],
       "population": [200.4, 143.5, 1252, 1357, 52.98] }

# Impor package pandas
import pandas as pd

# Format the data into columns
brics = pd.DataFrame(dict)
# Set the index for brics
brics.index = ["BR", "RU", "IN", "CH", "SA"]

print(brics)


import pathlib
import plotly.io as pio
import plotly.express as px

import numpy

# ============================================================================ #
# ============================ HT_Meth ======================================= #
# ============================================================================ #
class HT_Meth:

    # ======================================================================
    # ============================ Generate HTML ===========================
    # ======================================================================
    @staticmethod
    def gen_HTML(fig, save_Loc, file_Name):

        # create output folder if required
        cwd = pathlib.Path.cwd()
        save_Loc = cwd / save_Loc
        save_Loc.mkdir(parents=True, exist_ok=True)

        # fig.show
        # store the figure as html
        save_Loc = f"{save_Loc}/{file_Name}.html"

        # include_mathjax --> Latex abilities
        # local load --> requires all folder --> would only work on prepared computers
        base = pathlib.Path.cwd()
        ajax_Load_Local = str(base / "Code/Help_Files/Visual/Dependencies/0_Mathjax/MathJax.js")

        # pass link --> latex is only available if pc is connected to net
        ajax_Load_Online = 'https://cdnjs.cloudflare.com/ajax/libs/mathjax/2.7.5/MathJax.js'

        pio.write_html(fig, file= save_Loc, auto_open=False, include_mathjax = ajax_Load_Online,  include_plotlyjs="cdn")

    # ======================================================================
    # =========================== Dark Mode ================================
    # ======================================================================
    # if the html file shall be able to switch between
    # templates (dark and light)
    @staticmethod
    def add_Dark_Mode(fig):

        # get the templates
        template_Dark = pio.templates["plotly_dark"]
        template_Plotly = pio.templates["plotly"]
        # plotly_Dark.layout
        # plotly_Plotly.layout

        fig.update_layout(
                    updatemenus=[
                        dict(
                            buttons=list([
                                dict(
                                    args=["template", template_Dark],
                                    label="Dark",
                                    method="relayout"
                                ),
                                dict(
                                    args=["template", template_Plotly],
                                    label="Presentation",
                                    method="relayout"
                                ),

                            ]),
                            direction="down",
                            pad={"r": 10, "t": 10},
                            showactive=True,
                            x=0,
                            xanchor="left",
                            y=  1.01,
                            yanchor="top"
                        ),
                    ]
                )
        return fig

    # ==========================================================================
    # =========================== Layout =======================================
    # ==========================================================================
    # if the html file shall be able to switch between
    # templates (dark and light)
    @staticmethod
    def update_Layout(fig,
                      ):

        fig.update_layout(

                        # add default dark theme
                        template ="plotly_dark",

                        title = r"$\text{Density of H}_2:\, \rho\,(p, T)$",
                        title_x = 0.5,

                        scene_xaxis_title=r"pressure [MPa]",
                        scene_yaxis_title=r"temperature [K]",
                        scene_zaxis_title=r"density [kg/m³]",

                        # camera settings
                        #x-y plane
                        scene_camera= dict(
                            eye = dict(x= 0.5,
                                       y= -2.5,
                                       z= 1),

                        ),

                        legend = dict(orientation="h",
                                      xanchor = "right",
                                      yanchor = "top",
                                      y = 1.05,
                                      x = 1,

                                      ),

                          )

        return fig

    # ======================================================================== #
    # ============================= Plotly Colors ============================ #
    # ======================================================================== #
    @staticmethod
    def plotly_Colors():

        # get default plotly colors
        # available [Dark24, Light24, Vivid, D3, G10, Bold, Antique]
        # plt_Cols = px.colors.qualitative.Plotly
        plt_Cols = px.colors.qualitative.Vivid

        return plt_Cols


def permute(nums):
    def backtrack(start, end):
        if start == end:
            result.append(nums[:])
            return
        for i in range(start, end):
            nums[start], nums[i] = nums[i], nums[start]  # 交换
            backtrack(start + 1, end)
            nums[start], nums[i] = nums[i], nums[start]  # 恢复

    result = []
    backtrack(0, len(nums))
    return result

# 测试用例
nums = [1, 2, 3]
print(permute(nums))


class Solution:
    def findTheDifference(self, s: str, t: str) -> str:
        freq_s = {}
        freq_t = {}

        for c in s:
            freq_s[c] = freq_s.get(c, 0) + 1

        for c in t:
            freq_t[c] = freq_t.get(c, 0) + 1

        for i in freq_t:
            if i not in freq_s or freq_s[i] != freq_t[i]:
                return i


class PriorityQueueNode:
    def __init__(self, data, priority):
        self.data = data
        self.priority = priority

class PriorityQueue:
    def __init__(self):
        self.pq = []

    def isEmpty(self):
        return len(self.pq) == 0

    def getSize(self):
        return len(self.pq)

    def getMax(self):
        if self.isEmpty():
            return None
        return self.pq[0].data

    def __percolateUp(self):
        childIndex = self.getSize() - 1
        while childIndex > 0:
            parentIndex = (childIndex-1)//2

            if self.pq[parentIndex].priority < self.pq[childIndex].priority:
                self.pq[parentIndex],self.pq[childIndex] = self.pq[childIndex],self.pq[parentIndex]
                childIndex = parentIndex
            else:
                break

    def __percolateDown(self):
        parentIndex = 0

        while (2 * parentIndex + 1) < self.getSize():
            childIndex = 2 * parentIndex + 1

            if childIndex + 1 < self.getSize() and self.pq[childIndex + 1].priority > self.pq[childIndex].priority:
                childIndex += 1

            if self.pq[parentIndex].priority > self.pq[childIndex].priority:
                break
            else:
                self.pq[parentIndex], self.pq[childIndex] = self.pq[childIndex], self.pq[parentIndex]

            parentIndex = childIndex

    def insert(self, ele, priority):
        pq_node = PriorityQueueNode(ele, priority)
        self.pq.append(pq_node)
        self.__percolateUp()

    def removeMax(self):
        if self.isEmpty():
            return None

        self.pq[0], self.pq[-1] = self.pq[-1], self.pq[0]
        element = self.pq.pop().data
        self.__percolateDown()
        return element


"""empty message

Revision ID: 4e4710949dd
Revises: 3bc88a29a22
Create Date: 2015-10-13 10:55:27.441589

"""

# revision identifiers, used by Alembic.
revision = '4e4710949dd'
down_revision = '3bc88a29a22'

from alembic import op
import sqlalchemy as sa

def upgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.drop_table('chart_block_defaults')
    ### end Alembic commands ###

def downgrade():
    ### commands auto generated by Alembic - please adjust! ###
    op.create_table('chart_block_defaults',
    sa.Column('id', sa.INTEGER(), nullable=False),
    sa.Column('title', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
    sa.Column('caption', sa.VARCHAR(length=255), autoincrement=False, nullable=True),
    sa.Column('slug', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
    sa.Column('dataset', sa.VARCHAR(length=255), autoincrement=False, nullable=False),
    sa.Column('content', sa.TEXT(), autoincrement=False, nullable=True),
    sa.PrimaryKeyConstraint('id', name='chart_block_defaults_pkey')
    )
    ### end Alembic commands ###


from django.shortcuts import render
from rest_framework.decorators import api_view
import os
import json
from bson import ObjectId, datetime
from django.http import JsonResponse, HttpResponse
from django.http import FileResponse
import datetime
from datetime import date
from collections import OrderedDict

import logging
import boto3
import io
import base64
import tempfile

from .env_secrets import aws_env

#CONSTANTS
BUCKET_DIR = aws_env['bucket_dir']
AWS_ACCESS_KEY = aws_env['aws_access_key']
AWS_SECRET_KEY = aws_env['aws_secret_key']
AWS_BUCKET_NAME = aws_env['aws_bucket_name']

class JSONEncoder(json.JSONEncoder):

    def default(self, o):
        if isinstance(o, ObjectId) or isinstance(o, (datetime.date, datetime.datetime)):
            return str(o)
        return json.JSONEncoder.default(self, o)

# Create your views here.
@api_view(['POST'])
def get_filename(request):
    try:
        print("Enter Try++++++++++++++++++", request)
        file_name = request.POST["file_name"]
        print("File_name++++++++++++++", file_name)
        os.system("bash get_files/search_script.sh "+ file_name)

        file_path = 'get_files/'+file_name
        print(file_path)
        file_result = FileResponse(open(file_path, 'rb'))
        print(type(file_result))
        json_result = {"FILE_NAME": file_name}
        # json_result = JSONEncoder().encode({"FILE_NAME": file_name})
        print("JSON",json_result)
        # return JsonResponse(json_result, safe=False)
        return file_result

    except Exception as error:
        print("error in get filename string",error)
        # LOGGER.exception(error)

@api_view(['POST'])
def upload_file(request):
    try:
        # logging.debug("Enter GET FILE FUNCTION")
        print("Enter GET FILE FUNCTION")
        fileToUpload = request.FILES.get('file')
        cloudFilename = BUCKET_DIR + fileToUpload.name

        # logging.info(cloudFilename)
        print('cloudFilename: ',cloudFilename)

        s3_client = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY,aws_secret_access_key=AWS_SECRET_KEY)
        s3_client.upload_fileobj(fileToUpload, AWS_BUCKET_NAME, cloudFilename)
        print("Upload done: ", fileToUpload.name)

        # session = boto3.session.Session(aws_access_key_id=AWS_ACCESS_KEY,
        #                                 aws_secret_access_key=AWS_SECRET_KEY)
        # s3 = session.resource('s3')
        # s3.Bucket(AWS_BUCKET_NAME).put_object(Key=cloudFilename, Body=fileToUpload)
        json_result = {"cloudFilename": cloudFilename}
        return JsonResponse(json_result, safe=False)

    except Exception as error:
        logging.error(error)

@api_view(['POST'])
def download_file(request):
    try:
        print("ENTER DOWNLOAD FILE FUNCTION")
        file_name = request.POST['file_name']
        cloudFilename = BUCKET_DIR + file_name

        print('cloudFilename: ', cloudFilename)

        s3_client = boto3.client('s3', aws_access_key_id=AWS_ACCESS_KEY, aws_secret_access_key=AWS_SECRET_KEY)

        # tmp = tempfile.NamedTemporaryFile()
        # with open(tmp.name, 'wb') as file_obj:
        #     s3_client.download_fileobj(AWS_BUCKET_NAME, cloudFilename, file_obj)

        tmp = tempfile.NamedTemporaryFile(mode='w', delete=False)
        with open(tmp.name, 'wb') as file_obj:
            s3_client.download_fileobj(AWS_BUCKET_NAME, cloudFilename, file_obj)

        print("file_obj: ",  file_obj)
        print("TYPE OF file_obj: ", type(file_obj))

        tmp.close()
        os.remove(tmp.name)

        # file_base64 = base64.b64encode(file_stream)

        json_result = {file_name: str(file_obj)}
        return JsonResponse(json_result, safe=False)

        # return HttpResponse(str(file_stream), 'image/jpeg')

    except Exception as error:
        logging.error(error)


import math
def factorial(n):
    if n == 0: return 1
    return n * factorial(n - 1)

def estimate_pi():
    constant = 2 * math.sqrt(2) / 9801
    k = 0
    sum = 0
    while True:
        numerator = factorial(4 * k) * (1103 + 26390 * k)
        denominator = (factorial(k)**4 * 396**(4 * k))
        tmp = numerator / denominator
        sum += tmp
        if tmp < 1e-6: break
        k += 1
    return 1 / (sum * constant)

print(estimate_pi())
string = 'hagshjdg'
print(string[:])
string = 'huyhuy'
print(string[:])


ar=[115,38,8,9,7,4,19,3,78,45,1];

def BubbleSort(array1):

    for j in range(len(array1)):
        swapped=False
        print(ar)
        for i in range(len(array1)-1-j):
            if ar[i]>ar[i+1]:
                temp=ar[i];
                ar[i]=ar[i+1];
                ar[i+1]=temp;
                swapped=True;
        if swapped==False:
            return ;

BubbleSort(ar)
# print(ar)


#!/usr/bin/env python
"""
    File Name   :   DEMC-model
    date        :   14/7/2019
    Author      :   wenbo
    Email       :   huwenbodut@gmail.com
    Description :
                              _     _
                             ( |---/ )
                              ) . . (
________________________,--._(___Y___)_,--._______________________
                        `--'           `--'
"""
import tensorflow as tf

def feature_cnn(inputData, is_training=True, output_channels=1):
    regularizer = tf.contrib.layers.l2_regularizer(scale=0.0)
    with tf.variable_scope('block1'):
        output = tf.layers.conv2d(inputData, 64, 3, padding='same', activation=tf.nn.relu,
                                  kernel_regularizer=regularizer)
    for layers in xrange(2, 3 + 1):
        with tf.variable_scope('block%d' % layers):
            output = tf.layers.conv2d(output, 64, 3, padding='same', name='conv%d' % layers,
                                      kernel_regularizer=regularizer)
            output = tf.nn.relu(tf.layers.batch_normalization(output, training=is_training))
    with tf.variable_scope('block4'):
        output = tf.layers.conv2d(output, output_channels, 3, padding='same', activation=tf.nn.relu,
                                  kernel_regularizer=regularizer)
        # output = tf.pow(output, 1.0 / 2.2)
    return output

def dualEncoder(x, edge_map, is_training):
    conv_layers, skip_layers = encoder(x, name='RGB')
    edge_conv, edge_skip = encoder(edge_map, name='edge_map')
    # network = skip_connection_layer(conv_layers,edge_conv,str='encoder/connect_rgb_edge')
    network = tf.layers.conv2d(conv_layers, 512, kernel_size=3, padding='same', name='encoder/h6/conv')
    network = tf.layers.batch_normalization(network, training=is_training, name='encoder/h6/batch_norm')
    network = tf.nn.relu(network, name='encoder/h6/relu')
    # Decoder network
    network = decoder(network, skip_layers, edge_skip, is_training=is_training)
    return network

def encoder(inputData, name):
    # Convolutional layers size 1
    network = conv_layer(inputData, [3, 64], '%s/encoder/h1/conv_1' % name)
    beforepool1 = conv_layer(network, [64, 64], '%s/encoder/h1/conv_2' % name)
    network = pool_layer(beforepool1, '%s/encoder/h1/pool' % name)

    # Convolutional layers size 2
    network = conv_layer(network, [64, 128], '%s/encoder/h2/conv_1' % name)
    beforepool2 = conv_layer(network, [128, 128], '%s/encoder/h2/conv_2' % name)
    network = pool_layer(beforepool2, '%s/encoder/h2/pool' % name)

    # Convolutional layers size 3
    network = conv_layer(network, [128, 256], '%s/encoder/h3/conv_1' % name)
    network = conv_layer(network, [256, 256], '%s/encoder/h3/conv_2' % name)
    beforepool3 = conv_layer(network, [256, 256], '%s/encoder/h3/conv_3' % name)
    network = pool_layer(beforepool3, '%s/encoder/h3/pool' % name)

    # Convolutional layers size 4
    network = conv_layer(network, [256, 512], '%s/encoder/h4/conv_1' % name)
    network = conv_layer(network, [512, 512], '%s/encoder/h4/conv_2' % name)
    beforepool4 = conv_layer(network, [512, 512], '%s/encoder/h4/conv_3' % name)
    network = pool_layer(beforepool4, '%s/encoder/h4/pool' % name)

    # Convolutional layers size 5
    network = conv_layer(network, [512, 512], '%s/encoder/h5/conv_1' % name)
    network = conv_layer(network, [512, 512], '%s/encoder/h5/conv_2' % name)
    beforepool5 = conv_layer(network, [512, 512], '%s/encoder/h5/conv_3' % name)
    network = pool_layer(beforepool5, '%s/encoder/h5/pool' % name)

    return network, (inputData, beforepool1, beforepool2, beforepool3, beforepool4, beforepool5)

# Decoder network
def decoder(input_layer, skip_layers, edge_skip, is_training=False):
    sb, sx, sy, sf = input_layer.shape.as_list()
    alpha = 0.0

    # Upsampling 1
    network = deconv_layer(input_layer, sf, 'decoder/h1/decon2d', alpha, is_training)

    # Upsampling 2
    network = skip_connection_layer(network, tf.concat([skip_layers[5], edge_skip[5]], axis=3),
                                    'decoder/h2/fuse_skip_connection')
    network = deconv_layer(network, sf, 'decoder/h2/decon2d', alpha, is_training)

    # Upsampling 3
    network = skip_connection_layer(network, tf.concat([skip_layers[4], edge_skip[4]], axis=3),
                                    'decoder/h3/fuse_skip_connection')
    network = deconv_layer(network, sf / 2, 'decoder/h3/decon2d', alpha, is_training)

    # Upsampling 4
    network = skip_connection_layer(network, tf.concat([skip_layers[3], edge_skip[3]], axis=3),
                                    'decoder/h4/fuse_skip_connection')
    network = deconv_layer(network, sf / 4, 'decoder/h4/decon2d', alpha,
                           is_training)

    # Upsampling 5
    network = skip_connection_layer(network, tf.concat([skip_layers[2], edge_skip[2]], axis=3),
                                    'decoder/h5/fuse_skip_connection', )
    network = deconv_layer(network, sf / 8, 'decoder/h5/decon2d', alpha,
                           is_training)

    # Skip-connection at full size
    network = skip_connection_layer(network, tf.concat([skip_layers[1], edge_skip[1]], axis=3),
                                    'decoder/h6/fuse_skip_connection')
    # Final convolution
    network = tf.layers.conv2d(network, 3, kernel_size=3, padding='same', activation=tf.nn.relu,
                               name='decoder/h7/conv2d')
    return network

# === Layers ==================================================================

# Convolutional layer
def conv_layer(input_layer, sz, str):
    network = tf.layers.conv2d(input_layer, sz[1], 3, padding='same', activation=tf.nn.relu, name=str)
    return network

# Max-pooling layer
def pool_layer(input_layer, str):
    network = tf.layers.max_pooling2d(input_layer, pool_size=2, strides=2, padding='same', name=str)
    return network

# Concatenating fusion of skip-connections
def skip_connection_layer(input_layer, skip_layer, str):
    _, sx, sy, sf = input_layer.shape.as_list()
    _, sx_, sy_, sf_ = skip_layer.shape.as_list()

    assert (sx_, sy_) == (sx, sy)
    network = tf.concat([input_layer, skip_layer], axis=3, name='%s/skip_connection' % str)
    network = tf.layers.conv2d(network, filters=sf, kernel_size=1, padding='same', name=str)
    return network

# Deconvolution layer
def deconv_layer(input_layer, num_out_channels, str, alpha, is_training=True):
    scale = 2
    filter_size = (2 * scale - scale % 2)
    network = tf.layers.conv2d_transpose(input_layer, num_out_channels, kernel_size=filter_size, strides=scale,
                                         padding='same', name=str)
    network = tf.layers.batch_normalization(network, training=is_training, name='%s/batch_norm_dc' % str)
    network = tf.maximum(alpha * network, network, name='%s/leaky_relu_dc' % str)
    return network


# -*- mode: python -*-
# coding=utf-8

import os, shutil

# Globals #####################################################################
angular_base_dir = os.path.abspath(os.path.join('..','frontend','wittymail'))
angular_dist_dir = os.path.abspath(os.path.join(angular_base_dir, 'dist', 'wittymail'))
flask_static_dir = os.path.abspath(os.path.join('..', 'backend', 'webserver', 'static'))
flask_main_module = os.path.abspath(os.path.join('..', 'backend', 'webserver', 'wittymail_web_gui.py'))

# Cleanup #####################################################################
print("## Deleting static files in Flask directory")
try:
    shutil.rmtree(flask_static_dir)
except FileNotFoundError:
    pass

print("## Deleting PyInstaller 'dist' directory...")
try:
    shutil.rmtree('dist')
except FileNotFoundError:
    pass
os.mkdir("dist")

# Pre-requisites ##############################################################
print("## Building Angular app for production")
cmd = 'cd "' + angular_base_dir + '" && yarn install && ng build --prod'
print("\t%s" % cmd)
r = os.system(cmd)
if r:
    print("## Failed to build Angular app, aborting...")
    exit(1)

print("## Collecting static files")
shutil.copytree(angular_dist_dir, flask_static_dir)

# PyInstaller #################################################################
block_cipher = None
entry_point =  flask_main_module
binary_name = 'wittymail'

a = Analysis([entry_point],
             pathex=[os.path.abspath(os.path.join('..', 'backend'))],
             binaries=[],
             datas=[(flask_static_dir,'static')],
             hiddenimports=[],
             hookspath=[],
             runtime_hooks=[],
             excludes=[],
             win_no_prefer_redirects=False,
             win_private_assemblies=False,
             cipher=block_cipher)

pyz = PYZ(a.pure, a.zipped_data,
             cipher=block_cipher)
exe = EXE(pyz,
          a.scripts,
          a.binaries,
          a.zipfiles,
          a.datas,
          name=binary_name,
          debug=False,
          strip=False,
          upx=True,
          console=True )


#Sorteando uma ordem na lista
from random import shuffle
n1 = str(input('primeiro Aluno: '))
n2 = str(input('Segundo Aluno: '))
n3 = str(input('terceiro Aluno: '))
n4 = str(input('quaro Aluno : '))
lista =[n1, n2, n3, n4]
shuffle(lista)        #shuffle significa embaralhar
print('A ordem de apresentaçao será:')
print(lista)


def is_perfect(x):
    divisors = []

    for i in range(1, x):
        if x % i == 0:
            divisors.append(i)

    print(divisors)

    if sum(divisors) == x:
        return True
    else:
        return False

print(is_perfect(28))


import numpy as np
import pylab as plt
import matplotlib.animation as animation

def x1_prime(t,x1,x2):
    return(x2)

def x2_prime(t,x1,x2):
    return(np.cos(x1)*grav/rad-x2*gamma/(mass*rad))

def second_order_runge_kutta_4_solver(x10,x20,t):
    x1 = np.zeros([t.shape[0],1])
    x2 = np.zeros([t.shape[0],1])
    x1[0,0] = x10
    x2[0,0] = x20
    for i in range (1,t.shape[0]):
        h = t[i,0]-t[i-1,0]
        k11 = h*x1_prime(t[i-1,0],x1[i-1,0],x2[i-1,0])
        k12 = h*x2_prime(t[i-1,0],x1[i-1,0],x2[i-1,0])
        k21 = h*x1_prime(t[i-1,0]+h/2,x1[i-1,0]+k11/2,x2[i-1,0]+k12/2)
        k22 = h*x2_prime(t[i-1,0]+h/2,x1[i-1,0]+k11/2,x2[i-1,0]+k12/2)
        k31 = h*x1_prime(t[i-1,0]+h/2,x1[i-1,0]+k21/2,x2[i-1,0]+k22/2)
        k32 = h*x2_prime(t[i-1,0]+h/2,x1[i-1,0]+k21/2,x2[i-1,0]+k22/2)
        k41 = h*x1_prime(t[i-1,0]+h,x1[i-1,0]+k31,x2[i-1,0]+k32)
        k42 = h*x2_prime(t[i-1,0]+h,x1[i-1,0]+k31,x2[i-1,0]+k32)
        x1[i,0] = x1[i-1,0] + (k11+2*k21+2*k31+k41)/6
        x2[i,0] = x2[i-1,0] + (k12+2*k22+2*k32+k42)/6
    return(x1,x2)

def init():
    x = np.linspace(0, rad*np.cos(x10), anim_points)
    y = np.negative(np.linspace(0, rad*np.sin(x10), anim_points))
    string.set_data(x, y)
    ball.set_data(rad*np.cos(x10), -rad*np.sin(x10))
    pivot.set_data(0, 0)
    return string, ball, pivot

def animate(i):
    x = np.linspace(0, rad*np.cos(pendulum_theta[i]), anim_points)
    y = np.negative(np.linspace(0, rad*np.sin(pendulum_theta[i]), anim_points))
    string.set_data(x, y)
    ball.set_data(rad*np.cos(pendulum_theta[i]), -rad*np.sin(pendulum_theta[i]))
    pivot.set_data(0, 0)
    return string, ball, pivot

grav = 9.81
rad = 1
mass = 1
gamma = 0.4
x10 = 0
x20 = 0
t_0 = 0
t_end = 100
n_points = 10000
anim_points = 1000

t = np.transpose(np.array([np.linspace(t_0,t_end,n_points)]))
pendulum_theta, pendulum_omega = second_order_runge_kutta_4_solver(x10,x20,t)

fig1 = plt.figure()
ax1 = plt.axes(xlim=(-2, 2), ylim=(-2, 2))
string, = ax1.plot([], [], '-', lw=2)
ball, = ax1.plot([], [], 'o', lw=8)
pivot, = ax1.plot([], [], 'o', lw=2)
pendulum_animation = animation.FuncAnimation(fig1, animate, init_func=init,
                               frames=n_points, interval=10, blit=True)
plt.show()


#!/usr/bin/env python
# coding: utf-8

# # Mapping using Python
#
# Here we use geotext library to extract places names from the sentence.
#
# ## Installation of geotext modules

# In[1]:

get_ipython().system('pip install geotext')

# ### Example to use GeoText module

# In[2]:

from geotext import GeoText

places = GeoText("I was in Chennai on that day and next day i went to Erode")
places.cities

# ## Example to Exract place names from a website
#
# * here we going to extract place names from the caption of the picture on the site , "https://www.gutenberg.org/files/64316/64316-h/64316-h.htm"
#
# * also we used the method of previous web scraping method using BeautifulSoup module
#
#
# ![](../images/map2.png)

# In[3]:

import urllib.request,sys,time
from bs4 import BeautifulSoup
import requests
import pandas as pd
from geotext import GeoText

# In[13]:

url="https://www.gutenberg.org/files/64316/64316-h/64316-h.htm"

# In[266]:

page=requests.get(url)

soup=BeautifulSoup(page.text,'html.parser')
frame=[]
resultframe=[]
links=soup.find_all('div',attrs={'class':'ills'})
#links=soup.find_all('li',attrs={'class':'o-listicle__item'})
#print(links)
filename="caption.csv"
f=open(filename,"w", encoding = 'utf-8')
headers="Link,Caption\n"
f.write(headers)
u='https://www.gutenberg.org/files/64316/64316-h/'
for i in links:
    k=i.find_all('div',attrs={'class':'figcenter'})
    for j in k:
        l=j.find_all('a')
        Link = u+l[1].find('img')['src'].strip()          #Extract Link of all the images
        cap=j.find('p',attrs={'class':'caption'}).text.strip()  #Extract caption of all the images

        a=cap.replace(' ',',').title()

        result = GeoText(a,'US').cities

        if(result!=[]):
            frame.append((Link,str(result[0])))
            f.write(Link+","+str(result[0])+"\n")   #stored only the link and caption that contains city names
    resultframe.extend(frame)
f.close()

# ### Result of the above Code

# In[14]:

data=pd.DataFrame(resultframe, columns=['Link','Caption'])
print(data)

# ### Installing arcgis to map the places

# In[214]:

get_ipython().system('pip install arcgis')

# ## Code to find latitude and longitude
# here we find the latitude and longitude of the places that extract in the caption of the images. and we mark the point on the map using simple loop condition.

# In[16]:

from arcgis.gis import GIS
from arcgis.geometry import Point
from arcgis.geocoding import geocode, reverse_geocode

my_gis = GIS()
# m = my_gis.map()

m = my_gis.map("US", zoomlevel=4)

# function to find the latitude and longitude
def place_names(get_places):
    i=get_places
    geocoded=geocode(i)[0]['location']
    return geocoded

for i in data['Caption']:

    geocoded=place_names(i)
    lat=geocoded['y']
    longi=geocoded['x']
    print(lat,longi)

    location = {
     'Y': lat,                 # `Y` is latitude
     'X':  longi,               # `X` is longitude
     'spatialReference': {
         'wkid':4326
     }
    }
    unknown_pt = Point(location)
    address = reverse_geocode(location=unknown_pt)
    print(address)  #matching address found from the latitude and longitude

    m.draw(address)

# ### Result Map of the above code

# In[17]:

m

# ![](../images/resmap1.png)

# ## Example to Find the address of the Given latitude and longitude

# In[19]:

from arcgis.geometry import Point
location = {
     'Y': 39.86347000000006,                 # `Y` is latitude
     'X':  -105.05000999999999,               # `X` is longitude
     'spatialReference': {
         'wkid':4326
     }
}
unknown_pt = Point(location)
address = reverse_geocode(location=unknown_pt)
address

# ### Draw a map for above address

# In[21]:

m = my_gis.map("USA", zoomlevel=5)
m.draw(address)
m

# ![](../images/resmap2.png)

# ## map can be save as html file

# In[22]:

file_path = r"C:\Users\Mohanapriya\city_map.html"
m.export_to_html(file_path)

# In[333]:

import webbrowser
webbrowser.open_new('http://127.0.0.1:2000/')


#
# unit test
# Test cases create a list of neighbor vertex , then display it by its method
#
import sys
sys.path.append('../')
import neighbor

n = neighbor.Neighbor()
n.setnb("node","edge0")
n.setnb("node","edge1")
n.setnb("node","edge2")

print(n)

print("vertex's name " + n.getname())

print(n.issame("node"))
print(n.issame("node1"))
print(n.issame("1"))

l = []
i = 0
while i<10:
	n = neighbor.Neighbor()
	n.setnb("node" + str(i),"edge1"+ str(i))
	i+=1
	l.append(n)
print(l)

print(l[0].getnb())

l[0].setnb("test","etest")

print(l[0].getnb())

print(l[0])


# -*- coding: utf-8 -*-
import xlrd
import string
import nltk
from nltk.stem import WordNetLemmatizer
from nltk.stem.porter import PorterStemmer
from nltk.corpus import wordnet
from nltk.corpus import stopwords
#import genism
from gensim import corpora, models
from gensim.models import CoherenceModel
import sys, errno
import xlsxwriter

dictionary = corpora.Dictionary.load("D:\\aproject\\dictionary1.dic")
#print( dictionary)
corpus = corpora.MmCorpus("D:\\aproject\\corpus1.m")
#print(len(corpus))
# 使用 gensim 来创建 LDA 模型对象
Lda = models.ldamodel.LdaModel
# 在 DT 矩阵上运行和训练 LDA 模型# iterations=50
Perplexity_list=[]
coherence_list=[]
#Passes=[300]
Iterations=[25]
for j in range(20,30):
    print('num_topics:',j)
    for it in Iterations:
        print('num_iter:',it)
        ldamodel = Lda(corpus, num_topics=j, id2word = dictionary,passes=300,alpha='auto',eta='auto',iterations=25, random_state=123,minimum_probability=0.0)
        #print(ldamodel.print_topics(num_topics=12, num_words=30))
        for i in  ldamodel.show_topics(num_topics=j):
            print (i[0], i[1])
        #, random_state=1  , num_words=10
        print('-----------------')

        file='D:\\aproject\\audience_text_classifier\\text_classifier_'+str(j)+'_i'+str(it)+'_v1.xlsx'
        workbook= xlsxwriter.Workbook(file)
        worksheet= workbook.add_worksheet(u'sheet1')
        for i in range(0,len(brand)):
            index1=0
            index2=0
            index1=brand0.index(brand[i])
            index2=i+360
            classifier1=ldamodel[corpus[index1]]
            ll1=[]
            for a,b in classifier1:
                ll1.append((b,a))
            ll1.sort(reverse=True)

            classifier2=ldamodel[corpus[index2]]
            ll2=[]
            for a,b in classifier2:
                ll2.append((b,a))
            ll2.sort(reverse=True)

            worksheet.write(i,0,brand[i])
            index3=0
            for a,b in ll1:
                if(index3<3):
                    if(a>0):
                        worksheet.write(i,index3+1,b)
                index3+=1

            worksheet.write(i,4,influencer[i])
            index4=0
            for a,b in ll2:
                if(index4<3):
                    if(a>0):
                        worksheet.write(i,index4+5,b)
                    else:
                        worksheet.write(i,index4+5,-1)
                index4+=1
        workbook.close()
        print('----------save-------')

        # Compute Perplexity
        print('\nPerplexity: ', ldamodel.log_perplexity(corpus))
        Perplexity_list.append(ldamodel.log_perplexity(corpus))
        # a measure of how good the model is. lower the better.
        # Compute Coherence Score
        coherence_model_lda = CoherenceModel(model=ldamodel,corpus=corpus,dictionary=dictionary, coherence='u_mass')
        try:
            coherence_lda = coherence_model_lda.get_coherence()
        except IOError as e:
            if e.errno == errno.EPIPE:
                print('err')
        print('\nCoherence Score: ', coherence_lda)
        coherence_list.append(coherence_lda)
        '''
        file2='D:\\aproject\\text_classifier\\text_classifier_vector.xlsx'
        workbook2= xlsxwriter.Workbook(file2)
        worksheet2= workbook2.add_worksheet(u'sheet1')
        for kk in range(0,len(corpus)):
            index_k=0
            if(kk<360):
                worksheet2.write(kk,0,brand0[kk])
            else:
                worksheet2.write(kk,0,influencer[kk-360])
            for a,b in ldamodel[corpus[kk]]:

                worksheet2.write(kk,1+index_k*2,a)
                worksheet2.write(kk,2+index_k*2,b)
                index_k+=1

        workbook2.close()
        '''
print(Perplexity_list)
print(coherence_list)


def scoreOfParentheses(S):
    stack = []
    res = 0
    for i in S:
        if i == "(":
            stack.append(res)
            res = 0
        elif i == ")":
            p = stack.pop()
            res = p + 1 if res == 0 else p + 2 * res
        else:
            res += int(i)
    return res

S ="(()(()))"
print(scoreOfParentheses(S))


import warnings

from rmui_drivers import prx_utils

from force_proximity_ros.msg import Proximity

try:
    import smbus
except ImportError:
    warnings.warn('Please install smbus for IMU: apt-get install python-smbus')

class VCNL4040(object):

    def __init__(self, bus=1, address=0x60, ea=0.3, sensitivity=50):
        super(VCNL4040, self).__init__()
        self.bus = smbus.SMBus(bus)
        self.address = address
        self.average = None
        self.fa2 = 0
        self.ea = ea
        self.sensitivity = sensitivity

    def init_sensor(self):
        try:
            self.bus.write_word_data(self.address, 0x00, 0x0001)
            return True
        except IOError:
            return False

    def start_sensor(self):
        try:
            self.bus.write_word_data(self.address, 0x03, 0x080e)
            return True
        except IOError:
            return False

    def stop_sensor(self):
        try:
            self.bus.write_word_data(self.address, 0x03, 0x0100)
            return True
        except IOError:
            return False

    def read_proximity(self):
        try:
            prx_d = self.bus.read_word_data(self.address, 0x0008)
            return prx_d
        except IOError:
            return None

    def get_proximity_msg(self, prx_d):
        if prx_d is None:
            prx_msg = Proximity()
        else:
            if self.average is None:
                self.average = prx_d
            prx_msg, average, fa2 = prx_utils.get_proximity_msg(
                prx_d, self.average, self.fa2, self.ea, self.sensitivity)
            self.average = average
            self.fa2 = fa2
        return prx_msg


# implemintation seems to be a little bit tricky for this one
# I can use Counter to easily find scores for each category
# but, I am not sure how I can keep track of who got what place for each of the categories
# can have a defaultdict for each category and keep track of a score for each value, thats a lot of passes, but it is O(n) and it is easy to code
# 100% sure there is a better way, but this is good enough for now
from pprint import pprint
from collections import Counter
import sys
sys.stdin = open('05.in')

T = int(input())
for league in range(T):
    print(f'League {league+1}')
    n, m = map(int, input().split())
    owners = [0] * n
    categories = [{} for _ in range(m)]
    arr = []
    for _ in range(n):
        arr.append(list(map(int, input().split())))

    # go over each category and keep track of how much points certain number scores in each of the categories
    for i, category in enumerate(zip(*arr)):
        c = Counter(category)
        total = 1
        for num, freq in sorted(c.items()):
            score =  sum(range(total, total+freq))/freq
            categories[i][num] = score
            total += freq

    # go through all the owners and calculate their total points
    for i in range(n):
        for j in range(m):
            num = arr[i][j]
            owners[i] += categories[j][num]

    print(*owners, sep='\n')


import torch
from PIL import Image
from io import BytesIO
import streamlit as st
from model import EasyVQAEarlyFusion
from transformers import AutoTokenizer, AutoFeatureExtractor, AutoModel
import warnings
warnings.filterwarnings("ignore")

device = torch.device("cuda" if torch.cuda.is_available() else "cpu")

idx2label = {0:'circle',
 1:'green',
 2:'red',
 3:'gray',
 4:'yes',
 5:'teal',
 6:'black',
 7:'rectangle',
 8:'yellow',
 9:'triangle',
 10:'brown',
 11:'blue',
 12:'no'}

@st.cache(allow_output_mutation=True, show_spinner=False)
def load_language_model():
    tokenizer = AutoTokenizer.from_pretrained("bert-base-uncased")
    text_encoder = AutoModel.from_pretrained("bert-base-uncased")
    text_encoder.to(device)
    for p in text_encoder.parameters():
        p.requires_grad = False

    return tokenizer, text_encoder

@st.cache(allow_output_mutation=True, show_spinner=False)
def load_vision_model():
    image_processor = AutoFeatureExtractor.from_pretrained("google/vit-base-patch16-224-in21k")
    image_encoder = AutoModel.from_pretrained("google/vit-base-patch16-224-in21k")
    image_encoder.to(device)
    for p in image_encoder.parameters():
        p.requires_grad = False

    return image_processor, image_encoder

@st.cache(allow_output_mutation=True, show_spinner=False)
def load_model():
    model = EasyVQAEarlyFusion()
    model.load_state_dict(torch.load('./weights/final.model', map_location=device))
    model.to(device)
    return model

def process_text(question, tokenizer, text_encoder):
    text_inputs = tokenizer(question, return_tensors="pt")
    text_inputs = text_inputs.to(device)
    text_outputs = text_encoder(**text_inputs)
    text_embedding = text_outputs.pooler_output
    text_embedding = text_embedding.view(-1)
    text_embedding = text_embedding.detach()

    return text_embedding.view(1, -1)

def process_image(image, image_processor, image_encoder):
    image_inputs = image_processor(image, return_tensors="pt")
    image_inputs = image_inputs.to(device)
    image_outputs = image_encoder(**image_inputs)
    image_embedding = image_outputs.pooler_output
    image_embedding = image_embedding.view(-1)
    image_embedding = image_embedding.detach()

    return image_embedding.view(1, -1)

def predict(input, model):
    model.eval()
    with torch.no_grad():
        output = model(**input)

    probs = round(torch.max(output.softmax(dim=1), dim=-1)[0].detach().cpu().numpy()[0]*100, 4)
    output = output.argmax(-1)
    logit = output.detach().cpu().numpy()
    label = idx2label[logit[0]]

    return label, probs

if __name__=="__main__":

    st.title("Visual Question-Answering with Early Fusion Transformers on EasyVQA Dataset")
    with st.spinner('Models are being loaded.This could take some seconds...'):
        model=load_model()
        tokenizer, text_encoder = load_language_model()
        image_processor, image_encoder = load_vision_model()
    btn = None
    image_embedding = None
    text_embedding = None
    image = st.file_uploader("Upload an Image", type=['jpeg', 'jpg', 'png'], accept_multiple_files=False)

    if image:
        image_bytes = image.getvalue()
        img = Image.open(BytesIO(image_bytes)).convert("RGB")
        image_embedding = process_image(img, image_processor=image_processor, image_encoder=image_encoder)

        st.image(img, caption="Uploaded Image")

        question = st.text_input('Enter input question: (Play with questions to see some funny results)', '')
        if question:
            text_embedding = process_text(question, tokenizer=tokenizer, text_encoder=text_encoder)
            btn = st.button("Answer")
    if btn:
        if image_embedding is not None and text_embedding is not None:
            with st.spinner("Running Prediction..."):
                input = {"image_emb":image_embedding, "text_emb":text_embedding}
                label, prob = predict(input, model)

            st.text(f"Answer: {label}\nConfidence: {prob}")


#!/usr/bin/env python
#encoding: utf-8

import os
import logging
import traceback
import time
import datetime
import threading
import copy
import re

try:
    import gconf
except BaseException:
    import sys
    sys.path.insert(0, '..')
    import gconf

from cmdutils import exec_cmd
from fmonitor import folder_monitor
from fileutils import get_all_files

INTERVAL_CALLBACK = 60

_logger = logging.getLogger('root.utils.crontab')

_lock = threading.Lock()
_script_path_dir = os.path.join(gconf.PROCESS_PATH, 'scripts')

_commands = []

def _execute_cmd(cmd, cwd):
    return exec_cmd(cmd, True, cwd=cwd)[0]

def _validate_time_sequence(time_sequence):
    for _seq in time_sequence:
        if re.match("^([*]|[\d]{1,2}([,-][\d]{1,2})*|[*][/][\d]{1,2})$", _seq) is None:
            return False
    return True

def _read_configs():
    global _commands

    _cmds = []
    _paths = get_all_files(_script_path_dir, filter=lambda x:os.path.basename(x)=='crontab')

    for _path in _paths:
        _cwd = os.path.dirname(_path)
        with open(_path, 'rb') as _handler:
            for _line in _handler:
                _line = _line.strip()
                if _line == '' or _line.startswith('#'):
                    continue

                _sp = _line.split()

                if len(_sp) < 6:
                    _logger.error('crontab file config error, path:%s, line:%s', _path, _line)
                    continue

                if not _validate_time_sequence(_sp[:5]):
                    _logger.error('crontab file config error, path:%s, line:%s', _path, _line)
                    continue

                _cmds.append({'time_sequence': _sp[:5], 'cmd': _sp[5:], 'cwd': _cwd})

    if _lock.acquire():
        try:
            _commands = _cmds
        finally:
            _lock.release()

    return _cmds

def _judge_time(current_time_sequence, time_sequence):
    for _i in xrange(5):
        if time_sequence[_i] == '*':
            continue
        elif str(time_sequence[_i]).startswith('*/'):
            if int(current_time_sequence[_i]) % int(str(time_sequence[_i])[2:]) != 0:
                return False
        else:
            _nodes = str(time_sequence[_i]).split(',')
            _rt = False
            for _node in _nodes:
                if _node.find('-') != -1:
                    _min, _max = _node.split('-')[:2]
                    if int(current_time_sequence[_i]) >= int(_min) and int(current_time_sequence[_i]) <= int(_max):
                        _rt = True
                        break
                else:
                    if int(_node) == int(current_time_sequence[_i]):
                        _rt = True
                        break
            if not _rt:
                return False

    return True

def _judge_execute_commands(current_time, commands):
    _current_datetime = datetime.datetime.fromtimestamp(current_time)
    _current_time_sequence = [_current_datetime.minute, _current_datetime.hour, _current_datetime.day, _current_datetime.month, (_current_datetime.weekday()) + 1 % 7]
    for _command in commands:
        _time_sequence = _command.get('time_sequence')
        if _judge_time(_current_time_sequence, _time_sequence):
            _cmd = _command.get('cmd')
            _cwd = _command.get('cwd')
            _code = _execute_cmd(_cmd, _cwd)
            _logger.debug('execute cmd: %s at dir:%s, result:%s', _cmd, _cwd, _code)

def run():
    _logger.debug('judge exec commands')

    _execute_commands = []
    if _lock.acquire():
        try:
            _execute_commands = copy.deepcopy(_commands)
        finally:
            _lock.release()

    _judge_execute_commands(time.time(), _execute_commands)

folder_monitor(_script_path_dir, _read_configs, sleeptime=5, content=True, filter=lambda x:os.path.basename(x)=='crontab')

if __name__ == '__main__':
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(name)s %(levelname)s:%(message)s',
                        datefmt='%Y-%m-%d %H:%M:%S',
                        )
    from runserver import Callback, run_as_server
    run_as_server(Callback(callback=run, interval=INTERVAL_CALLBACK))


# Part 3 - Chapter 15 이진 탐색 2 - 고정점 찾기
n = int(input())
arr = list(map(int, input().split()))

def search(array, start, end):
    mid = (start + end) // 2
    if start > end:
        return None
    if arr[mid] == mid:
        return mid
    elif arr[mid] > mid:
        return search(array, start, mid - 1)
    else:
        return search(array, mid + 1, end)

result = search(arr, 0, n - 1)

if result == None:
    print(-1)
else:
    print(result)


import numpy as np
import cv2

canavas = np.zeros((300,300,3),dtype="uint8")

for i in range(0,300,5):
    cv2.rectangle(canavas,(i,i-5),(i,i+5),(0,0,255),-1)

#måla upp en grön cirkel i mitten
cv2.circle(canavas,(canavas.shape[0]//2,canavas.shape[1]//2),canavas.shape[1]//8,(0,255,0),-1)

cv2.imshow("Bilden",canavas)
cv2.waitKey(0)


import numpy as np
import torch
import dataprocess.crossval_trainInSubset2_testInSubset1 as DL
# from network.mainNet.mainNet import mainNet
from network.mainNet.mainNet import mainNet
import torch.nn as nn
import time
import cv2
from torchvision import transforms
import pandas as pd
import os
import math
import torch.optim.lr_scheduler as lr_scheduler
from tqdm import tqdm
from torch.utils.tensorboard import SummaryWriter
import logging
from getDetail.computeRrate import computerRrate_test
from torchvision.models import resnet18
os.environ['CUDA_VISIBLE_DEVICES'] = '0,1'

saveFileName = 'end test in subset1'
epoch_num = 265
class trainer():

    def __init__(self,arg_file=None):
        LOG_FORMAT = "%(asctime)s - %(levelname)s - %(message)s"
        DATE_FORMAT = "%m/%d/%Y %H:%M:%S %p"
        if os.path.exists('./outputFile/MESSIDOR/{}'.format(saveFileName)) is False:
            os.makedirs('./outputFile/MESSIDOR/{}'.format(saveFileName))
        if os.path.exists('./outputFile/MESSIDOR/{}/my.log'.format(saveFileName)) is False:
            file = open('./outputFile/MESSIDOR/{}/my.log'.format(saveFileName), 'w')
            file.close()
        logging.basicConfig(filename='./outputFile/MESSIDOR/{}/my.log'.format(saveFileName), level=logging.DEBUG, format=LOG_FORMAT, datefmt=DATE_FORMAT)

    def eucliDist(self,pre,label):
        temp = np.square( pre - label )
        return np.sqrt( temp[:,0] + temp[:,1] )

    # def getTrainData(self):
    #     can_use_imgs_dict, label , image_names = DL.loadLabel()
    #     imgs, new_labels = DL.loadImgs(can_use_imgs_dict, label)
    #     train_loader , val_loader , val_image_names = DL.dataload(imgs, new_labels,image_names)
    #     return train_loader, val_loader , val_image_names

    def lossFunction(self,pred,label):
        loss = torch.mean(1.5*(label[:,0]-pred[:,0])**2+(label[:,1]-pred[:,1])**2)
        return loss

    def getTemplate(self,templatePath):
        input_transform = transforms.Compose([
            # transforms.CenterCrop([256, 256]),  # 将图像裁剪成指定大小
            transforms.ToPILImage(),
            transforms.ToTensor(),  # 图像转 Tensor ， 同时会将每个像素点除以 255 ， 取值为 0 - 1
            # transforms.Normalize([.485, .456, .406], [.229, .224, .225])  # 标准化 ，两个list分别是 均值 和 标准差
        ])
        template = cv2.imread(templatePath)  # 查询图像
        template = template.astype(np.uint8)
        template = input_transform(template).unsqueeze(0)
        return template

    def model_structure(self,model):
        blank = ' '
        print('-' * 90)
        print('|' + ' ' * 11 + 'weight name' + ' ' * 10 + '|' \
              + ' ' * 15 + 'weight shape' + ' ' * 15 + '|' \
              + ' ' * 3 + 'number' + ' ' * 3 + '|')
        print('-' * 90)
        num_para = 0
        type_size = 1  ##如果是浮点数就是4

        for index, (key, w_variable) in enumerate(model.named_parameters()):
            if len(key) <= 30:
                key = key + (30 - len(key)) * blank
            shape = str(w_variable.shape)
            if len(shape) <= 40:
                shape = shape + (40 - len(shape)) * blank
            each_para = 1
            for k in w_variable.shape:
                each_para *= k
            num_para += each_para
            str_num = str(each_para)
            if len(str_num) <= 10:
                str_num = str_num + (10 - len(str_num)) * blank

            print('| {} | {} | {} |'.format(key, shape, str_num))
        print('-' * 90)
        print('The total number of parameters: ' + str(num_para))
        print('The parameters of Model {}: {:4f}M'.format(model._get_name(), num_para * type_size / 1000 / 1000))
        print('-' * 90)

    def train(self,device):
        # 使用tensorBoard
        print('Strat Tensorboard with "tensorboard -- logdir=runs",view at http://locahost:6006/')
        tb_writer = SummaryWriter()
        device = device
        model = resnet18(pretrained=True)
        fc_inputs = model.fc.in_features
        # model.fc = nn.Sequential(
        #     nn.Linear(fc_inputs, 256),
        #     nn.ReLU(),
        #     nn.Dropout(0.4),
        #     nn.Linear(256, 2)
        # )
        model.fc = nn.Sequential(
            nn.Linear(fc_inputs, 2)
        )
        model = model.cuda(device)
        Dict = torch.load('./End_use_model_Param/train_in_subset2.pth',map_location={'cuda:1':'cuda:0'})
        paramDict = Dict['modelParam']
        model.load_state_dict(paramDict)
        self.model_structure(model)

        # model = torch.nn.DataParallel(model.cuda(), device_ids=[0, 1],output_device=0)
        batchSize = 1
        train_loader,val_loader,test_loader,val_imgName,test_imgNames = DL.getDataLoader(batchSize)
        # np.savetxt('vn.txt',val_image_names)

        logging.info('batchsize is {}'.format(batchSize))

        computer = computerRrate_test(1)

        # 获取模板图片
        templatePath1 = './template_50.jpg'
        template1 = self.getTemplate(templatePath1)

        # 用测试集训练模型model(),用验证集作为测试集来验证

        dist = 0.
        label_site = None
        pred_site = None
        curr_dist = None
        R_8 = 0

        # 验证集val
        model.eval()
        with torch.no_grad():

            for i, data in tqdm(enumerate(test_loader)):
                val_pred = model(data[0].cuda(device))

                # 模型成绩测试
                dist_list = self.eucliDist(val_pred.detach().cpu().numpy(),data[1].detach().cpu().numpy())
                R_8_list = dist_list[dist_list < 3.557]
                R_8 = R_8 + len(R_8_list)
                if curr_dist is None:
                    curr_dist = dist_list
                else:
                    curr_dist = np.concatenate((curr_dist,dist_list),axis=0)

                if label_site is None:
                    label_site = data[1].detach().cpu().numpy()
                else:
                    label_site = np.concatenate((label_site,data[1].detach().cpu().numpy()),axis=0)

                if pred_site is None:
                    pred_site = val_pred.detach().cpu().numpy()
                else:
                    pred_site = np.concatenate((pred_site,val_pred.detach().cpu().numpy()),axis=0)

                dist = dist + np.sum(dist_list)

            dist = dist / 568 # 验证图片有 568 张
            R_8_per = R_8 / 568
            print('avg_dist = {}'.format(dist))
            logging.info('avg_dist = {}'.format(dist))

            print('R_8_per = {}'.format(R_8_per))
            logging.info('R_8_per = {}'.format(R_8_per))

            if os.path.exists('testInMessidor/test_in_subset1') is False:
                os.makedirs('testInMessidor/test_in_subset1')
            count = computer.computer(pred_site, os.path.join('testInMessidor/test_in_subset1', saveFileName), epoch_num, test_imgNames.reshape(-1))

            real_r8_rate = count/568
            print('real_r8_reate = {}'.format(real_r8_rate))
            logging.info('real_r8_rate = {}'.format(real_r8_rate))

            dataframe = pd.DataFrame(
                {'image_name': test_imgNames.reshape(-1), 'label_site_x': label_site[:, 0].reshape(-1),
                 'label_site_y': label_site[:, 1].reshape(-1),
                 'pred_site_x': pred_site[:, 0].reshape(-1),
                 'pred_site_y': pred_site[:, 1].reshape(-1),
                 'curr_dist': curr_dist.reshape(-1)})
            if os.path.exists('./testInMessidor/test_in_subset1/{}'.format(saveFileName)) is False:
                os.makedirs('./testInMessidor/test_in_subset1/{}'.format(saveFileName))
            dataframe.to_csv('./testInMessidor/test_in_subset1/{}/{}.csv'.format(saveFileName,'pre_subset1'), sep=',')

import pynvml

# 字节数转GB
def bytes_to_gb(sizes):
    sizes = round(sizes / (1024 ** 3), 2)
    return f"{sizes} GB"

def gpu(num):
    pynvml.nvmlInit()
    handle = pynvml.nvmlDeviceGetHandleByIndex(num)  # 显卡句柄（只有一张显卡）
    gpu_name = pynvml.nvmlDeviceGetName(handle)  # 显卡名称
    gpu_memory = pynvml.nvmlDeviceGetMemoryInfo(handle)  # 显卡内存信息
    data = dict(
        gpu_name=gpu_name.decode("utf-8"),
        gpu_memory_total=bytes_to_gb(gpu_memory.total),
        gpu_memory_used=bytes_to_gb(gpu_memory.used),
        gpu_memory_free=bytes_to_gb(gpu_memory.free),
    )
    return data

if __name__ == '__main__':

    device = 0
    var = 1
    i = 0
    # while var == 1:
    #     time.sleep(1)
    #     gpu_0 = gpu(0)
    #     gpu_1 = gpu(1)
    #
    #     free = []
    #     free.append(float(gpu_0['gpu_memory_free'].split(' ')[0]))
    #     free.append(float(gpu_1['gpu_memory_free'].split(' ')[0]))
    #     if free[0] > 6:
    #         device = 0
    #         break
    #     if free[1] > 6:
    #         device = 1
    #         break
    #
    #     if i%60==0:
    #         print(i)
    #     i = i+1

    trianer = trainer()
    trianer.train(device)


# a[2,-1,5,6,-10,2,-3,7]

def function(lists):
    a = []
    b = []
    max_sum = lists[0]
    pre_sum = 0
    for i in lists:
        if pre_sum < 0:
            pre_sum = i
            b = a
            a=[]

        else:
            pre_sum += i
        if pre_sum > max_sum:
            max_sum = pre_sum
            a.append(i)
    return max_sum,a
if __name__ == '__main__':
    lists = [6, -3, 1, -2, 7, -15, 1, 2, 2]
    # lists = [-1,2,3,-5,10,15]
    print(function(lists))


STATS_SQL = [
    """
    update commits
    set n_lines_changed = (
        select COALESCE(sum(n_lines_changed),0)
        from committed_files
        where committed_files.commit_id = commits.sha
        and is_superfluous is false
        )
    where true
    """,
    """
    update commits
    set n_files_changed = (
        select count(1)
        from committed_files
        where committed_files.commit_id = commits.sha
        and is_superfluous is false
    )
    where true
    """,
    """
    update commits
    set n_lines_ignored = (
        select COALESCE(sum(n_lines_changed),0)
        from committed_files
        where committed_files.commit_id = commits.sha
        and is_superfluous is true
    )
    where true
    """,
    """
    update commits
    set n_files_ignored = (
        select count(1)
        from committed_files
        where committed_files.commit_id = commits.sha
        and is_superfluous is true
    )
    where true
    """,
    "drop view if exists all_commit_data",
    """
        create view all_commit_data
        as
        select
            authors.id as author_id,
            authors.name,
            authors.email,
            authors.real_name,
            authors.real_email,
            authors.company,
            authors.team,
            authors.author_group,
            commits.sha,
            commits.created_at as commit_date,
            case commits.is_merge when true then 1 else 0 end as is_merge,
            commits.n_lines as commit_n_lines,
            commits.n_files as commit_n_files,
            commits.n_insertions as commit_n_insertions,
            commits.n_deletions as commit_n_deletions,
            commits.n_lines_changed as commit_n_lines_changed,
            commits.n_lines_ignored as commit_n_lines_ignored,
            commits.n_files_changed as commit_n_files_changed,
            commits.n_files_ignored as commit_n_files_ignored,
            committed_files.id as committed_file_id,
            committed_files.change_type,
            committed_files.file_path,
            committed_files.file_name,
            committed_files.file_type,
            committed_files.n_lines_added,
            committed_files.n_lines_deleted,
            committed_files.n_lines_changed,
            committed_files.n_lines_of_code,
            committed_files.n_methods,
            committed_files.n_methods_changed,
            committed_files.is_on_exclude_list,
            committed_files.is_superfluous,
            repo.repo_name,
            repo.repo_group,
            repo.repo_type,
            repo.component,
            repo.clone_url,
            repo.id as repo_id,
            repo.is_active as repo_inlude_in_stats,
            repo.last_indexed_at
        from authors
            inner join commits on commits.author_id = authors.id
            inner join committed_files on committed_files.commit_id = commits.sha
            inner join repo_to_commits rtc on commits.sha = rtc.commit_id
            inner join repositories repo on rtc.repo_id = repo.id
        """,  # convert is_merge to integer to make it compatible to the existing schema that I cannot change.
]

QUERY_SQL = {
    "all_commit_data": " select * from all_commit_data limit 1000000",
}


"""Functions for importing data."""
import os
import csv
from typing import Dict, Tuple
import pandas as pd

from . import exceptions

def data_path(filename: str) -> str:
    """Get full path to a file in the data folder.

    Args:
        filename (str): The data file's name.

    Returns:
        path (str): The full path to the file.
    """
    return os.path.join(os.path.dirname(__file__), "data", filename)

def test_data_file(short_name: str) -> None:
    """Raise exception if data file unavailable.

    Args:
        short_name (str): file name.

    Raises:
        exceptions.DataFileMissingOrUnreadable

    Returns:
        None
    """
    path = data_path(short_name)
    if not os.path.isfile(path):
        raise exceptions.DataFileMissingOrUnreadable(short_name)

def read_csv_to_dict(short_name: str) -> Dict[str, str]:
    """Load csv into memory.

    Args:
        short_name (str): file name.

    Returns:
        Dict[str, str]: A dictionary of first column -> second column
    """
    path = data_path(short_name)
    test_data_file(short_name)
    with open(path, "r", encoding="utf-8-sig") as file:
        csv_reader = csv.reader(file, delimiter=",")
        mapping = {rows[0]: rows[1] for rows in csv_reader}
    return mapping

def read_nicknames_file(
    short_name: str
) -> Tuple[Dict[str, str], Dict[str, str]]:
    """Read a nicknames csv file into two dictionaries.

    The file is in the format:
        official,short,*other_nicknames

    Args:
        short_name (str): [description]

    Returns:
        A tuple of dictionaries (Tuple[Dict[str, str], Dict[str, str]]):
            nicknames_to_official
            official_to_short_name
    """
    nicknames_to_official: Dict[str, str] = {}
    official_to_short_name: Dict[str, str] = {}
    path = data_path(short_name)
    test_data_file(short_name)
    with open(path, "r", encoding="utf-8-sig") as file:
        csv_reader = csv.reader(file, delimiter=",")
        for row in csv_reader:
            official = row[0].strip()
            short = row[1].strip()
            nicknames_to_official[short.lower()] = official
            nicknames_to_official[official.lower()] = official
            official_to_short_name[official.lower()] = short
            for nickname in row[2:]:
                nicknames_to_official[nickname.lower()] = official
    # Green Party, with its different chapters, needs to be set by hand
    nicknames_to_official["green party"] = "Green Party"
    return nicknames_to_official, official_to_short_name

def read_csv_to_dataframe(
    short_name: str,
    separator: str = ","
) -> "pd.DataFrame":
    """Load csv into pandas dataframe.

    Args:
        short_name (str): Name of data file.
        separator (str, optional): Separator used in the file. Defaults to ",".

    Returns:
        data: dataframe
    """
    path = data_path(short_name)
    test_data_file(short_name)
    dataframe = pd.read_csv(path, sep=separator)
    return dataframe

PARTY_NICKNAMES, PARTY_SHORTNAMES = read_nicknames_file("party_nicknames.csv")
"""Official names from the nicknames we have on record."""

PARTY_COLORS = read_csv_to_dict("party_colors.csv")
"""Web color names for the parties."""

"""MIT License

Copyright (c) 2021 Stonehaven

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""


## keys.py: config file for pastebin2misp.py

## url and key for the MISP instance you want the pastes to be pushed to.
MISP_URL 		= ""
MISP_KEY 		= ""

# whether or not to alert by email when a new event is created. Turn this to False whenever you add new users to usernames.conf, and when you run it for the first time, because it will import all the previous pastes from those new authors
PUBLISH_EVENTS		= True
EMAIL_ALERTS		= False


from PyQt5 import QtWidgets,QtCore,QtGui
import json,os,sys

libs=('./lib','./lib_widget')
for p in libs:
    sys.path.insert(0,p)

import historyView,entryView
import libstatements as state

class history(state.statements):
    #history_file=None
    #path='.'

    def open_history(class_self,self):
        keys={}
        with open(self.configJson['historyFile'],'r') as c:
            keys=json.load(c)
        return keys

    def create_viewer(class_self,self):
        viewer={}
        viewer['0']={}
        viewer['0']['dialog']=QtWidgets.QDialog(self)
        viewer['0']['obj']=historyView.Ui_configView()
        viewer['0']['obj'].setupUi(viewer['0']['dialog'])
        viewer['0']['dialog'].setWindowIcon(QtGui.QIcon(self.configJson['history-icon-path']))
        return viewer

    def reload_history(class_self,self):
            #this will need to be converted to work specifically on the already existing gui in self
            keys=class_self.open_history(self)

            self.hist_d['entry']={}
            #viewer=class_self.create_viewer(self)
            #need to make children accessible by dict
            for em in keys.keys():
                self.hist_d['entry'][em]={}

                self.hist_d['entry'][em]['dialog']=QtWidgets.QDialog(self)
                self.hist_d['entry'][em]['obj']=entryView.Ui_entryView()
                self.hist_d['entry'][em]['obj'].setupUi(self.hist_d['entry'][em]['dialog'])
                self.hist_d['entry'][em]['cfg']=keys[em]
                tree=self.hist_d['entry'][em]['obj'].treeWidget

                modes=class_self.modesUseable(self,self.hist_d['entry'][em]['cfg'])
                class_self.entry_buttons_connect(self,self.hist_d['entry'][em],self.hist_d['entry'],modes,self.hist_d['viewer'])

                for mode in self.hist_d['entry'][em]['cfg'].keys():
                    if mode != 'date':
                        item=self.hist_d['entry'][em]['obj'].treeWidget.findItems(mode,QtCore.Qt.MatchExactly)[0]
                        #item_parts=[getattr(item,i) for i in dir(item)]
                        children=item.childCount()
                        self.hist_d['entry'][em]['num']=str(em)

                        item=class_self.countConf(self,self.hist_d['entry'][em]['cfg'][mode],item,tree,mode)
                        for cnf in self.hist_d['entry'][em]['cfg'][mode].keys():
                            for i in range(children):
                                subChild=item.child(i)
                                n=subChild.text(0)
                                if n == cnf:
                                    print('{} : {} {} {}'.format(
                                        self.sayit(tag=self.vul),
                                        n,
                                        self.hist_d['entry'][em]['cfg'][mode][cnf]
                                        ,mode
                                        )
                                        )
                                    if n != 'sources':
                                        print(n)
                                        subChild.setData(1,QtCore.Qt.EditRole,self.hist_d['entry'][em]['cfg'][mode][cnf])
                                        subChild.setFlags(item.flags())
                                    else:
                                        if self.hist_d['entry'][em]['cfg'][mode][cnf] != None:
                                            for src in self.hist_d['entry'][em]['cfg'][mode][cnf]:
                                                if src not in [None,'']:
                                                    print(src,mode,'srcs')
                                                    newChild=QtWidgets.QTreeWidgetItem(subChild)
                                                    newChild.setData(1,QtCore.Qt.EditRole,src)
                                                    newChild.setFlags(item.flags())
                                                    subChild.addChild(newChild)
                                                else:
                                                    break
                                        #need to add treewidgetitem as child for sources list elements
                                        pass

                    #problem ended beeing that i was overwriting previous declared widget leaving only half the cfg to display
                    if 'date' in self.hist_d['entry'][em]['cfg'].keys():
                        self.hist_d['entry'][em]['obj'].groupBox.setTitle('{}'.format(self.hist_d['entry'][em]['cfg']['date']))
                    else:
                        self.hist_d['entry'][em]['obj'].groupBox.setTitle('{}'.format(self.mkDate()))
                    self.hist_d['viewer']['0']['obj'].gridLayout_6.addWidget(self.hist_d['entry'][em]['dialog'],int(em),0,1,1)
            class_self.viewer_buttons_connect(self,self.hist_d['viewer'],self.hist_d['entry'])
            #viewer['0']['dialog'].show()
            '''
            historyViewer_dict={}
            historyViewer_dict['viewer']=viewer
            historyViewer_dict['entry']=entry
            return historyViewer_dict
            '''
            class_self.setClearState(self)

    def modesUseable(class_self,self,cfg):
        modes=[]
        print(cfg)
        for keys in cfg.keys():
            count=0
            if keys != 'date':
                for skeys in cfg[keys].keys():
                    if skeys != 'port' or skeys != 'useHostKey':
                        if cfg[keys][skeys] in ['',None]:
                            count+=1
                    if skeys == 'port':
                        if cfg[keys][skeys] in [22,None]:
                            count+=1
                    if skeys == 'useHostKey':
                        if cfg[keys][skeys] in [False,None]:
                            count+=1
                if count < len(cfg[keys].keys()):
                    modes.append(keys)
        return modes

    def viewer_setup(class_self,self):
            keys=class_self.open_history(self)

            entry={}
            viewer=class_self.create_viewer(self)
            #need to make children accessible by dict
            for em in keys.keys():
                entry[em]={}
                entry[em]['dialog']=QtWidgets.QDialog(self)
                entry[em]['obj']=entryView.Ui_entryView()
                entry[em]['obj'].setupUi(entry[em]['dialog'])
                entry[em]['cfg']=keys[em]
                tree=entry[em]['obj'].treeWidget
                modes=class_self.modesUseable(self,entry[em]['cfg'])
                class_self.entry_buttons_connect(self,entry[em],entry,modes,viewer)
                for mode in entry[em]['cfg'].keys():
                    if mode != 'date':
                        item=entry[em]['obj'].treeWidget.findItems(mode,QtCore.Qt.MatchExactly)[0]
                        item_parts=[getattr(item,i) for i in dir(item)]
                        children=item.childCount()
                        entry[em]['num']=str(em)
                        #here is the problem
                        #class_self.entry_buttons_connect(self,entry[em],entry,mode,viewer)
                        item=class_self.countConf(self,entry[em]['cfg'][mode],item,tree,mode)
                        for cnf in entry[em]['cfg'][mode].keys():
                            for i in range(children):
                                subChild=item.child(i)
                                n=subChild.text(0)
                                if n == cnf:
                                    print('{}: {} {} {}'.format(
                                        self.sayit(tag=self.vul),
                                        n,
                                        entry[em]['cfg'][mode][cnf],
                                        mode
                                        )
                                        )
                                    if n != 'sources':
                                       subChild.setData(1,QtCore.Qt.EditRole,entry[em]['cfg'][mode][cnf])
                                       subChild.setFlags(item.flags())
                                    else:
                                        if entry[em]['cfg'][mode][cnf] != None:
                                            for src in entry[em]['cfg'][mode][cnf]:
                                                if src not in [None,'']:
                                                    print('{} : {} {} {}'.format(
                                                        self.sayit(tag=self.vul),
                                                        src,
                                                        mode,
                                                        'srcs'
                                                        )
                                                        )
                                                    newChild=QtWidgets.QTreeWidgetItem(subChild)
                                                    newChild.setData(1,QtCore.Qt.EditRole,src)
                                                    newChild.setFlags(item.flags())
                                                    subChild.addChild(newChild)
                                                else:
                                                    break
                                        #need to add treewidgetitem as child for sources list elements
                                        pass

                    #problem ended beeing that i was overwriting previous declared widget leaving only half the cfg to display
                    if 'date' in entry[em]['cfg'].keys():
                        entry[em]['obj'].groupBox.setTitle('{}'.format(entry[em]['cfg']['date']))
                    else:
                        entry[em]['obj'].groupBox.setTitle('{}'.format(self.mkDate()))
                    viewer['0']['obj'].gridLayout_6.addWidget(entry[em]['dialog'],int(em),0,1,1)
            class_self.viewer_buttons_connect(self,viewer,entry)
            #viewer['0']['dialog'].show()
            historyViewer_dict={}
            historyViewer_dict['viewer']=viewer
            historyViewer_dict['entry']=entry
            return historyViewer_dict

    def loadEntry(class_self,self,cfg,mode):
        #this is gettings run 2x not suposed to be. why?!
        self.in_config=cfg
        print('{} : {} {}'.format(
            self.sayit(tag=self.vul),
            self.in_config,
            cfg),
            sep='\n'
            )
        for m in mode:
            self.loadFields(tab=m)
            self.get_creds_wrapped(tab=m,updateHistory=False)

    def removeEntry(class_self,self,entry_bottom,entry_top,viewer):
        entry_bottom['dialog'].hide()
        viewer['0']['obj'].gridLayout_6.removeWidget(entry_bottom['dialog'])
        entry_bottom['dialog'].deleteLater()

        keys=class_self.open_history(self)
        print(keys.keys())
        #keys.pop(entry_bottom['num'])

        newCfg={}

        for num,i in enumerate(entry_top.keys()):
            if entry_bottom['num'] != entry_top[i]['num']:
                newCfg[str(num)]=entry_top[i]['cfg']

        with open(self.configJson['historyFile'],'w') as cnf:
            json.dump(newCfg,cnf)

        class_self.removeAll(self,self.hist_d['viewer'],self.hist_d['entry'])
        #self.hist_d['viewer']['0']['dialog'].hide()

        class_self.reload_history(self)

        #self.hist_d=class_self.viewer_setup(self)
        #self.hist_d['viewer']['0']['dialog'].show()

    def entry_buttons_connect(class_self,self,entry_bottom,entry_top,mode,viewer):
        entry_bottom['obj'].load.clicked.connect(lambda: class_self.loadEntry(self,entry_bottom['cfg'],mode))
        entry_bottom['obj'].remove.clicked.connect(lambda: class_self.removeEntry(self,entry_bottom,entry_top,viewer))

    def viewer_destroy(class_self,self,viewer):
        viewer['0']['dialog'].destroy()
        self.hist=None
        self.hist_d=None

    def removeAll(class_self,self,viewer,entry):
        for i in entry.keys():
            try:
                entry[i]['dialog'].hide()
                viewer['0']['obj'].gridLayout_6.removeWidget(entry[i]['dialog'])
                entry[i]['dialog'].deleteLater()
            except Exception as e:
                print(e)

    def history_clear_warn(class_self,self):
        warn={}
        warn['box']=QtWidgets.QMessageBox()
        warn['box'].setStandardButtons(QtWidgets.QMessageBox.Yes | QtWidgets.QMessageBox.No)
        warn['box'].setWindowTitle('Warning')
        warn['box'].setText('You are about to clear your transaction History. Are You sure')
        warn['box'].setIcon(QtWidgets.QMessageBox.Warning)
        warn['box'].setDefaultButton(QtWidgets.QMessageBox.Yes)
        warn['box'].setEscapeButton(QtWidgets.QMessageBox.No)
        warn['box'].buttonClicked.connect(lambda arg: class_self.historyWarn(self,arg))
        return warn['box'].exec_()

    def historyWarn(class_self,self,arg):
        print('{} : user selected history clear : {} '.format(self.sayit(tag=self.vul),arg.text()))

    def history_clear(class_self,self,viewer,entry):
        warn=class_self.history_clear_warn(self)
        if warn == 16384:
            class_self.removeAll(self,viewer,entry)
            cfg={}
            mode='w'
            with open(self.configJson['historyFile'],mode) as cnf:
                json.dump(cfg,cnf)
            self.hist_d['entry']={}
        else:
            msg='User cancelled clearing history!'
            print(msg)
            self.statusBar().showMessage(msg)
        class_self.setClearState(self)

    def setClearState(class_self,self):
        h=class_self.historyLen(self)
        if h < 1:
            class_self.clearEnable(self,False)
        else:
            class_self.clearEnable(self,True)

    def historyLen(class_self,self):
        if self.hist_d == None:
            return 0
        else:
            return len(self.hist_d['entry'].keys())

    def clearEnable(class_self,self,state):
        self.hist_d['viewer']['0']['obj'].clear.setEnabled(state)

    def viewer_buttons_connect(class_self,self,viewer,entry):
        viewer['0']['obj'].close.clicked.connect(lambda: class_self.viewer_destroy(self,viewer))
        viewer['0']['obj'].clear.clicked.connect(lambda: class_self.history_clear(self,viewer,entry))

    def countConf(class_self,self,cfg,item,tree,mode,returnItem=True):
        count=0
        for key in cfg.keys():
            if key != 'port':
                if cfg[key] == None:
                    count+=1
                if cfg[key] == False:
                    count+=1
                if cfg[key] == ['']:
                    count+=1
                if cfg[key] == '':
                    count+=1
            elif key == 'port':
                if cfg[key] == 22:
                    count+=1
        print('{} : {}'.format(self.sayit(tag=self.vul),count))
        if count >= len(cfg.keys())-1:
            if returnItem == True:
                item.setHidden(True)
        if returnItem == True:
            return item


# N , L 이 주어질 떄 합이N 이면서 길이가 적어도 L인
# 가장 짧은 연속된 음이 아닌 정수 리스트를 수하는 프로그램 구하라

import sys
read = sys.stdin.readline
N,L = map(int,read().split())
# 길이가 적어도 L 인 연속된 음이 아닌 정수 리스트를 출력해야 한다.

#  #  m m+1 ... m+k 에 대해서
# m(k+1)+k(k+1)/2 -> [m + k/2](k+1) = N ;  k >= L-1
# 즉 위 수식을 만족하는 m,k 쌍을 찾는것이 목적
# N 에 관한 식이기 때문에 k 를 고정한다고 하였을 떄에 N 에 관한 1차식이 나옴
# [N - k(k+1)/2]/(k+1) 이 int 라면 good
# k 는 최대 L 까지 가능

k = L - 1 # k 는 계~속 커짐.
while True :
    m = (N - k*(k+1)/2)/(k+1) # 이 값은 m 이 나온다.
    if k > 99 :
        print(-1)
        break
    if m < 0 :
        k += 1
    else :
        if m == int(m):
            for i in range(k+1):
                print(int(m)+i,end = ' ')
            break
        else :
            k += 1


from django import forms
from django.utils.translation import gettext_lazy as _

from .models import Label

class FormLabel(forms.ModelForm):
    class Meta:
        model = Label
        fields = ("name",)

    label_place = _("Имя")

    def __init__(self, *args, **kwargs):
        super(FormLabel, self).__init__(*args, **kwargs)
        self.fields["name"].label = self.label_place

    def clean_name(self):
        name = self.cleaned_data["name"]
        if Label.objects.filter(name=name):
            raise forms.ValidationError(
                _("Метка с таким названием уже сущуствует")
            )
        return name


file = open("input.txt")
lookup = {
    'A': "ROCK",
    'B': "PAPER",
    'C': "SCISSORS",
    'X': "ROCK",
    'Y': "PAPER",
    'Z': "SCISSORS"
}

totScore = 0
for line in file:
    lineNoNL = line.split('\n')
    vals = lineNoNL[0].split(" ")

    scoreFromSel = 0
    if vals[1] == 'Y':
        scoreFromSel = 2 # Paper
    elif vals[1] == 'X':
        scoreFromSel = 1 # Rock
    else:
        scoreFromSel = 3 # Si

    scoreFromOutcome = 0
    if lookup[vals[0]] == "ROCK" and lookup[vals[1]] == "PAPER": # Rock and you: sc
        scoreFromOutcome = 6
    elif lookup[vals[0]] == "PAPER" and lookup[vals[1]] == "SCISSORS": # Paper and you: rock
        scoreFromOutcome = 6
    elif lookup[vals[0]] == "SCISSORS" and lookup[vals[1]] == "ROCK":
        scoreFromOutcome = 6
    elif lookup[vals[0]] == lookup[vals[1]]:
        scoreFromOutcome = 3

    totScore += scoreFromOutcome + scoreFromSel

print(totScore)


# encoding: utf-8

import time
from selenium import webdriver
from selenium.common.exceptions import NoAlertPresentException,NoSuchElementException

class Testcase1():
    '''写一个测试类，未继承unittest'''
    def testcase1(self):
            print('用例1，点击左边的按钮，弹出alert，点击接受')
            driver=webdriver.Chrome()
            driver.get('http://127.0.0.1:5000/')
            try:
                driver.find_element_by_xpath('//*[@id="testid"]').click()
            except NoSuchElementException as e:
                print(e)
            time.sleep(2)
            text=driver.switch_to.alert.text
            print(text)
            driver.switch_to.alert.accept()
    def testcase2(self):
        print('用例2，点击登录网站进入练习页面')
        username='15902127953'
        driver=webdriver.Chrome()
        driver.get('http://127.0.0.1:5000/')
        driver.find_element_by_xpath('/html/body/a').click()
        driver.find_element_by_xpath('/html/body/form/p[1]/input').send_keys(username)
        driver.find_element_by_xpath('/html/body/form/p[2]/input').send_keys('123456')
        driver.find_element_by_xpath('/html/body/form/p[3]/button').click()
        print('case2')

Testcase1().testcase1()
Testcase1().testcase2()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

#-:-:-:-:-:-:-::-:-:#
#     SIP Torch     #
#-:-:-:-:-:-:-::-:-:#

# Author: 0xInfection
# This module requires SIPTorch
# https://github.com/0xInfection/SIPTorch

import logging

def permuteCase(inp: str):
    '''
    Generate maximum permutations by changing case
    '''
    log = logging.getLogger('permuteCase')
    if not inp:
        log.error('Nothing available for parsing')
        return
    n = len(inp)
    mx = 1 << n
    inp = inp.lower()
    maxperm = list()
    for i in range(mx):
        combination = [k for k in inp]
        for j in range(n):
            if ((i >> j) & 1) == 1:
                combination[j] = inp[j].upper()
        temp = ''
        for i in combination:
            temp += i
        maxperm.append(temp)
    return maxperm


# menampilkan program bilangan ganjil

bb = 1
ba = 20
print('bilangan ganjil antara',bb,'dan',ba,': ')
for angka in range(bb,ba + 1):
    if angka > 1:
        for i in range(angka):
            if(angka % 2) == 0 : break
        else:
            print(angka)


import pygame
from second_b import Game_Code  # <-- add file

SCREEN_SIZE = (896, 896)

pygame.display.set_caption("Cazy Mazy")

# remove TheGame
#class Game_Code:
#    def __init__(self, SCREEN_SIZE):
#        self.display_surface = pygame.display.get_surface()
#        self.image = pygame.image.load("backgorund.png").convert_alpha() # <-- set background to image
#        self.background = pygame.transform.scale(self.image, SCREEN_SIZE) # <-- add transform on image

#    def draw(self):
#        self.display_surface.blit(self.background, (0, 0))

class Game:
    def __init__(self):
        pygame.init()
        self.screen = pygame.display.set_mode(SCREEN_SIZE)
        self.clock = pygame.time.Clock()
        self.TheGame = Game_Code(SCREEN_SIZE)

    def run(self): # <-- add run
        run = True
        while run:
            self.clock.tick(60)
            for event in pygame.event.get():
                if event.type == pygame.QUIT:
                    run = False
                    break
            # key press
            keys = pygame.key.get_pressed()
            if keys[pygame.K_SPACE]:
                self.screen.fill("blue")
                self.TheGame.draw()
                pygame.display.update()

if __name__ == "__main__":
    game = Game()
    game.run()