"""
https://www.acmicpc.net/problem/4386
"""
from heapq import heappop, heappush

def get_distance(a, b):
    temp = (a[0] - b[0]) ** 2
    temp += (a[1] - b[1]) ** 2
    return temp ** .5

def prim_jarnik(M, L, s):
    heap = [(0, s)]
    total_length = 0
    while heap:
        popped_distance, popped = heappop(heap)
        if L[M[popped]]:
            continue

        L[M[popped]] = True
        total_length += popped_distance
        for linked in M:
            if L[M[linked]]:
                continue
            heappush(heap, (get_distance(popped, linked), linked))

    return total_length

if __name__ == '__main__':
    N = int(input())
    star_map = {}
    star_list = [None] * N
    id = 0
    starting_star = None

    for _ in range(N):
        (x, y) = map(float, input().split())
        if (x, y) not in star_map:
            star_map[(x, y)] = id
            star_list[id] = False
            id += 1
        starting_star = (x, y)

    # print('star_map : {}'.format(star_map))
    # print('star_list : {}'.format(star_list))

    print(prim_jarnik(star_map, star_list, starting_star))


import matplotlib.pyplot as plt
import numpy as np
from matplotlib import cm
from numpy.random import randn
import statistics
import math
import time

arr=[]

N = input('Enter the matrix size(20-70k): ')
rho_d = input('Enter the value of rho-a(0.2-0.8): ')
rho_a = input('Enter the value of rho-b(0.2-0.8): ')
strategy = raw_input('Enter A for aggressive strategy and D for defensive strategy: ')

for ii in range(1,50,1):
    #declaring matrix size and initial conditions
    #N = 50    #matrix size
    R = ii      #value of range
    a0 = 50000   #initial reserve for attackers
    d0 = 50000   #initial reserve for defenders
    A0 = a0/2000  #parameter for colour settings
    plt.pause(1)
    data = np.zeros((N+(2*R),N+(2*R)))      #2d matrix for Battleground
    #rho_a = 0.2             #initial deployment probability for attackers
    #rho_d = 0.45            #deployment probability for defenders
    b1 = 1                  #attacking/defensive power of value 1
    b2 = 2                  #attacking/defensive power of value 2
    itr = 200               #number of iteretions
    flag_eradicated = 0
    #code for simulation of cellular automata
    fig, ax = plt.subplots()
    cax = ax.imshow(data[R:N+R,R:N+R], interpolation='nearest', cmap=cm.bwr, vmin=-A0, vmax=A0)
    ax.set_title('Battlefield')
    cbar = fig.colorbar(cax, ticks=[-100, 0, 100])
    plt.pause(1)

    #Initialize Defenders randomly with rho_d density in lattice
    a_reserve = a0
    d_reserve = d0
    for i in range(R,N+R):
        for j in range(R,N+R):
            r = np.random.rand()
            if r<rho_d:
                r = np.random.rand()
                if r<0.5:
                    data[i][j] = data[i][j] + b2
                    d_reserve = d_reserve-b2
                else:
                    data[i][j] = data[i][j] + b1
                    d_reserve = d_reserve-b1

    #Initialize Attackers randomly with rho_a density in lattice
    for i in range(R,N+R):
        for j in range(R,N+R):
            r = np.random.rand()
            if r<rho_a:
                r = np.random.rand()
                if r<0.5:
                    data[i][j] = data[i][j] - b2
                    a_reserve = a_reserve-b2
                else:
                    data[i][j] = data[i][j] - b1
                    a_reserve = a_reserve-b1

    plt.pause(1)
    cax = ax.imshow(data[R:N+R,R:N+R], interpolation='nearest', cmap=cm.coolwarm, vmin=-A0, vmax=A0)

    flagA = 0
    flagB = 0
    pA = 0          #Total no. of attackers in ground
    pD = 0          #Total no. of defenders in ground

    for it in range(itr):
        #Deployment of attackers
        for i in range(R,N+R):
            for j in range(R,N+R):
                #sum of defenders on 4 quadrants surrounding the attack site
                sum1 = 0;
                sum2 = 0;
                sum3 = 0;
                sum4 = 0;
                r = np.random.rand()
                #If attacker site then only deploy
                if data[i][j]<0:
                    #calculating sum in all four qudrants
                    for k in range(i-R,i+1):
                        for l in range(j-R,j+1):
                            sum2 = sum2 + data[k][l];
                    for k in range(i-R,i+1):
                        for l in range(j,j+R+1):
                            sum1 = sum1 + data[k][l];
                    for k in range(i,i+R+1):
                        for l in range(j-R,j+1):
                            sum3 = sum3 + data[k][l];
                    for k in range(i,i+R+1):
                        for l in range(j,j+R+1):
                            sum4 = sum4 + data[k][l];

                    sums = [sum1, sum2, sum3, sum4]
                    if strategy=='A':
                        max_sum = max(sums)
                    elif strategy=='D':
                        max_sum = min(sums)
                    b=b2
                    #Deploy attackers
                    if sum1 == max_sum:
                        if ((sum3 == max_sum) or (sum2==max_sum and sum4==max_sum)):
                            data[i][j] = data[i][j]
                        elif (sum2 == max_sum):
                            data[i-1][j] = data[i-1][j] - b
                        elif (sum4 == max_sum):
                            data[i][j+1] = data[i][j+1] - b
                        else:
                            data[i-1][j+1] = data[i-1][j+1] - b
                    elif sum2 == max_sum:
                        if (sum4 == max_sum) or (sum1==max_sum and sum3==max_sum):
                            data[i][j] = data[i][j]
                        elif (sum1 == max_sum):
                            data[i-1][j] = data[i-1][j] - b
                        elif (sum3 == max_sum):
                            data[i][j-1] = data[i][j-1] - b
                        else:
                            data[i-1][j-1] = data[i-1][j-1] - b
                    elif sum3 == max_sum:
                        if (sum1 == max_sum) or (sum2==max_sum and sum4==max_sum):
                            data[i][j] = data[i][j]
                        elif (sum2 == max_sum):
                            data[i][j-1] = data[i][j-1] - b
                        elif (sum4 == max_sum):
                            data[i+1][j] = data[i+1][j] - b
                        else:
                            data[i+1][j-1] = data[i+1][j-1] - b
                    elif sum4 == max_sum:
                        if (sum2 == max_sum) or (sum1==max_sum and sum3==max_sum):
                            data[i][j] = data[i][j]
                        elif (sum1 == max_sum):
                            data[i][j+1] = data[i][j+1] - b
                        elif (sum3 == max_sum):
                            data[i+1][j] = data[i+1][j] - b
                        else:
                            data[i+1][j+1] = data[i+1][j+1] - b

                    a_reserve = a_reserve-b
                    if a_reserve<0:
                        flagA=1
                if flagA==1:
                    break
            if flagA==1:
                break

        #deploy defenders
        for i in range(R,N+R):
            for j in range(R,N+R):
                r = np.random.rand()
                if r<rho_d:
                    r = np.random.rand()
                    if r<0.5:
                        data[i][j] = data[i][j] + b2
                        d_reserve = d_reserve-b2
                        if d_reserve<0:
                            flagB=1
                    else:
                        data[i][j] = data[i][j] + b1
                        d_reserve = d_reserve-b1
                        if d_reserve<0:
                            flagB=1
                if flagB==1:
                    break
            if flagB==1:
                break
        if flagB==1 or flagA==1:
            break

        cax = ax.imshow(data[R:N+R,R:N+R], interpolation='nearest', cmap=cm.coolwarm, vmin=-A0, vmax=A0)
        plt.pause(0.05)

        #calculation total number of sites occupied by defenders and attackers
        siteA = 0
        siteD = 0
        for i in range(R,N+R):
            for j in range(R,N+R):
                if data[i][j]<0:
                    siteA = siteA+1
                elif data[i][j]>0:
                    siteD = siteD+1
        if siteD==0:
            print("defenders are eradicated - ATTACKERS WON!")
            flag_eradicated = 1
            break
        if siteA==0:
            print("attackers are eradicated - DEFENDERS WON!")
            flag_eradicated = 1
            break
        #PA.append(a0)
        # PD.append(pD)
        # SITEA.append(siteA)
        # SITED.append(siteD)

    siteA = 0
    siteD = 0
    total_reserve = 0
    for i in range(R,N+R):
        for j in range(R,N+R):
            total_reserve = total_reserve + data[i][j]
            if data[i][j]<0:
                pA = pA-data[i][j]
                siteA = siteA + 1
            elif data[i][j]>0:
                pD = pD+data[i][j]
                siteD = siteD + 1
    pA = pA + a_reserve
    pD = pD + d_reserve
    if flag_eradicated==0:
        if a_reserve>0 and d_reserve<=0:
            print("Defenders ran out of resources : Attackers will win")
        elif a_reserve<=0 and d_reserve>0:
            print("Attackers ran out of resources : Defenders will win")
        elif a_reserve<=0 and d_reserve<=0:
            print("Both ran out of resourses : Match Draw")
    # print siteA, siteD, pA, pD
    total_reserve = total_reserve + a_reserve + d_reserve
    x=float(siteA*100)/(N*N)    #percentage sites occupied by attackers
    print(ii,pA,pD,a_reserve, d_reserve,siteA,siteD, total_reserve,x)
    arr.append(x)
plt.figure(2)
plt.plot(arr)
plt.ylabel('Percentage sites occupied by attackers')
plt.xlabel('Iteration')
plt.show()


from django.urls import path
from .views import (
    UsersRunListView,
    RunDetailView,
    RunCreateView,
    RunUpdateView,
    RunDeleteView,
)
from . import views

# urlpatterns = [
#     path('', views.index),
#     path('home/', views.UsersRunListView.as_view(), name='user-run-list')
# ]

urlpatterns = [
    path('', UsersRunListView.as_view(), name='users-run'),
    #path('run/user/<str:username>/', UserPostListView.as_view(), name='user-posts'),
    path('run/<int:pk>/', RunDetailView.as_view(), name='run-detail'),
    path('run/new/', RunCreateView.as_view(), name='run-create'),
    path('run/<int:pk>/update/', RunUpdateView.as_view(), name='run-update'),
    path('run/<int:pk>/delete/', RunDeleteView.as_view(), name='run-delete'),
]


import matplotlib as mpl
mpl.use('TkAgg')

import pickle
from scipy.io import savemat

expt = 'CircleSquare'

path_all = '/Volumes/GoogleDrive/My Drive/Fenton_Lab/CellPress_CircleSquare/MNS_Analysis/Data/CircleSquare/'
pathFigure = '/Volumes/GoogleDrive/My Drive/Fenton_Lab/CellPress_CircleSquare/MNS_Analysis/Figures/CircleSquare/savedFigs/IsoMap_Simon/'

TimeBinSize_AVC = 1000
TimeBinSize_TAU = 1000

threshMult = 2
thresh = 0.01* threshMult*(TimeBinSize_TAU/1000)

saveOutput = True

doStd = True
doPTI = True

saveAni = ['M19']

animalList = saveAni  #['M19']#,'M20', 'M29','M34','M19', 'M39']
nAni = len(animalList)

indic = [-1, 0, 1]
envList = ['HMC1','HMC2', 'CYL1','CYL2', 'RCT1','RCT2'] # environment HMC = Home Cage (-1), CYL = Cylinder (1), RCT = Rectangle (0)

if doPTI:
    loadStr = 'Zlinear'
else:
    loadStr = 'TempCorr'

for iAni, animal in enumerate(animalList):

    print(animal)

    with open(path_all + 'analysisFiles_Simon/' + loadStr + '_List_' +
              str(int(TimeBinSize_AVC)) + 'msAV_' + str(int(TimeBinSize_TAU)) + 'msKT'
              '_CircleSquare_' + animal +'.file', 'rb') as f:
        outputList = pickle.load(f)

    # from cnmfe_temporal_analysis
    # listsToSave = [[day_real_list, day_count_list, sess_list, S_conv_avc_list, S_conv_tau_list, isSeparatedList,
    #                 tauPairsSingleList, tauVecSingleList, trainingList],
    #                [trackList, [], aMaxLocList],
    #                [splitList, iDayList]]

    # from cnmfe_zscore_analysis
    # listsToSave = [[day_real_list, day_count_list, sess_list, S_conv_avc_list, [zConvTauList, S_conv_tau_list, sConvTauPcList], isSeparatedList,
    #                 tauPairsSingleList, [zTauVecSingleList,tauVecSingleList], trainingList, xBinnedPcList, yBinnedPcList],
    #                [trackList, [zBinnedRateMapsList, zRateMapsList], aMaxLocList],
    #                [atnSplitList, iDayList]]
    if doPTI:
        dayCountList = outputList[0][1]
        sessList = outputList[0][2]
        sTauList = outputList[0][4][0]
        isSeparatedList = outputList[0][5]
        tauPairsSingleList = outputList[0][6]
        tauVecSingleList = outputList[0][7][0]
        trainingList = outputList[0][8]
    else:
        dayCountList = outputList[0][1]
        sessList = outputList[0][2]
        sTauList = outputList[0][4]
        isSeparatedList = outputList[0][5]
        tauPairsSingleList = outputList[0][6]
        tauVecSingleList = outputList[0][7]
        trainingList = outputList[0][8]

if saveOutput:
    print('saving...')

    pathSave = path_all + 'analysisFiles_Simon/' + loadStr + '_List_' + str(int(TimeBinSize_AVC)) + 'msAV_' + str(int(TimeBinSize_TAU)) + 'msKT' +'_CircleSquare_' + animal + '.mat'

    mdic = {'dayCountList': dayCountList,'sessList':sessList, 'sTauList':sTauList,'isSeparatedList':isSeparatedList,'tauPairsSingleList':tauPairsSingleList,'tauVecSingleList':tauVecSingleList,'trainingList':trainingList}
    savemat(pathSave, mdic)

    print('saved!')

else:
    print('NOT SAVING')

print('done done done')


# Problem H 2017 - Connor Mattson

teams = {}
for i in range(int(input("How many teams do you wish to enter: "))):
	teams.update({input("Enter team {}'s name: ".format(i + 1)): [int(x) for x in input("Enter team {}'s data: ".format(i + 1)).split(' ')]})

for i in range(int(input("How many matches do you wish to enter: "))):
	homeTeam = input("Enter the name of the home team: ")
	hS = int(input("Enter the score of the home team: "))
	awayTeam = input("Enter the name of the away team: ")
	aS = int(input("Enter the score of the away team: "))
	for i, dataPoint in enumerate([1, hS > aS, hS == aS, hS < aS, hS, aS, 3*(hS > aS) + 1*(hS == aS)]): teams[homeTeam][i] += dataPoint
	for i, dataPoint in enumerate([1, hS < aS, hS == aS, hS > aS, aS, hS, 3*(hS < aS) + 1*(hS == aS)]): teams[awayTeam][i] += dataPoint

for team, data in sorted(teams.items(), key=lambda x: [-x[1][6], -(x[1][4]-x[1][5]), -x[1][4], x[0].lower()]): print(team, data)


'''
Detecting Vertical Edges in an image,
by implementing a Convolution Operation
'''

import tensorflow as tf
import tensorflow.keras as keras

import matplotlib.pyplot as plt

original_image = scipy.misc.ascent()
plt.axis('off')
plt.gray()
plt.imshow(original_image)
plt.show()

filters = np.array([[-2,0,2],[-1,0,1],[-2,0,2]], dtype='float32')
# To allow normalizing output, in case sum of filter indices != 1, here it is 1.
weight = 1
transformed_image = np.copy(original_image)

for i in range(1, transformed_image.shape[0]-1):
  for j in range(1, transformed_image.shape[1]-1):
    convolution = np.sum(np.multiply(original_image[i-1:i+2,j-1:j+2], filters))
    convolution *= weight
    if (convolution < 0):
      convolution = 0
    if (convolution > 255):
      convolution = 255
    transformed_image[i,j] = convolution

plt.imshow(transformed_image)
plt.show()


"""

some opencv wrappers to make video inference
more simple

"""
import cv2
from PIL import Image, ImageFont, ImageDraw
import os
import numpy as np

font_f = os.path.join(
    os.path.dirname(os.path.dirname(os.path.abspath(__file__))), "fonts/FZSSJW.TTF"
)

def put_cn_txt_on_img(img, txt, ori, font_scale, color):
    """
    put Chinese text on image
    """
    img_PIL = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    assert os.path.exists(font_f), "{} not found".format(font_f)
    font = ImageFont.truetype(font_f, 25)
    fillColor = color  # (255,0,0)
    position = ori  # (100,100)
    draw = ImageDraw.Draw(img_PIL)
    draw.text(position, txt, font=font, fill=fillColor)
    img = cv2.cvtColor(np.asarray(img_PIL), cv2.COLOR_RGB2BGR)
    return img


"""config URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.urls import path
from .views import *

urlpatterns = [
    path('', glavnaya, name='index'),
    path('books/add/', add_book, name='add-book'),
    path('books/view/<int:id>/', view_book, name='view-book'),
    path('books/delete/<int:id>/', delete_book, name='delete-book'),
    path('o-nas/', o_nas, name='o-nas'),
    path('manage/', manage, name='manage'),
    # path('example/', test_form_view, name='example'),
    path('publishers/', PublisherListView.as_view(), name='publishers'),
    path('publishers/create/', PublisherCreateView.as_view(), name='add-publisher'),
    path('publishers/view-publisher/<int:pk>/', PublisherDetialView.as_view(), name='detial-publisher'),
    path('publishers/update-publisher/<int:pk>/', PublisherUpdateView.as_view(), name='update-publisher'),
    path('publishers/delete-publisher/<int:pk>/', PublisherDeleteView.as_view(), name='delete-publisher'),
    path('login/',login_view,name ='login'),
    path('logout/', logout_request, name='logout'),
    path('register/', register_view, name='register'),
]


from os.path import exists
for i in range(1,26):
    files = {
        "input": f"d{i}_input.txt",
        "testinput": f"d{i}_testinput.txt",
        "script": f"d{i}.py",
    }

    for key in files:
        if not exists(files[key]):
            contents = ""
            if key == "script":
                contents = f"with open('{files['testinput']}', 'r') as f:\n"
                contents += "\tlines = [j.replace('\\n','') for j in f.readlines() if j != '\\n']"
                contents += "\n\n#part1\n\n\n#part2"
            f = open(files[key],'w'); f.write(contents); f.close()


import matplotlib.pyplot as plt
import numpy as np
from tensorflow.keras.preprocessing.image import load_img
import tensorflow as tf

# models = ["MiniCNN", "MiniResNet", "MLP", "Small2CNN", "Small3CNN"]
models = ["MiniResNet", "MiniResNetB"]
image_titles = ["Coat", "Coat", "Ankle Boot", "Sneaker", "Sandal"]
image_class = [4, 4, 9, 7, 5]
#
methods = ["grad", "smoothGrad", "integratedGrad"]

subplot_args = {
    "nrows": 10,
    "ncols": 3,
    "figsize": (15, 50),
    "subplot_kw": {"xticks": [], "yticks": []},
}

f, ax = plt.subplots(**subplot_args)

count = 1
for model in models:
    ax[0][count].set_ylabel("{}".format(model), fontsize=45)
    for i in range(0, 10):
        # ax[count][i].set_title(classification, fontsize=30)
        ax[i][count].imshow(
            np.array(
                load_img(
                    "../images/cifar10/res_examples/integratedGrad/{}_{}.png".format(
                        i, model
                    )
                )
            )
        )

    count += 1

for i in range(0, 10):
    # ax[0][i].set_title(title, fontsize=40)
    ax[i][0].imshow(
        np.array(load_img("../images/cifar10/res_examples/{}_image.png".format(i)))
    )

plt.tight_layout()
plt.savefig("../images/cifar10/res_examples/res2_integratedGrad_example.png")

# im1 = load_img("../images/FashionMnist/examples/grad/0_Small2CNN_4.png")
# im2 = load_img("../images/FashionMnist/examples/grad/0_Small3CNN_4.png")

# def ssim_single(image_id):
#     paths = []
#     for model in models:
#         image_path = "../images/FashionMnist/examples/grad/{}_{}_{}.png".format(image_id, model, image_class[image_id])
#         paths.append(image_path)
#
#     results_list = []
#
#     for i in range(0, len(paths)):
#         im1=load_img(paths[i])
#         image_list=[]
#         for j in range(0, len(paths)):
#             im2=load_img(paths[j])
#             ssim = (tf.image.ssim(im1, im2, 1).numpy())
#             image_list.append(ssim)
#         results_list.append(image_list)
#
#     return results_list
#
#
# def average_ssim(ssim_list):
#     av_list = []
#     for i in range(0, len(models)):
#         partial_list = []
#         for j in range(0, len(models)):
#             current_comparison = []
#             for comp in ssim_list:
#                 current_comparison.append(comp[i][j])
#             average = np.mean(current_comparison)
#             partial_list.append(average)
#
#         av_list.append(partial_list)
#     return av_list
#
# all_ssim = []
# for i in range(0, 5):
#     all_ssim.append(ssim_single(i))
#
# print(average_ssim(all_ssim))


#!/usr/bin/env python3
'''
todo
    - update list of commands in /help
    - add category: Sparen

info
- the added expenses get saved twice: with and without date (expenses and date_expenses)
    -> let's you analyse spending patterns (i.e. times of the months, week days, etc.)

- when the bot is reset, all previous expenses get saved to a file including the date
    -> kind of back-up for accidental resets
    -> makes long-term analyses possible

- plots do not get saved but are overwritten by the newest plot
    -> if you want to save plots, download the image from the telegram chat

'''
import telebot
from telebot import types
import pickle, re
import seaborn as sns
import matplotlib.pyplot as plt
from datetime import date, datetime
import logging
import os, sys
from InitializeData import initialize

try:
    with open('data/api_token.txt', 'r') as  file:
        token = file.read().strip()
except FileNotFoundError:
    raise Exception("Please create the file 'api_token.txt' that contains your bot's api token.")

bot = telebot.TeleBot(token, parse_mode=None)

logging.basicConfig(level=logging.INFO, filename=f"logfiles/logging{date.today()}.log")

current_cat = None

def load_data(file):
    '''load data from file if exists'''
    with open(file, 'rb') as f:
        return pickle.load(f)

def save_data(data, file):
    '''save data to pickle file'''
    with open(file, 'wb') as f:
        pickle.dump(data, f)

def load_keyboard():
    '''load buttons of inline keyboard'''
    with open('data/inline_keyboard.pickle', 'rb') as file:
        return pickle.load(file)

def update_serialized_data():
    '''save updated data to pickle files'''
    save_data(expenses, 'serialized_data/expenses.pickle')
    save_data(date_expense, 'serialized_data/date_of_expenses.pickle')

@bot.message_handler(commands=['help'])
def welcome_message(message):
    bot.reply_to(message, '''Welcome to CurBot. I respond to these commands:
    /start - start using the bot
    /help - obtain a list of commands
    /info - learn more about CurBot
    /ausgaben - list and plot all expenses
    /show_fixkosten - show all regular expenses
    /del - delete last expense
    /reset - reset all expenses
    ''')

@bot.message_handler(commands=['info'])
def introduce_bot(message):
    bot.reply_to(message, 'Du kannst ganz einfach neue Ausgaben hinzufügen, indem du /add sendest.' \
        ' Den Betrag schickst du entweder direkt mit dem Befehl, oder danach.\n' \
        'Mit /plot erhältst du eine graphische Übersicht aller Ausgaben, mit /ausgaben die genauen Beträge.\n'\
        'Außerdem kannst du alle Ausgaben zurücksezten (z.B. am Monatsende), sende einfach /reset und bestätige.'
    )

@bot.message_handler(commands=['start'])
def welcome_message(message):
    '''send a welcome message and usage tips'''
    bot.reply_to(message, 'Willkommen! Ich bin ExpenseTrackerBot und fasse deine Ausgaben zusammen.'\
        ' Sende /help für eine Liste meiner Befehle oder füge eine neue Ausgabe hinzu mit /add.'\
            ' Mit /info erhältst du zusätzliche Tips und Tricks.')

@bot.message_handler(commands=['add'])
def use_bot(message):
    '''
    use inline keyboard to add expenses or reset them;
    when a new category is added, it needs to be added to be accessed in the bot chat
    '''
    keyboard = types.InlineKeyboardMarkup(row_width=3)
    # include all categories
    inline_keyboards = load_keyboard()
    for kb in inline_keyboards:
        keyboard.add(kb)
    bot.reply_to(message, "Welche Art von Ausgabe möchtest du hinzufügen?", reply_markup=keyboard)

    @bot.callback_query_handler(func=lambda m: True)
    def parse_callback(call):
        ''''''
        global expenses
        cat = call.data

        if cat in categories:
            global current_cat
            current_cat = cat
            bot.reply_to(call.message, 'Bitte nenne den Betrag.')

        else:
            bot.reply_to(call.message, 'Bitte nutze das Inline-Keyboard oder einen Befehl.')

def reset_bot():
    '''
    makes a back-up of current expenses and then resets them
    '''
    no_answer = True
    while no_answer:
        @bot.message_handler(content_types=['text'])
        def double_check(message):
            nonlocal no_answer
            global date_expense, expenses
            if message.text.lower() in ('yes', 'ja'):
                # save current expenses to file
                with open(f'previous_expenses/expenses_{date.today()}.pickle', 'wb') as file:
                    pickle.dump(expenses, file)
                with open(f'previous_expenses/date_expenses_{date.today()}.pickle', 'wb') as file:
                    pickle.dump(date_expense, file)
                # reset expenses
                expenses, date_expense = dict(), dict()
                for cat in categories:
                    expenses[cat] = []
                    date_expense[cat] = []
                update_serialized_data()
                bot.reply_to(message, 'Ausgaben wurden zurückgesetzt.')
                no_answer = False
                logging.info(f'Expenses reset on {datetime.now().strftime("%d/%m/%Y %H:%M:%S")}.')
                logging.basicConfig(filename=f"logfiles/logging{date.today()}.log")
            elif message.text.lower() in ('no', 'nein'):
                bot.reply_to(call.message, 'Abgebrochen. Ausgaben bleiben unverändert.')
                no_answer = False

@bot.message_handler(commands=['reset'])
def reset_expenses(message):
    '''reset expenses (alternative to inline keyboard)'''
    bot.reply_to(message, 'Willst du wirklich alle bisherigen Ausgaben löschen?')
    reset_bot()

@bot.message_handler(regexp='[0-9]+([.,][0-9]+)?')
def get_expense(message):
    '''any number types into the chat will be considered as expense
    as long as there is a current_cat(egory)'''
    global current_cat
    # numbers are only considered when there is an active category (avoids spam)
    if current_cat:
        try:
            exp = float(message.text)
        except ValueError:
            # substitute , with .
            exp = float(message.text.replace(',', '.'))

        expenses[current_cat].append(exp)
        date_expense[current_cat].append((exp, datetime.today()))
        # save updated data to pickle files
        update_serialized_data()
        bot.reply_to(message, f'{exp}€ wurden zu {current_cat} hinzugefügt.')
        print(expenses)
        logging.info(f'New expense was added on {datetime.now().strftime("%d/%m/%Y %H:%M:%S")}.')
        current_cat = None
    else:
        bot.reply_to(message, 'Gib eine Kategorie an mit /start oder /add.')

@bot.message_handler(commands=['del'])
def del_expense(message):
    '''Deletes most recently added expense for
    a requested category'''
    bot.reply_to(message, 'Von welcher Kategorie willst du die letzte Ausgabe löschen?')

    @bot.message_handler(content_types=['text'], func=lambda m: m.text in categories)
    def del_category_expense(message):
        global expenses
        cat = message.text
        try:
            del expenses[cat][-1]
            del date_expense[cat][-1]
            update_serialized_data()
            bot.reply_to(message, f'Die letzte Ausgabe für {cat} wurde gelöscht.')
            logging.info(f'Expense deleted added on {datetime.now().strftime("%d/%m/%Y %H:%M:%S")}.')
        except IndexError:
            bot.reply_to(message, f'Keine Ausgaben für {cat}.')

@bot.message_handler(commands=['ausgaben'])
def plot_expenses(message):
    exps, cats = list(), list()
    overview_text = ''
    total_sum = 0

    for cat in categories:
        overview_text += f'{cat}: {sum(expenses[cat])}€\n'
        total_sum += sum(expenses[cat])
        if expenses[cat]:
            exps.append(sum(expenses[cat]))
            cats.append(cat)

    if total_sum != 0:
        bot.reply_to(message, f'Gesamte Ausgaben bisher: {total_sum}€')
        bot.reply_to(message, overview_text)

        # set style for bar chart
        sns.set_style('darkgrid')
        sns.set_palette('crest')

        sns.barplot(cats, exps)
        plt.ylabel('Ausgaben in €')

        # save plot to file and send to chat
        plt.savefig('ausgaben.png')
        bot.send_photo(message.chat.id, photo=open('ausgaben.png', 'rb'))

    else:
        bot.reply_to(message, 'Keine Ausgaben bisher.' )

@bot.message_handler(commands=['show_fixkosten'])
def monthly_expenses(message):
    '''calculate and update fix monthly expenses'''
    try:
        with open('serialized_data/regular_expenses.pickle', 'rb') as f:
            fix_expenses = pickle.load(f)
    except FileNotFoundError:
        # insert values for each category
        fix_expenses = {'Miete': 0, 'Strom': 0, 'Gebühren': 0, 'Internet': 0, 'Fitness': 0 ,'TV': 0}
        save_data(fix_expenses, 'serialized_data/regular_expenses.pickle')

    overview = f'Deine monatlichen Fixkosten liegen bei {sum(fix_expenses.values())}:\n'

    # plot data
    exps, cats = list(), list()
    for cat, val in fix_expenses.items():
        exps.append(val)
        cats.append(cat)
        overview += f'{cat}: {val}\n'

    bot.reply_to(message, overview)

    # set style for bar chart
    sns.set_style('darkgrid')
    sns.set_palette('crest')

    sns.barplot(cats, exps)
    plt.ylabel('Kosten in €')

    # save plot to file and send to chat
    plt.savefig('fixkosten.png')
    bot.send_photo(message.chat.id, photo=open('fixkosten.png', 'rb'))

# load data
categories = load_data('data/categories.pickle')
expenses = load_data('serialized_data/expenses.pickle')
date_expense = load_data('serialized_data/date_of_expenses.pickle')

try:
    bot.polling()
except RuntimeError:
    os.execv(sys.executable, ['python'] + [sys.argv[0]])    # restart script


"""
栈：
    栈是一种基于先进后出(FILO)的数据结构，是一种只能在一端进行插入和弹出操作的特殊线性表。
    按照先进后出的原则，先进入的元素压入栈底，最后的数据在栈顶，弹出数据时，从栈顶开始弹出。
    我们称数据进入栈的动作为 压栈， 数据从栈中出去的动作为 弹栈。

API设计：
    构造方法：
        - __init__() 创建Stack对象
    成员方法：
        - is_empty(): 判断栈是否为空，是返回True，否返回False
        - size(): 获取栈中的元素个数
        - pop(): 弹出栈顶元素
        - push(node: Node): 向栈中压入元素
    成员变量：
       - head：记录首结点
       - N：记录当前栈中元素个数
    成员内部类：
        - Node：
            构造方法：
                - __init__(self, item, next): 创建一个Node结点对象，初始化数据item， 下一个结点类next
            成员变量：
                - item: 结点存储的数据
                - next: 指向下一个结点
"""

class Stack:
    class Node:
        def __init__(self, item, next):
            self.item = item
            self.next = next

    def __init__(self):
        self.head = self.Node(None, None)
        self.N = 0

        # 迭代结点变量
        self.node = self.head

    @property
    def is_empty(self):
        return self.N == 0

    @property
    def size(self):
        return self.N

    def push(self, item):
        # 拿到当前栈的第一个结点
        old_node = self.head.next

        # 创建一个新结点，并使其指向old_node
        new_node = self.Node(item, old_node)

        # 更新头结点的指向
        self.head.next = new_node

        # 栈中元素数量加一
        self.N += 1

    def pop(self):
        # 拿到当前栈的第一个结点
        old_node = self.head.next

        # 如果没有下一个结点直接返回None
        if not old_node:
            return None

        # 拿到当前栈的第二个结点
        new_node = old_node.next

        # 让头结点指向第二个结点，即弹出了第一个结点
        self.head.next = new_node

        # 栈中元素减一
        self.N -= 1

        # 返回被弹出的结点
        return old_node.item

    # 实现栈可迭代
    def __iter__(self):
        return self

    def __next__(self):
        if self.node.next:
            self.node = self.node.next
            return self.node.item

        self.node = self.head  # 重置迭代位置
        raise StopIteration

if __name__ == '__main__':
    s = Stack()
    s.push('a')
    s.push('b')
    s.push('c')
    s.push('d')

    for i in s:
        print(i)

    print('-------------')

    print(s.pop())
    print(s.size)

    print(s.pop())
    print(s.size)

    print(s.pop())
    print(s.is_empty)

    print(s.pop())
    print(s.is_empty)

    print(s.pop())
    print(s.is_empty)

数据结构与算法/数据结构/线性表/栈/栈.py


import sys

from mrjob.job import MRJob

class MRWordFrequencyCount(MRJob):
    def mapper(self, _, line):
        yield "chars", len(line)
        yield "words", len(line.split())
        yield "lines", 1

    def reducer(self, key, values):
        yield key, sum(values)

if __name__ == '__main__':
    sys.argv.append('-r')
    sys.argv.append('hadoop')
    sys.argv.append('my_file.txt')
    MRWordFrequencyCount.run()


"""
    目标：yaml写入方法
    步骤：
        1. data：要写入的内容
        2. stream: 文件流-写到哪个目录叫什么文件名(文件流需要打开操作)
        3. 调用 dump()方法

"""
import yaml
# 写入数据

data = {'Search_Data': {
    'search_test_002': {'expect': {'value': '你好'}, 'value': '你好'},
    'search_test_001': {'expect': [4, 5, 6], 'value': 456}}}
# 写入文件流
with open("../data/data03_write.yaml", "w", encoding="utf-8")as f:
    # 调用 dump方法
    yaml.dump(data,f,encoding='utf-8',allow_unicode=True)


from ..core import *
from ..callback import *
from ..basic_train import Learner, LearnerCallback

__all__ = ['GeneralScheduler', 'TrainingPhase']

@dataclass
class TrainingPhase():
    "Schedule hyper-parameters for a phase of `length` iterations."
    length:int

    def __post_init__(self): self.scheds = dict()
    def schedule_hp(self, name, vals, anneal=None):
        "Adds a schedule for `name` between `vals` using `anneal`."
        self.scheds[name] = Scheduler(vals, self.length, anneal)
        return self

class GeneralScheduler(LearnerCallback):
    "Schedule multiple `TrainingPhase` for a `Learner`."
    def __init__(self, learn:Learner, phases:Collection[TrainingPhase], start_epoch:int=None):
        super().__init__(learn)
        self.phases,self.start_epoch = phases,start_epoch

    def on_train_begin(self, epoch:int, **kwargs:Any)->None:
        "Initialize the schedulers for training."
        res = {'epoch':self.start_epoch} if self.start_epoch is not None else None
        self.start_epoch = ifnone(self.start_epoch, epoch)
        self.scheds = [p.scheds for p in self.phases]
        self.opt = self.learn.opt
        for k,v in self.scheds[0].items():
            v.restart()
            self.opt.set_stat(k, v.start)
        self.idx_s = 0
        return res

    def jump_to_epoch(self, epoch:int)->None:
        for _ in range(len(self.learn.data.train_dl) * epoch):
            self.on_batch_end(True)

    def on_batch_end(self, train, **kwargs:Any)->None:
        "Take a step in lr,mom sched, start next stepper when the current one is complete."
        if train:
            if self.idx_s >= len(self.scheds): return {'stop_training': True, 'stop_epoch': True}
            sched = self.scheds[self.idx_s]
            for k,v in sched.items(): self.opt.set_stat(k, v.step())
            if list(sched.values())[0].is_done: self.idx_s += 1


# -*- coding: utf-8 -*-
# @Time    : 2022/9/11 16:27
# @Author  : Lason
# @FileName: testCloud.py
# @Software: PyCharm

import jieba            # 分词
import matplotlib.pyplot as plt     # 绘图  可视化
from wordcloud import WordCloud     # 词云
from PIL import Image       # 图像处理
import numpy as np          # 矩阵运算
import sqlite3      # 数据库

# 1.准备词云所需要的文字（词）
conn = sqlite3.connect("movie_top250.db")
cursor = conn.cursor()
sql = "select introduction from movie250"
text = ""
data = cursor.execute(sql)
for item in data:
    text = text + item[0]
# print(text)
cursor.close()
conn.close()

# 2. 分词
cut = jieba.cut(text)
string = ' '.join(cut)
print(len(string))
print(string)

img = Image.open(r'.\static\assets\img\tree.jpg')     # 打开遮罩图片
img_array = np.array(img)       # 生成数组
wc = WordCloud(
    background_color='white',
    mask=img_array,
    font_path="msyh.ttc"            # 字体所在位置    C:\Windows\Fonts
)
wc.generate_from_text(string)       # 生成遮罩图

# 绘制图片

flag = plt.figure(1)
plt.imshow(wc)
plt.axis('off')     # 是否显示坐标轴

# plt.show()      # 显示生成的云图片

# 输出词云图片到文件
plt.savefig(r'.\static\assets\img\word.png', dpi=500)


from django.db import models
from user.models import User
from utils.fields import LimitedImageField

# Create your models here.
class Post(models.Model):
    user = models.ForeignKey(User, models.CASCADE, related_name="user_posts")
    created_at = models.DateTimeField(auto_now_add=True)
    title = models.ManyToManyField('translations.Translation', related_name="post_title_translations_set", blank=True)
    body = models.ManyToManyField('translations.Translation', related_name="post_body_translations_set", blank=True)
    thumbnail = LimitedImageField(blank=True, null=True)
    slug = models.SlugField(unique=True, null=True)

class Subscription(models.Model):
    email = models.EmailField(unique=True)
    created_at = models.DateTimeField(auto_now_add=True)


import sys

sys.path.append('..')

from commons import utils
from commons.utils import ScoringThread, BackupThread

import pandas as pd
import numpy as np

from tqdm import tqdm

import datetime, threading, time

import datetime, threading, time

def solve():

    cities = pd.read_csv("../input/cities.csv")
    ids = cities.CityId.values[1:]
    xy = np.array([cities.X.values, cities.Y.values]).T[1:]
    path = [0,]
    pbar = tqdm(total=len(ids))

    k = 0
    while len(ids) > 0:
        last_x, last_y = cities.X[path[-1]], cities.Y[path[-1]]
        dist = ((xy - np.array([last_x, last_y]))**2).sum(-1)
        nearest_index = dist.argmin()
        path.append(ids[nearest_index])
        ids = np.delete(ids, nearest_index, axis=0) ## When a city is added to path, remove it from the list of remaining cities.
        xy = np.delete(xy, nearest_index, axis=0)
        pbar.update(1)
        if k % 1000 == 0: ## Run scoring every 1000 cities added to path
            scoring_thread = ScoringThread(target=utils.score_path, args=([path + list(ids) + [0]]))
            scoring_thread.start()

            backup_thread = BackupThread(target=utils.make_submission, args=("backup_baseline", path + list(ids) + [0]))
            backup_thread.start()
        k += 1

    path.append(0)

    return path

if __name__ == "__main__":
    path = solve()
    score = utils.score_path(path)

    print(score)

    util.make_submission('baseline_nearest_neighbour.{}'.format(np.round(score,2)), path)


import tensorflow as tf
from tensorflow.keras import layers, Sequential

gpus = tf.config.experimental.list_physical_devices('GPU')
if gpus:
    try:
        # Currently, memory growth needs to be the same across GPUs
        for gpu in gpus:
            tf.config.experimental.set_memory_growth(gpu, True)
        logical_gpus = tf.config.experimental.list_logical_devices('GPU')
        print(len(gpus), "Physical GPUs,", len(logical_gpus), "Logical GPUs")
    except RuntimeError as e:
        # Memory growth must be set before GPUs have been initialized
        print(e)

# 8.5.1 加载模型
# 加载ImageNet预训练网络模型，并去掉最后一层
resnet = tf.keras.applications.ResNet50(weights='imagenet', include_top=False)
resnet.summary()
# 测试网络的输出
x = tf.random.normal([4, 224, 224, 3])
out = resnet(x)
print(out.shape)

# 新建池化层
global_average_layer = layers.GlobalAveragePooling2D()
# 利用上一层的输出作为本层的输入，测试其输出
x = tf.random.normal([4, 7, 7, 2048])
out = global_average_layer(x)  # 池化层降维
print(out.shape)

# 新建全连接层
fc = layers.Dense(100)
# 利用上一层的输出作为本层的输入，测试其输出
x = tf.random.normal([4, 2048])
out = fc(x)
print(out.shape)

# 重新包裹成我们的网络模型
mynet = Sequential([resnet, global_average_layer, fc])
mynet.summary()

# 冻结ResNet部分网络参数，只训练新建的网络层，从而快速、高效完成网络模型的训练
resnet.trainable = False
mynet.summary()


from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.utils import plot_model
from keras.optimizers import SGD
from keras import regularizers
import matplotlib.pyplot as plt
import pandas as pd
import numpy as np
from SupportMethods.ContentSupport import isNotNone, isNone
from keras.callbacks import History, ReduceLROnPlateau, BaseLogger, EarlyStopping, ModelCheckpoint

class Model(object):
    """
    This class includs all necessary functionalities round about the keras model train, predict, print and so on.
    """
    _model = None

    def __init__(self, init_shape:tuple, model_folder:str, categories:int = -1):
        """
        The constructor.
            :param init_shape:tuple: train data input shape
            :param model_folder:str: folder where the model staff should be saved
            :param categories:int: amount of categories
        """
        try:
            self._init_shape:tuple = init_shape
            self._categories:int = categories
            self._model_folder:str = model_folder if isNotNone(model_folder) else None
        except Exception as ex:
            template = "An exception of type {0} occurred in [Model.Constructor]. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            print(message)

    def NewDense(self, input_shape:tuple=None, output_dim:int = 256, activation:str='relu', kernel_initializer:str='glorot_normal'):
        """
        This method return a predefined Dense layer depending on the inputs.
            :param input_shape:tuple: input shape of the first layer otherwise set None
            :param output_dim:int: output dim of the layer
            :param activation:str: layer activation function
            :param kernel_initializer:str: kernel generation initializer
        """
        try:
            if input_shape != None:
                return Dense(units=output_dim, input_shape=input_shape, kernel_initializer=kernel_initializer, activation=activation)
            else:
                return Dense(units=output_dim, kernel_initializer=kernel_initializer, activation=activation)
        except Exception as ex:
            template = "An exception of type {0} occurred in [Model.NewDense]. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            print(message)

    def Create(self):
        """
        This method constructs the network model.
        """
        try:
            self._model = Sequential()
            self._model.add(self.NewDense(input_shape=self._init_shape))
            self._model.add(Dropout(0.25))
            self._model.add(self.NewDense())
            self._model.add(Dropout(0.5))
            self._model.add(self.NewDense(output_dim=80))
            self._model.add(self.NewDense(output_dim=self._categories, input_shape=None, activation="softmax"))
            self._model.summary()
        except Exception as ex:
            template = "An exception of type {0} occurred in [Model.Create]. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            print(message)

    def Compile(self, loss_func:str='categorical_crossentropy', metrics:list=['acc']):
        """
        This method compile a model. Additionally the SGD optimizer will be set.
            :param loss_func:str: desired loss function
            :param metrics:list: list of desired metrics
        """
        try:
            self._model.compile(loss=loss_func, optimizer='adam', metrics=metrics)
        except Exception as ex:
            template = "An exception of type {0} occurred in [Model.Compile]. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            print(message)

    def Train(self, train_x, train_y, val_split:float = 0.2, eps:int = 20, batches:int = 64):
        """
        This method executes the model training process.
            :param train_x: train input
            :param train_y: train desired result
            :param val_split:float: validation split of the train set
            :param eps:int: train epochs
            :param batches:int: the dataset batch size
        """
        try:
            verbose:int = 1
            base_lr = BaseLogger()
            reduce_lr = ReduceLROnPlateau(monitor='val_loss', factor=0.02, patience=5, min_lr=0.000125, verbose=verbose)
            es = EarlyStopping(monitor='val_loss', mode='min', verbose=verbose, patience=75)
            mc = ModelCheckpoint(self._model_folder+'best_model.h5', monitor='val_acc', mode='max', verbose=verbose, save_best_only=True)

            return self._model.fit( train_x, train_y,
                                    validation_split=val_split,
                                    epochs=eps,
                                    batch_size=batches,
                                    shuffle=True,
                                    callbacks=[base_lr, reduce_lr, es, mc])
        except Exception as ex:
            template = "An exception of type {0} occurred in [Model.Train]. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            print(message)

    def ShowResultAccuracy(self, history):
        """
        This method show the train acc results.
            :param history: history of the training
        """
        try:
            return "Training accuracy: %.2f%% / Validation accuracy: %.2f%%" % (100*history.history['acc'][-1], 100*history.history['val_acc'][-1])
        except Exception as ex:
            template = "An exception of type {0} occurred in [Model.ShowResultAccuracy]. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            print(message)

    def ShowResultLoss(self, history):
        """
        This method show the train loss results.
            :param history: history of the training
        """
        try:
            return 'Training loss: '+ str(history.history['loss'][-1])[:-6] +' / Validation loss: ' + str(history.history['val_loss'][-1])[:-6]
        except Exception as ex:
            template = "An exception of type {0} occurred in [Model.ShowResultLoss]. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            print(message)

    def PlotResults(self, history, model_description:str, orientation:str = 'landscape', image_type:str = 'png'):
        """
        This method plot acc and loss from history and store it into seperate files.
            :param history: the train history
            :param model_description:str: name of the model
            :param orientation:str: image orientation
            :param image_type:str: image file type
        """
        try:
            acc_figure = plt.figure(1)
            acc_figure.suptitle('model categorical accuracy', fontsize=14, fontweight='bold')
            plt.title(self.ShowResultAccuracy(history))

            plt.plot(history.history['acc'])
            plt.plot(history.history['val_acc'])
            plt.ylabel('categorical accuracy')
            plt.xlabel('epoch')
            plt.legend(['train', 'valid'], loc='upper left')
            acc_figure.savefig((model_description+'acc_plot.'+image_type), orientation=orientation)
            acc_figure.clf()

            loss_figure = plt.figure(2)
            loss_figure.suptitle('model loss', fontsize=14, fontweight='bold')
            plt.title(self.ShowResultLoss(history))

            plt.plot(history.history['loss'])
            plt.plot(history.history['val_loss'])
            plt.ylabel('loss')
            plt.xlabel('epoch')
            plt.legend(['train', 'valid'], loc='upper left')
            loss_figure.savefig((model_description+'loss_plot.'+image_type), orientation=orientation)
            loss_figure.clf()
        except Exception as ex:
            template = "An exception of type {0} occurred in [Model.PlotResults]. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            print(message)

    def PlotSummary(self, file_name:str = None, show_shapes:bool = True):
        """
        This method print the model summary.
            :param file_name:str=None:
            :param show_shapes:bool=True:
        """
        try:
            file_name = (file_name + "_ModelGraph.png") if isNotNone(file_name) else "ann__ModelGraph.png"

            plot_model(self._model, to_file=file_name, show_shapes=show_shapes)
        except Exception as ex:
            template = "An exception of type {0} occurred in [Model.PlotSummary]. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            print(message)

    def PredictAndVisualize(self,
                            test_set,
                            categories:list,
                            decode_dict:dict,
                            test_words:list,
                            test_docs:list,
                            submission_file_name:str = "submission_all.csv",
                            isClasses:bool = True):
        """
        This method predict results for a given test set and store it in a csv file.
            :param test_set: predictable input
            :param categories:list: proba lables
            :param decode_dict:dict: class decoder dicts
            :param test_words:list: prediction words
            :param test_docs:list: predictions docs
            :param submission_file_name:str: name of the prdicted results file
            :param isClasses:bool: predict classes otherwise probability
        """
        try:
            mapped:dict = {}
            predictions = self._model.predict_classes(test_set) if isClasses else self._model.predict_proba(test_set)

            submission_file_name = submission_file_name if isNotNone(submission_file_name) else "submission_all.csv"
            if isNotNone(test_words): mapped['Words'] = test_words
            if isNotNone(test_docs): mapped['Docs'] = test_docs
            if isNotNone(predictions): mapped['PredClasses'] = predictions
            if isNotNone(decode_dict) and isNotNone(predictions): mapped['ClassNames'] = [decode_dict[p] for p in predictions]
            submission = pd.DataFrame(mapped)
            if categories != None: submission.columns = categories
            submission.to_csv(submission_file_name, index=False)
            submission.head()
        except Exception as ex:
            template = "An exception of type {0} occurred in [Model.PredictAndVisualize]. Arguments:\n{1!r}"
            message = template.format(type(ex).__name__, ex.args)
            print(message)


test1 = [1,2,3,4,5]
test2 = [22,13, 15, 1000,1001,1002,10003,10004, 77, 18, 199, 205, 65, 66,67]
def increasing(arr):
    print("Starting subsequences")
    global subsequences
    subsequences = [0] * len(arr)
    #print(subsequences)
    subsequences[0] = 1
    findMaxSubsequence(arr)
    print("Subsequences were -> ", subsequences)
    return max(subsequences)

def findMaxSubsequence(arr):
    # Find all subsequences size < length - 1 that have last value <= arr[length-1]
    if subsequences[len(arr)-1]: # If we already have a result stored in our array.
        print("Returning early, we already have a value here")
        return subsequences[len(arr)-1]
    length = len(arr)
    #print(length)
    for i in range (0, length-1):
# If the subsequence at [i-1] ends with a number less than the current number being looked at.
            if findMaxSubsequence(arr[0:i+1]) > subsequences[length-1] and arr[i] <= arr[length-1]: # If that subsequence is > than the current max value, update it.
                subsequences[length-1] = subsequences[i]

    subsequences[length-1] += 1 # Add one for the actual element that we have at that index.
    print(subsequences[length-1])
    return subsequences[length-1]

#print(increasing(test1))
print(increasing(test2))


import random
N = int(input())
M = int(input())
z = 0
m=0
b=10
for i in range (N):
    a = [random.randint(0,10) for j in range(M)]
    for k in range(M):
        z=a[k]+z
    m = z/M
    a.append(m)                            #Какая то средняя
    z = 0
    print(a)


import sys
import getopt
import random

from compare_tools import load_local_database, make_pairs_to_compare

import torch
from torch import nn
from torch.utils.data import DataLoader

from sentence_transformers import InputExample, losses, SentenceTransformer, models
from sentence_transformers.evaluation import SimilarityFunction, EmbeddingSimilarityEvaluator

def parse_args_trainer(argv):
    """récupère les arguments envoyé en ligne de commande"""

    #tous les arguments à renvoyer en sortie
    arg_loss = ""
    arg_epochs = ""
    arg_output = ""
    arg_embedding_name = ""

    #aide des commandes à afficher à l'utilisateur
    arg_help = "{0} [--loss loss_name] [--epoch 10] -o <output_name> <embedding_name>".format(argv[0])

    try:
        #récupération des paramètres envoyés
        opts, args = getopt.getopt(argv[1:], "hl:e:o:", ["help", "loss=", "epochs=", "output="])
        if len(args):
            arg_embedding_name = args[0]
        for opt, arg in opts:
            if opt in ("-h", "--help"):
                print(arg_help)
                sys.exit(2)
            elif opt in ("-l", "--loss"):
                arg_loss = arg
            elif opt in ("-e", "--epochs"):
                arg_epochs = int(arg)
            elif opt in ("-o", "--output"):
                arg_output = arg
    except:
        #si l'utilisateur a fait une erreur, on lui montre ce qu'il doit faire
        print(arg_help)
        sys.exit(2)

    #on regarde quel paramètre(s) manque(nt)
    missing_param = False
    if arg_output == "":
        print("output parameter is missing")
        missing_param = True
    if arg_embedding_name == "":
        print("embedding_name parameter is missing")
        missing_param = True
    if missing_param: #si un paramètre manque, on arrete tout
        sys.exit(2)
    return arg_loss, arg_epochs, arg_output, arg_embedding_name

def print_eval(score, epoch, step):
    """Affichage du résultat des evaluation"""
    print("Epoch {} - Step {} : {}".format(epoch, step, score))

def train(sentence_file, model_name,  output_model, loss_name, epochs):
    """fonction d'entrainement

    Arguments:
    sentence_file -- fichier des phrases d'entrainement
    model_name -- model sentece_transformers à affiner
    output_model -- nom du model entrainé
    loss_name -- nom de la fonction loss à utiliser : cosine, contrastive ou MNR
    epochs -- nombre d'epochs
    """
    BATCH_SIZE = 8
    TRAINING_DATA_SIZE = 8192
    TEST_DATA_SIZE = 8192
    OUTPUT_FOLDER = "my_models/"

    # check for incorrect values
    if loss_name != "" and not (loss_name == "cosine" or loss_name == "contrastive" or loss_name == "MNR"):
        print("unknown loss_name (either cosine, contrastive or none)")
        sys.exit(2)
    if type(epochs) is not int or epochs <= 0:
        print("epochs must be a non zero integer")
        sys.exit(2)
    if output_model == "":
        print("output_model can't be empty")
        sys.exit(2)
    if model_name == "":
        print("model_name can't be empty")
        sys.exit(2)
    if sentence_file == "":
        print("sentence_file can't be empty")
        sys.exit(2)

    #chargement du model dans le GPU (ou CPU)
    device = "cuda" if torch.cuda.is_available() else "cpu"
    model = SentenceTransformer(model_name, device=device)

    # convertit loss_name en loss
    if loss_name == "" or loss_name == "cosine":
        train_loss = losses.CosineSimilarityLoss(model)
    elif loss_name == "contrastive":
        train_loss = losses.ContrastiveLoss(model)
    elif loss_name == "MNR":
        train_loss = losses.MultipleNegativesRankingLoss(model)

    # load sentences
    dataset = load_local_database(sentence_file)
    pairs, similarities_int, similarities_float, ids = make_pairs_to_compare(dataset)
    sentences = dataset["sentence"]

    # prepare training and test sentences
    train_data = []
    sentences1 = []
    sentences2 = []
    test_data = []
    for i in range(len(pairs)):
        test_data.append((sentences[pairs[i][0]], sentences[pairs[i][1]], similarities_int[i]))
        if loss_name == "MNR":
            if similarities_int[i]:
                train_data.append(InputExample(texts=[sentences[pairs[i][0]], sentences[pairs[i][1]]]))
        else:
            train_data.append(InputExample(texts=[sentences[pairs[i][0]], sentences[pairs[i][1]]], label=similarities_int[i]))

    random.shuffle(train_data)
    random.shuffle(test_data)
    dataloader = DataLoader(train_data, batch_size=BATCH_SIZE, shuffle=True)
    sentences1, sentences2, similarities_trunc = zip(*test_data[:TEST_DATA_SIZE])

    evaluator = EmbeddingSimilarityEvaluator(sentences1=sentences1, sentences2=sentences2, scores=similarities_trunc,  name="eval.csv", show_progress_bar=True, main_similarity=SimilarityFunction.COSINE, batch_size=128)

    # training
    print("init score : ", model.evaluate(evaluator))
    print("Start training")
    warmup_steps = int(len(dataloader) * epochs * 0.1)
    model.fit(train_objectives=[(dataloader, train_loss)], evaluator=evaluator, epochs=epochs, warmup_steps=warmup_steps, evaluation_steps=10000, output_path=OUTPUT_FOLDER+output_model, use_amp=True, callback=print_eval, steps_per_epoch=TRAINING_DATA_SIZE//BATCH_SIZE)
    print("Training Done")

if __name__ == "__main__":
    # parse input
    loss, epochs, output, embedding_name = parse_args_trainer(sys.argv)

    train("databases/response_1000.json", embedding_name, output, loss, epochs)


import os

from read_bundle_version import read_bundle_version, read_short_bundle_version, format_result

info_plist_path = os.environ.get('bitrise_tag_info_plist_path', None)
xcode_path = os.environ.get('bitrise_tag_xcodeproj_path', None)
xcworkspace_path = os.environ.get('bitrise_tag_xcworkspace_path', None)
scheme = os.environ.get('bitrise_tag_xcworkspace_scheme', None)
config = os.environ.get('bitrise_tag_xcconfig_name', None)
input_format = os.environ.get('bitrise_tag_format', None)

bundle_version = read_bundle_version(info_plist_path=info_plist_path,
                                     xcode_path=xcode_path,
                                     xcworkspace_path=xcworkspace_path,
                                     scheme=scheme,
                                     config=config)

short_bundle_version = read_short_bundle_version(info_plist_path=info_plist_path,
                                                 xcode_path=xcode_path,
                                                 xcworkspace_path=xcworkspace_path,
                                                 scheme=scheme,
                                                 config=config)

print(format_result(input_format=input_format, bundle_version=bundle_version, short_version=short_bundle_version))


import setuptools

from lmt_india_covid19_risk_assessment import __version__

with open("README.md", "r") as f:
    description = f.read()

setuptools.setup(
    name=f"lmt-india-covid19-risk-assessment",
    version=__version__,
    author="IST Research",
    author_email="support@istresearch.com",
    description="LMT-India COVID-19 Risk Assessment",
    license="MIT License",
    long_description=description,
    long_description_content_type="text/markdown",
    url="https://github.com/istresearch/lmt-india-covid19-risk-assessment",
    packages=["lmt_india_covid19_risk_assessment"],
    classifiers=[
        "Programming Language :: Python :: 3.6",
        "Programming Language :: Python :: 3.7",
        "Programming Language :: Python :: 3.8",
        "License :: OSI Approved :: MIT License",
        "Operating System :: OS Independent",
    ],
    install_requires=[
        "limesurvey-coconut>=1.0.1"
    ],
    include_package_data=True,
)


import discord

from ....utils import Permissions

async def masskickUsers(plugin, ctx, targets, reason):
    targets = list(set(targets))
    failing = 0
    to_kick = list()
    for t in targets:
        member = ctx.guild.get_member(t.id)
        bot = ctx.guild.me
        if member is not None:
            if member.top_role.position >= bot.top_role.position \
                or member.top_role.position >= ctx.author.top_role.position \
                or member.id == ctx.author.id \
                or member.id == ctx.guild.owner.id:
                    failing += 1
            else:
                to_kick.append(t)
        else:
            failing += 1

    if failing >= len(targets):
        return await ctx.send(plugin.t(ctx.guild, "cant_kick_anyone", _emote="WARN"))

    confirm = await ctx.prompt(f'This action will kick {len(to_kick)} member{"" if len(to_kick) == 1 else "s"}. Are you sure?', timeout=15)
    if not confirm:
        return await ctx.send(plugin.t(ctx.guild, "aborting"))

    kicked = 0
    for t in to_kick:
        try:
            await ctx.guild.kick(user=t, reason=reason)
            plugin.bot.ignore_for_event.add("bans_kicks", t.id)

            _ = plugin.bot.utils.newCase(ctx.guild, "Ban", t, ctx.author, f"[Massban] {reason}")
        except discord.HTTPException:
            pass
        else:
            kicked += 1

    await ctx.send(plugin.t(ctx.guild, "mkick_success", _emote="YES", users=kicked, total=len(to_kick)))
    await plugin.action_logger.log(
            ctx.guild,
            "mass_kick",
            moderator=ctx.message.author,
            moderator_id=ctx.message.author.id,
            users=kicked,
            reason=reason
        )


from subprocess import run
from conf.settings import SUDO_STR
from .models import Disk

class DiskManager:
    """
    Класс для выполнения операций форматирования, монтирования
    и отмонтирования дисков.
    """
    def __init__(self, instance):
        self.instance = instance

    def formats_disk(self):
        """Метод форматирования диска."""
        cmd = SUDO_STR + f'mkfs -t ext4 /dev/{self.instance.name}'
        if self.instance.format:
            if self.instance.mount_state == 'mount':
                DiskManager.__disk_umount(self.instance)
                run(cmd, shell=True)
                DiskManager.__disk_mount(self.instance)
            else:
                run(cmd, shell=True)
            print(f'Диск {self.instance.name} успешно отформатирован')

    def mounts_or_umounts_disk(self):
        """Метод монтирования и отмонтирования диска."""
        if self.instance.mount_state == 'mount':
            DiskManager.__disk_mount(self.instance)
        else:
            DiskManager.__disk_umount(self.instance)

    def __disk_mount(inst):
        """
        Монтирует диск и отмонтирует предыдущий.
        При этом создает новую папку если данной точки
        монтирования ранее не существовало
        """
        previous_mounted = Disk.objects.get(id=inst.id)
        DiskManager.__disk_umount(previous_mounted)

        cmd = SUDO_STR + f'mkdir -p {inst.mount_point} && ' + \
              SUDO_STR + f'mount /dev/{inst.name} {inst.mount_point}'

        run(cmd, shell=True)
        print(f'Диск {inst.name} успешно монтирован на {inst.mount_point}')

    def __disk_umount(inst):
        """Отмонтирует диск"""
        cmd = SUDO_STR + f'umount {inst.mount_point}'
        run(cmd, shell=True)
        print(f'Диск {inst.name} успешно отмонтирован от {inst.mount_point}')


#setting up the necessary libraries
import mediapipe as mp
import numpy as np
import pandas as pd
import cv2
import os
import warnings
warnings.filterwarnings('ignore')
mp_drawing = mp.solutions.drawing_utils
mp_pose = mp.solutions.pose
mp_holistic = mp.solutions.holistic
import csv

#directories to the necessary files
running_path = r'C:\Users\stanl\OneDrive\Desktop\Pose Estimation\second pose estimation model\running'
walking_path = r'C:\Users\stanl\OneDrive\Desktop\Pose Estimation\second pose estimation model\walking'

#function code to extract the different videos
def get_videos(running_path):
    video_paths = []
    for dirName, subdirList, fileList in os.walk(running_path):
        for filename in fileList:
            if ".mp4" in filename.lower():
                video_paths.append(os.path.join(dirName, filename))
    return video_paths

#fuction call to the different video directories
running_videos = get_videos(running_path)
walking_videos = get_videos(walking_path)

#quick test to see if the directories have been properly cap
print(len(running_videos)), print(len(walking_videos))

#capture landmarks and export csv files
class_name = 'walking'
csv_filename = 'walking(2).csv'

with mp_holistic.Holistic(min_detection_confidence=0.5, min_tracking_confidence=0.5) as holistic:
    for video_path in walking_videos:
        # Initialize VideoCapture for the current video
        cap = cv2.VideoCapture(video_path)

        while cap.isOpened():
            ret, frame = cap.read()

            if not ret:
                print(f"Finished processing {video_path}")
                break

            # Rest of your processing code remains the same
            # recolor image to RGB
            image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            image.flags.writeable = False

            # Make detection
            results = holistic.process(image)

            # Recolor back to BGR
            image.flags.writeable = True
            image = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)

            # Pose Detection
            mp_drawing.draw_landmarks(image, results.pose_landmarks, mp_holistic.POSE_CONNECTIONS,
                                     mp_drawing.DrawingSpec(color=(245, 117, 66), thickness=2, circle_radius=4),
                                     mp_drawing.DrawingSpec(color=(245, 66, 230), thickness=2, circle_radius=2)
                                     )

            # Export coordinates to a CSV file for each video
            try:
                # Extract Pose landmarks
                pose = results.pose_landmarks.landmark
                pose_row = list(np.array([[landmark.x, landmark.y, landmark.z, landmark.visibility] for landmark in pose]).flatten())

                # Concatenate rows
                row = pose_row

                # Append class name
                row.insert(0, class_name)

                # Export to CSV for each video
                with open(csv_filename, mode='a', newline='') as f:
                    csv_writer = csv.writer(f, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL)
                    csv_writer.writerow(row)

            except:
                pass

        # Release video capture for the current video
        cap.release()
        # cv2.destroyAllWindows()


from python_interface.gecco_interface import *
from python_interface.gecco_modules.NoticeUtil import *

i_am='diag_precon'

minexc= keywords.get('method.MR.minexc')
minexc = int(minexc) if minexc is not None else 1

maxexc= keywords.get('method.MR.maxexc')
maxexc = int(maxexc) if maxexc is not None else 1

useT1=(minexc==1)

# perturbative triples are handled differently, keep this for non-iterative cases
if maxexc>2:
    word = keywords.get('method.MR.triples')
    if word is None:
      triples=3
    elif word == "B" or word == "3":
      triples=3
    elif word == "E" or word == "4":
      triples=4
    elif word == "F" or word == "5":
      triples=5
    else:
      quit_error('triples must be one of B,E,F,3,4,5; found: '+word)
    quit_error('full triples: diag_precon requires adaptation')

#------------------------------------------------------------------
#Setting up A_TRF
#-------------------------------------------------------------------

new_target('MAKE_A_TRF')
depend('MakeOrthBasis')

depend('DEF_T')

depend('DEF_LAM')

depend('DEF_O')

depend('MakeRefState')
depend('H0')

comment('Setting up A_TRF')

_A_TRF_shape=',;V,V;,|'\
              ',V;VV,VV;V,|'\
              ',;VV,VV;,|'\
              ',V;,;V,|'\
              ',VV;V,V;VV,|'\
              ',V;V,V;V,|'\
              ',VV;,;VV,'

DEF_SCALAR({
        LABEL:'A_TRF_SCAL'})
DEF_OP_FROM_OCC({
        LABEL:'A_TRF',
        JOIN:3,
        DESCR:_A_TRF_shape})
DEF_ME_LIST({
        LIST:'A_TRF_LST',
        OPERATOR:'A_TRF',
        IRREP:1,
        '2MS':0})

#The actual Formula for A_TRF
#A_TRF=C0^+*t'^+*X^+*[H,t'*X]*C0
#procedure:
#SCAL=<C0^+*L*[H,T]*C0>
#Insert transformation formulas for L and T
#derive with respect to L' and T'
_hamil_='H'
# there is a option to try more here: FOCK_EFF alone is not good, needs shifts (I guess)
#_hamil_='FOCK_EFF'
#depend('MAKE_FOCK_EFF')

EXPAND_OP_PRODUCT({
        LABEL:'FORM_A_TRF',
        OP_RES:'A_TRF_SCAL',
        OPERATORS:['C0^+','LAM2g',_hamil_,'T2g','C0'],
        IDX_SV:[1,2,3,4,5],
        NEW:True})
EXPAND_OP_PRODUCT({
        LABEL:'FORM_A_TRF',OP_RES:'A_TRF_SCAL',
        OPERATORS:['C0^+','LAM2g','T2g',_hamil_,'C0'],
        IDX_SV:[1,2,3,4,5],
        FIX_VTX:True,
        FAC:-1,
        NEW:False})
#eliminate all terms that are ruled out by the commutation(show up with +1 and -1 as prefactor)
SUM_TERMS({
        LABEL_IN:'FORM_A_TRF',
        LABEL_RES:'FORM_A_TRF'})

FACTOR_OUT({
        LABEL_RES:'FORM_A_TRF',
        LABEL_IN:'FORM_A_TRF',
        INTERM:'FORM_GAM0'})

EXPAND({
        LABEL_IN:'FORM_A_TRF',
        LABEL_RES:'FORM_A_TRF',
        INTERM:'FORM_LAM_TRF'})
EXPAND({
        LABEL_IN:'FORM_A_TRF',
        LABEL_RES:'FORM_A_TRF',
        INTERM:'FORM_T2_orth'})
SELECT_SPECIAL({
        LABEL_IN:'FORM_A_TRF',
        LABEL_RES:'FORM_A_TRF',
        OPERATORS:['T2_orth','LAM_TRF'],
        TYPE:'SAME'})

#Double derivative to T' and T'^+ to get A_TRF=<|t^+[H,t]|>
DERIVATIVE({
        LABEL_IN:'FORM_A_TRF',
        LABEL_RES:'FORM_A_TRF_INTERM',
        OP_RES:'Ov',
        OP_DERIV:'LAM_TRF'})
DERIVATIVE({
        LABEL_IN:'FORM_A_TRF_INTERM',
        LABEL_RES:'FORM_A_TRF_FINAL',
        OP_RES:'A_TRF',
        OP_DERIV:'T2_orth'})

debug_FORM('FORM_A_TRF_FINAL')

OPTIMIZE({
        LABEL_OPT:'FOPT_A_TRF_FINAL',
        LABELS_IN:'FORM_A_TRF_FINAL'})
#PRINT_FORMULA({LABEL:'FOPT_A_TRF_FINAL', MODE:'SHORT'})
#PRINT_FORMULA({LABEL:'FORM_A_TRF_FINAL', MODE:'SHORT'})

EVALUATE({
        FORM:'FOPT_A_TRF_FINAL'})

debug_MEL('A_TRF_LST')

#-------------------------------------------------------------------
#building the actual preconditioner
#-------------------------------------------------------------------
new_target('BUILD_PRECON')
depend('MAKE_A_TRF')
depend('EVAL_F_EFF_INACT')

CLONE_OPERATOR({
        LABEL:'PRECON',
        TEMPLATE:'T2g'})
DEF_ME_LIST({
        LIST:'ME_PRECON2g',
        OPERATOR:'PRECON',
        IRREP:1,
        '2MS':0,
        AB_SYM:0}) # AB not well defined for orthog. basis!
#        AB_SYM:+1})

# Uncomment to get a print out of the active preconditioner
#CLONE_OPERATOR({
#        LABEL:'TEST_PRECON',
#        TEMPLATE:'T2g'})
#DEF_ME_LIST({
#        LIST:'TEST',
#        OPERATOR:'TEST_PRECON',
#        IRREP:1,
#        '2MS':0,
#        AB_SYM:0})
#DEF_ME_LIST({
#        LIST:'TEST_DIFF',
#        OPERATOR:'TEST_PRECON',
#        IRREP:1,
#        '2MS':0,
#        AB_SYM:0})

#extract preconditioner
PRECONDITIONER({
        LIST_PRC:'ME_PRECON2g',
        LIST_INP:'FOCK_EFF_INACT_LST'})
#PRECONDITIONER({
#        LIST_PRC:'TEST',
#        LIST_INP:'FOCK_EFF_INACT_LST'})
#
#PRINT_MEL({
#        LIST:'ME_PRECON2g',
#        COMMENT:'hello: inactive'})

EXTRACT_DIAG({
        LIST_RES:'ME_PRECON2g',
        LIST_IN:'A_TRF_LST',
        MODE:'extend'})
SCALE_COPY({
        LIST_RES:'ME_PRECON2g',
        LIST_INP:'ME_PRECON2g',
        FAC:0.2,
        MODE:'prc_thresh'})

#PRINT_MEL({
#        LIST:'ME_PRECON2g',
#        COMMENT:'hello: inactive + active'})

#PRINT_MEL({
#        LIST:'TEST',
#        COMMENT:'hello: test1'})
#ADD({LIST_SUM:'TEST_DIFF',
#     LISTS:['TEST', 'ME_PRECON2g'],
#     FAC:[-1,1]})
#
#PRINT_MEL({
#        LIST:'TEST_DIFF',
#        COMMENT:'hello: test2'})

PRINT_MEL_INFO({
        LIST:'ME_PRECON2g'})

#PRINT_MEL({
#        LIST:'A_TRF_LST',
#        COMMENT:'hello: active'})

debug_MEL('ME_PRECON2g')

#----------------------------------------------------------
#Preconditioner for T1
#----------------------------------------------------------

if (useT1):
  CLONE_OPERATOR({
        LABEL:'PRECON1',
        TEMPLATE:'T1'})
  DEF_ME_LIST({
        LIST:'ME_PRECON1',
        OPERATOR:'PRECON1',
        IRREP:1,
        '2MS':0,
        AB_SYM:0})

  #extract preconditioner
  PRECONDITIONER({
        LIST_PRC:'ME_PRECON1',
        LIST_INP:'FOCK_EFF_INACT_LST'})

  EXTRACT_DIAG({
        LIST_RES:'ME_PRECON1',
        LIST_IN:'A_TRF_LST',
        MODE:'extend'})
  SCALE_COPY({
        LIST_RES:'ME_PRECON1',
        LIST_INP:'ME_PRECON1',
        FAC:0.2,
        MODE:'prc_thresh'})

  debug_MEL('ME_PRECON1')


import os
os.chdir("/workspace/Python/advent of code/day1")
with open("input.txt","r") as input:
    lines= [0,0]+input.read().splitlines()#input.read().splitlines()
    lines= [int(line) for line in lines]

    temp= lines[2]
    count=0
    for i in range(len(lines)):
        total_sum = sum(lines[i:i+3])
        if total_sum>temp:
            count+=1

        temp= total_sum
    print(count-2)


import time
import Adafruit_PCA9685
import signal
import math
import RPi.GPIO as GPIO # README: https://pypi.org/project/RPi.GPIO/
from itertools import cycle
import PID

# The servo hat uses its own numbering scheme within the Adafruit library.
# 0 represents the first servo, 1 for the second, and so on.
LSERVO = 1
RSERVO = 0

LENCODER = 17
RENCODER = 18

ipsLeftCurrent=0
ipsRightCurrent=0

def initPID():
    global pidL, pidR
    P=0.1
    I=0.001
    D=0
    pidL = PID.PID(P,I,D)
    pidR = PID.PID(P,I,D)
    pidL.SetPoint=0
    pidR.SetPoint=0

# This function is called when Ctrl+C is pressed.
# It's intended for properly exiting the program.
def ctrlC(signum, frame):
    print("Exiting")

    # Stop the servos

    GPIO.cleanup()
    setSpeedsPWM (1.5,1.495)
    exit()

# Attach the Ctrl+C signal interrupt
signal.signal(signal.SIGINT, ctrlC)

def initMotors():
    global pwm
    # Initialize the servo hat library.
    pwm = Adafruit_PCA9685.PCA9685()

    # 50Hz is used for the frequency of the servos.
    pwm.set_pwm_freq(50)
    return pwm

def remap(value, fromLow, fromHigh, toLow, toHigh):
    fromRange = (fromHigh - fromLow)
    toRange= (toHigh - toLow)
    newValue = (((value - fromLow) * toRange) / fromRange) + toLow
    # newValue=round(newValue,3)
    return newValue

def clamp(value, low, high):
    return max(min(high, value), low)

def moveXV(X,V):
    travel_time=abs(X/V)
    print("Moving a distance of {} inches at {} linear inches per second for {} seconds".format(X,V,travel_time))

    num_ticks= X/0.255254

    second_timer=time.time()+1
    start_time=time.time()
    status=setSpeedsIPS(V, V)
    if status:
        # while time.time()<end_time:
        ticks_elapsed=(getCounts()[1]+getCounts()[0])/2
        while ticks_elapsed <num_ticks:

            if time.time()>second_timer:
                second_timer=time.time()+1
                time_elapsed=round(time.time()-start_time,3)
                distance_elapsed=round(ticks_elapsed*0.255254,3)
                print("{} seconds pased, moved {} inches".format(time_elapsed,distance_elapsed))

            ticks_elapsed=(getCounts()[1]+getCounts()[0])/2

        time_elapsed=round(time.time()-start_time,3)
        print("Finished moving in {} seconds\n".format(time_elapsed))
        setSpeedsPWM (1.5,1.495)
    else:
        print("Requested velocity is not able to be set, movement cancelled\n")
        setSpeedsPWM (1.5,1.495)

def setSpeedsPWM (pwmLeft, pwmRight):
    global pidL, pidR
    Lcal=0
    Rcal=0

    if abs(pwmLeft-1.5)>0.2 or abs(pwmRight-1.5)>0.2:
        print("Not able to set motor speed to PWM, left: {} right: {}".format(pwmLeft,pwmRight))
    # minPWM=1.3
    # maxPWM=1.7
    # pwmLeft=clamp(pwmLeft,minPWM,maxPWM)
    # pwmRight=clamp(pwmRight,minPWM,maxPWM)
        status=False
    else:
        #print(pidL.SetPoint,getSpeeds()[0],"\t",pidR.SetPoint,getSpeeds()[1])
        pwmLeft=round(pwmLeft,5)
        pwmRight=round(pwmRight,5)
        #print("Setting motor speed in PWM, left: {} right: {}".format(pwmLeft,pwmRight))
        pwm.set_pwm(LSERVO, 0, math.floor(pwmLeft / 20 * 4096));
        pwm.set_pwm(RSERVO, 0, math.floor(pwmRight / 20 * 4096));
        status=True
    return status

def setSpeedsRPS (rpsLeft, rpsRight):
    #print("Setting motor speed in RPS, left: {} right: {}".format(rpsLeft,rpsRight))
    minRPS=-0.8
    maxRPS=0.8
    # rpsLeft=clamp(rpsLeft,minRPS,maxRPS)
    # rpsRight=clamp(rpsRight,minRPS,maxRPS)

    rpsLeft=clamp(rpsLeft,minRPS,maxRPS)
    rpsRight=clamp(rpsRight,minRPS,maxRPS)

    ipsLeft=rpsLeft*2*math.pi*1.3
    ipsRight=rpsRight*2*math.pi*1.3

    setSpeedsIPS(ipsLeft,ipsRight)

def setSpeedsIPS(ipsLeft, ipsRight):
    global ipsLeftCurrent, ipsRightCurrent
    global pidL,pidR
    #print("Setting motor speed in IPS, left: {} right: {}".format(ipsLeft,ipsRight))
    minIPS=-6.8
    maxIPS=6.8
    ipsLeft=clamp(ipsLeft,minIPS,maxIPS)
    ipsRight=clamp(ipsRight,minIPS,maxIPS)

    ipsLeftCurrent=ipsLeft
    ipsRightCurrent=ipsRight

    pidL.SetPoint=ipsLeftCurrent
    pidR.SetPoint=ipsRightCurrent
    # print(pidL.SetPoint)

    pwmL=remap(ipsLeft,minIPS,maxIPS,1.3,1.7)
    pwmR=remap(ipsRight,minIPS,maxIPS,1.7,1.3)
    status=setSpeedsPWM(pwmL,pwmR)
    return status

def setSpeedsVW(V, W):
    print("Setting motor speed in VW, V: {} W: {}".format(V,W))

    if W == 0:
        Vl=V
        Vr=V
    else:
        R=abs(V/W) #inches

        dmid=2 #half of wheel axis distance in inches
        if W>0:
            Vl=abs(W)*(R-dmid)#V of outer wheel
            Vr=abs(W)*(R+dmid)#V of innner wheel
        else:
            Vl=abs(W)*(R+dmid)#V of outer wheel
            Vr=abs(W)*(R-dmid)#V of innner wheel

    if abs(Vl) <=6.8 and abs(Vr) <=6.8:

        setSpeedsIPS(Vl,Vr)
    else:
        print("Motors are not capable of completing maneuver, outer {} inner {}".format(Vl,Vr))

countL=0
countR=0

speedL=0
speedR=0

def onLeftEncode(pin):
    global ipsLeftCurrent, ipsRightCurrent
    global pidL
    global countL
    global prevEncL
    global speedL
    minIPS=-6.8
    maxIPS=6.8

    countL=countL+1 #Increment tick count

    now=time.time()
    speedL=2*math.pi*1.3*(1/32)/(now-prevEncL)

    if ipsLeftCurrent<0:
        speedL=-speedL
    print(speedL)

    pidL.update(speedL)
    ipsLeftCurrent=pidL.output+ipsLeftCurrent

    pwmL=remap(ipsLeftCurrent,minIPS,maxIPS,1.3,1.7)
    pwmR=remap(ipsRightCurrent,minIPS,maxIPS,1.7,1.3)

    setSpeedsPWM(pwmL,pwmR)

    prevEncL=now

    #print("Left encoder ticked!")

# This function is called when the right encoder detects a rising edge signal.
def onRightEncode(pin):
    global ipsLeftCurrent, ipsRightCurrent
    global pidR
    global countR
    global prevEncR
    global speedR
    minIPS=-6.8
    maxIPS=6.8

    countR=countR+1 #Increment tick count

    now=time.time()

    speedR=2*math.pi*1.3*(1/32)/(now-prevEncR)

    if ipsRightCurrent<0:
        speedR=-speedR

    pidR.update(speedR)
    ipsRightCurrent=pidR.output+ipsRightCurrent

    pwmL=remap(ipsLeftCurrent,minIPS,maxIPS,1.3,1.7)
    pwmR=remap(ipsRightCurrent,minIPS,maxIPS,1.7,1.3)

    setSpeedsPWM(pwmL,pwmR)

    prevEncR=now

def initEncoders():
    global prevEncL
    global prevEncR

    prevEncL=time.time()
    prevEncR=time.time()

    GPIO.setwarnings(False)
    GPIO.setmode(GPIO.BCM)

    GPIO.setup(LENCODER, GPIO.IN, pull_up_down=GPIO.PUD_UP)
    GPIO.setup(RENCODER, GPIO.IN, pull_up_down=GPIO.PUD_UP)

    GPIO.add_event_detect(LENCODER, GPIO.RISING, onLeftEncode)
    GPIO.add_event_detect(RENCODER, GPIO.RISING, onRightEncode)

def getCounts():
    global countL, countR
    return (countL,countR)

def resetCounts():
    global countL, countR
    countL=0
    countR=0

def getSpeeds():
    global speedL, speedR
    retL=speedL
    retR=speedR
    # speedL=0
    # speedR=0
    return (retL,retR)

def turnRV(R, V):
    W=V/R
    setSpeedsVW(V,W)


import re
from os import listdir
from json import dumps, load
from config import maximalArrayItem, ignored_texts
from functions import updateEQ

source = "datasets"
intents = []

def patternOrResponse(num):
    return "pattern" if num % 2 == 0 else "response"

regrex_pattern = re.compile(pattern = "["
                        u"\U0001F600-\U0001F64F"  # emoticons
                        u"\U0001F300-\U0001F5FF"  # symbols & pictographs
                        u"\U0001F680-\U0001F6FF"  # transport & map symbols
                        u"\U0001F1E0-\U0001F1FF"  # flags (iOS)
                           "]+", flags = re.UNICODE)

for fl in listdir(source):
    if fl.endswith(".json"):
        if fl.startswith("telegram"):
             file = load(open(f"{source}/{fl}", "r+", encoding="utf8"))
             patterns = []
             responses = []

             messages = file["messages"]
             index = 1
             for message in messages:
                 if type(message["text"]) == str and len(message["text"]) > 0:
                    message["text"] = regrex_pattern.sub(r"", message["text"]).strip()
                    if len(message["text"]) > 2 and message["text"].lower() not in ignored_texts:
                        if len(patterns) < maximalArrayItem and patternOrResponse(index) == "pattern":
                            patterns.append(message["text"].lower())
                        elif len(responses) < maximalArrayItem and patternOrResponse(index) == "response":
                            responses.append(message["text"].lower())
                 index += 1
             tagName = fl.split("_")[1].split(".")[0]
             intents.append({"tag": tagName, "patterns": list(dict.fromkeys(patterns)), "responses": list(dict.fromkeys(responses)), "context": []})
             print(f"{tagName} intent loaded. Parsing {len(messages)} messages to {len(patterns)} patterns, and {len(responses)} responses")
        elif fl.startswith("custom"):
            file = load(open(f"{source}/{fl}", "r+", encoding="utf8"))
            patterns = []
            for message in file["messages"]:
                if len(message) > 0:
                    if len(patterns) < maximalArrayItem:
                        patterns.append(message.lower())
            tagName = fl.split("_")[1].split(".")[0]
            intents.append({"tag": tagName, "patterns": list(dict.fromkeys(patterns)), "responses": file.get("responses", []), "context": file.get("context", [])})
            print(f"{tagName} intent loaded, {len(patterns)} patterns")

print("Saving intents to intents.json")
with open("intents.json", "r+") as f:
    f.write(dumps({"intents": intents}, indent=4))
    updateEQ()
    print("Intents saved")


#!/usr/bin/env python
'''Ray implementation - for general raytracing

David Dunn
Jan 2017 - created by splitting off from dGraph

ALL UNITS ARE IN METERS
    ie 1 cm = .01

www.qenops.com

'''
__author__ = ('David Dunn')
__version__ = '1.6'

import numpy as np
from numpy import dot, cross
from numpy.linalg import norm
import operator
from dGraph.shapes import Shape

class Ray(object):
    ''' A ray shot from a point in a particular direction for calculating intersections in generating shadows and general rendering
        point
        direction
        evaluate (intersect ray with all objects in scene and evaluate t for each)
        possible tMin, tMax
    '''
    def __init__(self, point, vector):
        self._pnt = point
        self._vec = vector/norm(vector)
        self._invec = 1.0/self._vec
    @property
    def point(self):
        return self._pnt
    @property
    def vector(self):
        return self._vec
    def evaluate(self, scene):
        ''' intersect ray with all children objects of scene and return list of intersections
        (walk the graph using bouding boxes on the transforms -
            if it intersects:
                evaluate children
                if it is a surface:
                    if it intersects:
                        get point and t value (from Surface)
                        may intersect multiple times - need to do something about that
                    else return None)
        That is pie in the sky, for now just brute force it, call the intersect method on every surface object in scene
        '''
        intersections = []
        for obj in scene:
            if isinstance(obj, Shape):
                possibles = obj.intersection(self)  # distance, point, normal, material
                if possibles is not None:
                    for p in possibles:
                        p['object'] = obj
                        intersections.append(p)
        return intersections
    def render(self, world):
        # evaluate the collisions the ray and find the closest
        intersections = self.evaluate(world)
        intersections.sort(key=operator.itemgetter('distance'))
        # calculate color
        if intersections == []:
            return np.array([0,0,0])
        else:
            first = intersections[0]
            return first['material'].render(first['point'], first['normal'], viewVector=self.vector, world=world)
    @classmethod
    def _calcVector(cls, basePoint, goalPoint):
        ''' calculate the vector that starts at basePoint and travels through goalPoint '''
        return goalPoint - basePoint
    def intersectBox(self, bMin, bMax):
        tx1 = (bMin[0]-self._pnt[0])*self._invec[0]
        tx2 = (bMax[0]-self._pnt[0])*self._invec[0]
        tmin = min(tx1, tx2)
        tmax = max(tx1, tx2)
        ty1 = (bMin[1]-self._pnt[1])*self._invec[1]
        ty2 = (bMax[1]-self._pnt[1])*self._invec[1]
        tmin = max(tmin, min(ty1, ty2))
        tmax = min(tmax, max(ty1, ty2))
        tz1 = (bMin[2]-self._pnt[2])*self._invec[2]
        tz2 = (bMax[2]-self._pnt[2])*self._invec[2]
        tmin = max(tmin, min(tz1, tz2))
        tmax = min(tmax, max(tz1, tz2))
        return tmax >= max(0.0, tmin)
    def intersectBoxOld(self, bMin, bMax):
        cMin = [-float('inf'),-float('inf'),-float('inf')]
        cMax = [float('inf'),float('inf'),float('inf')]
        if self._vec[0] != 0:
            cMin = self._vec*((bMin[0]-self._pnt[0])/self._vec[0]) + self._pnt  # get x min
            cMax = self._vec*((bMax[0]-self._pnt[0])/self._vec[0]) + self._pnt   # get x max
            if (cMin[0]-self._pnt[0])/self._vec[0] < 0 and (cMax[0]-self._pnt[0])/self._vec[0] < 0:  # verify it crosses ray after start point
                return False #, cMin, cMax
        if self._vec[1] != 0:
            yMin = self._vec*((bMin[1]-self._pnt[1])/self._vec[1]) + self._pnt # get y min
            yMax = self._vec*((bMax[1]-self._pnt[1])/self._vec[1]) + self._pnt  # get y max
            if (yMin>cMax).all() or (cMin>yMax).all():
                return False #, cMin, cMax
            if (cMin<yMin).all():
                cMin = yMin
            if (cMax>yMax).all():
                cMax = yMax
            if (cMin[1]-self._pnt[1])/self._vec[1] < 0 and (cMax[1]-self._pnt[1])/self._vec[1] < 0:  # verify it crosses ray after start point
                return False #, cMin, cMax
        if self._vec[2] != 0:
            zMin = self._vec*((bMin[2]-self._pnt[2])/self._vec[2]) + self._pnt # get z min
            zMax = self._vec*((bMax[2]-self._pnt[2])/self._vec[2]) + self._pnt  # get z max
            if (zMin>cMax).all() or (cMin>zMax).all():
                return False #, cMin, cMax
            if (cMin<zMin).all():
                cMin = zMin
            if (cMax>zMax).all():
                cMax = zMax
            if (cMin[2]-self._pnt[2])/self._vec[2] < 0 and (cMax[2]-self._pnt[2])/self._vec[2] < 0:  # verify it crosses ray after start point
                return False #, cMin, cMax
        #if (cMin<self._pnt).all():
        #    cMin = self._pnt
        #if (cMax>self._pnt).all():
        #    cMax = self._pnt
        return True #, cMin, cMax
    def intersectPlane(self, point, normal):
        denom = dot(self._vec,normal)
        if denom == 0:
            return None, None
        dist = (dot(point-self._pnt,normal))/denom
        if dist <= 0:
            return None, None
        point = dist*self._vec + self._pnt
        return dist, point
    def intersectTriSlow(self, a, b, c, normal=None):  # Moller-Trumbore algorithm
        global epsilon
        # Find vectors for two edges sharing point 'a'
        e1 = b - a
        e2 = c - a
        # Begin calculating determinant - also used to calculate 'u' parameter
        P = cross(self._vec, e2)
        # if determinant is near zero, ray lies in plane of triangle
        det = dot(e1, P)
        # NOT CULLING
        if det > -epsilon and det < epsilon:
            return False, None, None
        inv_det = 1.0 / det
        # calculate distance from 'a' to ray origin
        T = self._pnt - a
        # Calculate u parameter and test bound
        u = dot(T, P) * inv_det
        # The intersection lies outside of the triangle
        if u < 0 or u > 1:
            return False, None, None
        # Prepare to test 'v' parameter
        Q = cross(T, e1)
        # Calculate 'v' parameter and test bound
        v = dot(self._vec, Q) * inv_det
        # The intersection lies outside of the triangle
        if v < 0 or u+v > 1:
            return False, None, None
        t = dot(e2, Q) * inv_det
        if(t > epsilon): #ray intersection
            dist, point = self.intersectPlane(a, normal)
            return True, dist, point
        # No intersection
        return False, None, None
    def intersectTri(self, a, b, c, normal=None):
        if normal is None:
            normal = PolySurface.calcTriNorm(a,b,c)
        dist, point = self.intersectPlane(a, normal)
        if dist is None:
            return False, None, None
        # calculate baycentric
        v0 = c - a
        v1 = b - a
        v2 = point - a
        # get dot products
        dot00 = dot(v0, v0)
        dot01 = dot(v0, v1)
        dot02 = dot(v0, v2)
        dot11 = dot(v1, v1)
        dot12 = dot(v1, v2)
        # get barycentric coordinates
        invDenom = 1 / (dot00 * dot11 - dot01 * dot01)
        u = (dot11 * dot02 - dot01 * dot12) * invDenom
        v = (dot00 * dot12 - dot01 * dot02) * invDenom
        inside = u>=0 and v>=0 and u+v<1
        return inside, dist, point
    def intersectRay(self, other):
        # get the distance and midpoint of the line of smallest distance between two lines
        v1 = self.vector
        v2 = other.vector
        p1 = self.point
        p2 = other.point
        X = np.cross(v1,v2)
        ray1Pnt = p1 + np.dot(np.cross(p2-p1,v2),X)/np.dot(X,X)*v1
        ray2Pnt = p2 + np.dot(np.cross(p2-p1,v1),X)/np.dot(X,X)*v2
        midPnt = (ray1Pnt+ray2Pnt)/2
        distance = norm(ray2Pnt-ray1Pnt)
        return (distance, midPnt, ray1Pnt, ray2Pnt)
    def projectPointOnRay(self, pnt):
        diff = pnt - self.point
        return np.dot(diff,self.vector)*self.vector+self.point
    def distanceToPoint(self, pnt):
        diff = self.point - pnt
        return norm(diff-(np.dot(diff,self.vector)*self.vector))


from scrapy.http import FormRequest, Request
from scrapy.selector import Selector
from scrapy.spiders import BaseSpider
j = 0
class Happytrips(BaseSpider):
	name = "trips"
	start_urls = ['https://timesofindia.indiatimes.com/travel/destinations']
	#start_urls = ['https://timesofindia.indiatimes.com/travel/romantic-places']

	def parse(self, response):
		reference = response.url
		sel = Selector(response)
		des = ['romantic', 'historical', 'religious', 'beaches', 'city', 'hill+stations', 'adventure', 'wildlife']
		for i in des:
			url = 'https://timesofindia.indiatimes.com/travel/travel_destination.cms?curpg=1&ajax=1&query=mData_GuideGenre:%22'+i+'%22'
			import pdb;pdb.set_trace()
			yield Request(url, callback = self.parse_data, meta = {'des':des, 'url':url})

	def parse_data(self, response):
		sel = Selector(response)
		reference = response.url
		des = response.meta['des']
		# write xpaths for page numbers and take in list
		for i in range(1, 7):
			complete_url = 'https://timesofindia.indiatimes.com/travel/travel_destination.cms?curpg='+str(i)+'&ajax=1&query=mData_GuideGenre:%22'+des[j]+'%22'
			yield Request(complete_url, callback=self.parse_next, meta={'reference':reference, 'complete_url':complete_url})

	def parse_next(self, response):
		sel = Selector(response)
		nodes = sel.xpath('//div[@id="content_wrapper"]//div[contains(@class, "box1 one-third")]')
		for node in nodes:
			title = (''.join(node.xpath('.//h3/a/text()').extract()).replace('\n', '')).encode("utf-8")
			tags = ','.join(node.xpath('.//p[@class="toggle tags"]//a/text()').extract())
			#print (title)
		yield Request(response.url, callback=self.parse)
		#import pdb;pdb.set_trace()

'''

	def parse(self, response):
		sel = Selector(response)
		#index = sel.xpath('//div[@class="pagination2"]//a[@class="next"]/@lastindex').extract()
		node = sel.xpath('//div[@class="clearfix tab_data"]//li/a')
		for x in node:
			destination_link = ''.join(x.xpath('./@href').extract())
			yield Request(destination_link, callback = self.parse_next)

	def parse_next(self, response):
		sel = Selector(response)
		nodes = sel.xpath('//div[@id="content_wrapper"]//div[@itemtype="https://schema.org/ImageObject"]')
		for node in nodes:
			title = (''.join(node.xpath('.//h3/a/text()').extract()).replace('\n', '')).encode("utf-8")
			tags = ','.join(node.xpath('.//p[@class="toggle tags"]//a/text()').extract())
			#import pdb;pdb.set_trace()'''
'''	def parse_next(self, response):
		sel = Selector(response)
		nodes = sel.xpath('//div[@id="content_wrapper"]//div[@itemtype="https://schema.org/ImageObject"]')
		for node in nodes:
			title = (''.join(node.xpath('.//h3/a/text()').extract())).replace('\n', '')
			tags = ','.join(node.xpath('.//p[@class="toggle tags"]//a/text()').extract())
			link = ''.join(node.xpath('.//h3/a/@href').extract())
			page_link = 'https://timesofindia.indiatimes.com' + link
		#index = ''.join(sel.xpath('//div[@class="pagination2"]//a[@class="next"]/@lastindex').extract())
		link = sel.xpath('//div[@class="pagination2"]//a')
		for x in link:
			page = ''.join(x.xpath('./@href').extract())
			full_link = 'https://timesofindia.indiatimes.com' + page
			if full_link:  tried for next page urls code'''

'''	'for next in next_page:
			next_link = next.xpath('.//@href').extract()
			import pdb;pdb.set_trace()
		nodes = sel.xpath('//div[@id="content_wrapper"]//div[@class="box1 one-third"]')
		for node in nodes:
			tags = ''.join(node.xpath('.//p[@class="toggle tags"]/a/text()').extract())
			title = ''.join(node.xpath('.//h3/a/text()').extract())
			link = ''.join(node.xpath('.//h3/a/@href').extract())
			#print (tags)'''


# %%

import numpy as np
import scipy.linalg as la
import sympy as sympy
from numba import jit
from matplotlib import pyplot as plt

# %%

# %%
'''

{Ti_m + 2H_si} + {2Fe3_m + V_m} = Ti_si + 2Fe2_m + 2H_m

K = (H_m^2 * Fe2_m^2 * Ti_si)/(Ti_Cli * {2Fe3_m + V_m})

sum_Ti = Ti_Cli + Ti_si
sum_H = H_m + Ti_Cli + {2Fe3_m + V_m} This is wrong it should be sum_H = H_m + Ti_Cli
sum_Fe = Fe2_m + {2Fe3_m + V_m}

#_________________________________________ Mg-Site reaction
{Ti_m + 2H_si} = [Ti_si] + [2H_m]

K = ([Ti_si][2H_m])/[Ti_m+2H_si]

sum_Ti = [Ti_si] + [Ti_m+2H_si]
sum_H = [2H_m] + [Ti_m+2H_si]

eq = solve(eq2,Ti_Cli)
eq1 = subs(eq1,Ti_Cli, eq)
'''
K = sympy.symbols("K", positive = True, real=True)
Ti_Cli, Ti_si, H_m, sum_Ti, sum_H, Fe3V, sumFe, Fe2_m = sympy.symbols(
    "Ti_Cli Ti_si H_m sum_Ti sum_H Fe3V sumFe Fe2_m", positive=True, real = True)

# %%

#%%
eq1 = (sum_Ti - Ti_si - Ti_Cli)
eq2 = (sum_H - H_m - Ti_Cli ) #- Fe3V)
eq3 = (sumFe - Fe2_m - Fe3V)
# I am wondering if there are other reactions we could write to help combine some of these other equations
#K = (H_m ^ 2 * Fe2_m ^ 2 * Ti_si)/(Ti_Cli * {2Fe3_m + V_m})
eqk = sympy.Eq((H_m ** 2 * Fe2_m ** 2 * Ti_si)/(Ti_Cli * Fe3V),K)
# %%

# %%
# %%
sympy.solve([eq1, eq2, eq3, eqk], [Ti_si, Ti_Cli, Fe3V, Fe2_m], exclude = [sum_H, sum_Ti, sumFe, K], dict = True)

# %%
sympy.nonlinsolve([eq1, eq2, eq3, eqk], [Ti_si, Ti_Cli, Fe3V, Fe2_m])
# %%

# %%

# %%

# %%

# %%
eq = sympy.solve(eq1_new, Ti_si)
eqk_new = eqk_new.subs(Ti_si, eq[0])
sympy.solve(eqk_new, H_m)

# this returns an empty list. I am not sure why?
sympy.nonlinsolve([eq1, eqk, eq2], [Ti_si, Ti_Cli])


import tensorflow as tf
from PIL import Image
import numpy as np

image_size = (28, 28)

# load model
model = tf.keras.models.load_model('tensorflow_model/mnist_ann_model.h5')

graph = tf.get_default_graph()

def predict_image(test_image):
	# load test image, resize and normalize it
	img = Image.open(test_image)
	img.thumbnail(image_size, Image.ANTIALIAS)
	img = img.convert('L')
	image_data = np.asarray(img, dtype=np.float32)
	image_data = image_data / 255
	image_data_test = image_data.reshape((1, image_size[0], image_size[1]))

	global graph
	with graph.as_default():

		# predit the output
		classes = model.predict(image_data_test)
		image_pred = str(np.argmax(classes))
		confidence = round(classes[0][np.argmax(classes)], 2) * 100
		print(image_pred, confidence)

		return image_pred, confidence

# test with dummy image
if __name__ == '__main__':
	predict_image('tensorflow_model/seven.png')


def bubble(unsorted):

	length_unsorted = len(unsorted)

	#If we don't swap any numbers, the list is sorted.
	swaps = True
	while(swaps==True):
		swaps=False

		#Compare n=0 and n=1, then n=1 and n=2, ...
		for i in range(length_unsorted-1):
			if (unsorted[i] > unsorted [i+1]):
				#Swap two numbers, using a temp variable so we don't overwrite
				temp = unsorted[i+1]
				unsorted[i+1] = unsorted[i]
				unsorted[i] = temp
				swaps=True

		#We know the largest number will be at the end of the list
		#No point in continuing to check it!
		length_unsorted = length_unsorted-1

	return unsorted

def bubble_counter(unsorted):

	length_unsorted=len(unsorted)

	comparisons=0

	swaps=True
	while(swaps==True):
		swaps=False

		for i in range(length_unsorted-1):
			if (unsorted[i] > unsorted [i+1]):
				temp = unsorted[i+1]
				unsorted[i+1] = unsorted[i]
				unsorted[i] = temp
				swaps=True
				comparisons+=1

		length_unsorted = length_unsorted-1

	return(comparisons)

def main():

	unsorted = [5,4,3,2,1]
	sorted = bubble(unsorted)
	print(sorted)
	print(bubble_counter([5,4,3,2,1]))

if __name__ == '__main__':
	main()