#!/usr/bin/env python3

"""
Copyright (c) 2016-present, Facebook, Inc.
All rights reserved.

This source code is licensed under the BSD-style license found in the
LICENSE file in the root directory of this source tree. An additional grant
of patent rights can be found in the PATENTS file in the same directory.
"""

import argparse

from magma.policydb.rule_store import PolicyRuleDict
from lte.protos.policydb_pb2 import FlowMatch, FlowDescription, PolicyRule

def add_rule(args):
    rule_id = args.rule_id
    policy_dict = PolicyRuleDict()
    arg_list = {'ip_proto': args.ip_proto,
                'ipv4_dst': args.ipv4_dst,
                'ipv4_src': args.ipv4_src,
                'tcp_dst': args.tcp_dst,
                'tcp_src': args.tcp_src,
                'udp_dst': args.udp_dst,
                'udp_src': args.udp_src,
                'direction': args.direction}
    match = FlowMatch(**arg_list)
    flow = FlowDescription(match=match, action=args.action)
    rule = policy_dict.get(rule_id)
    if not rule or args.overwrite:
        action = 'add'
        rule = PolicyRule(id=rule_id, flow_list=[flow])
    else:
        action = 'edit'
        rule.flow_list.extend([flow])
    policy_dict[rule_id] = rule
    print("Rule '%s' successfully %sed!" % (rule_id, action))

def create_parser():
    """
    Creates the argparse parser with all the arguments.
    """
    parser = argparse.ArgumentParser(
        description='Management CLI for policydb',
        formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    # Add subcommands
    subparsers = parser.add_subparsers(title='subcommands', dest='cmd')
    parser_add = subparsers.add_parser('add_rule', help='Add rule')
    parser_add.add_argument('rule_id', help='rule id to add')
    parser_add.add_argument('-ipd', '--ipv4_dst', help='ipv4 dst for rule')
    parser_add.add_argument('-ips', '--ipv4_src', help='ipv4 src for rule')
    parser_add.add_argument('-p', '--ip_proto', help='ip proto for rule',
                            type=int)
    parser_add.add_argument('-td', '--tcp_dst', type=int,
                            help='tcp dst for rule, set -p to IPPROTO_TCP(6)')
    parser_add.add_argument('-ts', '--tcp_src', type=int,
                            help='tcp src for rule, set -p to IPPROTO_TCP(6)')
    parser_add.add_argument('-ud', '--udp_dst', type=int,
                            help='udp dst for rule, set -p to IPPROTO_UDP(17)')
    parser_add.add_argument('-us', '--udp_src', type=int,
                            help='udp src for rule, set -p to IPPROTO_UDP(17)')
    parser_add.add_argument('-d', '--direction', type=int,
                            help='0 == UPLINK, 1 == DOWNLINK')
    parser_add.add_argument('-a', '--action', type=int,
                            help='0 == PERMIT, 1 == DENY')
    parser_add.add_argument('-o', '--overwrite', action='store_true',
                            help='overwrite existing rule')

    parser_add.set_defaults(func=add_rule)
    return parser

def main():
    parser = create_parser()

    # Parse the args
    args = parser.parse_args()
    if not args.cmd:
        parser.print_usage()
        exit(1)

    # Execute the subcommand function
    args.func(args)

if __name__ == "__main__":
    main()


# coding:utf-8
'''
求出平均数量最大的10个年龄
'''

from mrjob.job import MRJob
from mrjob.job import MRStep

class Friend(MRJob):
    # 第一个step，得到每一个年龄的平均朋友数量
    def mapper1(self,_,line):
        row = line.split(',')
        yield row[2],int(row[3])

    def reducer1(self,age,num):
        l = list(num)
        yield age,sum(l)/len(l)

    # 第二个step：求出平均数量最大的10个年龄
    def mapper2(self,age,avernum):
        # 【很重要】mapper2的输入是reducer1的输出
        # 【重要】mapper2执行了几次？有多少个age，就执行了几次！或者说，reducer1输出了几次，mapper2就执行几次
        # 必须把平均朋友数量和相对应的年龄写在同一个元组当中，这样才能一一对应
        yield None,(avernum,age)

    def reducer2(self,_,values):
        # values是元组的列表，列表的每个元素都是平均朋友数量和相对应的年龄组成的一个元组
        # reducer2只执行了一次，因为mapper2中只输出了一个key，那就是None
        l = list(values)
        # l.sort()
        for i in l[-10:]:
            yield i[1],i[0]

    def steps(self):
        return [
            MRStep(mapper = self.mapper1,
                   reducer = self.reducer1
                   ),
            MRStep(mapper = self.mapper2,
                   reducer = self.reducer2
                   )
        ]

if __name__ == '__main__':
    Friend.run()


import re
import nltk
import numpy as np
import pandas as pd
from nltk.stem import PorterStemmer, WordNetLemmatizer
from nltk.sentiment.vader import SentimentIntensityAnalyzer
from nltk.corpus import stopwords
from sklearn.feature_extraction.text import TfidfVectorizer
from server_side.apps.module_interaction.additional_modules import constants
from server_side.apps.data_interaction import crud

def find_danger(id_disaster, language):
    disaster = crud.read_disaster_id(id_disaster)
    if disaster == '':
        return ''
    quantity_indicator = find_quantity_indicator(disaster)
    peak = np.random.normal(find_center_distribution(quantity_indicator, disaster.term))
    content_analysis = make_content_analysis(disaster.about, language, disaster.id)
    return peak * content_analysis

def find_quantity_indicator(disaster):
    intensity_list = [constants.MIN_INTENSITY, disaster.intensity, constants.MAX_INTENSITY]
    intensity = [float(i) / max(intensity_list) for i in intensity_list][1]
    readiness_list = [constants.MIN_READINESS, disaster.readiness_degree, constants.MAX_READINESS]
    readiness = [float(i) / max(readiness_list) for i in readiness_list][1]
    return intensity / readiness

def find_center_distribution(indicator, term):
    indicator_list = [constants.MIN_INDICATOR, indicator, constants.MAX_INDICATOR]
    indicator = [float(i) / max(indicator_list) for i in indicator_list][1]
    return term / indicator

def make_content_analysis(text, language, id_disaster):
    sid = SentimentIntensityAnalyzer()
    text = clean_text(text)
    text = process_text(text, language)
    crud.update_disaster_about(id_disaster, text)
    dictionary = make_dictionary(id_disaster)
    dictionary.insert(0, text)
    tfidf_vectorizer = TfidfVectorizer()
    values = tfidf_vectorizer.fit_transform(dictionary)
    feature_names = tfidf_vectorizer.get_feature_names()
    data = pd.DataFrame(values.toarray(), columns=feature_names)
    data = data.T[data.T[0] != 0]
    words = list(data.index)
    sum_ = 0
    sum_f = 0
    for word in words:
        polarity = sid.polarity_scores(word)['compound']
        frequency = data[0][word]
        sum_f += frequency
        sum_ += polarity * frequency
    return sum_ + sum_f

def clean_text(text):
    pattern = r"[\W\d_]"
    return re.sub(pattern, " ", text)

def process_text(text, language):
    stemmer = PorterStemmer()
    lemmatizer = WordNetLemmatizer()
    stop_words = set(stopwords.words(get_language_name(language)))
    sentences = nltk.sent_tokenize(text)
    sentences_processed = []
    for sentence in sentences:
        words_processed = []
        words = nltk.word_tokenize(sentence)
        words = [word for word in words if word not in stop_words]
        for word in words:
            word = stemmer.stem(word)
            word = lemmatizer.lemmatize(word)
            words_processed.append(word)
        words = [word for word in words_processed if word not in stop_words]
        sentences_processed.append(" ".join(words))
    text_processed = " ".join(sentences_processed)
    return text_processed

def make_dictionary(id_disaster):
    disasters = crud.read_disasters()
    dictionary = []
    for disaster in disasters:
        if disaster.about_clean != "" and disaster.id != id_disaster:
            dictionary.append(disaster.about_clean)
    return dictionary

def get_language_name(language):
    if language == "en":
        return "english"
    if language == "de":
        return "german"
    if language == "ru" or language == "be" or language == "uk":
        return "russian"


import os
import sys
import feedparser
from bs4 import BeautifulStoneSoup
from nltk import clean_html
import urllib
#import HTMLParser

def cleanHtml(html):
    return BeautifulStoneSoup(clean_html(html),
                              convertEntities=BeautifulStoneSoup.HTML_ENTITIES).contents[0]

def get_feedparser_feed(FEED_URL):

    fp = feedparser.parse(FEED_URL)

    if fp and fp.entries and fp.entries[0]:
        print("Fetched %s entries from '%s'" % (len(fp.entries), fp.feed.title))
    else:
        print('No entries parseed!')
        sys.exit()
    return fp

def get_blog_posts(fp):
    global feed_dict, blog_posts

    blog_posts = []
    for e in fp.entries:
        try:
            content = e.content[0]
        except AttributeError:
            content = e.summary_detail
        feed_dict = {'title': e.title,
                     'content': content.value,
                     'link': e.links[0].href}
        blog_posts.append(feed_dict)
    return blog_posts

if __name__ == '__main__':
    FEED_URL = 'http://www.alldeaf.com/archive/index.php/t-7.html'
    fp = get_feedparser_feed(FEED_URL)
    blog_posts = get_blog_posts(fp)
    for each in blog_posts:
        print(each)


# -*- coding: utf-8 -*-
"""
Created on Thu Dec 14 09:13:25 2017

@author: Thijs IJPelaar

Dit script leest de safetyfactors uit berekende BM-grasdocumenten uit
"""

import xml.etree.cElementTree as ET
import os

#Aan te passen pad, selecteer de folder met de uitgerekende BM-grasbestanden
dir = r'\\tsclient\W\WB\1. Toetssporen\36-1\6. GEBU\6. Projectbestanden BM Gras'

with open('output.csv', 'w') as f:
    for xml in os.listdir(dir):
        tree = ET.ElementTree(file=os.path.join(dir,xml))
        for output in tree.iter(tag='Output'):
            if output.attrib['Key'] == '14':
                f.write(str(xml)+';'+str(output.attrib['FoS'])+'\n')
                print(xml,output.attrib['FoS'])


"""
Created on Tue Mar 03 15:57:41 2015
@author: Ching-Yen
"""
"""
This script is to make a file recording which SMILES are outliers in each combination.
1 stands for Outliers. 0 stands for fitted group.
<input> argument: percentage of outliers

DFT_(property)_(index)_(flavorName).csv
SMILES,amount of this SMILES, max, min, median, mean, MAD, SD, CV

"""
# remember to remove  "break"
filename_CountBB = "BB_test.csv"
str_property = "HOMO"

import pandas as pd
import argparse
import time
start = time.time()
import csv
import numpy as np
import matplotlib
matplotlib.use('Agg')
### the HelpFormatter and provide a special intro for the options that should be handled "raw"
### Any other calls to .add_argument() where the help does not start with R| will be wrapped as normal.
class SmartFormatter(argparse.HelpFormatter):

    def _split_lines(self, text, width):
        # this is the RawTextHelpFormatter._split_lines
        if text.startswith('R|'):
            return text[2:].splitlines()
        return argparse.HelpFormatter._split_lines(self, text, width)

parser = argparse.ArgumentParser(description="Do Linear Regression to the data",
                                 formatter_class=SmartFormatter)

#parser.add_argument("property", type=int, choices=[1,2,3,4],
#                    help="R|choose the options of property:\n"
#                    "1 = HOMO  2 = LUMO  3 = Dipole  4 = Gap")
parser.add_argument("percent_outlier", type=float, help="R|define the outlier\n"
                    "enter the percentage of data taken out to be outliers\n"
                    "input only number part")
parser.add_argument("-x", "--x_flavor", type=int, default = 1,
                    choices=[1,2], help="R|choose the flavor for x-axis:\n"
                    "1 = BP86/SVP    2 = B3LYP/SVP")
parser.add_argument("-y", "--y_flavor", type=int, default = 999,
                    choices=[1,2,3,4,5,6,7,8,9], help="R|choose the flavor for y-axis:\n"
                    "1 = BP86/SVP    2 = B3LYP/SVP  3 = PBE0/SVP \n4 = BH&HLYP/SVP 5 = M06-2X/SVP"
                    " 6 = HF/SVP \n7 = BP86/TZVP   8 = B3LYP/TZVP 9 = PBE0/TZVP")

#parser.add_argument("-rb","--result_box",action='store_false',default=True,
#                    help="Hide the result display box in all plots")
#parser.add_argument("-rb1","--result_box1",action='store_false',default=True,
#                    help="Hide the result display box only in original data pool")
#parser.add_argument("-rb2","--result_box2",action='store_false',default=True,
#                    help="Hide the result display box only in outlier")
#parser.add_argument("-rb3","--result_box3",action='store_false',default=True,
#                    help="Hide the result display box only in remaining pool")
#
#parser.add_argument("-lr","--lr_line",action='store_false',default=True,
#                    help="Hide all the LinearReg lines.")
#parser.add_argument("-lr1","--lr_line1",action='store_false',default=True,
#                    help="Hide the LinearReg line for original data pool.")
#parser.add_argument("-lr2","--lr_line2",action='store_false',default=True,
#                    help="Hide the LinearReg line for outliers.")
#parser.add_argument("-lr3","--lr_line3",action='store_false',default=True,
#                    help="Hide the LinearReg line for remaining pool.")
#
#args = parser.parse_args('1 1 -x 1 -y 6 -lr2 -lr3'.split())
args = parser.parse_args('1'.split())
#args = parser.parse_args('1 1 -x 1 -y 6 -lr2 -lr3'.split())
#args = parser.parse_args()

#args = parser.parse_args()
###############################Function #######################################
def record_time(part,start,timenow,timelast):
#    str1 = str(part)
    str2 = str(timenow - timelast)
    str3 = str(timenow - start)
    str6 = "time_record.txt"
    txt = open(str6, 'a')
    txt.write(part),txt.write("    "),txt.write(str2),txt.write("    "),
    txt.write(str3),txt.write("\n")

###################### Load building blocks dictionary file ##################
def readDict(fn):
    f=open(fn,'rb')
    dict_rap={}

    for key, val in csv.reader(f):
        dict_rap[key]=eval(val)
    f.close()
    return(dict_rap)

#dict_BB = readDict(filename_CountBB)
###############################Define Variable#################################
#if args.property == 1: #HOMO
#str_property = "HOMO"
#if args.property == 2: #LUMO
#    str_property = "LUMO"
#if args.property == 3: #Dipole
#    str_property = "Dipole"
#if args.property == 4: #eGap
#    str_property = "eGap"
num_percentage = str(args.percent_outlier)
str_f1 = "BP86/SVP"
str_f2 = "B3LYP/SVP"
str_f3 = "PBE0/SVP"
str_f4 = "BH&HLYP/SVP"
str_f5 = "M06-2X/SVP"
str_f6 = "HF/SVP"
str_f7 = "BP86/TZVP"
str_f8 = "B3LYP/TZVP"
str_f9 = "PBE0/TZVP"
str_f1_2 = "BP86s"
str_f2_2 = "B3LYPs"
str_f3_2 = "PBE0s"
str_f4_2 = "BH&HLYPs"
str_f5_2 = "M06s"
str_f6_2 = "HFs"
str_f7_2 = "BP86t"
str_f8_2 = "B3LYPt"
str_f9_2 = "PBE0t"
list_fname_1 = ["BP86/SVP","B3LYP/SVP","PBE0/SVP","BH&HLYP/SVP","M06-2X/SVP","HF/SVP",
                "BP86/TZVP","B3LYP/TZVP","PBE0/TZVP"]
list_fname_2 = ["BP86s","B3LYPs","PBE0s","BH&HLYPs","M06s","HFs",
                "BP86t","B3LYPt","PBE0t"]

"""
1 = BP86/SVP    2 = B3LYP/SVP  3 = PBE0/SVP 4 = BH&HLYP/SVP 5 = M06-2X/SVP
6 = HF/SVP      7 = BP86/TZVP   8 = B3LYP/TZVP 9 = PBE0/TZVP
"""
list_textname = ['DFT_%s_%s_%s.csv' %(str_property,'1',str_f1_2),
                 'DFT_%s_%s_%s.csv' %(str_property,'2',str_f2_2),
                 'DFT_%s_%s_%s.csv' %(str_property,'3',str_f3_2),
                 'DFT_%s_%s_%s.csv' %(str_property,'4',str_f4_2),
                 'DFT_%s_%s_%s.csv' %(str_property,'5',str_f5_2),
                 'DFT_%s_%s_%s.csv' %(str_property,'6',str_f6_2),
                 'DFT_%s_%s_%s.csv' %(str_property,'7',str_f7_2),
                 'DFT_%s_%s_%s.csv' %(str_property,'8',str_f8_2),
                 'DFT_%s_%s_%s.csv' %(str_property,'9',str_f9_2),]

name_directory = "Zscore_BB"
#os.makedirs(name_directory)

#####################Import Values############################################

###read x file
def dic_SMILES_x_y(xfilename,yfilename):
    dic_SMILES_x_y = {}

    f = open(xfilename)
    csv_f = csv.reader(f)
    next(csv_f)
    for row in csv_f:
      dic_SMILES_x_y.setdefault(row[0],[]).append(row[4])
    f.close()
    f = open(yfilename)
    csv_f = csv.reader(f)
    next(csv_f)
    for row in csv_f:
        dic_SMILES_x_y.setdefault(row[0],[]).append(row[4])
    return dic_SMILES_x_y

def distrubute_xy(dic):
    for key,value in dict.items(dic):
        if len(value) == 2:
            list_SMILES.append(key)
            list_x.append(float(value[0]))
            list_y.append(float(value[1]))
        else:
            pass
def outliers(x,y):
    from scipy import stats
    slope, intercept, r_value, p_value, std_err = stats.linregress(x,y)
    y2 = []
    for i in list_x:
        num7 = slope * i + intercept
        y2.append(round(num7,5))
    list_1 = zip(list_y,y2)
    array1 = np.asarray(list_1)

    list_dis = []
    for i1,i2 in array1:
        num3 = i2 - i1
        list_dis.append(round(num3,5))

    list_2 = zip(list_y,list_dis)   ## ((y2-y1)/y1)*100%
    array2 = np.asarray(list_2)

    list_percentage = []
    for i_y1, i_dis in array2:
        num4 = abs(i_dis/i_y1) * 100
        list_percentage.append(round(num4,2))
    for i,line in enumerate(list_percentage):
        if line >= args.percent_outlier:
            list_outliers_SMILES.append(list_SMILES[i])
        if line < args.percent_outlier:
            list_fitted_SMILES.append(list_SMILES[i])

#def sum_BB(list_SMILES):
#    list_sum = [0] *26
#    for i in list_SMILES:
#        for index,value in enumerate(dict_BB[i]):
#            if int(value) > 0:
#                list_sum[index] += 1
#    return list_sum
#
#def get_zscore(outlierList,fittedList):
#    import math
#    list_zscore = [0]*26
#    for i in range(0,26):
#        value_upperK = float(outlierList[i] + fittedList[i])
#        value_k = float(outlierList[i])
#        value_expected_k = value_n * value_upperK / value_N
#        value_sigma = math.sqrt(value_n*value_upperK*(value_N-value_upperK)/value_N/value_N*(value_N-value_n)/(value_N-1))
#        try:
#            num_z = (value_k - value_expected_k) / value_sigma
#        except ZeroDivisionError:
#            num_z = 100.0
#        list_zscore[i] = round(num_z,2)
#    return list_zscore
#def sortZ(list_z):
#    list_1 = zip(range(1,27),list_z)
#    from operator import itemgetter
#    list_4 = sorted(list_1, key= itemgetter(1))
#    list_index = []
#    list_z = []
#    for i in list_4:
#        list_index.append(str(i[0]))
#        list_z.append(i[1])
#    list_5 = [list_index, list_z]
#    return list_5
#def Z_plot(list_z,y,x_flavorname):
#    list_1 = sortZ(list_z)
#    import matplotlib.pyplot as plt
#    N = 26
#    ind = np.arange(N)
#    width = 0.8
#    plt.bar(ind,list_1[1],width)
#    plt.xticks(ind+width/2.0, list_1[0],rotation=75 )
#    plt.yticks(np.arange(-300,301,50))
#    plt.title("%s%% %s   %s vs. %d"%(num_percentage,str_property,x_flavorname,y+1))
#    plt.xlabel("Building blocks")
#    plt.ylabel("Z-score")
##    plt.show()
#    str_1 = str_property + "_Zscore_%d%d_sorted.png"%(args.x_flavor,y+1)
#    plt.savefig(str_1)
#    plt.close()
#    ########################plot unsorted plot#################
#    plt.bar(ind,list_z,width,color="r")
#    plt.xticks(ind+width/2.0, xrange(1,27),rotation=75 )
#    plt.yticks(np.arange(-300,301,50))
#    plt.title("%s%% %s   %s vs. %d"%(num_percentage,str_property,x_flavorname,y+1))
#    plt.xlabel("Building blocks")
#    plt.ylabel("Z-score")
##    plt.show()
#    str_2 = str_property + "_Zscore_%d%d.png"%(args.x_flavor,y+1)
#    plt.savefig(str_2)
#    plt.close()
###############
if args.y_flavor == 999 and args.x_flavor == 1:
    args.y_flavor = [1,2,3,4,5,6,7,8]
elif args.y_flavor == 999 and args.x_flavor == 2:
    args.y_flavor = [2,3,4,5,6,7,8]
else:
    args.y_flavor = [args.y_flavor]
#txt_zscore = open('result_Zscore.txt', 'a')
#txt_zscore.write("\n%s   %s %% \n"%(str_property,num_percentage))
SMILES_list = []
with open(filename_CountBB) as f:
    for i,line in enumerate(f):
        values = line.strip().split(',')
        SMILES_list.append(values[0].strip())
f.close()
list_yesno = []
for y in args.y_flavor:
    filename_x = list_textname[args.x_flavor-1]
    filename_y = list_textname[y]
    #############
    if filename_y != "DFT_HOMO_8_B3LYPt.csv":   ## specify the y file
        continue
    ##############
    y_flavorname = list_fname_1[y]
    x_flavorname = list_fname_1[args.x_flavor-1]
    dic_all = dic_SMILES_x_y(filename_x,filename_y)
    list_x = []
    list_y = []
    list_SMILES = []
    list_outliers_SMILES = []
    list_fitted_SMILES = []
    distrubute_xy(dic_all) ## to get list_x and list_y
    outliers(list_x,list_y) ## to get list_outliers_SMILES and list_fitted_SMILES
    list_0_1_NA = []
    end0 = time.time()
    record_time("Part1_18_0",start,end0,start)
    for SMILES in SMILES_list:
        if SMILES in list_outliers_SMILES:
            list_0_1_NA.append(1)
        elif SMILES in list_fitted_SMILES:
            list_0_1_NA.append(0)
        else:
            list_0_1_NA.append("NA")
    list_yesno.append(list_0_1_NA)
#    list_sumBB_outliers = sum_BB(list_outliers_SMILES)
#    list_sumBB_fitted = sum_BB(list_fitted_SMILES)

    ###### Z-Score #######
#    value_n = float(len(list_outliers_SMILES))
#    value_N = float(len(list_SMILES))
#    list_zscore = get_zscore(list_sumBB_outliers,list_sumBB_fitted)
#    txt_zscore.write("\n%s vs %d\n"%(args.x_flavor,y+1))
#    txt_zscore.write(str(list_zscore))
#    Z_plot(list_zscore,y,x_flavorname)
#    break

#txt_zscore.close()
#outlierList = list_sumBB_outliers
#fittedList = list_sumBB_fitted
#import math
#list_zscore = []
#for i in range(0,2):
#    print i
#    value_upperK = float(outlierList[i] + fittedList[i])
#    value_k = float(outlierList[i])
#    value_expected_k = value_n * value_upperK / value_N
#    value_sigma = math.sqrt(value_n*value_upperK*(value_N-value_upperK)/value_N/value_N*(value_N-value_n)/(value_N-1))
#    num_z = (value_k - value_expected_k) / value_sigma

df_1 = pd.DataFrame({"SMILES": SMILES_list,
#                     "F12": list_yesno[0],
#                     "F13": list_yesno[1],
#                     "F14": list_yesno[2],
#                     "F15": list_yesno[3],
#                     "F16": list_yesno[4],
#                     "F17": list_yesno[5],
                     "F18": list_yesno[0]})
#                     "F19": list_yesno[7]})

#df_1.to_csv("DFT_HOMO_BP86s_1percent_1outlier0fitted.csv")
df_1.to_csv("DFT_HOMO_BP86s_1percent_1outlier0fitted_F18.csv")

#####
end1 = time.time()
record_time("Part1_18",start,end1,start)
#####


"""ratemyrig URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/2.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.contrib import admin
from django.urls import path, include, re_path
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic.base import RedirectView
from django.views.static import serve

urlpatterns = [
    path('admin/', admin.site.urls),
    path('', include('home.urls')),
    path('home/', RedirectView.as_view( pattern_name='home', permanent=False)),
    path('builds/', RedirectView.as_view( pattern_name='blog-home', permanent=False)),
    path('blog/search/', RedirectView.as_view( pattern_name='search', permanent=False)),
    path('blog/', include('blog.urls')),
    path('user/', include('users.urls')),
    path('cart/', include('cart.urls')),
    path('checkout/', include('checkout.urls')),
    path('contact/', include('sendemail.urls')),
    path('search/', include('search.urls')),
    re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT}),
]


#!/usr/bin/env python

import os, sys
import subprocess
import hashlib
import datetime

CLI_PATH = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
sys.path.append(CLI_PATH)

from flask import Flask, request, jsonify, Response, make_response
from flask_cors import CORS
import json
from detail import get_subject
from gateway import gatewaySuccess,gateway

app = Flask(__name__)
app.debug=True
CORS(app)

SUCCESS_MESSAGE = '{"status": "success"}'

def update_environemnt(my_env, email):
    DATA_DIR="/data/whatnext/users"
    my_env['WHATNEXT_CONF'] = DATA_DIR + "/" + email + "/whatnext.conf"
    my_env['WHATNEXT_GOALS'] = DATA_DIR + "/" + email + "/whatnext_goals.conf"
    my_env['WHATNEXT_HISTORY'] = DATA_DIR + "/" + email + "/whatnext_history"
    my_env['WHATNEXT_USER'] = email

    return my_env

def check_authorization(request):
    if not 'Authorization' in request.cookies:
        raise NameError('No authorization cookie')

    authHash = request.cookies['Authorization']
    email = gateway(['getEmailByHash', authHash])
    if email == '':
        raise NameError('Invalid token')

    return email

@app.route('/scheduler')
def index():
    email = check_authorization(request)
    my_env = update_environemnt(os.environ.copy(), email)

    tiredMode = request.args.get('tiredMode', default = False, type = bool)
    if tiredMode:
        my_env["TIRED_MODE"] = "1"

    cmd = [
        CLI_PATH + '/Scheduler',
    ]

    my_env["TO_JSON"] = "1"
    content = subprocess.run(cmd, env=my_env, stdout=subprocess.PIPE).stdout.decode('UTF-8')

    return content, 200, {'Content-Type': 'application/json; charset=utf-8'}

@app.route('/log')
def history():
    email = check_authorization(request)
    my_env = update_environemnt(os.environ.copy(), email)

    cmd = [ CLI_PATH + '/log.sh', '--json']
    content =  subprocess.run(cmd, env=my_env, stdout=subprocess.PIPE).stdout.decode('UTF-8')

    return content, 200, {'Content-Type': 'application/json; charset=utf-8'}

@app.route('/done/<subjectName>', methods = ['POST'])
def done(subjectName):
    email = check_authorization(request)
    my_env = update_environemnt(os.environ.copy(), email)

    data=request.json
    cmd = [
        CLI_PATH + '/done.sh',
        subjectName,
        data['description'],
        data['whatToDoNext']
    ]

    my_env["NO_ITERACTIVE"] = "1"
    response = subprocess.run(cmd, env=my_env, stdout=subprocess.PIPE)
    if response.stdout.decode('UTF-8') != "":
        return error_json(response.stdout.decode('UTF-8')), 500, {'Content-Type': 'application/json; charset=utf-8'}

    return SUCCESS_MESSAGE, 200, {'Content-Type': 'application/json; charset=utf-8'}

@app.route('/addOrUpdate', methods = ['POST'])
def add():
    email = check_authorization(request)
    my_env = update_environemnt(os.environ.copy(), email)

    data=request.json
    cmd = [
        CLI_PATH + '/alterSubject.sh',
        data['name'],
        str(data['priority']),
        str(data['complexity']),
        data['whatToDoNext'],
        data['objective']
    ]
    response = subprocess.run(cmd, env=my_env, stdout=subprocess.PIPE)
    if response.stdout.decode('UTF-8') != "":
        return error_json(response.stdout.decode('UTF-8')), 500, {'Content-Type': 'application/json; charset=utf-8'}

    return SUCCESS_MESSAGE, 200, {'Content-Type': 'application/json; charset=utf-8'}

@app.route('/rm/<subjectName>', methods = ['GET'])
def rm(subjectName):
    email = check_authorization(request)
    my_env = update_environemnt(os.environ.copy(), email)

    cmd = [
        CLI_PATH + '/rm.sh',
        subjectName
    ]
    response = subprocess.run(cmd, env=my_env, stdout=subprocess.PIPE)
    if response.stdout.decode('UTF-8') != "":
        return response.stdout.decode('UTF-8'), 500, {'Content-Type': 'application/json; charset=utf-8'}

    return SUCCESS_MESSAGE, 200, {'Content-Type': 'application/json; charset=utf-8'}

@app.route('/detail/<subjectName>')
def detail(subjectName):
    email = check_authorization(request)
    my_env = update_environemnt(os.environ.copy(), email)

    my_env["TO_JSON"] = "1"

    cmd = [
        CLI_PATH + '/detail.py',
        subjectName
    ]
    result = subprocess.run(cmd, env=my_env, stdout=subprocess.PIPE).stdout.decode('UTF-8')
    return result, 200, {'Content-Type': 'application/json; charset=utf-8'}

@app.route('/signup', methods = ['POST'])
def signup():
    data=request.json

    m = hashlib.sha256()
    m.update(data['email'].encode('utf-8'))
    m.update(data['password'].encode('utf-8'))
    authHash = m.hexdigest()

    cmd = [
        os.path.dirname(os.path.realpath(__file__)) + '/signup.sh',
        data['email'],
        authHash
    ]

    result = subprocess.run(cmd, stdout=subprocess.PIPE)

    if result.returncode != 0:
        return error_json(result.stdout.decode('UTF-8')) , 500, {'Content-Type': 'application/json; charset=utf-8'}

    my_env = os.environ.copy()
    my_env = update_environemnt(my_env, data['email'])

    cmd = [
        CLI_PATH + '/init.sh',
    ]

    result = subprocess.run(cmd, env=my_env, stdout=subprocess.PIPE)

    return SUCCESS_MESSAGE, 200, {'Content-Type': 'application/json; charset=utf-8'}

def error_json (msg):
    return '{"status": "failure", "message": "' +  msg + '"}'

@app.route('/login', methods = ['POST'])
def login():
    data=request.json

    m = hashlib.sha256()
    m.update(data['email'].encode('utf-8'))
    m.update(data['password'].encode('utf-8'))
    authHash = m.hexdigest()
    if not gatewaySuccess(['validLogin', data['email'], authHash]):
        return '{"authHash": "'+authHash+'", "status": "failure", "message": "Invalid user or password"}', 401, {'Content-Type': 'application/json; charset=utf-8'}

    response = make_response(SUCCESS_MESSAGE)
    expire_date = datetime.datetime.now()
    expire_date = expire_date + datetime.timedelta(days=90)
    response.set_cookie("Authorization", authHash, domain='.thewhatnext.net', path = "/",  expires=expire_date)

    return response, 200, {'Content-Type': 'application/json; charset=utf-8'}

app.run(host= '0.0.0.0', port=5000)


# -*- coding: utf-8 -*-
"""
player_list.py
"""

from common.common import Config, File, Path

class PlayerList():
    """
    PlayerList
    """

    HOME = 1
    AWAY = 2

    def __init__(self):
        self.__filepath = self.__get_file_path()
        self.__columns = []
        self.__rows = []
        self.__load()

    def __get_file_path(self) -> str:
        config = Config.load()
        path = \
            config["SPORTS_DATA_FOLDER_PATH"] +\
            config["BALL_TOUCH_DATA_FOLDER_PATH"] +\
            config["BALL_TOUCH_PLAYER_LIST_PATH"]
        return Path.get_abs_pass(path)

    def __load(self) -> None:
        self.__columns, self.__rows = File.read_csv(self.__filepath)

    def get_player_id(self, match_id, is_home, uniform_number) -> int:
        """
        get_player_id
        """
        if is_home:
            homeaway_f = self.HOME
        else:
            homeaway_f = self.AWAY

        for row in self.__rows:
            _homeaway_f = int(row[self.__columns.index("ホームアウェイF")])
            _match_id = int(row[self.__columns.index("試合ID")])
            _uniform_number = int(row[self.__columns.index("背番号")])
            _player_id = int(row[self.__columns.index("選手ID")])

            if _homeaway_f == homeaway_f and \
               _match_id == match_id and \
               _uniform_number == uniform_number:
                return _player_id
        raise ValueError("プレイヤーが存在しませんでした。")


import os
import numpy as np
import copy
from pathlib import Path
from ..utils.visualization import heat_map, contour, contour_heat, draw_pr_line

def main(data: np.array):
    # contour_heat(data)
    contour(data)
    # heat_map(data)

def mean(data: np.array, i: int, j: int):
    sum = 0
    counter = 0
    dirs = [[1,0],[-1,0],[0,1],[0,-1]]
    for dir in dirs:
        newi = i + dir[0]
        newj = j + dir[1]
        if(newi >=0 and newi < len(data) and newj >=0 and newj < len(data[i])):
            sum += data[newi][newj]
            counter += 1
    return sum/counter

def process(data_origin: np.array):
    data = copy.deepcopy(data_origin)
    for i in range(len(data)):
        for j in range(len(data[i])):
            data[i][j] = mean(data, i, j)
    # for i in range(len(data)):
    #     for j in range(len(data[i])):
    #         data[i][j] /= 2
    return data

def calc_mean(data: np.array):
    sum = 0
    counter = 0
    for i in range(len(data)):
        for j in range(len(data[i])):
            if data[i][j] != 0:
                sum += data[i][j]
                counter += 1
    return sum/counter

if __name__ == '__main__':
    # get ROOT DIR
    ROOT_DIR = Path(__file__).resolve().parents[2]

    # data_dir = os.path.join(str(ROOT_DIR), 'src/LidCamFusion/eval/20220820-110456/heat_map_alpha.txt')
    data_dir = os.path.join(str(ROOT_DIR), 'src/LidCamFusion/eval/20220822-034113/heat_map_alpha_similarity.txt')
    # txt_dir = os.path.join(str(ROOT_DIR), 'src/LidCamFusion/eval/20220820-110456/tp_fp_fn.txt')
    data_origin = np.loadtxt(data_dir)
    print(calc_mean(data_origin))
    # data = process(data_origin)
    # main(data)
    # draw_pr_line(txt_dir)


import sys
from PyQt5.QtWidgets import *
from PyQt5.QtGui import QIcon
from PyQt5.QtCore import pyqtSlot, QBasicTimer
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
from data import *
import matplotlib.animation as animation
import matplotlib.dates as mdates
from matplotlib import style
eth, btc, usdt = names_eth_btc_usdt()
choose=0
choose1=0
ss2="ETC"
ss="LTC"
class App(QMainWindow):
    def __init__(self):
        super().__init__()
        self.height = 200
        self.width=470
        self.setGeometry(500,250,self.width,self.height)
        self.setWindowTitle('Crypto Coin Currency Program - Bee Software Industries')
        self.setMinimumHeight(200)
        self.setMinimumWidth(470)
        self.setMaximumHeight(200)
        self.setMaximumWidth(470)
        self.table_widget = MyTableWidget(self)
        self.setCentralWidget(self.table_widget)
        self.show()
class MyTableWidget(QWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QVBoxLayout(self)
        # Initialize tab screen
        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()
        self.tab3 = QWidget()
        self.tab4 = QWidget()
        self.tab5 = QWidget()
        self.tabs.resize(300, 300)
        self.press = None
        self.cur_xlim = None
        self.cur_ylim = None
        self.x0 = None
        self.y0 = None
        self.x1 = None
        self.y1 = None
        self.xpress = None
        self.ypress = None
        # Add tabs
        self.tabs.addTab(self.tab1, "Main Page")

        ############# FIRST TAB #############

        self.tab1.layout = QGridLayout(self)
        self.step=0
        self.message = QLabel('This software was made by Kaan Bee Software')
        self.message.setGeometry(0, 0, 270, 25)
        self.pbar = QProgressBar(self)
        self.pbar.setGeometry(30, 40, 200, 25)
        self.timer = QBasicTimer()
        self.button1 = QPushButton('Load App', self)
        self.button1.clicked.connect(self.doAction)
        self.tab1.layout.addWidget(self.message,1,2)
        self.tab1.layout.addWidget(self.pbar,2,1,1,2)
        self.tab1.layout.addWidget(self.button1,2,3)
        self.tab1.setLayout(self.tab1.layout)

        ############# SECOND TAB-BTC TAB ############# FINISHED

        self.tab2.layout = QHBoxLayout(self)
        self.layout1 = QHBoxLayout(self)
        self.layout2 = QVBoxLayout(self)
        self.figure1 = Figure(figsize=(15, 10), dpi=50)
        self.canvas1 = FigureCanvas(self.figure1)
        self.toolbar1 = NavigationToolbar(self.canvas1, self)
        self.search1 = QLineEdit(self)
        self.search1.setPlaceholderText("Also you can write here")
        self.box1 = QComboBox(self)
        self.box1.addItem("According to BTC")
        self.box1.addItem("According to USD")
        self.button2 = QPushButton("Search")
        self.button2.clicked.connect(self.searchitem)
        self.box1.activated[int].connect(self.onActivated)
        self.layout1.addWidget(self.search1)
        self.layout1.addWidget(self.box1)
        self.layout1.addWidget(self.button2)
        self.list1 = QListWidget(self)
        self.list1.itemClicked.connect(self.touchme)
        self.layout2.addLayout(self.layout1)
        self.layout2.addWidget(self.canvas1)
        self.layout2.addWidget(self.toolbar1)
        self.tab2.layout.addLayout(self.layout2)
        self.tab2.layout.addWidget(self.list1)
        self.tab2.setLayout(self.tab2.layout)

        ################THIRD TAB-ETH TAB################ FINISHED

        self.tab3.layout = QHBoxLayout(self)
        self.layout3 = QHBoxLayout(self)
        self.layout4 = QVBoxLayout(self)
        self.figure2 = Figure(figsize=(15, 10), dpi=50)
        self.canvas2 = FigureCanvas(self.figure2)
        self.toolbar2 = NavigationToolbar(self.canvas2, self)
        self.search2 = QLineEdit(self)
        self.search2.setPlaceholderText("Also you can write here")
        self.box2 = QComboBox(self)
        self.box2.addItem("According to ETH")
        self.box2.addItem("According to USD")
        self.button3 = QPushButton("Search")
        self.button3.clicked.connect(self.searchitem2)
        self.box2.activated[int].connect(self.onActivated2)
        self.layout3.addWidget(self.search2)
        self.layout3.addWidget(self.box2)
        self.layout3.addWidget(self.button3)
        self.list2 = QListWidget(self)
        self.list2.itemClicked.connect(self.touchme2)
        self.layout4.addLayout(self.layout3)
        self.layout4.addWidget(self.canvas2)
        self.layout4.addWidget(self.toolbar2)
        self.tab3.layout.addLayout(self.layout4)
        self.tab3.layout.addWidget(self.list2)
        self.tab3.setLayout(self.tab3.layout)

        ################USER GUIDE################

        self.tab4.layout = QVBoxLayout(self)
        self.layout6 = QHBoxLayout(self)
        self.layout32= QHBoxLayout(self)
        self.layout33=QVBoxLayout(self)
        self.message1=QLabel('Hi friend, thanks to you for choosing us.')
        self.layout6.addWidget(self.message1)
        self.message6=QLabel('This program is Open-Source and It will always be free')
        self.layout32.addWidget(self.message6)
        self.layout33.addLayout(self.layout6)
        self.layout33.addLayout(self.layout32)
        self.tab4.layout.addLayout(self.layout33)
        self.tab4.setLayout(self.tab4.layout)

        ##################CALCULATOR#####################

        self.tab5.layout = QVBoxLayout(self)
        self.layout7 = QVBoxLayout(self)
        self.layout8 = QHBoxLayout(self)
        self.layout9 = QHBoxLayout(self)
        self.layout10=QHBoxLayout(self)
        self.message7 = QLabel(' You can calculate all currencies here')
        self.btcbutton = QPushButton("BTC Based Coins")
        self.btcbutton.clicked.connect(self.calculator1)
        self.layout8.addWidget(self.btcbutton)
        self.info3 = QLabel(" Choose the Type of Your Coin Bases for 1.Coin ")
        self.layout8.addWidget(self.info3)
        self.ethbutton = QPushButton("ETH Based Coins")
        self.ethbutton.clicked.connect(self.calculator2)
        self.layout8.addWidget(self.ethbutton)
        self.calc1 = QLineEdit(self)
        self.calc1.setPlaceholderText("Value(ex 1,01)")
        self.layout9.addWidget(self.calc1)
        self.box7 = QComboBox(self)
        self.box7.addItem("1.Coin")
        self.box7.activated[int].connect(self.calculator3)
        self.layout9.addWidget(self.box7)
        self.info5 = QLabel(" =========== ")
        self.layout9.addWidget(self.info5)
        self.info6 = QLineEdit(self)
        self.info6.setPlaceholderText(" Result ")
        self.layout9.addWidget(self.info6)
        self.box8 = QComboBox(self)
        self.box8.addItem("2.Coin")
        self.box8.addItem("BTC")
        self.box8.addItem("ETH")
        self.box8.addItem("ETC")
        self.box8.addItem("LTC")
        self.box8.addItem("USDT")
        self.box8.activated[str].connect(self.calculator4)
        self.summary=QPushButton("Calculate")
        self.summary.clicked.connect(self.calculator5)
        self.layout10.addWidget(self.summary)
        self.layout9.addWidget(self.box8)
        self.layout7.addLayout(self.layout8)
        self.layout7.addLayout(self.layout9)
        self.layout7.addLayout(self.layout10)
        self.tab5.layout.addLayout(self.layout7)
        self.tab5.setLayout(self.tab5.layout)

        ############# Add tabs to widget ################

        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

        #################----------------------#FUNCTIONS#-----------------------#####################################

    def calculator1(self):
        global selected1
        self.box7.clear()
        self.box7.addItem("Select")
        self.box7.addItems(btc)
        selected1 = 0

    def calculator2(self):
        global selected1
        self.box7.clear()
        self.box7.addItem("Select")
        self.box7.addItems(eth)
        selected1=1

    def calculator3(self, number5):
        global coin1
        if selected1==0:
            if number5!=0:coin1=btc[number5-1]
        else:
            if number5!=0:coin1=eth[number5-1]

    def calculator4(self, type55):
        global coin2
        coin2=type55

    def calculator5(self):
        if (self.calc1.text() != ""):
            x,y=current(coin2,coin1)
            y=float(y)*float(self.calc1.text())
            self.info6.setText(format(y,'.10f'))
        else:
            self.info6.setText("Please Write Down Some Value")

    def searchitem(self):#####SORUNSUZ######
        global ss
        if (self.search1.text() != ""):
            ss = self.search1.text().upper()
            true1=matching(ss,"BTC")
            if 1==true1:
                self.figure1.clear()
                self.search1.clear()
                self.search1.setPlaceholderText("Also you can write here")
                self.plot1()
            else:
                self.search1.clear()
                self.search1.setPlaceholderText("Wrong Name, Try Again")

    def searchitem2(self):#####SORUNSUZ#####
        global ss2
        if (self.search2.text() != ""):
            ss2 = self.search2.text().upper()
            true2 = matching(ss2, "ETH")
            if 1 == true2:
                self.figure2.clear()
                self.search2.clear()
                self.search2.setPlaceholderText("Also you can write here")
                self.plot2()
            else:
                self.search2.clear()
                self.search2.setPlaceholderText("Wrong Name, Try Again")

    def onActivated(self, number): ####SORUNSUZ#####
        global choose1
        self.figure1.clear()
        if 0==number:
            self.search1.setPlaceholderText("Also you can write here")
            self.list1.clear()
            self.list1.addItems(btc)
            choose1=0
        if 1==number:
            self.search1.setPlaceholderText("Don't use me. Here. Our Api is broken nowadays")
            self.list1.clear()
            self.list1.addItem("BTC")
            self.list1.addItem("LTC")
            self.list1.addItem("XMR")
            self.list1.addItem("XRP")
            self.list1.addItem("ZEC")
            choose1 = 1

    def onActivated2(self, number2): ####SORUNSUZ#####
        global choose
        self.figure2.clear()
        if 0==number2:
            self.search2.setPlaceholderText("Also you can write here")
            self.list2.clear()
            self.list2.addItems(eth)
            choose=0
        if 1==number2:
            self.search2.setPlaceholderText("Don't use me. Here. Our Api is broken nowadays")
            self.list2.clear()
            self.list2.addItem("ETH")
            self.list2.addItem("XRP")
            self.list2.addItem("ZEC")
            self.list2.addItem("XMR")
            choose = 1

    def touchme(self):###SORUNSUZ###
        global ss
        self.figure1.clear()
        ss = self.list1.currentItem().text()
        self.plot1()

    def touchme2(self): ###SORUNSUZ###
        global ss2
        self.figure2.clear()
        ss2 = self.list2.currentItem().text()
        self.plot2()

    ###############################################-----PLOT1 SORUNSUZ-----################################################

    def plot1(self):
        if choose1==0:
            #ax = self.figure1
            type6 = ss
            style.use('ggplot')
            ax = self.figure1.add_subplot(1, 1, 1)
            type5="BTC"
            time1, value1 = current(type5, type6)
            title2 = type5 + " - " + type6 + " Latest History Chart\nCurrent Price = " + format(value1,'.10f')
            ax.set_title(title2)
            plt.xticks(rotation=90, size=15)
            plt.yticks(size=15)
            self.figure1.autofmt_xdate()
            myFmt = mdates.DateFormatter('%H:%M:%S')
            ax.xaxis.set_major_formatter(myFmt)
            x1, y1 = history(type5, type6)
            ax.plot(x1, y1, color='red')
            def animate1(i):
                time1, value1 = current(type5, type6)
                title2 = type5 + " - " + type6 + " Latest History Chart\nCurrent Price = " + str(value1)
                ax.set_title(title2)
                plt.xticks(rotation=90,size=15)
                plt.yticks(size=15)
                self.figure1.autofmt_xdate()
                myFmt = mdates.DateFormatter('%H:%M:%S')
                ax.xaxis.set_major_formatter(myFmt)
                x1, y1 = history(type5, type6)
                ax.plot(x1, y1, color='red')
            ani1 = animation.FuncAnimation(self.figure1, animate1, interval=20000)
            scale = 1.1
            figZoom = self.zoom_factory(ax, base_scale=scale)
            figPan = self.pan_factory(ax)
            self.canvas1.draw()
        if choose1==1:
            ax=self.figure1
            type1=ss
            style.use('ggplot')
            ax = self.figure1.add_subplot(1, 1, 1)
            plt.xticks(rotation=90, size=15)
            plt.yticks(size=15)
            plt.gcf().autofmt_xdate()
            myFmt = mdates.DateFormatter('%Y:%m:%d')
            plt.gca().xaxis.set_major_formatter(myFmt)
            x, y = usd_x_alltime(type1)
            ax.plot(x, y, color='red')
            time, value = current("USDT", type1)
            title = "USD - " + type1 + " All Time History Chart\nCurrent Price = " + format(value,'.10f')
            ax.set_title(title)
            scale = 1.1
            figZoom = self.zoom_factory(ax, base_scale=scale)
            figPan = self.pan_factory(ax)
            self.canvas1.draw()

    ###############################################-----PLOT2 Sorunsuz-------################################################

    def plot2(self):
        if choose==0:
            #ax = self.figure2
            type4 = ss2
            style.use('ggplot')
            ax = self.figure2.add_subplot(1, 1, 1)
            type3="ETH"
            time2, value2 = current(type3, type4)
            title2 = type3 + " - " + type4 + " Latest History Chart\nCurrent Price = " + format(value2,'.10f')
            ax.set_title(title2)
            plt.xticks(rotation=90, size=15)
            plt.yticks(size=15)
            self.figure2.autofmt_xdate()
            myFmt = mdates.DateFormatter('%H:%M:%S')
            ax.xaxis.set_major_formatter(myFmt)
            x2, y2 = history(type3, type4)
            ax.plot(x2, y2, color='red')
            def animate2(i):
                time2, value2 = current(type3, type4)
                title2 = type3 + " - " + type4 + " Latest History Chart\nCurrent Price = " + str(value2)
                ax.set_title(title2)
                plt.xticks(rotation=90,size=15)
                plt.yticks(size=15)
                self.figure2.autofmt_xdate()
                myFmt = mdates.DateFormatter('%H:%M:%S')
                ax.xaxis.set_major_formatter(myFmt)
                x2, y2 = history(type3, type4)
                ax.plot(x2, y2, color='red')
            ani = animation.FuncAnimation(self.figure2, animate2, interval=20000)
            scale = 1.1
            figZoom = self.zoom_factory(ax, base_scale=scale)
            figPan = self.pan_factory(ax)
            self.canvas2.draw()
        if choose==1:
            self.figure2.clear()
            ax=self.figure2
            type1=ss2
            style.use('ggplot')
            ax = self.figure2.add_subplot(1, 1, 1)
            plt.xticks(rotation=90, size=15)
            plt.yticks(size=15)
            self.figure2.autofmt_xdate()
            myFmt = mdates.DateFormatter('%Y:%m:%d')
            ax.xaxis.set_major_formatter(myFmt)
            x2, y2 = usd_x_alltime(type1)
            ax.plot(x2, y2, color='red')
            time, value = current("USDT", type1)
            title = "USD - " + type1 + " All Time History Chart\nCurrent Price = " + format(value,'.10f')
            ax.set_title(title)
            scale = 1.1
            figZoom = self.zoom_factory(ax, base_scale=scale)
            figPan = self.pan_factory(ax)
            self.canvas2.draw()

    def timerEvent(self, e):################SORUNSUZ################
        if self.step >= 100:
            self.button1.setText('Click to Open App')
            self.timer.stop()
        if self.step ==50:
            self.button1.setText('Thanks your patient')
        if self.step ==5:
            self.tabs.addTab(self.tab4,"User Guide")
            self.tabs.setTabEnabled(1,False)
        if self.step == 35:
            self.list1.addItems(btc)
            self.tabs.addTab(self.tab2, "BTC Based Coins")
            self.tabs.setTabEnabled(2, False)
        if self.step == 60:
            self.list2.addItems(eth)
            self.tabs.addTab(self.tab3, "ETH Based Coins")
            self.tabs.setTabEnabled(3, False)
        if self.step ==90:
            self.tabs.addTab(self.tab5,"Calculator")
            self.tabs.setTabEnabled(4,False)
        #self.step = self.step + 1
        self.step = self.step + 5
        self.pbar.setValue(self.step)

    def doAction(self):################SORUNSUZ################
        self.timer.start(100, self)
        self.button1.setText('App is Loading...')
        if self.step>=100:
            ex.resize(600, 610)
            ex.setMaximumWidth(610)
            ex.setMaximumHeight(600)
            ex.setMinimumWidth(610)
            ex.setMinimumHeight(600)
            ex.move(400,80)
            self.tabs.removeTab(0)
            self.height=500
            self.width=500
            self.tabs.setTabEnabled(0, True)
            self.tabs.setTabEnabled(1, True)
            self.tabs.setTabEnabled(2, True)
            self.tabs.setTabEnabled(3,True)
            self.tabs.setCurrentIndex(0)

    def zoom_factory(self, ax, base_scale=2.):
        def zoom(event):
            cur_xlim = ax.get_xlim()
            cur_ylim = ax.get_ylim()
            xdata = event.xdata
            ydata = event.ydata
            if event.button == 'down':
                scale_factor = base_scale
            elif event.button == 'up':
                scale_factor = 1 / base_scale
            else:
                scale_factor = 1
            new_width = (cur_xlim[1] - cur_xlim[0]) * scale_factor
            new_height = (cur_ylim[1] - cur_ylim[0]) * scale_factor
            relx = (cur_xlim[1] - xdata) / (cur_xlim[1] - cur_xlim[0])
            rely = (cur_ylim[1] - ydata) / (cur_ylim[1] - cur_ylim[0])
            ax.set_xlim([xdata - new_width * (1 - relx), xdata + new_width * (relx)])
            ax.set_ylim([ydata - new_height * (1 - rely), ydata + new_height * (rely)])
            ax.figure.canvas.draw()
        fig = ax.get_figure()
        fig.canvas.mpl_connect('scroll_event', zoom)
        return zoom

    def pan_factory(self, ax):
        def onPress(event):
            if event.inaxes != ax: return
            self.cur_xlim = ax.get_xlim()
            self.cur_ylim = ax.get_ylim()
            self.press = self.x0, self.y0, event.xdata, event.ydata
            self.x0, self.y0, self.xpress, self.ypress = self.press

        def onRelease(event):
            self.press = None
            ax.figure.canvas.draw()

        def onMotion(event):
            if self.press is None: return
            if event.inaxes != ax: return
            dx = event.xdata - self.xpress
            dy = event.ydata - self.ypress
            self.cur_xlim -= dx
            self.cur_ylim -= dy
            ax.set_xlim(self.cur_xlim)
            ax.set_ylim(self.cur_ylim)
            ax.figure.canvas.draw()

        def enter_figure(event):
            event.canvas.figure.patch.set_facecolor('red')
            event.canvas.draw()
        fig = ax.get_figure()
        fig.canvas.mpl_connect('button_press_event', onPress)
        fig.canvas.mpl_connect('button_release_event', onRelease)
        fig.canvas.mpl_connect('motion_notify_event', onMotion)
        fig.canvas.mpl_connect('figure_enter_eventasdfasdf', enter_figure)
        return onMotion

    @pyqtSlot()
    def on_click(self):
        self.figure2.clear()
        self.figure1.clear()
        print("\n")
        for currentQTableWidgetItem in self.tableWidget.selectedItems():
            print(currentQTableWidgetItem.row(), currentQTableWidgetItem.column(), currentQTableWidgetItem.text())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())


from django.urls import path, re_path, include

from quiz.views import (QuizzesList, CreateQuizView, QuizDetailView,
                        DeleteQuizView, UpdateQuizView, ResultView,
                        ResultsListView)

app_name = "quiz"

urlpatterns = [
    path('', QuizzesList.as_view(), name='quizzes-list'),
    path('create_quiz/', CreateQuizView.as_view(), name='create-quiz'),
    path('quiz_detail/<int:pk>/', QuizDetailView.as_view(),
         name='detail-quiz'),
    path('delete_quiz/<int:pk>/', DeleteQuizView.as_view(),
         name='delete-quiz'),
    path('update_quiz/(<int:pk>/', UpdateQuizView.as_view(),
         name='update-quiz'),
    path('result_list/<int:pk>/', ResultsListView.as_view(),
         name='result-list'),
    re_path('^column_chart/(?P<pk>\\d+)/', include([
        re_path('^group=(?P<group>\\w+.*\\w*)/$',
                ResultView.as_view(), name='result-chart-group'),
        re_path('^user=(?P<current_user>\\w+[\\s,-]*\\w*)/$',
                ResultView.as_view(), name='result-chart-user'),

        ])),
]


from os.path import relpath
from tkinter import *
from tkinter import filedialog
from tkinter import ttk, messagebox

from PIL import ImageTk

#CHange to local .basefunctions during deployment
from basefunctions import *
from ReadBarcodes import getBarcode

class LeafAreaCalculatorGUI:
    """
    Class LeafAreaCalculatorGUI is a Tkinter GUI manager, that is responsible for interacting with the user
    and displaying results.
    The backend application is a convulutional neural network that is trained with green, red and other colors,
    to generate a robust and reliable classifier that can detect green leaf within a given image in varying light conditions and leaf shades,
    and computes the area of the green leaf with respect to a fixed red square of 4 cm^2.

    GUI includes two preview panes:
    left pane is the original window pane, that displays the original image and the name of image.
    right pane is the updated window pane, that displays the resultant analyzd image from classifier.

    Under the left pane is a navigation bar, with which user can switch left or right through multiple images. This option is diabled if user is working on only one image.

    """
    IMAGE_HEIGHT = 300
    IMAGE_WIDTH = 300

    def __init__(self, root):
        """
        LeafAreaCalculatorGUI constructor accepts the root as Tkinter main window.

        :param root: Tkinter Main Window
        Sets parameters and configurations to default.
        :type root: Tk()
        """
        self.root = root
        self.current_page = IntVar()
        self.stored_area_dict = dict()
        self.stored_barcode_dict = dict()

        self.current_image_name = None
        self.font = 'Helvetica'
        self.font_size = 9
        self.font_param = (self.font, self.font_size, 'bold')

        self.process_clicked = False
        self.all_results = list()

        self.default_image_path = os.path.dirname(__file__)
        self.default_save_path = os.path.join(os.path.dirname(__file__), 'saved_images/')
        self.was_default_set = False

        self.set_grid()
        self.set_menus()

        self.area_red_square = int(self.set_red_square.get())

    def set_menus(self):
        """
        Function set_menus: Sets the Menu tool bar for the application.
        User can select default image directory and perform batch process usind File and Tools menu options.
        """
        menu = Menu(self.root)
        self.root.config(menu=menu)
        filemenu = Menu(menu)
        menu.add_cascade(label="File", menu=filemenu)
        filemenu.add_command(label="Set Default Image Folder", command=self.setDefaultImageLocation)
        filemenu.add_separator()
        filemenu.add_command(label="Exit", command=self.root.destroy)

        toolsmenu = Menu(menu)
        menu.add_cascade(label='Tools', menu=toolsmenu)
        toolsmenu.add_command(label='Batch Process Images', command=self.process_all)
        toolsmenu.add_separator()
        toolsmenu.add_command(label='ReTrain Model', command=self.retrain_model)

        toolsmenu.add_separator()
        toolsmenu.add_command(label='View Recent Result', command=self.view_results)
        toolsmenu.add_command(label='Save Recent Results As CSV', command=self.save_results)

        helpmenu = Menu(menu)
        menu.add_cascade(label="Help", menu=helpmenu)
        helpmenu.add_command(label="About...", command=self.About)
        helpmenu.add_command(label="Documentation", command=self.documentation)

    def retrain_model_run(self):
        """
        Function retrain_model_run: Displays model training status to user.
        A window is popped up with message: Model Training In Process. Window is closed when model training is complete.
        """
        if (RETRAIN_MODEL_FROM_SCRATCH()):
            self.retrain_window.after(5000, self.retrain_window.destroy)
            self.my_frame.update_idletasks()

    def retrain_model(self):
        """
        Function retrain_model: Performs re-training of the classifier on user input from Tools->Retrain model.
        Note: User should retrain the model only if training images have changed, or classification model seems corrupt.
        """
        self.retrain_window = Toplevel(self.my_frame)

        label_ = Label(self.retrain_window, text='Model Training In Progress..')
        label_.pack()

        self.retrain_window.after(1000, self.retrain_model_run)

    def setDefaultImageLocation(self):
        """
        Function setDefaultImageLocation: Sets the default image directory to find images for analysis.
        """
        self.was_default_set = True
        self.default_image_path = filedialog.askdirectory(initialdir=self.default_image_path)

    def About(self):
        """
        Displays the File->About pop up box.
        """
        messagebox.showinfo("pyleaf", "pyleaf:\n Simplified Leaf Area Analysis Using Machine Learning")

    def display_this_image(self, passed_image):
        """
        Function that collects a passed image from disk and displays in the original preview window and updated result window.

        :param passed_image: The image name to be fetched from default_image_path and default_save_path
        """
        originalonly = not self.process_clicked

        self.label_image_name['text'] = passed_image
        self.show_barcode['text'] = self.stored_barcode_dict[passed_image]

        # Original Preview Pane
        image = Image.open(os.path.join(self.default_image_path, passed_image))
        image = image.resize((LeafAreaCalculatorGUI.IMAGE_WIDTH, LeafAreaCalculatorGUI.IMAGE_HEIGHT), Image.ANTIALIAS)
        photo = ImageTk.PhotoImage(image)
        self.label1.config(image=photo)
        self.label1.image = photo  # keep a reference!

        if (not originalonly):
            # Processed Preview Pane
            image = Image.open(self.default_save_path + passed_image)
            image = image.resize((LeafAreaCalculatorGUI.IMAGE_WIDTH, LeafAreaCalculatorGUI.IMAGE_HEIGHT),
                                 Image.ANTIALIAS)
            photo = ImageTk.PhotoImage(image)
            self.label2.config(image=photo)
            self.label2.image = photo  # keep a reference!

    def display_left(self):
        """
        The Left Arrow button of the navigation control under original preview pane.
        Disabled if navigation reaches 1/N , Enabled otherwise.
        """
        print('Left')
        self.current_page.set(self.current_page.get() - 1)
        print('Current page: ', self.current_page.get())
        self.display_this_image(self.list_[self.current_page.get()])
        self.page_label['text'] = '{}/{}'.format(self.current_page.get() + 1, self.number_of_images)

        if (self.process_clicked):
            self.display_result(self.stored_area_dict[self.list_[self.current_page.get()]])

        if (self.current_page.get() - 1 < 0):
            self.button_left['state'] = DISABLED
            self.button_right['state'] = ACTIVE
            self.current_page.set(0)
        else:
            self.button_left['state'] = ACTIVE
            self.button_right['state'] = ACTIVE

    def display_right(self):
        """
        The Right Arrow button of the navigation control under original preview pane.
        Disabled if navigation reaches N/N , Enabled otherwise.
        """

        print('Right')
        self.current_page.set(self.current_page.get() + 1)
        print('Current page: ', self.current_page.get())
        self.display_this_image(self.list_[self.current_page.get()])
        self.page_label['text'] = '{}/{}'.format(self.current_page.get() + 1, self.number_of_images)

        if (self.process_clicked):
            self.display_result(self.stored_area_dict[self.list_[self.current_page.get()]])
        if (self.current_page.get() + 1 > (self.number_of_images - 1)):
            self.button_right['state'] = DISABLED
            self.button_left['state'] = ACTIVE
            self.current_page.set(self.number_of_images - 1)
        else:
            self.button_left['state'] = ACTIVE
            self.button_right['state'] = ACTIVE

    def change_result_preview(self, every):
        """
        Update the result window pane with the passed image.

        :param every: name of the image file to load.
        :type every: string
        """
        print('Evrry: ', every)
        analysis_info = PROCESS_IMAGE([every], self.default_image_path, self.area_red_square)
        self.area_green_leaf = analysis_info[1]

        print('EVery: ', every)
        self.stored_area_dict[every] = round(self.area_green_leaf, 2)

        self.stored_barcode_dict[every] = getBarcode(os.path.join(self.default_image_path , every))

        analysis_info[1] = round(analysis_info[1], 2)
        analysis_info.append(self.stored_barcode_dict[every])
        self.all_results.append(analysis_info)

        # Now that image analysis is complete, load the transformed image to Label2
        image = Image.open(self.default_save_path + every)
        image = image.resize((LeafAreaCalculatorGUI.IMAGE_WIDTH, LeafAreaCalculatorGUI.IMAGE_HEIGHT), Image.ANTIALIAS)
        photo = ImageTk.PhotoImage(image)

        self.label2.config(image=photo)
        self.label2.image = photo  # keep a reference!

    def update_original_preview(self, photo):
        """
        Update the original window pane with the passed image.

        :param photo: name of the image file to load.
        :type photo: string
        """
        self.label1.config(image=photo)
        self.label1.image = photo  # keep a reference!

        self.label_image_name['text'] = self.current_image_name
        if (self.number_of_images == 1):
            self.page_label['text'] = '1/1'
        else:
            self.page_label['text'] = '{}/{}'.format(self.number_of_images, self.number_of_images)
            self.button_left['state'] = NORMAL
            self.button_right['state'] = NORMAL

    def display_result(self, area=None):
        """
        Displays the area in cm^2 with an option to switch to mm^2 by clicking on the numerical result displayed.

        :param area: The area to display in the 'Leaf Area:'  field.
        :type area: float, 2 bit decimal.
        """
        if (area == None):
            area = round(self.area_green_leaf, 2)

        self.area_green_leaf = area
        self.show_area.config(text='{} cm\u00b2'.format(area))

        print('Seting a: ', self.a.get())
        self.a.set(self.a.get() + 1)

        if self.a.get() >= self.number_of_images and self.a.get() > 1:
            try:
                self.progress.update_idletasks()
                self.newwin.after(5000, self.newwin.destroy)
                self.root.update_idletasks()

                # Save results
                dataFrameMeasure = pd.DataFrame(self.all_results,
                                                columns=['Sample', 'Area', 'Red Pixels', 'Red Ratio', 'Green Pixels',
                                                         'Dimensions', 'BarCode'])
                dataFrameMeasure.to_csv(os.path.join(os.path.dirname(__file__), 'storedMeasuredValues.csv'))
            except Exception:
                pass

    def documentation(self):
        import webbrowser
        webbrowser.open('file://' + os.path.realpath(os.path.join(os.path.dirname(__file__), 'pyleaf.pdf')))

    def view_results(self):
        '''
        Function to display the recently saved results in a new window.
        Displays results available in storedMeasuredValues.csv data file.
        '''

        self.result_window = Toplevel(self.root)
        storedAreas = pd.read_csv(os.path.join(os.path.dirname(__file__), 'storedMeasuredValues.csv'))

        self.result_frame = Frame(self.result_window)
        self.result_frame.grid(row=0, columnspan=storedAreas.shape[1] + 2)

        Label(self.result_frame, text="Leaf Area Results", font=("Arial", 24), relief='sunken').grid(row=0,
                                                                                columnspan=
                                                                                storedAreas.shape[
                                                                                1] + 2)

        for col, every_col in enumerate(['Sample', 'Area']):
            Label(self.result_frame, text=str(every_col), font=self.font_param, relief='flat', fg='green').grid(row=1,
                                                                                column=col + 1)

        for row, (index, every_row) in enumerate(storedAreas.iterrows()):
            for col, every_col in enumerate(['Sample', 'Area']):
                label_ = Label(self.result_frame, text=str(every_row[every_col]), font=self.font_param, relief='flat')
                label_.grid(row=row + 2, column=col + 1, columnspan=1)

        Label(self.result_frame, text="", font=("Arial", 30)).grid(row=storedAreas.shape[0] + 2,
                                                                   columnspan=storedAreas.shape[1] + 2)

    def save_results(self):
        '''
        Function to display the save recent results to location of user choise.
        Displays results available in storedMeasuredValues.csv data file.
        '''
        import shutil

        # storedAreas = pd.read_csv(os.path.join(os.path.dirname(__file__), 'storedMeasuredValues.csv'))
        savePath = filedialog.askdirectory(initialdir=self.default_image_path)

        shutil.copy(os.path.join(os.path.dirname(__file__), 'storedMeasuredValues.csv'), savePath)
        messagebox.showinfo("File Saved", "Success:\n Results Location: "+savePath)

    def change_unit(self, event):
        """
        Function that allows the numerical leaf area result to switch between cm^2 and mm^2.
        The result is displayed in Leaf Area label field.

        :param event: Accept the button click event.
        :type event: Tkinter Button Press 1.
        :return: Return 'NA' back if 'NA' is clicked.
        :rtype: int
        """
        is_cm = True if 'cm' in self.show_area['text'] else False

        if ('NA' in self.show_area['text']):
            return 0

        if (not is_cm):
            area = round(self.area_green_leaf, 2)
            self.show_area.config(text='{} cm\u00b2'.format(area))
        else:
            area = round(self.area_green_leaf * 100, 2)
            self.show_area.config(text='{} mm\u00b2'.format(area))

    def new_winF(self):  # new window definition
        """
        Function that creates a progress window to display progress of leaf analysis with multiple images.
        A new window updates the status with analysis of every leaf in the default_image_folder, and closes automatically when program processes all images.

        The window is positioned to be in the centre of the main window.
        """
        window_height = 150
        window_width = 300

        self.newwin = Toplevel(self.my_frame)
        x_cordinate = int((820 / 2) - (window_width / 2))
        y_cordinate = int((500 / 2) - (window_height / 2))

        self.newwin.geometry("{}x{}+{}+{}".format(window_width, window_height, x_cordinate, y_cordinate))
        self.progress = ttk.Progressbar(self.newwin, orient=HORIZONTAL, length=100, mode='determinate')
        self.progress.place(x=50, y=50, height=50, width=200)

        self.prog_label = Label(self.newwin, width=15, text='Processing...', font=self.font_param)
        self.prog_label.place(x=50, y=30, height=15, width=200)

    def change_progress(self):
        """
        Update the progress value in the progress window.
        """
        self.newwin.update_idletasks()
        val = int((self.a.get() / self.number_of_images) * 100)
        self.progress['value'] = val
        print('Getting a: ', self.a.get())
        print('Val: ', val)
        self.progress.update()

    def process_all(self):
        """
        Function that is triggered when Batch Process feature is activated by user.
        Iterate over all images one by one from the list of images in default_image_path, and update the Leaf Area and preview panes as the results become available.
        While the operation is in progress, new window is popped that displays dynamic progress of task.
        """
        self.process_clicked = True

        self.list_ = list(filter(lambda x: str(x).lower().__contains__('.jp'), os.listdir(self.default_image_path)))
        self.number_of_images = len(self.list_)

        print('DF: ', self.default_image_path)
        print('List_: ', self.list_)

        if (self.was_default_set):
            if (self.number_of_images == 1):
                self.button_left['state'] = DISABLED
                self.button_right['state'] = DISABLED
            else:
                self.button_left['state'] = DISABLED
                self.button_right['state'] = DISABLED
                print('Setting current page..')
                self.current_page.set(self.number_of_images - 1)
                print(self.current_page)

            for index, every in enumerate(self.list_):
                # Load original picture
                image = Image.open(os.path.join(self.default_image_path, every))
                image = image.resize((LeafAreaCalculatorGUI.IMAGE_WIDTH, LeafAreaCalculatorGUI.IMAGE_HEIGHT),
                                     Image.ANTIALIAS)
                photo = ImageTk.PhotoImage(image)

                self.label1.after(500, self.update_original_preview, photo)
                self.current_image_name = every

                self.button_select['state'] = DISABLED
                self.button_area['state'] = NORMAL

            print('NOI: ', self.number_of_images)
            self.process_image()
        else:
            messagebox.showwarning("Default Path", "Default Image Path was not set. Use File->Set Default Image Folder")

    def process_image(self, every=None):
        """
        Function that accepts only one image name as input, and performs analysis.
        Updates the Leaf Area and preview panes as the result become available. If no input is provides, iteratively processes all images in the global list_ maintained by class as list of all
        images in the default image path.

        :param every: Image name to process
        :type every: string
        """
        self.process_clicked = True
        self.a = IntVar()
        self.a.set(1)

        if (self.number_of_images == 1):
            every = self.current_image_name
            self.label2.after(100, self.change_result_preview, every)
            self.show_area.after(100, self.display_result)
            self.show_barcode.after(100, self.display_barcode, every)
        else:
            self.new_winF()
            for index, every in enumerate(self.list_):
                self.progress.update_idletasks()
                self.progress.after(5000, self.change_progress)
                self.label2.after(5000, self.change_result_preview, every)
                self.show_area.after(5000, self.display_result)
                self.show_barcode.after(100, self.display_barcode, every)

    def display_barcode(self,filename):
        self.barcode = getBarcode(os.path.join(self.default_image_path , filename))
        self.show_barcode.config(text='{}'.format(self.barcode))

    # Ask the user to select a one or more file names.
    def answer(self, x):
        """
        Allows user to select base image path from where all images in that folder can be polled for batch analysis.
        When user selects the default folder through the dialog box, all images in the selected folder are loaded in the original preview pane.

        :param x: Tkinter Instance of main window or root
        :type x: Tk()
        """
        self.my_frame.update_idletasks()
        # Build a list of tuples for each file type the file dialog should display
        my_filetypes = [('all files', '.*'), ('image files', '.JPG')]

        self.list_ = filedialog.askopenfilenames(parent=x, initialdir=self.default_image_path,
                                                 title="Please select one or more files:",
                                                 filetypes=my_filetypes)

        self.default_image_path = os.path.dirname(self.list_[0])
        self.list_ = [relpath(x, self.default_image_path) for x in self.list_]
        print(list(self.list_))

        self.number_of_images = len(self.list_)
        print('NOI: ', self.number_of_images)

        if (self.number_of_images == 1):
            self.button_left['state'] = DISABLED
            self.button_right['state'] = DISABLED
        else:
            print('Setting current page..')
            self.current_page.set(self.number_of_images - 1)
            print(self.current_page)

        for index, every in enumerate(self.list_):
            # Load original picture
            image = Image.open(os.path.join(self.default_image_path, every))
            image = image.resize((LeafAreaCalculatorGUI.IMAGE_WIDTH, LeafAreaCalculatorGUI.IMAGE_HEIGHT),
                                 Image.ANTIALIAS)
            photo = ImageTk.PhotoImage(image)

            self.label1.after(500, self.update_original_preview, photo)
            self.current_image_name = every

            self.button_select['state'] = DISABLED
            self.button_area['state'] = NORMAL
            self.button_right['state'] = DISABLED

        self.my_frame.update_idletasks()
        self.display_this_image(self.current_image_name)

    def reset_workspace(self):
        """
        Resets the workspace to defaults. This provides a fresh GUI configuration to user.
        Clears all images in the default save path directory.
        """
        self.set_grid()
        self.stored_area_dict = dict()
        for every in os.listdir(self.default_save_path):
            os.remove(os.path.join(self.default_save_path, every))

        self.process_clicked = False

    def disable_red_button(self, event):
        """
        Disable the Set Red Button.
        """
        self.set_red_label['state'] = DISABLED
        self.set_red_square['state'] = DISABLED

        self.area_red_square = int(self.set_red_square.get())

    def set_grid(self):
        """
        Creates a blueprint of the various GUI elements in a window of size 820x500.
        Tkinter Frame is creates and place geometry manager is used to position the elements exactly where desired.
        Positions labels ans preview panes in the desired locations, as per the GUI guidelines of this project.
        """
        self.my_frame = Frame(self.root)
        self.my_frame.place(x=0, y=0, height=500, width=820)

        image = Image.open(os.path.join(os.path.dirname(__file__), 'leaf_top.png'))
        image = image.resize((40, 50), Image.ANTIALIAS)
        photo = ImageTk.PhotoImage(image)

        self.label_leaf_top = Label(self.my_frame, image=photo,
                                    height=40, width=50,
                                    font=self.font_param)
        self.label_leaf_top.image = photo
        self.label_leaf_top.place(x=0, y=0, height=40, width=50)

        self.label1 = Label(self.my_frame, text='Please upload an image.',
                            height=LeafAreaCalculatorGUI.IMAGE_HEIGHT, width=LeafAreaCalculatorGUI.IMAGE_WIDTH,
                            font=self.font_param)
        self.label1.image = photo  # keep a reference!
        self.label1.place(x=20, y=50, height=300, width=300)

        self.label2 = Label(self.my_frame, text='Processed Image \nPreview appears here.',
                            height=LeafAreaCalculatorGUI.IMAGE_HEIGHT,
                            font=self.font_param, width=LeafAreaCalculatorGUI.IMAGE_WIDTH)
        self.label2.image = photo  # keep a reference!
        self.label2.place(x=500, y=50, height=300, width=300)

        # Pagination
        self.button_left = Button(self.my_frame, text='<', height=1, width=5,
                                  command=self.display_left, font=self.font_param)
        self.button_left.place(x=20, y=400)

        self.page_label = Label(self.my_frame, text='0/0', font=self.font_param)
        self.page_label.place(x=150, y=400, width=60)

        self.button_right = Button(self.my_frame, text='>', height=1, width=5,
                                   command=self.display_right, font=self.font_param, state=DISABLED)
        self.button_right.place(x=270, y=400)

        self.label_image_name = Label(self.my_frame, text='', font=self.font_param)
        self.label_image_name.place(x=20, y=370, width=300)

        self.button_left['state'] = DISABLED
        self.button_right['state'] = DISABLED

        self.button_select = Button(self.my_frame, text='Select Image(s)', height=1, width=15,
                                    command=lambda x=self.root: self.answer(x), font=self.font_param)
        self.button_select.place(x=350, y=100)

        self.button_area = Button(self.my_frame, text='Compute Leaf Area', height=1, width=15,
                                  command=self.process_image, font=self.font_param)

        self.button_area.place(x=350, y=160)
        self.button_area['state'] = DISABLED

        self.text_area = Label(self.my_frame, text='Leaf Area:', width=30, font=self.font_param)
        self.text_area.place(x=450, y=370)

        self.show_area = Label(self.my_frame, text='NA', width=20, font=self.font_param)
        self.show_area.bind("<Button-1>", self.change_unit)
        self.show_area.place(x=600, y=370)

        self.barcode_label = Label(self.my_frame, text='Barcode ID:', width=30, font=self.font_param)
        self.barcode_label.place(x=450, y=390)

        self.show_barcode = Label(self.my_frame, text='NA', width=20, font=self.font_param)
        self.show_barcode.place(x=600, y=390)

        self.reset_button = Button(self.my_frame, text='Reset Workspace', height=1, width=15,
                                   command=self.reset_workspace,
                                   font=self.font_param)

        self.reset_button.place(x=700, y=20)

        self.set_red_label = Button(self.my_frame, text='Set Red Area:', width=12, font=self.font_param)
        self.set_red_label.bind('<Button-1>', self.disable_red_button)
        self.set_red_label.place(x=500, y=20)
        self.set_red_square = Entry(self.my_frame, width=7, font=self.font_param)
        self.set_red_square.place(x=600, y=20)
        self.set_red_square.insert(0, '{}'.format(4))
        # self.set_red_square.bind("<Return>", evaluate)
        self.set_red_square_cm = Label(self.my_frame, width=3, font=self.font_param, text='cm\u00b2')
        self.set_red_square_cm.place(x=630, y=20)
        self.set_red_square.config(justify=LEFT)
        # self.set_red_square.foc
        # self.set_red_square.insert(10, '{} cm\u00b2'.format(4))
        # entry.bind("<Return>", evaluate)

if __name__ == '__main__':
    root = Tk()
    root.title('Leaf Area Calculator')
    root.geometry("820x500")
    root.resizable(False, False)
    leaf_compute = LeafAreaCalculatorGUI(root)

    # leaf_compute.retrain_model()

    root.mainloop()

{'webbrowser': 'webbrowser', 'shutil': 'shutil'}.IMAGE_WIDTH

{'webbrowser': 'webbrowser', 'shutil': 'shutil'}.IMAGE_HEIGHT


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Created on Fri May 17 14:33:06 2019

@author: tao
"""
#coding:utf-8
import csv
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
from argparse import ArgumentParser
from matrix_completion import *
from matrix_completion import gen_mask
import matplotlib.pyplot as plt
from impyute.imputation.cs import fast_knn
from impyute.imputation.cs import mice
from sklearn.metrics import mean_squared_error #均方误差
from sklearn.metrics import mean_absolute_error #平方绝对误差
from sklearn.metrics import r2_score#R square
from sklearn import preprocessing
from fancyimpute import KNN, NuclearNormMinimization, SoftImpute, BiScaler
import tensorflow as tf
from sklearn.preprocessing import scale
from sklearn.preprocessing import StandardScaler
import time

def gen_mask2():
    mat = np.ones((40,40),dtype=int)
    for i in range(15):
        for j in range(15):
            mat[i][j]=0
    return np.reshape(mat,(1,-1))

def plot_image(A):
    plt.imshow(A.T)
    plt.show()
def show():
    time_slots = 100

    data_path = "../data/DlRsrpSinrStats.txt"

    #data_set = np.loadtxt(data_path,delimiter='	',skiprows=1);
    data_set = pd.read_table(data_path,delimiter='\t')
    print(data_set.shape)

    df = pd.DataFrame(data_set)

    rsrp=[]
    #construct matrix with location and timeslot
    bias = 3200*149
    for i in range(time_slots):
        temp = np.array((df.loc[bias+i*3200:bias+(i+1)*3200-1].sort_values('IMSI'))['rsrp'])
        temp=temp[0:1600]

        row = np.array(temp)

        rsrp.append(row)
    #rsrp = np.array((df.loc[0:time_slots*total_num-1].sort_values('IMSI'))['rsrp'])
    #print('rsrp shape:',rsrp.shape)
    #print(rsrp.shape)

    mrsrp=[]
    for power in rsrp:
        temp_power = 10*np.log10(power) + 30
        mrsrp.append(temp_power)

    mrsrp = np.array(mrsrp)

#    mrsrp = scale(mrsrp)

    print('mrsrp',mrsrp.shape)

    # generate a maskmatrix
    m = 40
    n = 40

    missing_rates = [0.75]
    #[0.5,0.55,0.6,0.65,0.7,0.75,0.8,0.85,0.9,0.95]
    #random_mat = np.random.uniform(size=[])
    xaxis=[]

    knnxaxis=[]
    knnyaxis=[]

#    iiyaxis=[]
    nnmxaxis=[]
    nnmyaxis=[]
    micexaxis=[]
    miceyaxis=[]

    knntime=[]
    nnmtime=[]
    micetime=[]

    for missing_rate in missing_rates:
        knny=[]
#        iiy=[]
        nny=[]
        micey=[]
        nnmy=[]

        ktime=0
        ntime=0
        mtime=0

        for mat_rsrp in mrsrp:
            mat_rsrp = np.array(mat_rsrp).reshape(40,40)
            mask = gen_mask(m, n, missing_rate)
#            mask = gen_mask2().reshape(40,40)
            print(mask)
            sample_data = mat_rsrp* mask

            print('origin_data')
            plot_image(mat_rsrp)

            print('the sample_data')
            plot_image(sample_data)

            try:
                t1 = time.time()
                sample_data[sample_data==0] = np.nan
                knn_recover = fast_knn(sample_data,k=3)
                print('knn')
                plot_image(knn_recover)
                error_knn = mean_absolute_error(mat_rsrp,knn_recover)
                print(error_knn)
                knny.append(error_knn)
                t2 = time.time()
                ktime = ktime + (t2-t1)
            except ValueError:
                knny.append(2)
                t2 = time.time()
                ktime = ktime + 600*(1+missing_rate)

            try:
                t1 = time.time()
                mice_data = mice(sample_data)
                print('mice')
                plot_image(mice_data)
                error_mice = mean_absolute_error(mat_rsrp,mice_data)

                micey.append(error_mice)

                t2 = time.time()
                mtime = mtime + (t2-t1)
            except ValueError:
                micey.append(2)

                t2 = time.time()
                mtime = mtime + 600*(1+missing_rate)

            try:
                t1 = time.time()

                X_filled_nnm = SoftImpute().fit_transform(sample_data)
                print('NuclearNormMinimization')
                plot_image(X_filled_nnm)
                error_nuclear = mean_absolute_error(mat_rsrp,X_filled_nnm)
                nnmy.append(error_nuclear)

                t2 = time.time()
                ntime = ntime + (t2-t1)
            except:
                nnmy.append(2)

                t2 = time.time()
                ntime = ntime + 600*(1+missing_rate)

            break
#            print("\tknn:",error_knn,"\tmice:",error_mice,"\titer:",error_iter,"\tnuclear",error_nuclear)
        knntime.append(ktime)
        nnmtime.append(ntime)
        micetime.append(mtime)

        knnyaxis.append(np.mean(np.array(knny)))
        miceyaxis.append(np.mean(np.array(micey)))
#        iiyaxis.append(np.mean(np.array(iiy)))
        nnmyaxis.append(np.mean(np.array(nnmy)))
        xaxis.append(missing_rate)

#    plt.plot(xaxis,iiy,c='red',label='iter')
#    plt.plot(xaxis,knny,c='blue',label='knn')
#    plt.plot(xaxis,nnmy,c='orange',label='nnm')
#    plt.plot(xaxis,micey,c='black',label='mice')
#
#    plt.xlabel("missing rate")
#    plt.ylabel("mae")
#    plt.legend()
#    plt.show()
        res = np.array([xaxis,knnyaxis,nnmyaxis,miceyaxis, knntime,nnmtime,micetime])
    return res ;

res = show()
print(res)
out = open('test.csv','a', newline='')
#csv_write = csv.writer(out,dialect='excel')
for d in res:
    print(d)
    csv_write.writerow(d)
out.close()


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

# What is the predicted price of a car with 50000 kilometres?

# In[1]:

import pandas as pd

df = pd.read_csv("./autos_prepared.csv")
df.head()

# In[2]:

from sklearn.model_selection import train_test_split

X = df[["kilometer"]].values
Y = df[["price"]].values

X_train, X_test, y_train, y_test = train_test_split(X, Y, random_state = 0, test_size = 0.25)

# In[3]:

from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit(df[["kilometer"]], df[["price"]])

# In[4]:

get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.pyplot as plt

plt.scatter(X_train, y_train)
plt.scatter(X_test, y_test, color = "red")
plt.show()

# In[5]:

from sklearn.linear_model import LinearRegression

model = LinearRegression()
model.fit(X_train, y_train)

print("Intercept: " + str(model.intercept_))
print("Coef: " + str(model.coef_))

# In[6]:

get_ipython().run_line_magic('matplotlib', 'inline')
import matplotlib.pyplot as plt

predicted = model.predict(X_test)

plt.scatter(X_test, y_test, color = "red")
plt.plot(X_test, predicted)
plt.show()

# In[ ]:

Lineare Regression/Lineare Regression - train_test.py


#!/usr/bin/python3
import os
import multiprocessing
import time

def rot13(entrada):
    codec = "abcdefghijklmnopqrstuvwxyz"
    codec2 = codec + codec
    salida = ""
    for caracter in entrada:
        indice = (codec.find(caracter))
        if indice >= 0:
            salida = salida + codec2[indice+13]
        else :
            salida = salida + caracter
    return (salida)

def h1(h1pipe):
    print ("hijo1 escribiendo ...")
    while True:
        leido = os.read (0, 1024)
        h1pipe.send(leido)
        if leido == b'':
            break
    print ("hijo1 leyendo .......")
    leido = h1pipe.recv()
    while leido != b'EOF':
        os.write(1, leido)
        leido = h1pipe.recv()

def h2(h2pipe):
    print ("hijo2 reemplazando ..")
    linea = h2pipe.recv().decode('utf-8')
    while linea != '':
        # procesar línea
        salida = rot13(linea)
        h2pipe.send(salida.encode())
        linea = h2pipe.recv().decode('utf-8')
    h2pipe.send(b'EOF')

if __name__ == '__main__':

    h1pipe,h2pipe = multiprocessing.Pipe()
#
#      ------ h112      h212  ------  h221        h121 ------
#      | h1 | --------------> | h2 | ----------------> | h1 |
#      ------                 ------                   ------
    ph1 = multiprocessing.Process(target=h1, args=(h1pipe,))
    ph2 = multiprocessing.Process(target=h2, args=(h2pipe,))

    ph1.start()
    ph2.start()

    ph1.join()
    ph2.join()

    print ("terminaron todos los hijos")