n=int(input())
numList=list(map(int,input().split()))
method=0
partialSum=0
searchList=[]
for i in numList:
    partialSum+=i
    searchList.append(partialSum)
divideNum=searchList.pop()
if divideNum%3==0:
    while divideNum//3 in searchList:
        beginLoc=searchList.index(divideNum//3)
        searchList=searchList[beginLoc+1:]
        method+=(searchList.count(divideNum*2//3))
if divideNum==0:
    method+=2
print(method)


# -*- coding: utf-8 -*-
import time, functools
# 装饰器
f = lambda x : x ** 3

def quart (x):
    return x ** 2

print(quart.__class__)
print(quart.__code__)   #函数的绝对地址
print(quart.__name__)  #函数的名称

# 练习
# 请设计一个decorator，它可作用于任何函数上，并打印该函数的执行时间：
def metric(fn):
    def wrapper(fn):
        print('%s executed in %s ms' % (fn.__name__, 10.24))
        f
    return fn
# 测试
@metric
def fast(x, y):
    time.sleep(0.0012)
    return x + y;

@metric
def slow(x, y, z):
    time.sleep(0.1234)
    return x * y * z;

f = fast(11, 22)
s = slow(11, 22, 33)
if f != 33:
    print('测试失败!')
elif s != 7986:
    print('测试失败!')


# This code uses TensorFlow and Keras to build and train a deep learning model for image classification. It loads a pre-trained MobileNetV2 model and adds custom layers. The model is compiled and trained on the training data, validated on the validation data, and evaluated on the test data. The PlotCallback class creates a plot of the accuracy and loss of the model during training. The ReduceLROnPlateau and EarlyStopping callbacks are used to adjust the learning rate and stop training early if the validation loss does not improve. The final trained model is saved to a file.

###################################
# Author: Sharjeel Arif
# SID: 200388331
# 08th March 2023
###################################

# REVISION HISTORY

# 08 MAR 23: Created file to train machine learning model

# 08 MAR 23: Followed steps of setting up training model on deeplizard

# 09 MAR 23: Was able to train first model
# Model was scratch. First model did not use transfer learning

# 11 Mar 23: Consulted Dr. Bais regarding accuracy of a trained model
# Suggested I use transfer learning on a pre-existing model
# Rather than training a model from scratch

# 12 MAR 23: Implemented changes to import VGG19 Model and use transfer learning to train

# 15 MAR 23: Implemented changes to import VGG16 model and use transfer learning to train

# 20 MAR 23: Implemented changes to import MobileNetV2 model and use transfer learning to train

# 21 MAR 23: Trained first few iterations off 600 size dataset. Inaccurate

# 23 MAR 23: Consulted Dr. Bais to increase accuracy of model
# Was advised to increase dataset

# 29 Mar 23: Increased dataset using augmentation

# 30 Mar 23: Trained new MobileNetV2 model

# 30 Mar 23: Tested Model, Adjusted Parameters (Added dense and dropout layers and unfroze layers), Trained another

# 30 Mar 23: Tested Model, Adjusted Parameters (Learning Rate), Trained another

# 30 Mar 23: Tested Model, Adjusted Parameters (Adjusted frozen layers), Trained another

# 31 Mar 23: Tested Model, Adjusted Parameters (Adjusted frozen layers), Trained another

import tensorflow as tf
from tensorflow.keras.preprocessing.image import ImageDataGenerator
from tensorflow.keras.layers import Dense, Dropout
from tensorflow.keras.models import Model
from tensorflow.keras.optimizers import Adam
from tensorflow.keras.applications.mobilenet_v2 import MobileNetV2
from tensorflow.keras.callbacks import ReduceLROnPlateau, EarlyStopping
import matplotlib.pyplot as plt
import numpy as np

class PlotCallback(tf.keras.callbacks.Callback):
    def on_train_begin(self, logs=None):
        self.acc = []
        self.val_acc = []
        self.loss = []
        self.val_loss = []

    def on_epoch_end(self, epoch, logs=None):
        self.acc.append(logs.get('accuracy'))
        self.val_acc.append(logs.get('val_accuracy'))
        self.loss.append(logs.get('loss'))
        self.val_loss.append(logs.get('val_loss'))

        plt.figure(figsize=(10, 5))

        plt.subplot(1, 2, 1)
        plt.plot(np.arange(epoch + 1), self.acc, label='Train')
        plt.plot(np.arange(epoch + 1), self.val_acc, label='Validation')
        plt.title('Model accuracy')
        plt.ylabel('Accuracy')
        plt.xlabel('Epoch')
        plt.legend()
        plt.grid(True)

        plt.subplot(1, 2, 2)
        plt.plot(np.arange(epoch + 1), self.loss, label='Train')
        plt.plot(np.arange(epoch + 1), self.val_loss, label='Validation')
        plt.title('Model loss')
        plt.ylabel('Loss')
        plt.xlabel('Epoch')
        plt.legend()
        plt.grid(True)

        plt.tight_layout()
        plt.show(block=False)
        plt.pause(1)
        plt.close()

    def save_plot(self, file_name='training_plot4.png'):
        plt.figure(figsize=(10, 5))

        plt.subplot(1, 2, 1)
        plt.plot(self.acc, label='Train')
        plt.plot(self.val_acc, label='Validation')
        plt.title('Model accuracy')
        plt.ylabel('Accuracy')
        plt.xlabel('Epoch')
        plt.legend()
        plt.grid(True)

        plt.subplot(1, 2, 2)
        plt.plot(self.loss, label='Train')
        plt.plot(self.val_loss, label='Validation')
        plt.title('Model loss')
        plt.ylabel('Loss')
        plt.xlabel('Epoch')
        plt.legend()
        plt.grid(True)

        plt.tight_layout()
        plt.savefig(file_name)
        plt.close()

# Define the paths to the training, validation, and test directories
train_dir = 'dataset/train'
val_dir = 'dataset/val'
test_dir = 'dataset/test'

# Define the image size and batch size
img_size = (224, 224)
batch_size = 16

# Define the number of output classes
num_classes = 4

# Define the MobileNetV2 model with pre-trained weights from ImageNet
base_model = MobileNetV2(input_shape=(img_size[0], img_size[1], 3), include_top=False, weights='imagenet')

# Freeze all layers in the base model
for layer in base_model.layers:
    layer.trainable = False

# Unfreeze the last 30 layers
for layer in base_model.layers[-35:]:
    layer.trainable = True

# Add custom layers on top of the base model for your specific use case
x = base_model.output
x = tf.keras.layers.GlobalAveragePooling2D()(x)
x = Dense(128, activation='relu')(x)
x = Dropout(0.5)(x)
x = Dense(64, activation='relu')(x)  # Additional Dense layer
x = Dropout(0.5)(x)  # Additional Dropout layer
x = Dense(32, activation='relu')(x)  # New dense layer
x = Dropout(0.5)(x)  # New dropout layer
predictions = Dense(num_classes, activation='softmax')(x)

# Create the model
model = Model(inputs=base_model.input, outputs=predictions)

# Compile the model with the desired optimizer, loss function, and metrics
model.compile(optimizer=Adam(lr=1e-4), loss='categorical_crossentropy', metrics=['accuracy'])

# Print a summary of the model architecture
model.summary()

# Define the data generators for training, validation, and test sets
datagen = ImageDataGenerator(
    rescale=1./255,
    validation_split=0.2
)

train_generator = datagen.flow_from_directory(
    train_dir,
    target_size=img_size,
    batch_size=batch_size,
    class_mode='categorical',
    subset='training'
)

val_generator = datagen.flow_from_directory(
    val_dir,
    target_size=img_size,
    batch_size=batch_size,
    class_mode='categorical',
    subset='validation'
)

test_generator = datagen.flow_from_directory(
    test_dir,
    target_size=img_size,
    batch_size=batch_size,
    class_mode='categorical'
)

# Define the ReduceLROnPlateau and EarlyStopping callbacks
reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.2, patience=3, min_lr=1e-6)
early_stopping = EarlyStopping(monitor='val_loss', patience=5, restore_best_weights=True)

# Train the model on the training data, and validate it on the validation data
plot_callback = PlotCallback()

history = model.fit(
    train_generator,
    epochs=30,
    validation_data=val_generator,
    callbacks=[reduce_lr, early_stopping, plot_callback]
)

# Save final plot
plot_callback.save_plot('final_training_plot4.png')

# Evaluate the model on the test data
test_loss, test_acc = model.evaluate(test_generator)
print('Test accuracy:', test_acc)

# Save the trained model to a file (optional)
model.save('baby_posture_modelv4.h5')


from transposition.ngramTransposition import decrypt_horizontal, decrypt_vertical, convert_to_tuple
from random import randrange
from copy import deepcopy
from numpy.random import permutation
from itertools import combinations
from substitution.manualSubDecoder import color
from englishDetection import ngramScore, englishScore

#decrypts a ciphertext by using a custom algorithm
#Algorithm doesn't work 100% of the time, somewhat unpredictable
#It is kind of like bogosort: https://en.wikipedia.org/wiki/Bogosort

def decrypt(ciphertext, lowerBound, upperBound, n=1, direction='H', num_of_decryptions=10, num_of_times=200,
            fitness_score=ngramScore.ngram_score(ngramScore.QUADGRAMS).score): #this is the default fitness score

    decryptMessage = decrypt_horizontal if direction.upper() == 'H' else decrypt_vertical

    scores_list = []

    #generate two random indexes
    for key in range(lowerBound, upperBound + 1):
        #max num of allowed failures (new score not greater than old)
        #randomly choose a starting initial permutation (the "best" permutation only initially)
        best_perm = list(permutation(key))
        #initial "best" is decryption with the initial permutation
        best_plaintext = decryptMessage(key=tuple(best_perm), message=ciphertext)
        best_score = fitness_score(best_plaintext)
        #add initial as an entry
        scores_list.append((best_score, best_perm, best_plaintext))
        g = get_switched_permutations(best_perm)
        for i in range(num_of_times):
           entries = []
           for j in range(len(g)):
               new_perm = switch(best_perm, g[j][0], g[j][1])
               new_plaintext = decryptMessage(key=tuple(new_perm), message=ciphertext)
               new_score = fitness_score(new_plaintext)
               entry = (new_score, new_perm, new_plaintext)
               entries.append(entry)

           entries.sort(key=lambda x: x[0], reverse=True)
           if not entries[0][0] > best_score: #if this seems to be a possible decryption, add it to the scores-list
               best_entry = (best_score, best_perm, best_plaintext)
               #print it out
               print("%-10.0f %-50s %-10s" % (best_score, best_perm, best_plaintext))
               if not best_entry in scores_list:
                   scores_list.append(best_entry)
               #re-randomize best values
               best_perm = list(permutation(key))
               best_plaintext = decryptMessage(key=tuple(best_perm), message=ciphertext)
               best_score = fitness_score(best_plaintext)

           else:
                best_score, best_perm, best_plaintext = entries[0][0], entries[0][1], entries[0][2]

    print()
    scores_list.sort(key=lambda x: x[0], reverse=True)
    return scores_list[:num_of_decryptions + 1] if len(scores_list) <= num_of_decryptions else scores_list

def print_best_solutions(scores_list):
    print(color.RED + color.BOLD + " BEST SOLUTIONS: " + color.END)
    print((color.BOLD + "%10s %15s %54s" + color.END) % ("Score:", "Key:", "Message:"))
    for i in range(10):
        try:
            print("%-5d %-15.0f %-50s %-10s" % (i+1, scores_list[i][0], str(tuple(scores_list[i][1])), scores_list[i][2]))
        except IndexError:
            break

#returns list with switched elements at two distinct indexes in a list
def switch(li, pos1, pos2):
    return_li = deepcopy(li)
    return_li[pos1], return_li[pos2] = return_li[pos2], return_li[pos1]
    return return_li

#returns a list containing all the possible index swaps on a permutation
def get_switched_permutations(perm):
    return list(combinations(range(len(perm)), 2))

def main():
    message = input("Enter a message: ")
    remove = input("Remove spaces? [y/n]: ")
    if remove == 'y':
        message = ''.join(message.split())
    direction = input("horizontal or vertical <h/v>?: ").upper()
    n = int(input("n = "))
    lower = int(input("Lower bound: "))
    upper = int(input("Upper bound: "))
    num_of_times = int(input("How many iterations for each permutation length?: "))

    print_best_solutions(decrypt(message, lower, upper, n, direction, num_of_times,
    fitness_score= lambda x: englishScore.english_word_score(x, englishScore.COMMON_WORDS, 2)))
    # fitness score can be changed! Sometimes works better with ngram logarithmic probabilities, n = 3

if __name__ == '__main__':
    main()


class Solution(object):
    def maximumGap(self, nums):
        """
        :type nums: List[int]
        :rtype: int
        """
        """
        It's a problem with bucket sort.Also, we should
        has some idea of math.
        Assume the min of the array is A, and the max is B
        the min of the gap would be make all the gap equal,
        otherwise, if some gets smaller other gaps would be larger.
        So, the bucket length would be ceiling((B-A)/(N-1))
        and the maxium bucket numer is (B-A)/bucketlen+1
        some of the bucket would be empty
        """
        n=len(nums)
        if n<2: return 0
        min_num=min(nums)
        max_num=max(nums)

        # the math ceil might influence the efficency
        #bucket_range=max(1,int(math.ceil((max_num-min_num)/(n-1))))
        bucket_range=max(1,int((max_num-min_num-1)/(n-1))+1)
        bucket_len=(max_num-min_num)/bucket_range+1
        buckets=[None]*bucket_len

        # adding to buckets
        for num in nums:
            pos=(num-min_num)/bucket_range
            t_bucket=buckets[pos]
            if not t_bucket:
                # record the min and max
                t_bucket={'min':num,'max':num}
                buckets[pos]=t_bucket
            else:
                # update min and max
                t_bucket['min']=min(t_bucket['min'],num)
                t_bucket['max']=max(t_bucket['max'],num)
        # get the possible maxgap
        # using the n.min-(n-1).max
        res=0
        for i in xrange(bucket_len):
            # get rid of the empty
            if not buckets[i]:
                continue
            j=i+1
            # get rid the continue j is empty
            # EX NULL,[1,2],NULL,NULL,[4,5]
            while j<bucket_len and not buckets[j]:
                j+=1
            # get the max gap
            if j<bucket_len:
                res=max(res,buckets[j]['min']-buckets[i]['max'])
            i=j

        return res


# -*- coding: utf-8 -*-
"""
Created on Wed Aug 10 11:58:35 2016

@author: Eward Comyn-Platt
"""

import netCDF4 as nc
from SoilTools import BrooksCorey as BC
from SoilTools import VanGenucthen as VG

Input_Dir='/users/eow/edwcom/GREENHOUSE/SOIL_PROPERTIES/datasets/'
Comp_File=Input_Dir+'Merged_Soil_Composition_CHESSgrid.nc'

Output_Dir=Input_Dir
OUT_BC_file=Output_Dir+'SoilProperties_BC_CHESSgrid.nc'
OUT_VG_file=Output_Dir+'SoilProperties_VG_CHESSgrid.nc'

# Read Soil Composition File
INPUT_vars=['sand','silt','clay','carbon']
COMP_data={}
COMPinf=nc.Dataset(Comp_File,'r')
for var in INPUT_vars:
    COMP_data[var]=COMPinf.variables[var][:]
COMPinf.close()

# Compute the Brooks and Corey Soil Properties
BC_Properties=BC.get_BC_soil_properties(COMP_data['clay'],\
                                        COMP_data['sand'],\
                                        COMP_data['silt'] )

# Compute the Brooks and Corey Soil Properties
VG_Properties=VG.get_VG_soil_properties(COMP_data['clay'],        \
                                        COMP_data['sand'],        \
                                        COMP_data['silt'],        \
                                        OC_PC=COMP_data['carbon'],\
                                        RETURN_SOIL_TEXTURE=True  )

print(BC_Properties)

import matplotlib.pyplot as plt

plotdata=COMP_data['sand']

plt.figure(figsize=(15,15))
for iSD in range(4):
    plt.subplot(2,2,iSD+1)
    plt.imshow(plotdata[iSD,:],origin='bottom')
    plt.colorbar()

plt.show()


# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
	def deleteDuplicates(self, head):
		if head == None:
			return None
		pre = head
		cur = head.next
		while cur != None:
			if pre.val == cur.val:
				pre.next = cur.next
				cur = cur.next
			else:
				pre = cur
				cur = cur.next
		return head

83. Remove Duplicates from Sorted List.py


import pygame
from pygame.locals import *

pygame.init()

screen_width: int = 700
screen_height: int = 700

screen: pygame.Surface = pygame.display.set_mode((screen_width, screen_height), 0, 32)
pygame.display.set_caption("Using Mouse")
screen.fill((0, 0, 0))

sprite1: pygame.Surface = pygame.image.load('./images/butterfly.png')
sprite1 = pygame.transform.scale(sprite1, (64, 64))
sprite_width: int = sprite1.get_width()
sprite_height: int = sprite1.get_height()

x: int = 0
y: int = 0

clock: int = pygame.time.Clock()
game_over: bool = False
while not game_over:
    dt = clock.tick(100)
    for event in pygame.event.get():
        if event.type == pygame.QUIT:
            game_over = True
        elif event.type == pygame.MOUSEMOTION:
            x, y = event.pos
            x -= sprite_width / 2
            y -= sprite_height / 2

    pressed = pygame.key.get_pressed()
    if pressed[K_UP]:
        y -= 0.5 * dt
    if pressed[K_DOWN]:
        y += 0.5 * dt
    if pressed[K_RIGHT]:
        x += 0.5 * dt
    if pressed[K_LEFT]:
        x -= 0.5 * dt
    if pressed[K_SPACE]:
        x, y = 0, 0

    x = min(screen_width - sprite_width, x)
    x = max(0, x)
    y = min(screen_height - sprite_height, y)
    y = max(0, y)

    screen.fill((128, 0, 255))
    screen.blit(sprite1, (x, y))
    pygame.display.update()
pygame.quit()


from siteinterface.mod_calendar import bp_calendar
from siteinterface import app
from flask import request, jsonify
from logic.StandardPointName import *
from openpyxl import Workbook
import os
from datetime import datetime
import traceback
from .. BEOPMySqlDBContainer import BEOPMySqlDBContainer
from siteinterface.BEOPSqliteAccess import *
from siteinterface.BEOPDataAccess import BEOPDataAccess
import logging
import xlrd
from siteinterface.utils import send_alert_to_cloud_center, get_proj_name

def isValidDate(strDate, strFormat):
    res = False
    try:
        if not isinstance(strDate, str):
            return res

        tTime = datetime.strptime(strDate, strFormat)
        res = True
    except:
        pass
    finally:
        return res

def get_last_day_of_this_month(curDate):
    res = None
    try:
        if not isinstance(curDate, datetime):
            return None

        tNextMonth = curDate.replace(day=28) + timedelta(days=4)
        firstDayOfNextMonth = tNextMonth.replace(day=1)
        res = firstDayOfNextMonth - timedelta(days=1)
    except:
        pass
    finally:
        return res

def modeIdExistsInMode(modeId):
    """
    检查modeId是否已存在于mode表中
    """
    res = False
    try:
        rvConduct = BEOPDataAccess.getInstance().modeIdExistsInMode(modeId)
        if rvConduct is None:
            return None

        if rvConduct and len(rvConduct):
            if len(rvConduct[0]):
                if rvConduct[0][0] > 0:
                    res = True

    except Exception as e:
        strLog = "ERROR in modeIdExistsInMode: %s" % e.__str__()
        logging.error(strLog)

    finally:
        return res

@bp_calendar.route("/getCalendarWithWeather", methods=["POST"])
def get_calendar_with_weather():
    try:
        rcv = request.get_json()
        year = rcv.get("year") if rcv.get("year") else None
        month = rcv.get("month") if rcv.get("month") else None

        if not year:
            return jsonify(dict(err=1, msg="年不能为空", data=[]))

        if not month:
            return jsonify(dict(err=1, msg="月不能为空", data=[]))

        timeFormat = "%Y-%m-%d"

        strTimeStart = "%s-%02d-01" % (year, month)

        tTimeStart = datetime.strptime("%s-%02d-01" % (year, month), timeFormat)

        tTimeEnd = get_last_day_of_this_month(datetime.strptime("%s-%02d-01" % (year, month), timeFormat))

        strTimeEnd = tTimeEnd.strftime(timeFormat)

        weatherDict = BEOPDataAccess.getInstance().getCalendarWithWeather(strTimeStart, strTimeEnd)

        if weatherDict is None:
            return jsonify(dict(err=1, msg="数据库繁忙，请重试", data=[]))

        if not weatherDict:
            return jsonify(dict(err=1, msg="无日历数据", data=[]))

        dataList = list()
        curDate = tTimeStart
        while curDate <= tTimeEnd:

            strCurDate = curDate.strftime("%Y-%m-%d")

            weatherInfo = weatherDict.get(strCurDate) if weatherDict.get(strCurDate) else {}

            dataList.append({
                "day": curDate.day,
                "weather": weatherInfo
            })

            curDate = curDate + timedelta(days=1)

        return jsonify(dict(err=0, data=dataList, msg="获取成功"))

    except Exception as e:
        strLog = "ERROR in /calendar/getMonthWeatherData: %s" % e.__str__()
        logging.error(strLog)

        return jsonify(dict(err=1, msg="获取失败: %s" % e.__str__(), data=[]))

@bp_calendar.route("/addModeToCalendar", methods=["POST"])
def add_mode_to_calendar():
    try:
        rcv = request.get_json()
        date = rcv.get("date") if rcv.get("date") else None
        modeId = rcv.get("modeId") if rcv.get("modeId") is not None else None
        type = rcv.get("type") if rcv.get("type") is not None else None
        creator = rcv.get("creator") if rcv.get("creator") else None
        now = datetime.now()
        dateToday = datetime.strptime(now.strftime("%Y-%m-%d"), "%Y-%m-%d")

        strSource = rcv.get("source", "")
        strIP = request.remote_addr
        strLog = '[IMPORTANT]addModeToCalendar: 来自IP:%s, 用户:%s, date:%s, type:%s  modeId:%s' % (
        strIP, strSource, date, type, modeId)
        logging.error(strLog)

        if strSource:
            bReadOnly = BEOPDataAccess.getInstance().is_user_read_only(strSource)
            if bReadOnly:
                return json.dumps(dict(err=1, msg='user has no write priority', data={}), ensure_ascii=False)

        if date is None:
            return jsonify(dict(err=1, msg="日期不能为空"))

        if not isValidDate(date, "%Y-%m-%d"):
            return jsonify(dict(err=1, msg="日期格式有误"))

        tDate = datetime.strptime(date, "%Y-%m-%d")

        if tDate < dateToday:
            return jsonify(dict(err=1, msg="今日之前的模式不可编辑"))

        if modeId is None:
            return jsonify(dict(err=1, msg="模式ID不能为空"))

        if not isinstance(modeId, int):
            return jsonify(dict(err=1, msg="模式ID必须为整数"))

        if not modeIdExistsInMode(modeId):
            return jsonify(dict(err=1, msg="模式ID不存在"))

        if type is None:
            return jsonify(dict(err=1, msg="模式类型不能为空"))

        if not isinstance(type, int):
            return jsonify(err=1, msg="模式类型必须为整数")

        if not creator:
            return jsonify(dict(err=1, msg="创建者不能为空"))
        if not isinstance(creator, str):
            return jsonify(err=1, msg="创建者名称必须为字符串")

        rvConduct = BEOPDataAccess.getInstance().getModeById(modeId)
        if rvConduct is None:
            return jsonify(dict(err=1, msg="数据库繁忙，请重试"))

        if not len(rvConduct[1]):
            strMsg = "IP为{ip}的用户正在执行模式绑定(项目:{proj},模式ID:{modeId})，但该模式内容为空".format(ip=strIP,
                                                                                proj=get_proj_name(), modeId=modeId)
            send_alert_to_cloud_center(get_proj_name(), strMsg)

        result = BEOPDataAccess.getInstance().insertIntoModeCalendar(date, modeId, creator, type)
        try:
            BEOPDataAccess.getInstance().appendOperationLog(strSource, '从地址%s发起模式修改'%(strIP))
        except:
            pass

        if result.get("code") > 0:
            return jsonify(dict(err=1, msg=result.get("msg"), data=result.get("data")))
        else:
            return jsonify(dict(err=0, msg=result.get("msg"), data=result.get("data")))

    except Exception as e:
        strLog = "ERROR in /calendar/addModeToCalendar: %s" % e.__str__()
        logging.error(strLog)

        return jsonify(dict(err=1, msg="保存失败: %s" % e.__str__(), data=False))

@bp_calendar.route("/batchAddModeToCalendar", methods=["POST"])
def batch_add_mode_to_calendar():
    try:
        rcv = request.get_json()
        year = rcv.get("year") if rcv.get("year") is not None else None
        month = rcv.get("month") if rcv.get("month") is not None else None
        modeId = rcv.get("modeId") if rcv.get("modeId") is not None else None
        type = rcv.get("type") if rcv.get("type") is not None else None
        creator = rcv.get("creator") if rcv.get("creator") else None
        strSource = rcv.get("source", "")
        nWeekdayList = rcv.get('weekdayList', [])
        if len(nWeekdayList)==0:
            nWeekdayList = [0,1,2,3,4,5,6]
        strIP = request.remote_addr

        strLog = '[IMPORTANT]batchAddModeToCalendar: 来自IP:%s, 用户:%s, year:%s,  month:%s,  modeId:%s'%(strIP, strSource, year, month, modeId)
        logging.error(strLog)

        if strSource:
            bReadOnly = BEOPDataAccess.getInstance().is_user_read_only(strSource)
            if bReadOnly:
                return json.dumps(dict(err=1, msg='user has no write priority', data={}), ensure_ascii=False)

        now = datetime.now()
        today = now.day
        thisYear = now.year
        thisMonth = now.month

        if year is None:
            return jsonify(dict(err=1, msg="年不能为空"))

        if not isinstance(year, int):
            return jsonify(dict(err=1, msg="年必须为整数"))

        if month is None:
            return jsonify(dict(err=1, msg="月不能为空"))

        if not isinstance(month, int):
            return jsonify(dict(err=1, msg="月必须为整数"))

        if year < thisYear:
            return jsonify(dict(err=1, msg="无法编辑去年的日程"))

        if year == thisYear and month < thisMonth:
            return jsonify(dict(err=1, msg="无法编辑本月之前的日程"))

        if modeId is None:
            return jsonify(dict(err=1, msg="模式ID不能为空"))

        if not isinstance(modeId, int):
            return jsonify(dict(err=1, msg="模式ID必须为整数"))

        if not modeIdExistsInMode(modeId):
            return jsonify(dict(err=1, msg="模式ID不存在"))

        if type is None:
            return jsonify(dict(err=1, msg="模式类型不能为空"))

        if not isinstance(type, int):
            return jsonify(err=1, msg="模式ID必须为整数")

        if not creator:
            return jsonify(dict(err=1, msg="创建者不能为空"))

        if not isinstance(creator, str):
            return jsonify(err=1, msg="创建者名称必须为字符串")

        fromDay = 1
        if year == thisYear and month == thisMonth:
            fromDay = today

        lastDate = get_last_day_of_this_month(datetime.strptime("%s-%02d-01" % (year, month), "%Y-%m-%d"))
        toDay = lastDate.day

        rvConduct = BEOPDataAccess.getInstance().getModeById(modeId)
        if rvConduct is None:
            return jsonify(dict(err=1, msg="数据库繁忙，请重试"))

        if not len(rvConduct[1]):
            strMsg = "IP为{ip}的用户正在执行批量模式绑定(项目:{proj},模式ID:{modeId})，但该模式内容为空".format(ip=strIP,
                                                                                proj=get_proj_name(), modeId=modeId)
            send_alert_to_cloud_center(get_proj_name(), strMsg)

        result = BEOPDataAccess.getInstance().batchInsertIntoModeCalendar(year, month, fromDay, toDay, modeId, creator, type, nWeekdayList)

        try:
            BEOPDataAccess.getInstance().appendOperationLog(strSource, '从地址%s发起模式批量绑定'%(strIP))
        except:
            pass

        if result.get("code") > 0:
            return jsonify(dict(err=1, msg=result.get("msg"), data=result.get("data")))

        return jsonify(dict(err=0, msg=result.get("msg"), data=result.get("data")))

    except Exception as e:
        strLog = "ERROR in /calendar/batchAddModeToCalendar: %s" % e.__str__()
        logging.error(strLog)

        return jsonify(dict(err=1, msg="保存失败: %s" % e.__str__(), data=[]))

@bp_calendar.route("/getCalendarWithMode", methods=["POST"])
def get_calendar_with_mode():
    try:
        rcv = request.get_json()
        year = rcv.get("year") if rcv.get("year") else None
        month = rcv.get("month") if rcv.get("month") else None
        type = rcv.get("type") if rcv.get("type") is not None else None

        if type is not None:
            if not isinstance(type, int):
                return jsonify(dict(err=1, msg="type必须是一个整数"))

        if not year:
            return jsonify(dict(err=1, msg="年不能为空", data=[]))

        if not month:
            return jsonify(dict(err=1, msg="月不能为空", data=[]))

        strTimeStart = "%s-%02d-01" % (year, month)

        tTimeStart = datetime.strptime("%s-%02d-01" % (year, month), "%Y-%m-%d")

        tTimeEnd = get_last_day_of_this_month(datetime.strptime("{0}-{1}-01".format(year, month), "%Y-%m-%d"))

        strTimeEnd = tTimeEnd.strftime("%Y-%m-%d")

        result = BEOPDataAccess.getInstance().getCalendarWithMode(strTimeStart, strTimeEnd, type)

        if result["code"] == 1:
            return jsonify(dict(err=1, msg=result["msg"], data=result.get("data")))

        if result["code"] == 2:
            return jsonify(dict(err=0, msg=result["msg"], data=result.get("data")))

        dataList = []
        curDate = tTimeStart
        dataDict = result.get("data")[0]
        weatherDict = result.get("data")[1]
        while curDate <= tTimeEnd:
            strCurDate = curDate.strftime("%Y-%m-%d")

            lInfo = dataDict.get(strCurDate) if dataDict.get(strCurDate) else []
            weather = weatherDict.get(strCurDate) if weatherDict.get(strCurDate) else {}
            dataList.append({
                "day": curDate.day,
                "mode": lInfo,
                "weather": weather
            })

            curDate = curDate + timedelta(days=1)

        return jsonify(dict(err=0, msg="获取成功", data=dataList))

    except Exception as e:
        strLog = "ERROR in /calendar/getCalendarWithMode: %s" % e.__str__()
        logging.error(strLog)

        return jsonify(dict(err=1, msg="保存失败: %s" % e.__str__(), data=[]))

@bp_calendar.route("/removeModeFromCalendar", methods=["POST"])
def remove_mode_from_calendar():
    try:
        rcv = request.get_json()
        modeId = rcv.get("modeId") if rcv.get("modeId") is not None else None
        date = rcv.get("date") if rcv.get("date") else None
        strSource = rcv.get("source", "")
        strIP = request.remote_addr

        strLog = '[IMPORTANT]removeModeFromCalendar: 来自IP:%s, 用户:%s, date:%s, modeId:%s'%(strIP, strSource, date, modeId)
        logging.error(strLog)

        if strSource:
            bReadOnly = BEOPDataAccess.getInstance().is_user_read_only(strSource)
            if bReadOnly:
                return json.dumps(dict(err=1, msg='user has no write priority', data={}), ensure_ascii=False)

        if modeId is None:
            return jsonify(dict(err=1, msg="模式ID不能为空"))

        if not isinstance(modeId, int):
            return jsonify(dict(err=1, msg="模式ID必须为整数"))

        if not modeIdExistsInMode(modeId):
            return jsonify(dict(err=1, msg="模式ID不存在"))

        if not isValidDate(date, "%Y-%m-%d"):
            return jsonify(dict(err=1, msg="日期格式有误"))

        result = BEOPDataAccess.getInstance().removeModeFromCalendar(modeId, date)

        try:
            BEOPDataAccess.getInstance().appendOperationLog(strSource, '从地址%s发起模式解除'%(strIP))
        except:
            pass

        if result.get("code") > 0:
            return jsonify(dict(err=1, msg=result.get("msg"), data=False))
        else:
            return jsonify(dict(err=0, msg=result.get("msg"), data=True))

    except Exception as e:
        strLog = "ERROR in /calendar/removeModeFromCalendar: %s" % e.__str__()
        logging.error(strLog)

        return jsonify(dict(err=1, msg="删除失败: %s" % e.__str__(), data=False))

@bp_calendar.route("/batchRemoveModeFromCalendar", methods=["POST"])
def batch_remove_mode_from_calendar():
    try:
        rcv = request.get_json()
        modeId = rcv.get("modeId", None)
        strFrom = rcv.get("from", "")
        strTo = rcv.get("to", "")
        strSource = rcv.get("source", "")
        strIP = request.remote_addr

        strLog = '[IMPORTANT]batchRemoveModeFromCalendar: 来自IP:%s, 用户:%s, date:%s, modeId:%s' % (strIP, strSource, date, modeId)
        logging.error(strLog)

        if strSource:
            bReadOnly = BEOPDataAccess.getInstance().is_user_read_only(strSource)
            if bReadOnly:
                return json.dumps(dict(err=1, msg='user has no write priority', data={}), ensure_ascii=False)

        if modeId is None:
            return jsonify(dict(err=1, msg="模式ID不能为空", data=False))

        if not isinstance(modeId, int):
            return jsonify(dict(err=1, msg="模式ID必须为整数", data=False))

        if not modeIdExistsInMode(modeId):
            return jsonify(dict(err=1, msg="模式ID不存在", data=False))

        if not len(strFrom) or not len(strTo):
            return jsonify(dict(err=1, msg="开始、结束日期不能为空", data=False))

        if not isValidDate(strFrom, "%Y-%m-%d"):
            return jsonify(dict(err=1, msg="开始日期格式有误", data=False))

        if not isValidDate(strTo, "%Y-%m-%d"):
            return jsonify(dict(err=1, msg="结束日期格式有误", data=False))

        tFrom = datetime.strptime(strFrom, "%Y-%m-%d")
        tTo = datetime.strptime(strTo, "%Y-%m-%d")
        if tFrom < datetime.now().replace(hour=0, minute=0, second=0, microsecond=0):
            return jsonify(dict(err=1, msg="今天之前的模式无法解绑", data=False))

        if tFrom > tTo:
            return jsonify(dict(err=1, msg="开始日期不能大于结束日期", data=False))

        result = BEOPDataAccess.getInstance().batchRemoveModeFromCalendar(modeId, tFrom, tTo)

        try:
            BEOPDataAccess.getInstance().appendOperationLog(strSource, '从地址%s发起模式批量解除'%(strIP))
        except:
            pass

        if result.get("code") > 0:
            return jsonify(dict(err=1, msg=result.get("msg"), data=False))
        return jsonify(dict(err=0, msg=result.get("msg"), data=True))

    except Exception as e:
        strLog = "ERROR in /calendar/batchRemoveModeFromCalendar: %s" % e.__str__()
        logging.error(strLog)
        return jsonify(dict(err=1, msg="解绑失败: %s" % e.__str__(), data=False))

@bp_calendar.route("/batchRemoveModeFromCalendarThisMonth", methods=["POST"])
def batch_remove_mode_from_calendar_this_month():
    try:
        rcv = request.get_json()
        nType = rcv.get("type", None)
        strDate = rcv.get("date", "")

        strSource = rcv.get("source", "")
        strIP = request.remote_addr

        strLog = '[IMPORTANT]batchRemoveModeFromCalendarThisMonth: 来自IP:%s, 用户:%s, date:%s, modeId:%s' % (strIP, strSource, strDate, nType)
        logging.error(strLog)

        if strSource:
            bReadOnly = BEOPDataAccess.getInstance().is_user_read_only(strSource)
            if bReadOnly:
                return json.dumps(dict(err=1, msg='user has no write priority', data={}), ensure_ascii=False)

        # if nType is None:
        #     return jsonify(dict(err=1, msg="类型不能为空", data=False))

        if nType is not None:
            if not isinstance(nType, int):
                return jsonify(dict(err=1, msg="类型必须为整数", data=False))

        if not len(strDate):
            return jsonify(dict(err=1, msg="日期不能为空", data=False))

        if not isValidDate(strDate, "%Y-%m"):
            return jsonify(dict(err=1, msg="日期格式有误", data=False))

        tDate = datetime.strptime(strDate, "%Y-%m")
        tFrom = tDate.replace(day=1, hour=0, minute=0, second=0, microsecond=0)
        tTo = (time_get_first_day_of_next_month(tDate) - timedelta(days=1)).replace(hour=23, minute=59, second=59, microsecond=0)
        if tFrom < datetime.now():
            tFrom = datetime.now().replace(hour=0, minute=0, second=0, microsecond=0)

        result = BEOPDataAccess.getInstance().batchRemoveModeFromCalendarThisMonth(nType, tFrom, tTo)

        try:
            BEOPDataAccess.getInstance().appendOperationLog(strSource, '从地址%s发起模式批量解除'%(strIP))
        except:
            pass

        if result.get("code") > 0:
            return jsonify(dict(err=1, msg=result.get("msg"), data=False))
        return jsonify(dict(err=0, msg=result.get("msg"), data=True))

    except Exception as e:
        strLog = "ERROR in /calendar/batchRemoveModeFromCalendarThisMonth: %s" % e.__str__()
        logging.error(strLog)
        return jsonify(dict(err=1, msg="解绑失败: %s" % e.__str__(), data=False))

@bp_calendar.route("/getModeOfTypeOnCertainDate", methods=["POST"])
def get_mode_of_type_on_certain_date():
    rcv = request.get_json()
    nType = rcv.get("type", None)
    date = rcv.get("date", "")

    if nType is None:
        return jsonify(dict(err=1, msg="类型不能为空", data={}))
    if not isinstance(nType, int):
        return jsonify(dict(err=1, msg="类型必须为整数", data={}))
    if not date:
        return jsonify(dict(err=1, msg="日期不能为空", data={}))
    if not isinstance(date, str):
        return jsonify(dict(err=1, msg="日期必须为字符串", data={}))
    if not isValidDate(date, "%Y-%m-%d"):
        return jsonify(dict(err=1, msg="日期格式有误", data={}))

    res = BEOPDataAccess.getInstance().getModeOfTypeOnCertainDate(nType, date)
    if res.get("code") > 0:
        return jsonify(dict(err=1, msg=res.get("msg"), data={}))
    return jsonify(dict(err=0, msg="获取成功", data=res.get("data")))


import pandas as pd

f_path = '~/Desktop/test_exec_tools.xlsx'

data1 = pd.ExcelFile(f_path).sheet_names
# data2 = pd.read_excel(f_path)
# all_data = [data1, data2]

# data3 = pd.concat(all_data)
print(data1)


length = int(input())
A = [int(i) for i in input().split()]
mina = A[0]
result = 1
for i in range(len(A)):
	if(mina > A[i]):
		mina = A[i]
for i in range(len(A)):
	if(A[i] % mina != 0):
		result = 0
		break

if(result == 0):
	print(-1)
else:
	print(mina)


list1 = input("List 1: ")
list2 = input("List 2: ")

list1 = list(map(int, list1.split()))
list2 = list(map(int, list2.split()))

sum1 = list1[0] + list1[-1] if len(list1) > 1 else list1[0]
sum2 = list2[0] + list2[-1] if len(list2) > 1 else list2[0]

if sum1 > sum2:
    print("Output: ", sum1)
elif sum2 > sum1:
    print("Output: ", sum2)
else:
    print("Same")


from __future__ import annotations

from pathlib import Path

import pytest

from poetry.repositories.parsers.pypi_search_parser import Result
from poetry.repositories.parsers.pypi_search_parser import SearchResultParser

FIXTURES_DIRECTORY = Path(__file__).parent.parent / "fixtures" / "pypi.org" / "search"

@pytest.fixture
def search_page_data() -> str:
    with FIXTURES_DIRECTORY.joinpath("search.html").open(encoding="utf-8") as f:
        return f.read()

def test_search_parser(search_page_data: str) -> None:
    parser = SearchResultParser()
    parser.feed(search_page_data)
    assert parser.results == [
        Result(
            name="SQLAlchemy",
            version="1.3.10",
            description="Database Abstraction Library",
        ),
        Result(
            name="SQLAlchemy-Dao",
            version="1.3.1",
            description="Simple wrapper for sqlalchemy.",
        ),
        Result(
            name="graphene-sqlalchemy",
            version="2.2.2",
            description="Graphene SQLAlchemy integration",
        ),
        Result(
            name="SQLAlchemy-UTCDateTime",
            version="1.0.4",
            description=(
                "Convert to/from timezone aware datetimes when storing in a DBMS"
            ),
        ),
        Result(
            name="paginate_sqlalchemy",
            version="0.3.0",
            description="Extension to paginate.Page that supports SQLAlchemy queries",
        ),
        Result(
            name="sqlalchemy_audit",
            version="0.1.0",
            description=(
                "sqlalchemy-audit provides an easy way to set up revision "
                "tracking for your data."
            ),
        ),
        Result(
            name="transmogrify.sqlalchemy",
            version="1.0.2",
            description="Feed data from SQLAlchemy into a transmogrifier pipeline",
        ),
        Result(
            name="sqlalchemy_schemadisplay",
            version="1.3",
            description="Turn SQLAlchemy DB Model into a graph",
        ),
        Result(name="sqlalchemy_traversal", version="0.5.2", description="UNKNOWN"),
        Result(
            name="sqlalchemy-filters",
            version="0.10.0",
            description="A library to filter SQLAlchemy queries.",
        ),
        Result(
            name="SQLAlchemy-wrap",
            version="2.1.7",
            description="Python wrapper for the CircleCI API",
        ),
        Result(
            name="sqlalchemy-nav",
            version="0.0.2",
            description=(
                "SQLAlchemy-Nav provides SQLAlchemy Mixins for creating "
                "navigation bars compatible with Bootstrap"
            ),
        ),
        Result(
            name="sqlalchemy-repr",
            version="0.0.1",
            description="Automatically generates pretty repr of a SQLAlchemy model.",
        ),
        Result(
            name="sqlalchemy-diff",
            version="0.1.3",
            description="Compare two database schemas using sqlalchemy.",
        ),
        Result(
            name="SQLAlchemy-Equivalence",
            version="0.1.1",
            description=(
                "Provides natural equivalence support for SQLAlchemy "
                "declarative models."
            ),
        ),
        Result(
            name="Broadway-SQLAlchemy",
            version="0.0.1",
            description="A broadway extension wrapping Flask-SQLAlchemy",
        ),
        Result(
            name="jsonql-sqlalchemy",
            version="1.0.1",
            description="Simple JSON-Based CRUD Query Language for SQLAlchemy",
        ),
        Result(
            name="sqlalchemy-plus",
            version="0.2.0",
            description="Create Views and Materialized Views with SqlAlchemy",
        ),
        Result(
            name="CherryPy-SQLAlchemy",
            version="0.5.3",
            description="Use SQLAlchemy with CherryPy",
        ),
        Result(
            name="sqlalchemy_sqlany",
            version="1.0.3",
            description="SAP Sybase SQL Anywhere dialect for SQLAlchemy",
        ),
    ]


import xlrd,pymysql,time
from xlutils.copy import copy
import traceback
## ##读取目录下文件的第一页
##确文件的第六列跟第七列分别是离职与交接人的email
## ##
TIMEFORMAT="%Y-%m-%d %X"
data =xlrd.open_workbook('YW05-离职流程报表 (32).xls')
table = data.sheets()[0] ##通过索引顺序获取
##table = data.sheet_by_index(0) #通过索引顺序获取
##table =data.sheet_by_name(u'Sheet1')#通过名称获取 ##  获取整行和整列的值（数组）

try:
    ##测试环境and '@' in table.row_values(line)[9]
##        conn_online=pymysql.connect(host='****',user='****',passwd='****',db='****',port=3306,charset='utf8')
    ##线上环境
        conn_online=pymysql.connect(host='*******',user='****',passwd='****',db='****',port=3306,charset='utf8')
        cur_online=conn_online.cursor()#获取一个游标
##    cur_test=conn_test.cursor()
except  Exception as  e:
          print("发生异常",e)

for line in range(1,table.nrows):
    if table.row_values(line)[4] :
        quit_name =  table.row_values(line)[3]
        quit_email =  table.row_values(line)[5]
        jie_name = table.row_values(line)[6]
        jie_email = table.row_values(line)[7]

        try:
            sql_check_quit='select * from t_customer_aid_quit where quit_customer_email= "' +quit_email+'"'
            cur_online.execute(sql_check_quit)
            data=cur_online.fetchall()
            if len(data) != 0 and data:###处理已经离职过的数据
##                table.row_values(line)[13]='离职账号'+quit_email+'已经离过职';
##                wb = copy(table)
##                ws = wb.get_sheet(0)
##                ws.write(line,13,'离职账号'+quit_email+'  已经存在')
                sql_check_quit_2='select * from t_customer_aid where email= "' +jie_email+'"'
                cur_online.execute(sql_check_quit_2)
                data_2=cur_online.fetchall()
                if  len(data_2)==0:
                        print('接收人'+jie_email+' 不存在，未做离职处理')
                        continue
                if data_2 and data_2[0][7] ==3:
                    print('交接人'+data_2[0][2]+data_2[0][1]+'是分总，未做离职处理   ')
                    continue
                if data_2  and data_2[0][1] != jie_name:
                        if data_2[0][1] != jie_name+'1':
                            print('接收人：'+data_2[0][2]+':'+data_2[0][1]+'与 excel ：'+jie_email+':'+jie_name+' 姓名不一致!未做离职处理')
                            continue
                print("UPDATE t_customer_aid_quit SET  take_customer_id='"+str(data_2[0][0])+"', take_customer_name='"+data_2[0][1]+"', take_customer_email='"+data_2[0][2]+"',quit_time='"+time.strftime( TIMEFORMAT, time.localtime( ) )+"' ,account_process_status='0', relation_process_status='1', task_process_status='0' WHERE id='"+str(data[0][0])+"';")
                continue
##            sql_onlie1 ='select id,name,email from t_customer_aid where email="'+jie_email+'"'
##            status = cur_online.execute(sql_online1)
##            data=cur_online.fetchall()
##            if len(data) == 0:
##                 print('接收人账号'+jie_email +' 不存在')
##                 continue
###未离职处理
            sql_online ='select a.id,a.name,a.email,b.id,b.name,b.email,"0", "1", "0", "1",a.role from t_customer_aid a,(select id,name,email from t_customer_aid where email="'+jie_email+'") b  where a.email="'+quit_email+'"'
            status = cur_online.execute(sql_online)
            ##          print('sql_online: ')
            ##          print(sql_test)
            data=cur_online.fetchall()
            if len(data) == 0:
                print('接收人'+jie_email+' 或关闭助手人'+quit_email+' 不存在，未做离职处理')
                continue
            for d in data :
                if d[1] != quit_name:
                    print('关闭助手权限人：'+d[2]+':'+d[1]+'与 excel ：'+quit_email+':'+quit_name+' 姓名不一致')
                    continue
                if d[4] != jie_name:
                    print('接收人：'+d[4]+':'+d[5]+'与 excel ：'+jie_email+':'+jie_name+' 姓名不一致')
                    continue
##                if d[10] == 3:
##                        sql_online = ''
##                        if
##                    print('交接人'+d[4]+':'+d[5]+'是分总，未做离职处理   ')
##                    continue
                sql_test='insert into t_customer_aid_quit(quit_customer_id,quit_customer_name,quit_customer_email,take_customer_id,take_customer_name,take_customer_email,quit_time,account_process_status,relation_process_status,task_process_status,create_time,state) '
                sql_test +='values("'+str(d[0])+'","'+str(d[1])+'","'+str(d[2])+'","'+str(d[3])+'","'+str(d[4])+'","'+str(d[5])+'","'+\
                time.strftime( TIMEFORMAT, time.localtime( ) )+'","'+str(d[6])+'","'+str(d[7])+'","'+str(d[8])+'","'+time.strftime( TIMEFORMAT, time.localtime( ) )+'","'+str(d[9])+'")'
                ##              cur_test.execute(sql_test)
                ##              conn_test.commit()
                ##              print('sql_test: ')
                print(sql_test+';')
        except  Exception as  e:
            print("发生异常",e)
            traceback.print_exc()
    else:
        print("email没有@")

cur_online .close()#关闭游标
##cur_test.close()
conn_online.close()#释放数据库资源
##conn_test.close()
print("总计数量："+str(line))

##print(table.col_values(1))


from django.shortcuts import render
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import joblib
from sklearn.linear_model import LogisticRegression
from sklearn.ensemble import BaggingClassifier
from sklearn.preprocessing import LabelEncoder, MinMaxScaler
from sklearn.svm import SVC
# # Create your views here
#
def index(request):
    return render(request, 'home.html')

def text_uppercase(text):
    return text.upper()

def baglogr_prediction(col1,col2,col3,col4,col5,col6,col7,col8,col9,col10,col11):
    filename = 'classification/models/baggingClass_jb.aiml'
    loaded_model_v2 = joblib.load(filename)
    predictrun = [[int(col1),int(col2),int(col3),int(col4),int(col5),int(col6),int(col7),int(col8),int(col9),float(col10),int(col11)]]
    predicted = loaded_model_v2.predict(predictrun)
    return predicted

def classification(request):

    form_posted = False
    dictsdia = {0: "Subject has a normal heart.", 1: "Subject has a high probability of having a disease."}
    map_sex={'F': 0, 'M': 1}
    map_cpt={"ASY": 0, "ATA": 1, "NAP": 2, "TA": 3}
    map_recg={"LVH": 0, "NORMAL": 1, "ST": 2}
    map_ea={'N': 0, 'Y': 1}
    map_sts={"DOWN": 0, "FLAT": 1, "UP": 2}

    if request.method == 'POST':

        form_posted = True

        col1 = request.POST['age']
        col2 = text_uppercase(request.POST['sex'])
        col3 = text_uppercase(request.POST['cpt'])
        col4 = request.POST['rbp']
        col5 = request.POST['chol']
        col6 = request.POST['fbs']
        col7 = text_uppercase(request.POST['recg'])
        col8 = request.POST['mhr']
        col9 = text_uppercase(request.POST['ea'])
        col10 = request.POST['op']
        col11 = text_uppercase(request.POST['sts'])

        col2 = map_sex[col2[0]]
        col3 = map_cpt[col3]
        col7 = map_recg[col7]

        col9 = map_ea[col9[0]]
        col11 = map_sts[col11]

    else:
        col1 = None
        col2 = None
        col3 = None
        col4 = None
        col5 = None
        col6 = None
        col7 = None
        col8 = None
        col9 = None
        col10 = None
        col11 = None

    if form_posted:
        predicted = baglogr_prediction(col1,col2,col3,col4,col5,col6,col7,col8,col9,col10,col11)
        predicted = dictsdia[predicted[0]]

    context = {
        "is_posted": form_posted,
        'prediction' : 'None' if form_posted is False else predicted,
        "col1": col1,
        "col2": col2,
        "col3": col3,
        "col4": col4,
        "col5": col5,
        "col6": col6,
        "col7": col7,
        "col8": col8,
        "col9": col9,
        "col10": col10,
        "col11": col11
    }

    return render(request, 'dave.html', context)

def bike_input(request):

    return render(request, 'bikeinput.html')

def bike_output(request):
    # Get the text

    seasontext = request.GET.get('season')
    mnthtext = request.GET.get('mnth')
    holitext = request.GET.get('holiday')
    weekdtext = request.GET.get('weekday')
    weasittext = request.GET.get('weathersit')
    temptext = request.GET.get('temp')
    atemptext = request.GET.get('atemp')
    humtext =  request.GET.get('hum')
    wndspdtext  = request.GET.get('windspeed')

    sea = int(seasontext)
    mnth = int(mnthtext)
    holiday = int(holitext)
    weekday = int(weekdtext)
    weathersit = int(weasittext)
    temp = float(temptext)
    atemp = float(atemptext)
    hum = float(humtext)
    windspeed = float(wndspdtext)
    filename = 'classification/models/bike_model.aiml'
    loaded_model_v2 = joblib.load(filename)
    sampletest = [[sea, mnth, holiday, weekday, weathersit, temp, atemp, hum, windspeed]]
    predicted = loaded_model_v2.predict(sampletest)

    params = {'Category': round(predicted[0])}
    return render(request, 'bike.html', params)


from django.contrib.auth.models import User
from django.shortcuts import render, HttpResponse, redirect
# Create your views here.
from blog.forms import PostCreatForm, PostModifyForm
from blog.models import Post

def main_view(request):
    posts = Post.objects.order_by('-created_date')
    context = {
        'posts':posts
    }
    return render(request,'post/post-list.html' ,context=context)

def post_add_view(request):
    if request.method == "GET":
        form = PostCreatForm()
        context = {
            'form': form
        }
        return render(request, 'post/post-add.html', context=context)

    elif request.method == "POST":
        form = PostCreatForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data['title']
            text = form.cleaned_data['text']
            user = User.objects.first().id
            Post.objects.create(author_id=user,title = title, text = text)
            return redirect('main_view')
        else:
            context = {
                'form':form,
            }
            return render(request, 'post/post-add.html',context=context)

def post_modify_view(request,pk):
    post = Post.objects.get(id=pk)
    if request.method == "GET":
        form = PostModifyForm(initial={'title': post.title, 'text':post.text})
        context = {
            'form': form
        }
        return render(request, 'post/post-modify.html', context=context)

    elif request.method == "POST":
        form = PostModifyForm(request.POST)
        if form.is_valid():
            title = form.cleaned_data['title']
            text = form.cleaned_data['text']
            post.title=title
            post.text=text
            post.save()
            return redirect('main_view')
        else:
            context = {
                'form':form,
            }
            return render(request, 'post/post-modify.html',context=context)


from functions import *
from generator import *
from mainGUI import *
from PyQt5.QtGui     import *
from PyQt5.QtWidgets import *
from PyQt5.QtCore    import *
import sys

import os
import re

class MyWin(QtWidgets.QMainWindow):
	def __init__(self, parent=None):
		QtWidgets.QWidget.__init__(self, parent)
		self.ui = Ui_MainWindow()
		self.ui.setupUi(self)

		shortcut = QShortcut(QKeySequence("Ctrl+Return"), self)
		shortcut.activated.connect(self.ui.ProcessPushButton.click)

		self.Pattern = ''
		self.TestString = ''

		self.ui.ProcessPushButton.clicked.connect(self.PatternChanged)

		self.ui.RegexTextEdit.installEventFilter(self)

		self.ui.SheetDockWidget.hide()
		self.ui.RegexSheetPushButton.clicked.connect(self.Sheet)
		self.SheetFlag = False
		self.ui.CodeGeneratorPushButton.clicked.connect(self.CodeGenerator)
		self.ui.AboutPushButton.hide()

		self.ResultWidget = None
		self.horizontalLayout_4 = None
		self.ResultTag = None
		self.ResultRange = None
		self.ResultText = None
		self.Info = []
		self.Match = []

		self.ui.NoMatchesLabel.hide()

		self.resize(800, 600)

		self.WindowWidthFlag = 0
		self.WindowHeightFlag = 0

		self.ColorList = ['rgb(198, 227, 255)','rgb(198, 233, 157)','rgb(245, 171, 165)','rgb(255, 191, 109)','rgb(193, 203, 235)','rgb(215, 253, 227)','rgb(227, 255, 172)','rgb(232, 141, 238)','rgb(207, 221, 103)','rgb(255, 172, 192)','rgb(132, 214, 238)']

		self.GeneratedCode = Ui_MainWindow()

	def UpdateInfo(self):
		'''Visual display of search results'''
		for i, v in enumerate(self.Info):
			if 'Full match' in v[0]:
				FullMatchTagUI(self.ui.scrollAreaWidgetContents, self.ui.verticalLayout_5, v[0])
				color = self.ColorList[0]
			else:
				color = GenerateGroupColor(self.ColorList, v[0])
			InfoUI(self.ResultWidget, self.horizontalLayout_4, self.ResultTag, self.ResultRange, self.ResultText, i, color, self.ui.scrollAreaWidgetContents, self.ui.verticalLayout_5, v)
		SpacerItem = QtWidgets.QSpacerItem(20, 40, QtWidgets.QSizePolicy.Maximum, QtWidgets.QSizePolicy.Expanding)
		self.ui.verticalLayout_5.addItem(SpacerItem)
	def eventFilter(self, obj, event):
		if obj is self.ui.RegexTextEdit and event.type() == QEvent.KeyPress:
			if event.key() in (Qt.Key_Return, Qt.Key_Enter):
				self.PatternChanged()
				return True
		return super().eventFilter(obj, event)
	def PatternChanged(self):
		'''Search for test text based on a pattern and display the results'''
		clearLayout(self.ui.verticalLayout_5)
		self.Info = []
		self.Pattern = self.ui.RegexTextEdit.toPlainText()
		self.TestString = self.ui.TestStringTextEdit.toPlainText()
		self.Info = Process(self.TestString, self.Pattern, self.Info, self.ui.NoMatchesLabel)
		self.ResultWidget, self.horizontalLayout_4, self.ResultTag, self.ResultRange, self.ResultText = PreprocessInfo(self.Info)
		self.UpdateInfo()
		ClearHighlight(self.ui.TestStringTextEdit, self.TestString)
		for k, v in enumerate(self.Info):
			hrange = HighlightRange(v[1])
			if 'Full match' in v[0]:
				Highlight(self.ui.TestStringTextEdit, QColor(198, 227, 255), hrange[0], hrange[1])
			else:
				color = GenerateGroupColor(self.ColorList, v[0])
				r, g, b = strColorTolist(color)
				Highlight(self.ui.TestStringTextEdit, QColor(r,g,b), hrange[0], hrange[1])

	def Sheet(self):
		'''Display regular expression cheat sheet'''
		if not self.SheetFlag:
			self.WindowWidthFlag = self.width()
			self.WindowHeightFlag = self.height()
			self.ui.SheetDockWidget.show()
			self.SheetFlag = True
		elif self.SheetFlag:
			self.ui.SheetDockWidget.close()
			self.adjustSize()
			self.resize(self.WindowWidthFlag,self.WindowHeightFlag)
			self.SheetFlag = False

	def CodeGenerator(self):
		'''The code for Python regular expression is generated in a new window'''
		if not self.Pattern or not self.TestString:
			self.ui.NoMatchesLabel.show()
		else:
			self.CodeGeneratorWindow = QtWidgets.QMainWindow()
			self.gen_ui = Ui_CodeGenerator()
			self.gen_ui.setupUi(self.CodeGeneratorWindow)
			GetCode(self.gen_ui.textEdit, self.Pattern, self.TestString)
			self.CodeGeneratorWindow.show()

if __name__ == '__main__':
	app = QtWidgets.QApplication(sys.argv)
	myapp = MyWin()
	myapp.show()
	sys.exit(app.exec_())


class BoxCompany:
    dim = None
    cap = None
    price = None

    def __init__(self, dim, cap, price):
        self.dim = dim
        self.cap = cap
        self.price = price
        self.color = "Gree"

    def store_acce(self):
        self.acc = "Books"

me = BoxCompany("20x20", "30L", "$3.5")
me.store_acce()

friend = BoxCompany("40x40", "50L", "$5")
friend.store_acce()

print(me.dim, me.cap, me.price,me.acc)
print(friend.dim, friend.cap, friend.price,friend.acc)


import os
from PIL import Image, UnidentifiedImageError
from random import choice
from string import ascii_lowercase, ascii_uppercase

from django.core.files.uploadedfile import InMemoryUploadedFile

from mempage.settings import IMAGES_DIR
from .models import Post

def random_string(length: int):
    pool = ascii_lowercase + ascii_uppercase + "-_~!$&'()+,;=@"
    return ''.join([choice(pool) for _ in range(length)])

def is_image(file_path):
    try:
        t = Image.open(file_path)
        t.verify()
    except UnidentifiedImageError:
        return False
    return True

def name_save_file(file: InMemoryUploadedFile) -> str:
    """
    Saves a file using a random name and returns the name
    """
    file_extension = file.name.split('.')[-1]
    target_file_name = '.' + file_extension
    target_file_name = random_string(20 - len(target_file_name)) + target_file_name
    with open(
            os.path.join(IMAGES_DIR, target_file_name),
            'wb+'
    ) as destination:
        for chunk in file.chunks():
            destination.write(chunk)

    return target_file_name

def remove_post(post: Post):
    try:
        os.rename(
            os.path.join(IMAGES_DIR, post.image),
            os.path.join(IMAGES_DIR, 'removed', post.image)
        )
    except FileNotFoundError:
        pass
    post.delete()


from infographicsLoader.infographicsLoader import *

import cv2
from glob import glob
import os
import numpy as np
import re
import shutil

import logging
logger = logging.getLogger('stageRemoveTextIconIndex')
logger.setLevel(logging.DEBUG)
logging.disable(logging.DEBUG)  # the flag
# if logger.isEnabledFor(logging.DEBUG):  # for block

inx = 0
def rm_text_icon_index_in_bb(img, datacomponent):
    tl_i, tl_j, br_i, br_j = datacomponent.conner["tl_i"], datacomponent.conner["tl_j"], datacomponent.conner["br_i"], datacomponent.conner["br_j"],
    bg_color = datacomponent.colors["bg_color"]
    bg_color = tuple([int(x) for x in bg_color])

    bb_content = img[tl_i:br_i, tl_j:br_j]

    # ----- remove text/icon/index ----- #
    gray = cv2.cvtColor(bb_content, cv2.COLOR_BGR2GRAY)

    gray_threshold = cv2.threshold(gray,0,255,cv2.THRESH_BINARY+cv2.THRESH_OTSU)[1]

    uni, fre = np.unique(gray_threshold, return_counts=1)
    uni = [u[0] for u in sorted(zip(uni,fre), key = lambda x:x[1])]
    if len(uni) > 1 and uni[0] < uni[1]:
        gray_threshold = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)[1]

    ## dilation
    dilate_kernel = cv2.getStructuringElement(cv2.MORPH_RECT, (3, 3))
    dilate = cv2.dilate(gray_threshold, dilate_kernel, iterations=1)

    ## replace color

    bg_dilate = cv2.dilate(dilate, dilate_kernel, iterations=1)
    bg_dilate[dilate == 255] = 0 # outer dilation removing the small dilation
    near_bg_color = np.mean(bb_content[bg_dilate == 255], axis=0).astype('uint8')
    bb_content[dilate == 255] = near_bg_color

    ## smooth, making it more similar to near colors
    for i in range(10):
        bb_content = cv2.medianBlur(bb_content, 5)

    img[tl_i:br_i, tl_j:br_j] = bb_content

    if logger.isEnabledFor(logging.DEBUG):
        global inx
        cv2.imwrite("rm_tii_debug/{}.png".format(inx), np.vstack((gray, gray_threshold, dilate)))
        inx = inx + 1

    return img

# API
def remove_text_icon_index_from_image(img_file_name, bb_file_name, mode):
    img = cv2.imread(img_file_name)

    # try:
    if mode == "4300_infographics":
        infographics_data_components = constructDataComponents(img_file_name, bb_file_name)
    else:
        infographics_data_components = constructDataComponentsForTimelineFormat(img_file_name, bb_file_name)
    for key, values in infographics_data_components.items():
        if mode == "all_infographics":
            if key in ["event_mark", "annotation_mark", "main_body"]:
                continue
        for curDTComp in values:
            img = rm_text_icon_index_in_bb(img, curDTComp)

    return img, infographics_data_components

if __name__ == "__main__":
    # mode = "4300_infographics"
    mode = "all_infographics"
    data_root = DATA_ROOT if mode == "4300_infographics" else DATA_ROOT_2

    finish_removing_folder = os.path.join(data_root, REMOVED_TEXT_ICON_INDEX_FOLDER)

    if not os.path.exists(finish_removing_folder):
        os.makedirs(finish_removing_folder)

    info_files = sorted(glob(os.path.join(data_root, BOUNDING_BOX_FOLDER, "*.txt")))
    for img_file_name in info_files:
        file_sequence_order = re.findall(r'\d+', img_file_name.split('/')[-1])[0]
        file_sequence_order = str(file_sequence_order)
        img_file_name = os.path.join(data_root, INFOGRAPHICS_FOLDER, file_sequence_order+".jpg")
        bb_file_name = os.path.join(data_root, BOUNDING_BOX_FOLDER, file_sequence_order+".txt")

        if os.path.exists(os.path.join(finish_removing_folder, file_sequence_order + ".jpg")):
            logger.debug("skip " + file_sequence_order)
            continue

        try:
            img,_ = remove_text_icon_index_from_image(img_file_name, bb_file_name, mode)
            cv2.imwrite(os.path.join(finish_removing_folder, file_sequence_order + ".jpg"), img)
        except:
            print(file_sequence_order)


import argparse
import numpy as np
from Phase2.Modules import VisDescParser as vd

def parse_args_process():
    argument_parse = argparse.ArgumentParser()
    argument_parse.add_argument('--dim_red_algo', help='The model you want to use(PCA/SVD/LDA)', type=str, required=True,
                                choices=['PCA', 'SVD', 'LDA'])
    argument_parse.add_argument('--k', help='The number semantics you want to find', type=int, required=True)
    argument_parse.add_argument('--loc_id', help='Enter the location id -', type=str, required=True,
                                )
    argument_parse.add_argument('--vis_model', help='Enter the Visual descriptor model -', type=str, required=True,
                                )
    args = argument_parse.parse_args()
    return args

def clean_ouput():
    f = open("task4output.txt", "w+")
    f.close()

def write_output(line):
    f = open("task4output.txt", "a+")
    f.write(line+"\n")
    f.close()

def print_output(result , locInKSem, KSemInFet):
    write_output("Input :"+str(args))
    write_output("Location in K semantics")
    for sem in locInKSem:
        write_output(np.array2string(sem))
    write_output("K semantics in features")
    for fet in KSemInFet:
        write_output(np.array2string(fet))
    write_output("Top K locations")
    for locId in result:
        write_output(str(locId))

# Main starts here
clean_ouput()
args = parse_args_process()
obj = vd.VisDescParser()
result , locInKSem, KSemInFet = obj.getTask4Items(args.dim_red_algo, args.k, args.loc_id, args.vis_model ,5)
print_output(result , locInKSem, KSemInFet)


from cStringIO import StringIO
import json
import unittest

from etl import __main__ as main

from fixtures import TEST_CONTRIBUTIONS_LIST

class TestMain(unittest.TestCase):
    pass

    def test_main_module(self):

        input_file = StringIO(TEST_CONTRIBUTIONS_LIST)
        output_file = StringIO()
        main.main(input_file, output_file)

        output_file.seek(0)
        output = [
            json.loads(row)
            for row in output_file.readlines()
        ]

        excepted = [
            {"Contribution Date": "2/2/2004", "Contributor Name": "Inc, Caldera   Management", "Contributor Address": "4260 Hwy 1, Rehoboth, DE 19971"},
            {"Contribution Date": "9/22/2004", "Contributor Name": "Conset-vancy/LLC, Rehoboth   Bay", "Contributor Address": "1207 Delaware AveWilinin too/DE 19806, DE"},
            {"Contribution Date": "9/17/2004", "Contributor Name": "lingua, James.A", "Contributor Address": "28 The Circle.Georgetown/DE 19947, DE"}
        ]

        self.assertEqual(output, excepted)


class Offer:
    """Class representing an offer with its attributes and methods."""

    def __init__(self, name: str, profit: float, budget_needed: float, time_needed: int):
        self.name = name
        self.profit = profit
        self.budget_needed = budget_needed
        self.time_needed = time_needed
        self.roi = (profit / budget_needed) * 100

    # OVERLOADING METHODS
    # toString
    def __str__(self):
        return f"Name: {self.name}\nProfit: {self.profit}€\nBudget needed:{self.budget_needed}€\nROI: {self.roi}%\nTime needed: {self.time_needed}(days)"

    def __eq__(self, other: object) -> bool:
        if not isinstance(other, Offer):
            return False
        return (self.name == other.name and
                self.profit == other.profit and
                self.budget_needed == other.budget_needed and
                self.time_needed == other.time_needed)

    # GETTERS AND SETTERS
    @property
    def name(self):
        return self.__name

    @name.setter
    def name(self, value):
        if not isinstance(value, str):
            raise Exception("Bookmaker must be a string.")
        if value == '':
            raise Exception("Bookmaker cannot be empty.")
        if value == None:
            raise Exception("Bookmaker cannot be None.")
        self.__name = value.capitalize()

    @property
    def profit(self):
        return self.__profit

    @profit.setter
    def profit(self, value):
        value_name = "Profit"
        if not isinstance(value, (int, float)):
            raise Exception(f"{value_name} must be a float.")
        if isinstance(value, bool):
            raise Exception(f"{value_name} cannot be a boolean.")
        if value == "":
            raise Exception(f"{value_name} cannot be empty.")
        if value == None:
            raise Exception(f"{value_name} cannot be None.")
        if value < 0:
            raise Exception(f"{value_name} cannot be negative.")
        self.__profit = value

    @property
    def budget_needed(self):
        return self.__budget_needed

    @budget_needed.setter
    def budget_needed(self, value):
        value_name = "Budget needed"
        if not isinstance(value, (int, float)):
            raise Exception(f"{value_name} must be a float.")
        if isinstance(value, bool):
            raise Exception(f"{value_name} cannot be a boolean.")
        if value == "":
            raise Exception(f"{value_name} cannot be empty.")
        if value == None:
            raise Exception(f"{value_name} cannot be None.")
        if value < 0:
            raise Exception(f"{value_name} cannot be negative.")
        self.__budget_needed = value

    @property
    def time_needed(self):
        return self.__time_needed

    @time_needed.setter
    def time_needed(self, value):
        value_name = "Time needed"
        if not isinstance(value, int):
            raise Exception(f"{value_name} must be a float.")
        if isinstance(value, bool):
            raise Exception(f"{value_name} cannot be a boolean.")
        if value == "":
            raise Exception(f"{value_name} cannot be empty.")
        if value == None:
            raise Exception(f"{value_name} cannot be None.")
        if value < 0:
            raise Exception(f"{value_name} cannot be negative.")
        self.__time_needed = value


l=list(input())
width=len(l)
while width>1:
    index=0
    while index+width<=len(l):
        if len(list(set(l[index:index+width])))==width:
            print(width)
            index=-1
            break
        index+=1
    if index==-1:
        break
    width-=1
else:
    print(width)


from random import randint

# From a FreeCodeCamp Youtube tutorial

def guess(x):
    ran_num = randint(1, x)
    user_guess = 0
    turn = 0
    while turn < 5:
        user_guess = int(input(f"Guess a number between 1 and {x}: "))
        if user_guess > x:
            print("That's higher than the boundary, dummy. You lose automatically.")
            turn += 6
            break
        if user_guess < ran_num:
            turn += 1
            print("Wrong! You guessed too low.")
            print("You have " + str(5 - turn) + " guesses left.")
            print()
        elif user_guess > ran_num:
            turn += 1
            print("Wrong! You guessed too high.")
            print("You have " + str(5 - turn) + " guesses left.")
            print()
        else:
            print(f"Correct!! The answer was: {ran_num}")
            turn += 6
            break
    else:
        print(f"You're out of guesses! You lose. It was {ran_num}")


"""
[5,2,9,8,4]
[[0,1],[1,2],[2,3],[0,2],[1,3],[2,4]]

[9,20,6,4,11,12]
[[0,3],[5,3],[2,4],[1,3]]

[16,14,9,16,25,22]
[[1,0],[0,2],[2,3],[4,3]]

[2,1,8,2,6,8]
[[0,4],[0,5],[1,4],[4,3],[1,2],[1,0],[2,3]]
"""
import heapq

class Solution:
    def maximumScore(self, scores: List[int], edges: List[List[int]]) -> int:
        n = len(scores)
        g = [[] for _ in range(n)]
        for edge in edges:
            heapq.heappush(g[edge[0]], (-scores[edge[1]], edge[1]))
            heapq.heappush(g[edge[1]], (-scores[edge[0]], edge[0]))

        result = -1

        for node_a, node_b in edges:
            for node_x, node_y in [(node_a, node_b), (node_b, node_a)]:
                # print(node_a, node_b)
                node_c = self.findNode(g, node_x, {node_a, node_b})
                if node_c is not None:
                    node_d = self.findNode(g, node_y, {node_a, node_b, node_c})
                    if node_d is not None:
                        # print( [node_a, node_b, node_c, node_d])
                        # print(g)
                        result = max(result, sum([scores[i] for i in [node_a, node_b, node_c, node_d]]))

        return result

    def findNode(self, g, node, selected):
        backup = []
        while g[node] and g[node][0][1] in selected:
            backup.append(heapq.heappop(g[node]))
        result = None
        if g[node]:
            result = g[node][0][1]
        while backup:
            heapq.heappush(g[node], backup.pop())

        # print(result, node, selected)
        return result


import cv2
import numpy as np
from cv2 import aruco
import camara

DICCIONARIO = aruco.getPredefinedDictionary(aruco.DICT_5X5_50)
lena = cv2.imread("opencv/lena.tif")
h, w, _ = lena.shape

vlena = np.array([[0,0],[w,0],[w,h],[0,h]])

cap = cv2.VideoCapture(0)

if not cap.isOpened():
    print("No se puede abrir la cámara")
    exit()
while True:
    ret, frame = cap.read()

    if not ret:
        print("No he podido leer el frame")
        break

    gris = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
    bboxs, ids, rechazados = aruco.detectMarkers(gris, DICCIONARIO)

    if(ids is not None):
        aruco.drawDetectedMarkers(frame, bboxs, ids)
        for i in range(len(ids)):
            vertices = bboxs[i][0].astype(int)

            cv2.putText(frame, str(ids[i][0]), vertices[1], cv2.FONT_HERSHEY_SIMPLEX, 1, (0,0,0), 2)

            matriz, _ = cv2.findHomography(vlena, vertices)
            warplena = cv2.warpPerspective(lena, matriz, (frame.shape[1], frame.shape[0]))

            #cv2.fillConvexPoly(frame, vertices, (0,0,0))
            #frame = frame + warplena

    cv2.imshow('WEBCAM', frame)

    if cv2.waitKey(1) == ord(' '):
        break

cap.release()
cv2.destroyWindow('WEBCAM')


from mv3d import config
from mv3d.dsets import scenelists
from mv3d.dsets import frameselector
from mv3d.dsets import dataset
from mv3d.eval import tsdf_atlas
import os
import numpy as np
import glob
import tqdm
import json
import cv2
import torch
from scipy.spatial.transform.rotation import Rotation
import open3d as o3d

K = np.array([[525.0, 0.0, 320.0],
              [0.0, 525.0, 240.0],
              [0.0, 0.0, 1.0]])
IMG_BATCH = 20

# Volumetric-based 3D options
VOX_RES = 0.02
VOL_PRCNT = .995
VOL_MARGIN = 1.5
TRUNC_RATIO = 3

def get_projection_matrices(K, poses):
    n_imgs = poses.shape[0]
    zeros = torch.zeros((n_imgs, 3, 1)).type_as(K)  # append a column of 0s to camera intrinsics
    K = torch.cat((K, zeros), dim=2)
    P = torch.bmm(K, poses)
    return P

def depth_projection_batched(depth, P):
    h, w = depth.shape[-2:]
    n_imgs = depth.shape[0]

    pts_y = torch.arange(h).type_as(depth)
    pts_x = torch.arange(w).type_as(depth)
    pts_yy, pts_xx = torch.meshgrid(pts_y, pts_x)
    pts_zz = torch.ones_like(pts_xx)

    pts_H = torch.stack((pts_xx, pts_yy, pts_zz), dim=0)
    pts_H = pts_H.unsqueeze(0).repeat(n_imgs, 1, 1, 1)

    pts_ww = 1. / depth.unsqueeze(1)
    pts_H = torch.cat((pts_H, pts_ww), dim=1)

    # add [0, 0, 0, 1] row to projection matrix to make 4x4
    eye_row = torch.tensor([[0, 0, 0, 1]]).unsqueeze(0).repeat(n_imgs, 1, 1).type_as(P)
    P = torch.cat((P, eye_row), dim=1)
    P_inv = P.inverse()

    pts_H = torch.bmm(P_inv, pts_H.view(n_imgs, 4, h*w))
    pts = pts_H[:, :3] / pts_H[:, 3:]

    return pts.transpose(2, 1)

def generate_gt_mesh(scene, max_depth=None):
    # get frames for trimming mesh
    selector = frameselector.EveryNthSelector(1)
    dset = dataset.Dataset([scene, ], selector, IMG_BATCH, (480, 640), (480, 640), False, scale_rgb=1.,
                           mean_rgb=[0., 0., 0.], std_rgb=[1., 1., 1.], crop=False, n_src_on_either_side=0)
    n_imgs = len(json.load(open(os.path.join(scene, 'info.json'), 'r'))['frames'])
    n_batches = (n_imgs - 1) // IMG_BATCH + 1

    # first, run through to get vol bounds
    origin = None
    vol_max = None
    for i in range(n_batches):
        batch, _, _, img_idx = dset.get(0, seed_idx=i * IMG_BATCH, return_verbose=True)
        poses = torch.cat((batch.rotmats, batch.tvecs.unsqueeze(2)), dim=2)
        eye_row = torch.tensor([[[0., 0., 0., 1.]]]).repeat(poses.shape[0], 1, 1)
        poses = torch.cat((poses, eye_row), dim=1)

        # mask out large depth values if necessary
        if max_depth is not None:
            batch.depth_images[batch.depth_images > 4.] = 0.

        P = get_projection_matrices(batch.K, poses).cuda()
        pts = depth_projection_batched(batch.depth_images.cuda(), P)
        pts = pts.reshape(-1, 3)
        pts = pts[~torch.any(torch.isnan(pts), dim=1)]  # avoid any div/0s in projection step
        pts = pts.cpu().numpy()
        if pts.shape[0] == 0:  # avoid any fully 0 depth maps from cut off reconstruction
            continue

        # use top and bottom vol_prcnt of points plus vol_margin
        origin_batch = torch.as_tensor(np.quantile(pts, 1 - VOL_PRCNT, axis=0) - VOL_MARGIN).float()
        vol_max_batch = torch.as_tensor(np.quantile(pts, VOL_PRCNT, axis=0) + VOL_MARGIN).float()

        if origin is None:
            origin = origin_batch
        else:
            origin = torch.min(torch.stack((origin, origin_batch), dim=0), dim=0)[0]

        if vol_max is None:
            vol_max = vol_max_batch
        else:
            vol_max = torch.max(torch.stack((vol_max, vol_max_batch), dim=0), dim=0)[0]
    vol_dim = ((vol_max - origin) / VOX_RES).int().tolist()

    # re-run through dset for tsdf fusion step
    tsdf_fusion = tsdf_atlas.TSDFFusion(vol_dim, VOX_RES, origin, TRUNC_RATIO, torch.device('cuda'),
                                        label=False)
    for i in range(n_batches):
        batch, _, _, img_idx = dset.get(0, seed_idx=i * IMG_BATCH, return_verbose=True)

        poses = torch.cat((batch.rotmats, batch.tvecs.unsqueeze(2)), dim=2)
        eye_row = torch.tensor([[[0., 0., 0., 1.]]]).repeat(poses.shape[0], 1, 1)
        poses = torch.cat((poses, eye_row), dim=1)

        P = get_projection_matrices(batch.K, poses).cuda()
        for i in range(batch.depth_images.shape[0]):
            projection = P[i]
            image = batch.images[i].cuda()
            depth = batch.depth_images[i]
            tsdf_fusion.integrate(projection, depth, image)

    tsdf = tsdf_fusion.get_tsdf()
    trimmed_mesh = tsdf.get_mesh()
    return trimmed_mesh

def get_closest_index(target_timestamp, other_timestamps):
    differences = np.abs(other_timestamps - target_timestamp)
    return np.argmin(differences)

def process_scene(scene, overwrite_depth=False, overwrite_mesh=False):
    depth_out_dir = os.path.join(scene, 'depth_processed')
    if not os.path.exists(depth_out_dir):
        os.makedirs(depth_out_dir)
    scene_name = os.path.basename(scene)
    gt_mesh_file = os.path.join(scene, 'gt_mesh.ply')

    data = {
        'scene': scene_name,
        'path': scene,
        'intrinsics': K.tolist(),
        'gt_mesh': gt_mesh_file,
        'frames': []
    }

    image_filenames = sorted(glob.glob(os.path.join(scene, 'rgb', '*.png')))
    image_timestamps = np.loadtxt(os.path.join(scene, 'rgb.txt'), usecols=0)

    depth_filenames = sorted(glob.glob(os.path.join(scene, 'depth', '*.png')))
    depth_timestamps = np.loadtxt(os.path.join(scene, 'depth.txt'), usecols=0)

    poses_with_quat = np.loadtxt(os.path.join(scene, 'groundtruth.txt'))
    pose_timestamps = poses_with_quat[:, 0]
    pose_locations = poses_with_quat[:, 1:4]
    pose_quaternions = poses_with_quat[:, 4:]

    for i in range(len(depth_filenames)):
        depth_timestamp = depth_timestamps[i]

        pose_index = get_closest_index(depth_timestamp, pose_timestamps)
        image_index = get_closest_index(depth_timestamp, image_timestamps)

        depth_filename_src = depth_filenames[i]
        depth_filename_dst = os.path.join(depth_out_dir, os.path.basename(depth_filename_src))
        image_filename = image_filenames[image_index]
        pose_location = pose_locations[pose_index]
        pose_quaternion = pose_quaternions[pose_index]
        rot = Rotation.from_quat(pose_quaternion).as_matrix()
        pose = np.eye(4)
        pose[0:3, 0:3] = rot
        pose[0:3, 3] = pose_location

        if not os.path.exists(depth_filename_dst) or overwrite_depth:
            depth = cv2.imread(depth_filename_src, -1).astype(np.float32) / 5000.
            depth[np.isnan(depth)] = 0.
            depth[np.isinf(depth)] = 0.
            depth = (depth * 1000.).astype(np.uint16)
            cv2.imwrite(depth_filename_dst, depth)

        frame = {
            'filename_color': image_filename,
            'filename_depth': depth_filename_dst,
            'pose': pose.tolist()
        }
        data['frames'].append(frame)
    json.dump(data, open(os.path.join(scene, 'info.json'), 'w'))

    if not os.path.exists(gt_mesh_file) or overwrite_mesh:
        gt_mesh = generate_gt_mesh(scene)
        o3d.io.write_triangle_mesh(gt_mesh_file, gt_mesh)
    return

if __name__ == '__main__':
    scenes = scenelists.get_scenes_tum_rgbd(config.TUM_RGBD_DIR)
    for scene in tqdm.tqdm(scenes):
        process_scene(scene)


from bokeh.plotting import figure, show
from bokeh.models import HoverTool
from cds_reader import source_para_vis_2, data_para_vis_2

quakers_aroma = figure(title="Quakers: Grãos imaturos prejudicam o aroma do café",
                       x_axis_label="Quakers",
                       y_axis_label="Nota do Aroma: 1 a 10",
                       width=513,
                       height=483
                       )

#Plotar os circulos
dados = source_para_vis_2(data_para_vis_2)
alpha = source_para_vis_2(data_para_vis_2).data['Alpha']

quakers_aroma.circle(source = dados, x='Quakers', y ='Aroma', fill_color='Blue',
                     line_color='Black',
                     fill_alpha = 'Alpha',
                     legend_label="Pontuação geral: Maior para menor, mais escuro para mais claro",
                     size=10
                     )

hover = HoverTool(tooltips=[("Quakers", "@Quakers"), ("Aroma", "@Aroma"), ("Pontuação Geral", "@Overall")])
quakers_aroma.add_tools(hover)

# Retirando logo do Bokeh
quakers_aroma.toolbar.logo = None

show(quakers_aroma)


import paho.mqtt.client as mqtt
import time
import json
import sys
import os

# set options
roomName = "Gallery/"
languages = ["EN", "NL"]
nrPlayers = [2, 3, 4, 5, 6, 7]
programs = [{"name": "60 minutes", "file": "new_program.json"}, {"name": "60 minutes old", "file": "program.json"}]
debug = True
# end of options

# standard settings
selectedProgram = programs[0]['file']
players = 4
lang = 'NL'

currentProgram = {}
status = "Aborted"
rem = 0
totalTime = 0
startTime = 0
path = os.path.realpath('.')
devicesList = os.path.join(path, 'devices.json')
devices = []

try:
    with open(devicesList) as devicesFile:
        devices = json.load(devicesFile)
except FileNotFoundError:
    print("ERROR: Unable to load devices file")
except json.decoder.JSONDecodeError:
    print("ERROR: Fault in devices JSON file")

client = None

def signal_handler():
    print("\nprogram exiting nice")
    sys.exit(0)

def run_program(prog):
    global currentProgram
    global client
    try:
        for item in currentProgram[prog]["set"]:
            if item['topic'] == "status" or item['topic'] == "time":
                # always true?
                client.publish(roomName + item['topic'], item['action'], 1, True)
            else:
                client.publish(roomName + item['topic'], item['action'], 1, False)
        currentProgram[prog]['played'] = True
        client.publish(roomName + "message", prog, 1, False)
    except KeyError:
        print("unable to set settings for program: " + prog)
        client.publish(roomName + "message", "ERROR: Unable to run program: " + prog, 1, False)
    try:
        # Queue programs which are triggered by this program and cancel programs which are cancelled by this program
        for key, value in currentProgram.items():
            if currentProgram[key].get('start') == prog:
                if not currentProgram[key].get('played'):
                    print(key + " triggered at " + str(rem - int(currentProgram[key]['after'])))
                    currentProgram[key]['time'] = (rem - int(currentProgram[key]['after']))
            if currentProgram[key].get('cancel') == prog:
                currentProgram[key]['played'] = True

    except KeyError:
        print("error in program")
        client.publish(roomName + "message", "ERROR: Unable to queue or cancel after: " + prog, 1, False)
    client.publish(roomName + "currentProgram", json.dumps(currentProgram), 1, True)

def pause_program(prog):
    global currentProgram
    try:
        currentProgram[prog]["played"] = True
        client.publish(roomName + "currentProgram", json.dumps(currentProgram), 1, True)
    except KeyError:
        print("unable to pause program: " + prog)

def main():
    global client
    global status
    global rem
    global currentProgram

    last_rem = 0

    # connect to MQTT broker
    client = mqtt.Client()
    client.on_connect = on_connect
    client.on_message = on_message
    client.connect("localhost", 1883, 60)
    client.loop_start()

    while True:
        if status == "Started":
            rem = int(totalTime - (time.time() - startTime))
            if rem != last_rem and rem > -1:
                client.publish(roomName + "time", rem, 1, True)
                last_rem = rem
            if rem < -20:
                status = "Aborted"
                run_program("end")
            for key, value in currentProgram.items():
                if currentProgram[key].get('time') is not None and currentProgram[key].get('time') >= rem and \
                        not currentProgram[key].get('played'):
                    run_program(key)
        time.sleep(0.1)

def on_connect(client, userdata, flags, rc):

    if debug:
        print("Connected with result code "+str(rc))

    client.publish(roomName + "programs", json.dumps(programs), 1, True)
    client.publish(roomName + "selectedProgram", selectedProgram, 1, True)
    client.publish(roomName + "players", players, 1, True)
    client.publish(roomName + "languages", ",".join(languages), 1, True)
    client.publish(roomName + "lang", lang, 1, True)
    client.publish(roomName + "status", status, 1, True)
    client.publish(roomName + "devices", json.dumps(devices), 1, True)
    client.subscribe(roomName + "#")

def on_message(client, userdata, msg):
    global currentProgram
    global selectedProgram
    global programs
    global rem
    global status
    global totalTime
    global startTime

    pay = msg.payload.decode("utf-8")

    if debug and msg.topic != roomName + "time" and msg.topic != roomName + "currentProgram":
        print("Received: " + msg.topic + " " + pay)

    if msg.topic[:len(roomName) + 10] == roomName + "runProgram":
        run_program(pay)
    elif msg.topic[:len(roomName) + 12] == roomName + "pauseProgram":
        pause_program(pay)
    elif msg.topic == roomName + "status":
        status = pay
        if pay == "Prepared":
            rem = totalTime
            client.publish(roomName + "selectedProgram", selectedProgram, 1, True)
        elif pay == "Started":
            startTime = time.time()
            totalTime = rem
    elif msg.topic == roomName + "totalTime":
        try:
            totalTime = int(pay)
            rem = totalTime
        except ValueError:
            print("ERROR: unable to set totalTime")
    elif msg.topic == roomName + "selectedProgram":
        prev_program = selectedProgram
        selectedProgram = pay
        # print(traceback.format_exc())
        try:
            program_file_path = os.path.join(path, selectedProgram)
            with open(program_file_path) as program_file:
                currentProgram = json.load(program_file)
                client.publish(roomName + "currentProgram", json.dumps(currentProgram), 1, True)
        except FileNotFoundError:
            client.publish(roomName + "message", "ERROR: Program file not found", 1, False)
            selectedProgram = prev_program
            print("ERROR: Program file not found")
        except json.decoder.JSONDecodeError:
            client.publish(roomName + "message", "ERROR: Fault in program json file", 1, False)
            selectedProgram = prev_program
            print("ERROR: Fault in Program JSON file")
    elif pay == "Disconnected":
        # Handle disconnect of devices
        try:
            for area in devices['areas']:
                for device in area['devices']:
                    if device['device'] == msg.topic:
                        client.publish(device['topic'], "", 1, True)
        except KeyError:
            print("ERROR: Unable to clean disconnect")

if __name__ == '__main__':
    main()


from django.http import HttpResponse
from django.http import HttpResponseRedirect
from django.template import loader
from django.db.models import Sum
from .models import Account, AccountList
from transfers.models import Transfer
from transactions.models import Transaction
from django.shortcuts import render
from .forms import GetDateForm
from datetime import date
import numpy as np

def index(request):
    account_balance_array=[]
    template = loader.get_template('accounts/index.html')
    all_accounts = Account.objects.all()

    print (all_accounts)
    get_accounts = Account.objects.all()
    #print (get_accounts)
    #for account_list in get_account_list:
    #    print (account_list.account_name)
    #    print (account_list.account_type)
    #    print (account_list.initial_balance)
    #    print (account_list.date)

    #for account in get_accounts:
    #    print ('-------------------')
    #    print (account.balance_desc)
    #    print (account.account_name)
    #    print (account.balance)
    #    print (account.balance_date)
    #    print ('------------------')

    total_cash = 0
    for account_list in get_account_list:

        #get account name, account type and balance date (today) to load into array
        account_name = account_list.account_name
        account_id = account_list.id

        print ('-----------------')
        print (account_name)
        print ('------------------')
        balance_date = Account.objects.filter(account_name=account).last()
        print (balance_date)

        #get all transactions for current account
        #account_transactions = Transaction.objects.filter(account_name=account.id, trans_date__lte=balance_date).aggregate(sum=Sum('amount'))['sum'] or 0.00
        #get the current account balance (at the moment this is just the initial balance - need to get all transactions from current day forward??)
        #account_balance = Account.objects.filter(account=account_id).last()
        #print (account_balance)
        #get any transfers (likely need to only get stuff from current balance date..otherwise this may mess up if we write a new balance)
       # account_incoming_transfers = Transfer.objects.filter(incoming_account__pk=account.id, transfer_date__lte=balance_date).aggregate(sum=Sum('transfer_amount'))['sum'] or 0.00
       # account_outgoing_transfers = Transfer.objects.filter(outgoing_account__pk=account.id, transfer_date__lte=balance_date).aggregate(sum=Sum('transfer_amount'))['sum'] or 0.00
        #calculate the new balance
        #new_account_balance = account_balance + account_transactions + account_incoming_transfers - account_outgoing_transfers

        #calculate cash position by summing the new balance of each account
        #total_cash = new_account_balance + total_cash
        #build the array for display
        #account_balance_array.append((account_name, account_balance, balance_date))
        print ('yo')
    #card_total_object = Account.objects.filter(account_type__contains="credit card").values('balance')
    #card_total = card_total_object[0]['balance']
    #other_account_total = Account.objects.exclude(account_type__contains="credit card").aggregate(sum=Sum('balance'))['sum'] or 0.00
    context = {
        'total_cash': total_cash,
        'account_balance_array' : account_balance_array    }
    return HttpResponse(template.render(context, request))

def detail(request, account_id):
    template = loader.get_template ('accounts/details.html')
    selected_account = Account.objects.filter(id=account_id).values('account_list')
    acct_name = selected_account[0]['account_list']
    trans_for_account_id = Transaction.objects.filter(account_list=1)
    transaction_total = Transaction.objects.filter(account_list=1).aggregate(sum=Sum('amount'))['sum'] or 0.00
    print (acct_name)
    context ={
        'acct_name': acct_name,
        'trans_for_account_id': trans_for_account_id,
        'transaction_total': transaction_total
    }
    return HttpResponse((template.render(context,request)))


__author__ = "Thai Thien"
__link__ = "https://app.codesignal.com/challenge/D7xcKDseTa2gLondg"

class Fighter:
    def __init__(self, hp, atk, res):
        self.hp = hp
        self.atk = atk
        self.res = res

    def hit(self, target):
        """
        hit the target
        :param target:
        :return:
        """
        dmg = self.atk - target.res
        if dmg < 0:
            dmg = 0
        target.hp -= dmg
        return dmg

    def is_alive(self):
        if self.hp > 0:
            return True

def make_fighter(code):
    """

    :param code: a b g
    :return:
    """
    if code == "a":
        return Fighter(5, 6, 2)
    elif code == "b":
        return Fighter(6, 8, 2)
    elif code == "g":
        return Fighter(8, 6, 5)

def format_avg_dmg(values):
    newer_method_string = "{:.2f}".format(values)
    return newer_method_string

class Profiler:
    def __init__(self):
        self.winner = ""
        self.fightersDefeated = 0
        self.fightersRemain = 0
        self.masterHealth = 0
        self.hitsByFighters = 0
        self.hitsByMaster = 0
        self.avgDamageDealtByFighters = 0
        self.avgDamageDealtByMaster = 0
        self.figterDmg = 0
        self.masterDmg = 0

    def to_return_arr(self):
        self.avgDamageDealtByFighters = format_avg_dmg(self.avgDamageDealtByFighters)
        self.avgDamageDealtByMaster = format_avg_dmg(self.avgDamageDealtByMaster)
        # if self.avgDamageDealtByFighters[-1] == '0':
        #     self.avgDamageDealtByFighters = self.avgDamageDealtByFighters[:-1]
        # if self.avgDamageDealtByMaster[-1] == '0':
        #     self.avgDamageDealtByMaster = self.avgDamageDealtByMaster[:-1]

        ret_list = []
        ret_list.append(str(self.winner))
        ret_list.append(str(self.fightersDefeated))
        ret_list.append(str(self.fightersRemain))
        ret_list.append(str(self.masterHealth))
        ret_list.append(str(self.hitsByFighters))
        ret_list.append(str(self.hitsByMaster))
        ret_list.append(str(self.avgDamageDealtByFighters))
        ret_list.append(str(self.avgDamageDealtByMaster))
        return ret_list

def duel(master, fighter, profiler):
    """
    master and another fighter is hitting each other
    :param master: a Fighter
    :param fighter: a Fighter
    :param profiler: stat
    :return: True if master win
    """
    while master.is_alive() and fighter.is_alive():
        if fighter.is_alive():
            fighter_dmg = fighter.hit(master)
            profiler.figterDmg += fighter_dmg
            profiler.hitsByFighters += 1

        if master.is_alive():
            master_dmg = master.hit(fighter)
            profiler.masterDmg += master_dmg
            profiler.hitsByMaster +=1
    if master.is_alive():
        return True
    else:
        return False

def the_epic_fight(master, list_of_fighter, profiler):
    """
    single master, duel 1-on-1 with each fighter
    :param master: a Fighter
    :param list_of_fighter: a Fighter
    :param profiler: stat
    :return: number of fighter remained
    """
    remained = 0

    for fighter in list_of_fighter:
        if not master.is_alive():
            remained += 1
            continue
        result = duel(master, fighter, profiler)
        if not result:
            remained += 1
        else:
            profiler.fightersDefeated += 1
    return remained

def round_avg(value):
    answer = round(value, 2)
    return answer

def masterVsFighters(fighters, master):
    list_of_fighter = []
    for fighter_code in fighters:
        fighter = make_fighter(fighter_code)
        list_of_fighter.append(fighter)
    master_fighter = Fighter(master[0], master[1], master[2])
    profiler = Profiler()
    remained = the_epic_fight(master_fighter, list_of_fighter, profiler)
    profiler.fightersRemain = remained

    if master_fighter.is_alive():
        profiler.masterHealth = master_fighter.hp
        profiler.winner = "Master"
    else:
        profiler.masterHealth = 0
        profiler.winner = "Fighters"

    if profiler.hitsByMaster != 0:
        profiler.avgDamageDealtByMaster = round_avg(profiler.masterDmg/profiler.hitsByMaster)
    else:
        profiler.avgDamageDealtByMaster = 0

    if profiler.hitsByFighters != 0:
        profiler.avgDamageDealtByFighters = round_avg(profiler.figterDmg/profiler.hitsByFighters)
    else:
        profiler.avgDamageDealtByFighters = 0

    return profiler.to_return_arr()

if __name__ == "__main__":
    fighters = ["a", "a", "b"]
    master = [14, 6, 4]
    result = masterVsFighters(fighters, master)
    print(result)


import easyocr
import cv2

reader = easyocr.Reader(['en', 'ko'])
def fn_get_text(path):
    img = cv2.imread(path, cv2.IMREAD_GRAYSCALE)
    height, width = img.shape
    result = reader.readtext(img)
    print(result)
    result_dataset = []
    for bbox, text, prob in result:
        if prob > 0.1:
            result_dataset.append({'text':text, 'bbox':bbox, 'prob':prob})
    for i, v in enumerate(result_dataset):
        print(v['text'], v['bbox'], v['prob'])
    draw_bbox(path, result_dataset)
def draw_bbox(path, data):
    img = cv2.imread(path)
    for d in data:
        bbox = d['bbox']
        start_point = (int(bbox[0][0]), int(bbox[0][1]))  # Convert to integers
        end_point = (int(bbox[2][0]), int(bbox[2][1]))  # Convert to integers
        #사각형 그리기
        color = (0, 255, 0)
        thinkness = 2
        img = cv2.rectangle(img, start_point, end_point, color, thinkness)
    cv2.imwrite('output.jpg', img)

if __name__ == '__main__':
    fn_get_text('text.jpg')


import pandas as pd

tabla=pd.read_csv('./Siembras.csv')

#tabla estadisticas
tablaEstadisticas=tabla.describe()

#solo obtener medias de la tabla estadistica (solo 1 fila)
tablaMedias=tablaEstadisticas.loc[['mean']]

#solo obtener los datos de una columna
tablaMediaArboles=tablaMedias["Arboles"].to_frame()


#!/usr/bin/env python3
import requests
import argparse
from typing import cast, Union, Any

def readSecret(secretPath):
    with open(secretPath) as f:
            mySecret = f.readline().strip()
            return mySecret

def main():
    parser = argparse.ArgumentParser(description="Argument Parser")
    parser.add_argument("domain", type=str, help="Domain to Delete")
    args = parser.parse_args()

    api_url = "https://{}.console.ves.volterra.io/api/config/dns/namespaces/system/dns_zones/{}".format(readSecret(".secrets/.consoleDomain"), args.domain)

    api_headers = {
        "Authorization" :   readSecret(".secrets/.apiToken"),
        "Accept"        :   "application/json"
    }

    body = "{{\n\t\"fail_if_referred\": true,\n\t\"name\": {}\n\t\"namespace\": \"system\"\n}}".format(args.domain)
    print(body)
    deleteZone = requests.delete(api_url, verify=False, headers=api_headers).content.decode("utf8")
    print(deleteZone)

############################ GLOBALS ###############################

if __name__ == "__main__":
    main()