from selenium import webdriver
from selenium.common.exceptions import ElementNotVisibleException
from Classes.CleanText import CleanText
from Classes.RipPage import RipPage

class GrantForwardLeads(object):
    def __init__(self, searchTerm, isTest=False):
        self.isTest = isTest
        self.searchTerm = searchTerm
        self.driver = webdriver.Firefox()
        self.base_url = 'https://www.grantforward.com/'

        self.arrayOfGrantForwardLeads = []
        self.arrayOfResultsPageArrays = []

        self.driver.get(self.base_url + '/index')
        self.driver.find_element_by_id('keyword').clear()
        self.driver.find_element_by_id('keyword').send_keys(self.searchTerm)
        self.driver.find_element_by_xpath('//div[2]/button').click()
        self.driver.implicitly_wait(2)

    def processSearchResultsAndMakeLeadArray(self):
        self.getTitlesAndLinksFromSearchResults()

        if self.arrayOfResultsPagesLinks != []:
            if self.isTest != True:
                isThereNextPage = self.checkIfNextPage()
                pageCount = 2
                while isThereNextPage == True and pageCount <= 10:
                    self.goToNextPage()
                    self.getTitlesAndLinksFromSearchResults()
                    isThereNextPage = self.checkIfNextPage()
                    pageCount += 1

            for singleResultArray in self.arrayOfResultsPageArrays:
                self.makeLeadArrayAndAddToGrantForwardLeads(singleResultArray)

        self.driver.quit()

        return self.arrayOfGrantForwardLeads

    def getTitlesAndLinksFromSearchResults(self):
        self.arrayOfTitles = self.driver.find_elements_by_xpath("//a[@class = 'grant-url']")
        self.arrayOfResultsPagesLinks = []
        for i in self.arrayOfTitles:
            self.arrayOfResultsPagesLinks.append(i.get_attribute('href'))

        for i in range(len(self.arrayOfTitles)):
            title = self.arrayOfTitles[i].text
            resultPageLink = self.arrayOfResultsPagesLinks[i]
            singleResultArray = [title, resultPageLink]
            self.arrayOfResultsPageArrays.append(singleResultArray)

    def makeLeadArrayAndAddToGrantForwardLeads(self, singleResultArray):
        name = CleanText.cleanALLtheText(singleResultArray[0])
        url = singleResultArray[1]
        resultPageInfo = self.goToResultPageAndPullInformation(url)

        keyword = CleanText.cleanALLtheText(self.searchTerm)
        description = CleanText.cleanALLtheText(resultPageInfo[0])
        sponsor = CleanText.cleanALLtheText(resultPageInfo[1])
        amount = CleanText.cleanALLtheText(resultPageInfo[2])
        eligibility = CleanText.cleanALLtheText(resultPageInfo[3])
        submissionInfo = CleanText.cleanALLtheText(resultPageInfo[4])
        categories = CleanText.cleanALLtheText(resultPageInfo[5])
        opportunitySourceLink = resultPageInfo[6]
        opportunitySourceText = CleanText.cleanALLtheText(RipPage.getPageSource(opportunitySourceLink))

        singleLeadArray = [keyword, url, name, description, sponsor, amount, eligibility, submissionInfo, categories,
                           opportunitySourceLink, opportunitySourceText]

        self.arrayOfGrantForwardLeads.append(singleLeadArray)

    def goToResultPageAndPullInformation(self, resultPageLink):
        self.driver.get(resultPageLink)
        self.driver.implicitly_wait(2)
        description = ''
        sponsor = ''
        amount = ''
        eligibility = ''
        submissionInfo = ''
        categories = ''
        opportunitySourceLink = ''

        if self.checkIfElementExists("//div[@id = 'field-description']/div[@class = 'content-collapsed']"):
            descriptionDiv = self.driver.find_element_by_xpath(
                "//div[@id = 'field-description']/div[@class = 'content-collapsed']")
            description = descriptionDiv.get_attribute('textContent')

        if self.checkIfElementExists("//div[@class = 'sponsor-content']/div/a"):
            sponsorDiv = self.driver.find_element_by_xpath("//div[@class = 'sponsor-content']/div/a")
            sponsor = sponsorDiv.get_attribute('textContent')

        if self.checkIfElementExists("//div[@id = 'field-amount_info']/div[@class = 'content-collapsed']"):
            amountDiv = self.driver.find_element_by_xpath(
                "//div[@id = 'field-amount_info']/div[@class = 'content-collapsed']")
            amount = amountDiv.get_attribute('textContent')

        if self.checkIfElementExists("//div[@id = 'field-eligibility']/div[@class = 'content-collapsed']"):
            eligibilityDiv = self.driver.find_element_by_xpath(
                "//div[@id = 'field-eligibility']/div[@class = 'content-collapsed']")
            eligibility = eligibilityDiv.get_attribute('textContent')

        if self.checkIfElementExists("//div[@id = 'field-submission_info']/div[@class = 'content-collapsed']"):
            submissionInfoDiv = self.driver.find_element_by_xpath(
                "//div[@id = 'field-submission_info']/div[@class = 'content-collapsed']")
            submissionInfo = submissionInfoDiv.get_attribute('textContent')

        if self.checkIfElementExists("//div[@id = 'field-subjects']/ul"):
            categoriesDiv = self.driver.find_element_by_xpath("//div[@id = 'field-subjects']/ul")
            categories = categoriesDiv.get_attribute('textContent')

        if self.checkIfElementExists("//a[@class = 'source-link btn btn-warning']"):
            opportunitySourceLinkDiv = self.driver.find_element_by_xpath("//a[@class = 'source-link btn btn-warning']")
            opportunitySourceLink = opportunitySourceLinkDiv.get_attribute('href')

        resultPageInfo = [description, sponsor, amount, eligibility, submissionInfo, categories, opportunitySourceLink]
        return resultPageInfo

    def checkIfNextPage(self):
        checkNextPage = self.driver.find_elements_by_xpath("(//a[contains(text(), 'Next')])[1]")
        if checkNextPage != []:
            return True
        else:
            return False

    def goToNextPage(self):
        try:
            self.driver.find_element_by_xpath("(//a[contains(text(), 'Next')])[1]").click()
            self.driver.implicitly_wait(2)
        except ElementNotVisibleException:
            self.driver.implicitly_wait(2)

    def checkIfElementExists(self, xpath):
        checkElementExists = self.driver.find_elements_by_xpath(xpath)
        if checkElementExists != []:
            return True
        else:
            return False


brands = [
    'Abarth',
    'Alfa Romeo',
    'Aston Martin',
    'Audi',
    'Bentley',
	'BMW',
    'Ferrari',
    'Jaguar',
    'Lamborghini',
    'Maserati',
    'Mazda',
    'Mclaren',
    'Mercedes-Benz',
    'Mini',
    'Porsche',
    'Rolls-Royce',
	'Tesla',

]

infrequent_brands = [
    'Ford',
    'Chrysler',
    'Chevrolet',
    'Corvette',
    'Lotus',
    'MG',
    'Nissan',
    'Daihatsu',
    'Smart',
    'Peugeot',
    'Triumph',
    'Toyota',
    'Vauxhall',
]

models = {
    'audi': [
        'TT',
        'R8',
    ],
    'aston martin': [
        'DB',
        'Vanquish',
        'Vantage',
    ],
    'jaguar': [
        'XE',
        'XF',
        'XK',
        'XJ',
        'XJL',
        'F-Type',
        'F-Pace',
    ],
    'bentley': [
        'Continental GT',
        'Mulsanne',
        'Flying Spur',
    ],
    'bmw': [
        'i3',
        'i8',
        'Z3',
        'Z4',
    ],
    'tesla': [
        'Model S',
        'Model X'
    ],
    'porsche': [
        '911',
        'Carrera',
        'Panamera',
        'Cayman',
        'Boxster',
        'Targa',
        '911 Carrera',
        '911 Turbo',
        '911 Targa',
        '911 GT3',
        '718 Boxster',
        '718 Cayman',
        '718 Cayman GT4',
    ],
    'mazda': [
        "MX5",
        "RX8",
    ],
    'mercedes-benz': [
        'SLK',
        'SL',
        'AMG GT',
    ],
    'aston martin': [
        'DB',
        'Vantage'
    ],
    'lamborghini': [
        'Aventador',
        'Gallardo',
    ],
    'maserati': [
        'Ghibli',
        'GranTurismo',
        'GranCabrio',
        'Quattroporte',
    ],
    'rolls-royce': [
        'Dawn',
        'Ghost',
        'Phantom',
        'Wraith',
    ],
    'ford': [
        'Mustang GT',
        'Mustang',
        'Mustang Mach-E',
    ],
    'abarth': [
        '500',
        '595 Turismo',
        '124 Spider',
    ],
    'nissan': [
        'Leaf',
        '370Z',
        'GT-R',
    ],
    'mclaren': [
        '570S',
    ],
    'chrysler' : [
        '300',
        'Crossfire',
    ],
    "mini": [
        "Cooper",
        "Countryman",
        "Paceman",
        "Clubman",
    ],
    "daihatsu": [
        "Copen",
    ],
    'smart': [
        'Roadster',
    ],
    'lotus': [
        'Evora',
        'Exige',
        'Elise',
        '3-Eleven',
    ],
    'peugeot': [
        'RCZ',
        '206 CC',
    ],
    'corvette': [
        'Stingray',
    ],
    'vauxhall': [
        'Tigra',
    ],
    'alfa romeo': [
        'Brera',
        '4C',
    ],
}

model_sub_types = {
    'porsche': [
        'S',
        '3',
        '4',
        '4S',
        'GTS',
    ],
    'mini': [
        'S',
    ],
    'jaguar': [
        'S',
        'R',
    ],
    'tesla': [
        'P90D',
        '100D',
    ],
}


from multiprocessing import Pool, cpu_count
from time import time

import requests
from matplotlib import pyplot as plt

def baidu(_):
    rep = requests.get('https://www.baidu.com')
    code = rep.status_code
    return time()

def highConcurrent(count):

    pool = Pool(cpu_count())
    tl = []
    start_time = time()

    for i in range(count):
        p = pool.apply_async(baidu, args=(i, ))
        tl.append(p)

    tl = [t.get() for t in tl]
    pool.close()
    pool.join()

    time_li = []
    for t in tl:
        time_li.append(t - start_time)

    plt.rcParams['font.sans-serif'] = ['SimHei']  # 显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 这两行需要手动设置
    fig, ax = plt.subplots()
    ax.plot([i for i in range(1, len(time_li) + 1)], time_li)
    ax.set(xlabel='请求', ylabel='时间（s）',
           title='线程（并发）')
    ax.grid()
    fig.savefig('并发（进程 apply_async）.png')

if __name__ == '__main__':
    highConcurrent(100)


from flask import Flask, jsonify, request

app = Flask(__name__)
import sys
import os
sys.path.append(os.path.join(os.path.dirname(__file__), '..'))
from src.learner.walk_through import WalkThrougher

def init():
    pass

@app.route('/', methods=['GET', 'POST'])
def hello_world():
    return 'California: Data Understanding algorithms system.'

@app.route('/california_v1', methods=['POST'])
def intent_matching():
    # pass-through: return empty string.
    request_json = request.json
    first_letters = request_json['column_names']
    wt = WalkThrougher()
    res = []
    for fl in first_letters:
        res.append({
            'key': fl,
            'res': wt.combined_match(fl)
        })
    res_json = {
        'results': res
    }

    return jsonify(res_json)

if __name__ == '__main__':
    init()
    app.run(host='0.0.0.0', port=80)


"""
Course: CSE 251
Lesson Week: 14
File: assignment.py
Author: Jesse Gibbons
Purpose: Assignment 13 - Family Search

Instructions:

Depth First Search
https://www.youtube.com/watch?v=9RHO6jU--GU

Breadth First Search
https://www.youtube.com/watch?v=86g8jAQug04

Describe how to sped up part 1

Organize families with list comprehensions and fetch them all concurrently.
Prioritize fetching parents before children so we can
recurse to fetch the parent families concurrently with
requests to fetch the children.

Before change:
total_time                   : 102.31911579999996
People and families / second : 3.8702445472070837

After changes:
total_time                   : 4.1270161000011285
People and families / second : 88.44162250782114

Describe how to sped up part 2

Since part 2 does nothing, it cannot be faster.
It also doesn't work as expected, so I can only make it slower.
Breadth-first search is done one level at a time. It can be
accomplished as follows:
If the given list is not empty:
    get every element in the list, and put all the results in a new list.
    recurse with the new list.

10% Bonus to speed up part 2

Use a 5-semaphore to control the number of simultaneous requests.
Within semaphore block, call code to request.
Outside semaphore block, do all other processing.

"""
import time
import threading
import multiprocessing as mp
from multiprocessing.pool import ThreadPool
import json
import random
import requests

# Include cse 251 common Python files - Dont change
import os, sys
sys.path.append('../../code')
from cse251 import *

TOP_API_URL = 'http://127.0.0.1:8123'

# ----------------------------------------------------------------------------
class Person:
    def __init__(self, data):
        super().__init__()
        self.id = data['id']
        self.name = data['name']
        self.parents = data['parent_id']
        self.family = data['family_id']
        self.birth = data['birth']

    def __str__(self):
        output  = f'id        : {self.id}\n'
        output += f'name      : {self.name}\n'
        output += f'birth     : {self.birth}\n'
        output += f'parent id : {self.parents}\n'
        output += f'family id : {self.family}\n'
        return output

# ----------------------------------------------------------------------------
class Family:

    def __init__(self, id, data):
        super().__init__()
        self.id = data['id']
        self.husband = data['husband_id']
        self.wife = data['wife_id']
        self.children = data['children']

    def children_count(self):
        return len(self.children)

    def __str__(self):
        output  = f'id         : {self.id}\n'
        output += f'husband    : {self.husband}\n'
        output += f'wife       : {self.wife}\n'
        for id in self.children:
            output += f'  Child    : {id}\n'
        return output

# -----------------------------------------------------------------------------
class Tree:

    def __init__(self, start_family_id):
        super().__init__()
        self.people = {}
        self.families = {}
        self.start_family_id = start_family_id

    def add_person(self, person):
        if self.does_person_exist(person.id):
            print(f'ERROR: Person with ID = {person.id} Already exists in the tree')
        else:
            self.people[person.id] = person

    def add_family(self, family):
        if self.does_family_exist(family.id):
            print(f'ERROR: Family with ID = {family.id} Already exists in the tree')
        else:
            self.families[family.id] = family

    def get_person(self, id):
        if id in self.people:
            return self.people[id]
        else:
            return None

    def get_family(self, id):
        if id in self.families:
            return self.families[id]
        else:
            return None

    def get_person_count(self):
        return len(self.people)

    def get_family_count(self):
        return len(self.families)

    def does_person_exist(self, id):
        return id in self.people

    def does_family_exist(self, id):
        return id in self.families

    def display(self, log):
        log.write('Tree Display')
        for family_id in self.families:
            fam = self.families[family_id]

            log.write(f'Family id: {family_id}')

            # Husband
            husband = self.get_person(fam.husband)
            if husband == None:
                log.write(f'  Husband: None')
            else:
                log.write(f'  Husband: {husband.name}, {husband.birth}')

            # wife
            wife = self.get_person(fam.wife)
            if wife == None:
                log.write(f'  Wife: None')
            else:
                log.write(f'  Wife: {wife.name}, {wife.birth}')

            # Parents of Husband
            if husband == None:
                log.write(f'  Husband Parents: None')
            else:
                parent_fam_id = husband.parents
                if parent_fam_id in self.families:
                    parent_fam = self.get_family(parent_fam_id)
                    father = self.get_person(parent_fam.husband)
                    mother = self.get_person(parent_fam.wife)
                    log.write(f'  Husband Parents: {father.name} and {mother.name}')
                else:
                    log.write(f'  Husband Parents: None')

            # Parents of Wife
            if wife == None:
                log.write(f'  Wife Parents: None')
            else:
                parent_fam_id = wife.parents
                if parent_fam_id in self.families:
                    parent_fam = self.get_family(parent_fam_id)
                    father = self.get_person(parent_fam.husband)
                    mother = self.get_person(parent_fam.wife)
                    log.write(f'  Wife Parents: {father.name} and {mother.name}')
                else:
                    log.write(f'  Wife Parents: None')

            # children
            output = []
            for index, child_id in enumerate(fam.children):
                person = self.people[child_id]
                output.append(f'{person.name}')
            out_str = str(output).replace("'", '', 100)
            log.write(f'  Children: {out_str[1:-1]}')

    def _test_number_connected_to_start(self):
        # start with first family, how many connected to that family
        inds_seen = set()

        def _recurive(family_id):
            nonlocal inds_seen
            if family_id in self.families:
                # count people in this family
                fam = self.families[family_id]

                husband = self.get_person(fam.husband)
                if husband != None:
                    if husband.id not in inds_seen:
                        inds_seen.add(husband.id)
                    _recurive(husband.parents)

                wife = self.get_person(fam.wife)
                if wife != None:
                    if wife.id not in inds_seen:
                        inds_seen.add(wife.id)
                    _recurive(wife.parents)

                for child_id in fam.children:
                    if child_id not in inds_seen:
                        inds_seen.add(child_id)

        _recurive(self.start_family_id)
        return len(inds_seen)

    def _count_generations(self, family_id):
        max_gen = -1

        def _recurive_gen(id, gen):
            nonlocal max_gen
            if id in self.families:
                if max_gen < gen:
                    max_gen = gen

                fam = self.families[id]

                husband = self.get_person(fam.husband)
                if husband != None:
                    _recurive_gen(husband.parents, gen + 1)

                wife = self.get_person(fam.wife)
                if wife != None:
                    _recurive_gen(wife.parents, gen + 1)

        _recurive_gen(family_id, 0)
        return max_gen + 1

    def __str__(self):
        out = '\nTree Stats:\n'
        out += f'Number of people                    : {len(self.people)}\n'
        out += f'Number of families                  : {len(self.families)}\n'
        out += f'Max generations                     : {self._count_generations(self.start_family_id)}\n'
        out += f'People connected to starting family : {self._test_number_connected_to_start()}\n'
        return out

# ----------------------------------------------------------------------------
# Do not change
class Request_thread(threading.Thread):

    def __init__(self, url):
        # Call the Thread class's init function
        threading.Thread.__init__(self)
        self.url = url
        self.response = {}

    def run(self):
        response = requests.get(self.url)
        # Check the status code to see if the request succeeded.
        if response.status_code == 200:
            self.response = response.json()
        else:
            print('RESPONSE = ', response.status_code)

# -----------------------------------------------------------------------------
# Change this function to speed it up
def depth_fs_pedigree(family_id, tree):
    if family_id == None:
        return

    print(f'Retrieving Family: {family_id}')

    req_family = Request_thread(f'{TOP_API_URL}/family/{family_id}')
    req_family.start()
    req_family.join()

    new_family = Family(family_id, req_family.response)
    tree.add_family(new_family)

    # Get husband details
    husband_id, wife_id, children_ids = new_family.husband, new_family.wife, [c for c in new_family.children if not tree.does_person_exist(c)]
    print(f'   Retrieving Husband : {husband_id}')
    print(f'   Retrieving Wife    : {wife_id}')
    print(f'   Retrieving children: {str(children_ids)[1:-1]}')
    req_parents = [Request_thread(f'{TOP_API_URL}/person/{id}') for id in [husband_id, wife_id]]
    [t.start() for t in req_parents]
    [t.join() for t in req_parents]
    parents = [Person(r.response) for r in req_parents]

    family_threads = [threading.Thread(target=depth_fs_pedigree, args=(p.parents, tree)) for p in parents if p is not None]
    req_children = [Request_thread(f'{TOP_API_URL}/person/{id}') for id in children_ids]

    [t.start() for t in req_children]
    [tree.add_person(person) for person in parents]
    [thread.start() for thread in family_threads]
    [t.join() for t in req_children]
    for person in req_children:
        if person is not None:
            tree.add_person(Person(person.response))
    [thread.join() for thread in family_threads]

# -----------------------------------------------------------------------------
# You should not change this function
def part1(log, start_id, generations):
    tree = Tree(start_id)

    req = Request_thread(f'{TOP_API_URL}/start/{generations}')
    req.start()
    req.join()

    log.start_timer('Depth-First')
    depth_fs_pedigree(start_id, tree)
    total_time = log.stop_timer()

    req = Request_thread(f'{TOP_API_URL}/end')
    req.start()
    req.join()

    tree.display(log)
    log.write(tree)
    log.write(f'total_time                   : {total_time}')
    log.write(f'People and families / second : {(tree.get_person_count()  + tree.get_family_count()) / total_time}')
    log.write('')

# -----------------------------------------------------------------------------
def breadth_fs_pedigree(start_id, tree):
    #      - implement breadth first retrieval
    #      - Limit number of concurrent connections to the FS server to 5
    # This video might help understand BFS
    # https://www.youtube.com/watch?v=86g8jAQug04

    req_sem = threading.Semaphore(5)
    #tree_lock = threading.Lock()
    #Used internally.
    def get_family(family_id):
        """
        Fetches the family from id.
        Add family to tree.
        Put parents in current_parent_id_list
        put children in current_child_id_list
        """
        req_family = Request_thread(f'{TOP_API_URL}/family/{family_id}')
        with req_sem:
            #We are in a helper thread, so fetch without making a new thread.
            req_family.run()
        new_family = Family(family_id, req_family.response)
        #with tree_lock:
        tree.add_family(new_family)
        parents_ids = [new_family.husband, new_family.wife]
        current_parent_id_list.extend(parents_ids)
        children_ids = [c for c in new_family.children if not tree.does_person_exist(c)]
        current_child_id_list.extend(children_ids)

    def get_parent(id):
        """
        Fetch the person of the given id.
        Append the result's parents' family id to next_family_id_list
        Return the result person
        """
        req_person = Request_thread(f'{TOP_API_URL}/person/{id}')
        with req_sem:
            req_person.run()
        new_person = Person(req_person.response)
        if new_person != None:
            #with tree_lock:
            tree.add_person(new_person)
            return new_person.parents

    def get_child(id):
        """
        Fetch the person of the given id.
        Return the result person.
        """
        get_parent(id)

    current_family_id_list = [start_id]
    next_family_id_list = []
    while len(current_family_id_list) !=  0:
        current_parent_id_list = []
        current_child_id_list = []
        with ThreadPool(10) as pool:
            # get family and collect parents, children
            pool.map(get_family, current_family_id_list)
            print("got all the family pool")
            print(f"parents: {current_parent_id_list}")
            print(f"children: {current_child_id_list}")
            # get parents and collect people, next generation family ids
            next_family_id_list = pool.map(get_parent, current_parent_id_list)
            print(f"next family id list: {next_family_id_list}")
            # get children and collect people
            pool.map(get_child, current_child_id_list)
        current_family_id_list = [id for id in next_family_id_list if id is not None]
        next_family_id_list = []

# -----------------------------------------------------------------------------
# You should not change this function
def part2(log, start_id, generations):
    tree = Tree(start_id)

    req = Request_thread(f'{TOP_API_URL}/start/{generations}')
    req.start()
    req.join()

    log.start_timer('Breadth-First')
    breadth_fs_pedigree(start_id, tree)
    total_time = log.stop_timer()

    req = Request_thread(f'{TOP_API_URL}/end')
    req.start()
    req.join()

    tree.display(log)
    log.write(tree)
    log.write(f'total_time      : {total_time}')
    log.write(f'People / second : {tree.get_person_count() / total_time}')
    log.write('')

# -----------------------------------------------------------------------------
def main():
    log = Log(show_terminal=True, filename_log='assignment.log')

    # starting family
    req = Request_thread(TOP_API_URL)
    req.start()
    req.join()

    print(f'Starting Family id: {req.response["start_family_id"]}')
    start_id = req.response['start_family_id']

    part1(log, start_id, 6)

    part2(log, start_id, 6)

if __name__ == '__main__':
    main()


# -*- coding: utf-8 -*-
from odoo import models, api, fields
from odoo.osv import expression
from odoo.addons.account.models.product import ProductTemplate as PT

@api.multi
def _get_product_accounts(self):
    """计算商品的收入科目和费用科目路径：商品科目-->设置默认科目-->商品目录科目"""
    config_obj = self.env['ir.config_parameter'].sudo()
    account_obj = self.env['account.account'].sudo()

    # 收入科目
    income = self.property_account_income_id
    if not income:
        company_id = self._context.get('force_company')
        if not company_id:
            company_id = self.env.user.company_id.id

        # 获取商品默认收入科目的代码
        income_id = config_obj.get_param('account.product_account_income_id')
        if income_id:
            domain = [('code', '=', account_obj.browse(int(income_id)).code)]
            domain = expression.AND([domain, [('company_id', '=', company_id)]])
            income = account_obj.search(domain)

    if not income:
        income = self.account_categ_id.property_account_income_categ_id

    # 费用科目
    expense = self.property_account_expense_id
    if not expense:
        company_id = self._context.get('force_company')
        if not company_id:
            company_id = self.env.user.company_id.id

        # 获取商品默认费用科目的代码
        expense_id = config_obj.get_param('account.product_account_expense_id')
        if expense_id:
            domain = [('code', '=', account_obj.browse(int(expense_id)).code)]
            domain = expression.AND([domain, [('company_id', '=', company_id)]])
            expense = account_obj.search(domain)

    if not expense:
        expense = self.account_categ_id.property_account_expense_categ_id

    return {
        'income': income,
        'expense': expense
    }

PT._get_product_accounts = _get_product_accounts

class ProductTemplate(models.Model):
    _inherit = "product.template"

    account_categ_id = fields.Many2one('product.category', '第二层科目', compute='_compute_account_categ_id', store=1)

    @api.one
    @api.depends('categ_id')
    def _compute_account_categ_id(self):
        categ = [self.categ_id]

        categ_id = self.categ_id
        while categ_id.parent_id:
            categ.append(categ_id.parent_id)
            categ_id = categ_id.parent_id

        if len(categ) > 1:
            self.account_categ_id = categ[:-1][-1].id
        else:
            self.account_categ_id = self.categ_id.id


import torch
import torchvision.transforms as Transforms

use_gpu = True if torch.cuda.is_available() else False

# trained on high-quality celebrity faces "celebA" dataset
# this model outputs 512 x 512 pixel images
model = torch.hub.load('facebookresearch/pytorch_GAN_zoo:hub',
                       'PGAN', model_name='celebAHQ-512',
                       pretrained=True, useGPU=use_gpu)
# this model outputs 256 x 256 pixel images
# model = torch.hub.load('facebookresearch/pytorch_GAN_zoo:hub',
#                        'PGAN', model_name='celebAHQ-256',
#                        pretrained=True, useGPU=use_gpu)
num_images = 1

def pgan():
    noise, _ = model.buildNoiseData(num_images)
    with torch.no_grad():
        generated_images = model.test(noise)

    transform = Transforms.Compose([Transforms.Normalize((-1., -1., -1.), (2, 2, 2)),
                                    Transforms.ToPILImage()])
    generated_images = generated_images[0]
    generated_images = transform(generated_images.clamp(min=-1, max=1))
    return generated_images


import asyncio
import logging
import logging.config
import os
import time
import sys
import signal

import discord
import dotenv
import yaml
from discord.ext import commands

from discord_slash import SlashCommand
from discord_components import DiscordComponents

CORE_EXTENSIONS = [
    "bot.cogs.core.events",
    "bot.cogs.core.help",
    "bot.cogs.core.info",
    "bot.cogs.core.owner",
    "bot.cogs.core.settings",
    "bot.cogs.core.tasks",
]

EXTENSIONS = [
    # "bot.cogs.colors",
    # "bot.cogs.economy",
    "bot.cogs.embeds",
    "bot.cogs.fun",
    "bot.cogs.games",
    # "bot.cogs.greetings",
    # "bot.cogs.links",
    "bot.cogs.math",
    "bot.cogs.moderation",
    # "bot.cogs.modlogs",
    "bot.cogs.reaction_roles",
    "bot.cogs.search",
    "bot.cogs.starboard",
    "bot.cogs.suggestions",
]

with open("logging.yml", "r") as f:
    logging.config.dictConfig(yaml.load(f, Loader=yaml.SafeLoader))

def main():
    logger = logging.getLogger(__name__)
    dotenv.load_dotenv()
    try:
        with open("config.yml", "r") as f:
            config = yaml.load(f, Loader=yaml.SafeLoader)
    except FileNotFoundError:
        logger.critical(
            "No config.yml found. Please make sure it is in this directory.",
            extra={"botname": "N/A"},
        )
        sys.exit(1)

    logger.info("Parsing config.yml.", extra={"botname": "N/A"})
    bots = []
    for botconf in config["bots"]:
        adplogger = logging.LoggerAdapter(logger, extra={"botname": botconf["name"]})
        try:
            if not botconf["name"]:
                adplogger.error(
                    "Misconfigured config.yml file. You must set a name for each bot."
                )
            if not botconf["prefix"]:
                adplogger.error(
                    "Misconfigured config file. You must set a prefix for each bot."
                )
            if not botconf["token"]["value"] and not botconf["token"]["env"]:
                adplogger.error(
                    "Misconfigured config.yml file. You must set the bot's token either in config.yml or in your .env file."
                )
            if botconf["token"]["value"] and botconf["token"]["env"]:
                adplogger.error(
                    "Misconfigured config.yml file. You cannot have both value and env declared under token."
                )
        except KeyError:
            adplogger.error(
                "Invalid config.yml file. One or more keys are missing. Please use the template provided in the repository as well as the tutorial for configuring your bot.",
            )
            sys.exit(1)

        adplogger.info("Creating bot instance.")
        try:
            bot = commands.Bot(
                command_prefix=botconf["prefix"],
                help_command=commands.DefaultHelpCommand
                if botconf["use_default_help_command"]
                else None,
                intents=discord.Intents.all()
                if botconf["gateway_intents"]
                else discord.Intents.default(),
                description=botconf["description"],
            )
            bot.name = botconf["name"]
            bot.token = (
                os.environ[botconf["token"]["name"]]
                if botconf["token"]["env"]
                else botconf["token"]["value"]
            )
            bot.AZURE_KEY = os.environ["AZURE_KEY"]
        except:
            adplogger.error(
                "Failed to create bot instance. Check your config.yml file."
            )
            sys.exit(1)

        adplogger.info(
            "Activating Discord interactions (slash commands, buttons, and selects)."
        )

        slash = SlashCommand(bot, sync_commands=True)
        # DiscordComponents(bot)

        adplogger.info("Loading extensions.")

        for extension in CORE_EXTENSIONS:
            bot.load_extension(extension)

        for extension in EXTENSIONS:
            bot.load_extension(extension)

        # if botconf["extensions"]["enabled"]:
        #     for extension in botconf["extensions"]["enabled"]:
        #         try:
        #             bot.load_extension(extension)
        #         except:
        #             adplogger.error(
        #                 f"Unable to load extension {extension}. Check if the file exists."
        #             )
        # if botconf["extensions"]["disabled"]:
        #     for extension in EXTENSIONS:
        #         if extension not in botconf["extensions"]["disabled"]:
        #             bot.load_extension(extension)

        # if botconf["extensions"]["custom"]:
        #     for extension in botconf["extensions"]["custom"]:
        #         try:
        #             bot.load_extension(extension)
        #         except:
        #             adplogger.error(
        #                 f"Unable to load extension {extension}. Check if the file exists.",
        #                 exc_info=True,
        #             )

        bots.append(bot)

    loop = asyncio.get_event_loop()
    try:
        loop.add_signal_handler(signal.SIGINT, lambda: loop.stop())
        loop.add_signal_handler(signal.SIGTERM, lambda: loop.stop())
    except NotImplementedError:
        pass

    for bot in bots:
        logger.info("Starting bot.", extra={"botname": bot.name})
        loop.create_task(bot.start(bot.token))

    loop.run_forever()
    # except KeyboardInterrupt:
    #     logger.info("Received signal to shut down bots.", extra={"botname": "N/A"})
    #     loop.stop()
    # except Exception as e:
    #     print(e)

if __name__ == "__main__":
    main()


# pylint:disable=redefined-outer-name
# pylint:disable=protected-access

import pytest
from aiohttp import ClientSession, ClientWebSocketResponse, WSMessage, WSMsgType

from tinvest import Streaming

@pytest.fixture()
async def queue(streaming):
    return streaming._queue

@pytest.fixture()
async def message(mocker):
    msg = mocker.AsyncMock(WSMessage)
    msg.type = WSMsgType.TEXT
    return msg

@pytest.fixture()
async def ws(mocker):
    return mocker.AsyncMock(ClientWebSocketResponse)

@pytest.fixture()
async def session(mocker, ws, message):
    ws.__aiter__.return_value = [message]

    s = mocker.AsyncMock(ClientSession)
    s.closed = False
    s.ws_connect.return_value.__aenter__.return_value = ws
    s.ws_connect.return_value.__aexit__.return_value = False
    return s

@pytest.fixture()
def closed_session(session):
    session.closed = True
    return session

@pytest.fixture()
async def streaming(token, session):
    return Streaming(token, session=session, reconnect_enabled=False)


import json
from json import encoder

namen = 'n'
tip = 't'
barva = 'b'
rože = 'r'
izbira = 'i'
shrani_izbiro = 's'

class Sopek:
    """Izberemo kakšen aranžma želimo in nato poiščemo sliko, ki mu je vektorsko najbližje  """

    def __init__(self, uid, fp):
        self.uid = uid

        self.fp = fp

    def izbira(self,izbira):
        self.izbira = izbira[:]

    def vektor(self,vektor):
        self.vektor = vektor[:]

    def id(fp):
        uid = 0
        for x in fp:
            if x == fp:
                pass
            else:
                uid += 1

    def primerjava_fingerprint_izbira(fp, izbira):
        primerjava_namen = izbira & fp[1]
        primerjava_tip = izbira & fp[2]
        primerjava_barva = izbira & fp[3]
        primerjava_roze = izbira & fp[4]
        return [primerjava_namen, primerjava_tip, primerjava_barva, primerjava_roze]

    def najboljsi_kompromisi(izbira):
        stevilo_izbire = {}
        for x in izbira:
            for namen,tip,barva,roze in izbira:
                stevilo_izbire[namen] = stevilo_izbire.get(namen, 0) + 1
                stevilo_izbire[tip] = stevilo_izbire.get(tip, 0) + 1
                stevilo_izbire[barva] = stevilo_izbire.get(barva, 0) + 1
                stevilo_izbire[roze] = stevilo_izbire.get(roze, 0) + 1
        max_ujemanje = 0
        naj_priblizek = set()

        for izbira in stevilo_izbire:
            if stevilo_izbire[izbira] > max_ujemanje:
                naj_priblizek = {izbira}
                max_ujemanje = stevilo_izbire[izbira]
            elif stevilo_izbire[izbira] == max_ujemanje:
                naj_priblizek.add(izbira)

        return naj_priblizek

    def dobi_json_slovar(self):
        return {
            "fp": self.fp,
        }

class Orozarna:

    def __init__(self, zacetni_sopki = None , prost_id = 0):
        self.sopki = zacetni_sopki = {}
        self.prost_id = prost_id

    def json_slovar(self):
        slovar = {}
        for uid, sopek in self.sopki.items():
            slovar[uid] = sopek.dobi_json_slovar()
        return slovar

    def shrani_v_json_datoteko(self, ime_datoteke):
        with open(ime_datoteke, 'w') as out_file:
            json.dump(self.json_slovar(), out_file, indent=None)

    def nov_id(self):
        self.prost_id += 1
        return self.prost_id

    def dodaj_sopek(self, fp):
        uid = self.nov_id()
        sopek = Sopek(uid,fp)
        self.sopki[uid] = sopek

    @staticmethod
    def prevedi_json(json_slovar):
        slovar_sopek = {}
        for uid, sopek_slovar in json_slovar.items():
            slovar_sopek[int(uid)] = [
                Sopek.prevedi_json(sopek_slovar)
            ]

        return Orozarna(
            slovar_sopek, max(slovar_sopek.keys()) + 1
        )


#!/usr/bin/env python

"""
Phil Adams http://philadams.net

As always, `-h` is your friend.

Given a .csv file of VERA+ statuses, locally archive all default-sized images.

TODO: hook logging back up to args.verbose and args.quiet
"""

import logging
import os
from StringIO import StringIO
import csv
import json
import time

from pprint import pprint

import requests
from PIL import Image

def main():
    import argparse

    # populate and parse command line options
    parser = argparse.ArgumentParser(description='Image archiving for VERA+')
    group = parser.add_mutually_exclusive_group()
    group.add_argument('-v', '--verbose', action='count', default=0)
    group.add_argument('-q', '--quiet', action='store_true')
    group.add_argument('--outdir', help='dir in which to archive images')
    parser.add_argument('config', help='config params (json)')
    parser.add_argument('statuses', help='veraplus statuses (csv)')
    args = parser.parse_args()

    # load config params
    with open(args.config) as f:
        config = json.load(f)
        config['outdir'] = args.outdir or config.get('outdir', './gen')
        if not os.path.exists(config['outdir']):
            os.makedirs(config['outdir'])

    # logging config
    log_level = logging.WARNING  # default
    if args.verbose == 1:
        log_level = logging.INFO
    elif args.verbose >= 2:
        log_level = logging.DEBUG
    logging.basicConfig(level=logging.WARNING)  # global logging settings
    fmt = logging.Formatter('%(levelname)s:%(name)s:%(message)s')
    fmt_t = logging.Formatter('%(asctime)s - %(levelname)s:%(name)s:%(message)s')
    log_ch = logging.StreamHandler()
    log_ch.setLevel(logging.DEBUG)  # edit for debugging
    log_ch.setFormatter(fmt)
    log_fh = logging.FileHandler('%s/log.log' % config['outdir'])
    log_fh.setLevel(logging.WARNING)
    log_fh.setFormatter(fmt_t)
    imgdl_log = logging.getLogger('idl-tools.imagearchiver')
    imgdl_log.propagate = False
    imgdl_log.setLevel(logging.DEBUG)
    imgdl_log.addHandler(log_fh)
    imgdl_log.addHandler(log_ch)

    # load all the statuses into memory
    with open(args.statuses, 'rU') as f:
        statuses = [row for row in csv.reader(f)]

    fields = statuses.pop(0)  # header row
    for i, row in enumerate(statuses):
        if i % 25 == 0:
            imgdl_log.info('processing %d/%d' % (i+1, len(statuses)))

        status = dict(zip(fields, row))
        status['img_uri'] = '%s%s' % (config['urlbase'], status['image_path'])
        imgdir = '%s/%s' % (config['outdir'], status['user_id'])
        if not os.path.exists(imgdir):
            os.makedirs(imgdir)

        req = requests.get(status['img_uri'])
        time.sleep(0.1)
        if not req.ok:
            imgdl_log.error('sid%s img http req (%s)' % (status['status_id'],
                                                         status['img_uri']))
            continue
        try:
            img = Image.open(StringIO(req.content))
            img.save('%s/u%s_s%s.jpg' % (imgdir,
                                         status['user_id'],
                                         status['status_id']))
        except IOError as e:
            imgdl_log.error('sid%s img persist (%s)' % (status['status_id'],
                                                          status['img_uri']))
            continue

if '__main__' == __name__:
    main()


import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn.gaussian_process.kernels import ExpSineSquared
from sklearn.kernel_ridge import KernelRidge
from sklearn.metrics import mean_squared_error
from sklearn.preprocessing import StandardScaler
from sklearn.model_selection import GridSearchCV
from sklearn.svm import SVR, LinearSVC, LinearSVR
from sklearn.model_selection import cross_val_score
from sklearn import linear_model
from sklearn.preprocessing import PolynomialFeatures
from sklearn.metrics import r2_score
from sklearn.utils import shuffle
import matplotlib.ticker as ticker

# For SVR we need Feature Scaling
scaler = StandardScaler()

dataset = pd.read_pickle('./dataframe.pkl')
#train = dataset.iloc[:400]
#test = dataset.iloc[400:]

print(dataset)

#dataset selection
train_datasets = ['RW1', 'RW7','RW4', 'RW5','RW10', 'RW11', 'RW13', 'RW14', 'RW20','RW21', 'RW22', 'RW23', 'RW25', 'RW26', 'RW27']
test_datasets = ['RW8', 'RW12','RW6','RW15', 'RW24', 'RW28']

train = dataset[dataset.ID.isin(train_datasets)]
test = dataset[dataset.ID.isin(test_datasets)]

#feature selected to train the model
#features_cols = ['Qdelta', 'C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C10', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'CV', 'V10', 'CT', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'T8', 'T9', 'T10']
features_cols = ['C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C10', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'T8', 'T9', 'T10']
features_colsTest = ['ID','C1', 'C2', 'C3', 'C4', 'C5', 'C6', 'C7', 'C8', 'C9', 'C10', 'V1', 'V2', 'V3', 'V4', 'V5', 'V6', 'V7', 'V8', 'V9', 'V10', 'T1', 'T2', 'T3', 'T4', 'T5', 'T6', 'T7', 'T8', 'T9', 'T10']
X = train.loc[:, features_cols]

#X = np.array(X)

#response vector for train
response_col = ['Capacità']
y = pd.Series(train['Capacità'])

#get the test models
X_test = test.loc[:, features_colsTest]
#X_test = np.array(X_test)

y_labels = test.loc[:, ['ID', 'Capacità']]

X_testRW8 = X_test.where(X_test['ID'] == 'RW8').dropna()
X_testRW6 = X_test.where(X_test['ID'] == 'RW6').dropna()
X_testRW12 = X_test.where(X_test['ID'] == 'RW12').dropna()
X_testRW15 = X_test.where(X_test['ID'] == 'RW15').dropna()
X_testRW24 = X_test.where(X_test['ID'] == 'RW24').dropna()
X_testRW28 = X_test.where(X_test['ID'] == 'RW28').dropna()
X_testRW8.pop('ID')
X_testRW6.pop('ID')
X_testRW15.pop('ID')
X_testRW12.pop('ID')
X_testRW24.pop('ID')
X_testRW28.pop('ID')

y_labelsRW8 = y_labels.where(y_labels['ID'] == 'RW8').dropna()
y_labelsRW6 = y_labels.where(y_labels['ID'] == 'RW6').dropna()
y_labelsRW12 = y_labels.where(y_labels['ID'] == 'RW12').dropna()
y_labelsRW15 = y_labels.where(y_labels['ID'] == 'RW15').dropna()
y_labelsRW24 = y_labels.where(y_labels['ID'] == 'RW24').dropna()
y_labelsRW28 = y_labels.where(y_labels['ID'] == 'RW28').dropna()

y_labelsRW8.pop('ID')
y_labelsRW6.pop('ID')
y_labelsRW12.pop('ID')
y_labelsRW15.pop('ID')
y_labelsRW24.pop('ID')
y_labelsRW28.pop('ID')

x_labels = test.loc[:, ['ID', 'Qstart','Qend']]

aRW8 = x_labels.where(x_labels['ID'] == 'RW8').dropna()
aRW6 = x_labels.where(x_labels['ID'] == 'RW6').dropna()
aRW15 = x_labels.where(x_labels['ID'] == 'RW15').dropna()
aRW24 = x_labels.where(x_labels['ID'] == 'RW24').dropna()
aRW28 = x_labels.where(x_labels['ID'] == 'RW28').dropna()
aRW12 = x_labels.where(x_labels['ID'] == 'RW12').dropna()
aRW8.pop('ID')
aRW6.pop('ID')
aRW15.pop('ID')
aRW24.pop('ID')
aRW28.pop('ID')
aRW12.pop('ID')

#train the model

param_grid={
            'C': [0.0001, 0.001, 0.1, 1, 100, 1000, 1250, 1500],
            'epsilon': [0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1, 5, 10],
            'gamma': ['auto','scale','auto_deprecated']
        }

svr_rbf = SVR(kernel='rbf')

clf = GridSearchCV(svr_rbf, param_grid, cv=3, scoring='neg_mean_squared_error', verbose=0, n_jobs=-1)

clf.fit(X, y)

print(clf.best_params_)

test_predictionsRW8 =  clf.predict(X_testRW8)
test_predictionsRW6 =  clf.predict(X_testRW6)
test_predictionsRW12 =  clf.predict(X_testRW12)
test_predictionsRW15 =  clf.predict(X_testRW15)
test_predictionsRW24 =  clf.predict(X_testRW24)
test_predictionsRW28 =  clf.predict(X_testRW28)

print("\n-----R2 SCORE----")
print("RW8 -->", r2_score(y_labelsRW8, test_predictionsRW8))
print("RW6 -->", r2_score(y_labelsRW6, test_predictionsRW6))
print("RW12 -->", r2_score(y_labelsRW12, test_predictionsRW12))
print("RW15 -->", r2_score(y_labelsRW15, test_predictionsRW15))
print("RW24 -->", r2_score(y_labelsRW24, test_predictionsRW24))
print("RW28 -->", r2_score(y_labelsRW28, test_predictionsRW28))
print("---------")

print("\n-----MSE SCORE----")
print("RW8 -->", mean_squared_error(y_labelsRW8, test_predictionsRW8))
print("RW6 -->", mean_squared_error(y_labelsRW6, test_predictionsRW6))
print("RW12 -->", mean_squared_error(y_labelsRW12, test_predictionsRW12))
print("RW15 -->", mean_squared_error(y_labelsRW15, test_predictionsRW15))
print("RW24 -->", mean_squared_error(y_labelsRW24, test_predictionsRW24))
print("RW28 -->", mean_squared_error(y_labelsRW28, test_predictionsRW28))
print("---------")

print(np.mean([mean_squared_error(y_labelsRW8, test_predictionsRW8), mean_squared_error(y_labelsRW6, test_predictionsRW6)
                  , mean_squared_error(y_labelsRW12, test_predictionsRW12), mean_squared_error(y_labelsRW15, test_predictionsRW15)
                  ,mean_squared_error(y_labelsRW24, test_predictionsRW24), mean_squared_error(y_labelsRW28, test_predictionsRW28)]))

#new_loc = np.round(np.arange(aRW8['Qstart'].iloc[0], aRW8['Qend'].iloc[-1], (aRW8['Qend'].iloc[-1] - aRW8['Qstart'].iloc[0])/len(locs) ),2)

colors = ['#2300A8', '#00A658']
plt.subplot(2, 3, 2)
frequency = 3
x_ax = range(y_labelsRW8.shape[0])
plt.scatter(x_ax, y_labelsRW8, s=5, color=colors[0], label = "original")
plt.plot(x_ax, test_predictionsRW8, lw=1.5, color =colors[1], label="predicted")
plt.xticks(x_ax[::6],np.round(np.arange(aRW8['Qstart'].iloc[0], aRW8['Qend'].iloc[-1], (aRW8['Qend'].iloc[-1] - aRW8['Qstart'].iloc[0])/len(x_ax)))[::6], rotation = 45)
plt.yticks(y_labelsRW8.values[::6], np.round(np.arange(y_labelsRW8['Capacità'].iloc[-1], y_labelsRW8['Capacità'].iloc[0], (y_labelsRW8['Capacità'].iloc[0]-y_labelsRW8['Capacità'].iloc[-1])/len(y_labelsRW8.values)), 2)[::-1])
plt.xlabel("Time (h)")
plt.ylabel("Capacity (Ah)")
plt.title('RW8')
ax = plt.gca()
ax.tick_params(axis = 'both', which = 'major', labelsize = 8.5)
plt.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5)
plt.figlegend(loc = 'center left')

plt.subplot(2, 3, 1)
x_ax = range(y_labelsRW6.shape[0])
plt.scatter(x_ax, y_labelsRW6, s=5, color=colors[0], label = "original")
plt.plot(x_ax, test_predictionsRW6, lw=1.5, color =colors[1], label="predicted")
plt.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5)
plt.xticks(x_ax[::3],np.round(np.arange(aRW6['Qstart'].iloc[0], aRW6['Qend'].iloc[-1], (aRW6['Qend'].iloc[-1] - aRW6['Qstart'].iloc[0])/len(x_ax)))[::3], rotation = 45)
plt.yticks(y_labelsRW6.values[::3], np.round(np.arange(y_labelsRW6['Capacità'].iloc[-1], y_labelsRW6['Capacità'].iloc[0], (y_labelsRW6['Capacità'].iloc[0]-y_labelsRW6['Capacità'].iloc[-1])/len(y_labelsRW6.values)), 2)[::-1])
plt.xlabel("Time (h)")
plt.ylabel("Capacity (Ah)")
plt.title('RW6')
ax = plt.gca()
ax.tick_params(axis = 'both', which = 'major', labelsize = 8.5)

plt.subplot(2, 3, 4)
x_ax = range(y_labelsRW15.shape[0])
plt.scatter(x_ax, y_labelsRW15, s=5, color=colors[0], label = "original")
plt.plot(x_ax, test_predictionsRW15, lw=1.5, color =colors[1], label="predicted")
locs, labels=plt.xticks()
plt.xticks(x_ax[::6],np.round(np.arange(aRW15['Qstart'].iloc[0], aRW15['Qend'].iloc[-1], (aRW15['Qend'].iloc[-1] - aRW15['Qstart'].iloc[0])/len(x_ax)))[::6], rotation = 45)
plt.yticks(y_labelsRW15.values[::6], np.round(np.arange(y_labelsRW15['Capacità'].iloc[-1], y_labelsRW15['Capacità'].iloc[0], (y_labelsRW15['Capacità'].iloc[0]-y_labelsRW15['Capacità'].iloc[-1])/len(y_labelsRW15.values)), 2)[::-1])
plt.xlabel("Time (h)")
plt.ylabel("Capacity (Ah)")
plt.title('RW15')
plt.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5)
ax = plt.gca()
ax.tick_params(axis = 'both', which = 'major', labelsize = 8.5)

plt.subplot(2, 3, 5)
x_ax = range(y_labelsRW24.shape[0])
plt.scatter(x_ax, y_labelsRW24, s=5, color=colors[0], label = "original")
plt.plot(x_ax, test_predictionsRW24, lw=1.5, color =colors[1], label="predicted")
plt.xticks(x_ax[::frequency],np.round(np.arange(aRW24['Qstart'].iloc[0], aRW24['Qend'].iloc[-1], (aRW24['Qend'].iloc[-1] - aRW24['Qstart'].iloc[0])/len(x_ax)))[::frequency], rotation = 45)
plt.yticks(y_labelsRW24.values[::3], np.round(np.arange(y_labelsRW24['Capacità'].iloc[-1], y_labelsRW24['Capacità'].iloc[0], (y_labelsRW24['Capacità'].iloc[0]-y_labelsRW24['Capacità'].iloc[-1])/len(y_labelsRW24.values)), 2)[::-1])
plt.xlabel("Time (h)")
plt.ylabel("Capacity (Ah)")
plt.title('RW24')
plt.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5)
ax = plt.gca()
ax.tick_params(axis = 'both', which = 'major', labelsize = 8.5)

plt.subplot(2, 3, 6)
x_ax = range(y_labelsRW28.shape[0])
plt.scatter(x_ax, y_labelsRW28, s=5, color=colors[0], label = "original")
plt.plot(x_ax, test_predictionsRW28, lw=1.5, color =colors[1], label="predicted")
plt.xticks(x_ax[::frequency],np.round(np.arange(aRW28['Qstart'].iloc[0], aRW28['Qend'].iloc[-1], (aRW28['Qend'].iloc[-1] - aRW28['Qstart'].iloc[0])/len(x_ax)))[::frequency], rotation = 45)
plt.yticks(y_labelsRW28.values[::3], np.round(np.arange(y_labelsRW28['Capacità'].iloc[-1], y_labelsRW28['Capacità'].iloc[0], (y_labelsRW28['Capacità'].iloc[0]-y_labelsRW28['Capacità'].iloc[-1])/len(y_labelsRW28.values)), 2)[::-1])
plt.xlabel("Time (h)")
plt.ylabel("Capacity (Ah)")
plt.title('RW28')
plt.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5)
ax = plt.gca()
ax.tick_params(axis = 'both', which = 'major', labelsize = 8.5)

plt.subplot(2, 3, 3)
x_ax = range(y_labelsRW12.shape[0])
plt.scatter(x_ax, y_labelsRW12, s=5, color=colors[0], label = "original")
plt.plot(x_ax, test_predictionsRW12, lw=1.5, color =colors[1], label="predicted")
plt.xticks(x_ax[::8],np.round(np.arange(aRW12['Qstart'].iloc[0], aRW12['Qend'].iloc[-1], (aRW12['Qend'].iloc[-1] - aRW12['Qstart'].iloc[0])/len(x_ax)))[::8], rotation = 45)
plt.yticks(y_labelsRW12.values[::8], np.round(np.arange(y_labelsRW12['Capacità'].iloc[-1], y_labelsRW12['Capacità'].iloc[0], (y_labelsRW12['Capacità'].iloc[0]-y_labelsRW12['Capacità'].iloc[-1])/len(y_labelsRW12.values)), 2)[::-1])
plt.xlabel("Time (h)")
plt.ylabel("Capacity (Ah)")
plt.title('RW12')
plt.grid(color='grey', linestyle='-', linewidth=0.25, alpha=0.5)
ax = plt.gca()
ax.tick_params(axis = 'both', which = 'major', labelsize = 8.5)

plt.show()


try:
    import unzip_requirements
except ImportError:
    pass

import PIL
from PIL import Image

import io
import base64
from requests_toolbelt.multipart import decoder
import json
import numpy as np
import onnxruntime    # Using ONNX Runtime for inferencing onnx format model

# custom packages
from utils.hpe_skeleton_utils import get_skeleton
from utils.hpe_transform_utils import transform_image

print("Import End...")

HPE_QNNX_MODEL_PATH = 'hpe_trained_model/pose_resnet_50_256x256_quantized.onnx'

onnxrt_session = onnxruntime.InferenceSession(HPE_QNNX_MODEL_PATH)
print('onnx runtime session created for the model')

# HPE Pose Prediction using ONNX Runtime
def get_poses_predictions(ort_s, img):
    try:
        tr_img = transform_image(img)
        inp = {ort_s.get_inputs()[0].name: tr_img}
        out = ort_s.run(None, inp)
        out = np.array(out[0][0])
        return out
    except Exception as e:
        print(repr(e))
        raise(e)

def img_to_base64(img):
    img = Image.fromarray(img, 'RGB')
    buffer = io.BytesIO()
    img.save(buffer,format="JPEG")
    myimage = buffer.getvalue()
    img_str = f"data:image/jpeg;base64,{base64.b64encode(myimage).decode()}"
    return img_str

'''
Input image is received as formdata.
NOTE: In API gateway , Binay Media type shall be set to multipart/form-data
'''
def main_handler(event, context):
    try:
        content_type_header = event['headers']['content-type']
        print('content_type header: ' + content_type_header)
        #print('Event Body: ' + event["body"])

        body = base64.b64decode(event["body"])
        print('Image content Loaded')
        picture = decoder.MultipartDecoder(body, content_type_header).parts[0]
        print(f'MultipartDecoder processed')
        img = Image.open(io.BytesIO(picture.content))
        print(f'Input image data loaded')

        output = get_poses_predictions(ort_s=onnxrt_session, img=img)
        print(f'got image poses, output shape: {output.shape}')

        img = np.array(img)
        hpe_img = get_skeleton(img, output)
        print(f'Image prepared with all joints connected')

        filename = picture.headers[b'Content-Disposition'].decode().split(';')[1].split('=')[1]
        if len(filename) < 4:
            filename = picture.headers[b'Content-Disposition'].decode().split(';')[2].split('=')[1]

        return {
            "statusCode": 200,
            "headers": {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*',
                "Access-Control-Allow-Credentials": True

            },
            "body": json.dumps({'file': filename.replace('"', ''), 'hpeImg': img_to_base64(hpe_img)})
        }
    except Exception as e:
        print(repr(e))
        return {
            "statusCode": 500,
            "headers": {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*',
                "Access-Control-Allow-Credentials": True
            },
            "body": json.dumps({"error": repr(e)})
        }

'''
Input image is received as base64 encoded format in JSON body
'''
def main_handler_jsondata(event, context):
    try:
        content_type_header = event['headers']['content-type']
        print('content_type header: ' + content_type_header)
        #print('Event Body: ' + event["body"])

        # use this when input image is received as JSON body
        json_body = json.loads(event["body"])
        im = base64.b64decode(json_body["img"])
        print('Image content Loaded')

        img = Image.open(io.BytesIO(im))

        output = get_poses_predictions(ort_s=onnxrt_session, img=img)
        print(f'Got image poses, output shape: {output.shape}')

        img = np.array(img)
        hpe_img = get_skeleton(img, output)
        print(f'Image prepared with all joints connected')

        return {
            "statusCode": 200,
            "headers": {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*',
                "Access-Control-Allow-Credentials": True

            },
            "body": json.dumps({'hpeImg': img_to_base64(hpe_img)})
        }
    except Exception as e:
        print(repr(e))
        return {
            "statusCode": 500,
            "headers": {
                'Content-Type': 'application/json',
                'Access-Control-Allow-Origin': '*',
                "Access-Control-Allow-Credentials": True
            },
            "body": json.dumps({"error": repr(e)})
        }


from sklearn.metrics import classification_report
from sklearn.externals import joblib

def main():
    tp = fp = tn = fn = 0
    for line in open('knock76_ans.csv', encoding='utf8'):
        corr, ans, _ = line.strip().split('\t')
        if ans == '1' and corr == ans:
            tp += 1
        elif ans == '1' and corr != ans:
            fp += 1
        elif ans == '-1' and corr == ans:
            tn += 1
        else:
            fn += 1

    print('正解率\t', (tp + tn) / (tp + fp + tn + fn))
    print('正例に関する適合率\t', tp / (tp + fn))

if __name__ == '__main__':
    main()

''' 問
77. 正解率の計測

76の出力を受け取り，予測の正解率，正例に関する適合率，
再現率，F1スコアを求めるプログラムを作成せよ．
'''

''' 実行結果
正解率   0.8809791783905458
正例に関する適合率       0.8773213280810355
'''


from django.shortcuts import render, HttpResponse, redirect
# from django.core.urlresolvers import reverse
import random, time

def index(request):
    if "total" not in request.session:
        request.session['total'] = 0
    return render(request, 'ninjagold/index.html')

time = {"time": time.strftime('%B %d, %Y %I:%M %p')}
def process(request):
    randNum = {
        "farm": random.randrange(10, 21),
        "cave": random.randrange(5, 11),
        "house": random.randrange(2, 6),
        "casino": random.randrange(0, 51),
        "pick": random.randrange(0, 2)
    }
    building = request.POST['building']

    if "messages" not in request.session:
        request.session['messages'] = []
    if building == "farm":
        request.session['total'] += randNum['farm']
        result = {
            "message":"Earned " + str(randNum['farm']) + " golds from the farm! " + str(time['time']),
            "color": "green"
        }
        request.session['messages'].append(result)
    elif building == "cave":
        request.session['total'] += randNum['cave']
        result = {
            "message": "Earned " +  str(randNum['cave']) + " golds from a cave! " + str(time['time']),
            "color": "green"
        }
        request.session['messages'].append(result)
    elif building == "house":
        request.session['total'] += randNum['house']
        result = {
            "message" : "Earned " + str(randNum['house']) + " golds from the house! " + str(time['time']),
            "color": "green"
        }
        request.session['messages'].append(result)
    elif building == "casino":
        if randNum['pick'] == 0:
            request.session['total'] += randNum['casino']
            result = {
                "message":"Earned " + str(randNum['casino']) + " golds from a casino! " +     str(time['time']),
                "color": "green"
            }
            request.session['messages'].append(result)
        else:
            request.session['total'] -= randNum['casino']
            result = {
                "message":"Entered a casino and lost " + str(randNum['casino']) + " golds...Ouch..." + str(time['time']),
                "color": "red"
            }
            request.session['messages'].append(result)
    return redirect('ninjagold:index')

def clear(request):
    request.session['messages'] = []
    return redirect('ninjagold:index')

def restart(request):
    request.session['total'] = 0
    request.session['messages'] = []
    return redirect('ninjagold:index')