# Copyright (c), Google Inc, 2017
# Simplified BSD License (see licenses/simplified_bsd.txt or https://opensource.org/licenses/BSD-2-Clause)

try:
    import requests
    HAS_REQUESTS = True
except ImportError:
    HAS_REQUESTS = False

try:
    import google.auth
    import google.auth.compute_engine
    from google.oauth2 import service_account
    from google.auth.transport.requests import AuthorizedSession
    HAS_GOOGLE_LIBRARIES = True
except ImportError:
    HAS_GOOGLE_LIBRARIES = False

from ansible.module_utils.basic import AnsibleModule, env_fallback
from ansible.module_utils.six import string_types
from ansible.module_utils._text import to_text, to_native
import ast
import os
import json

def navigate_hash(source, path, default=None):
    if not source:
        return None

    key = path[0]
    path = path[1:]
    if key not in source:
        return default
    result = source[key]
    if path:
        return navigate_hash(result, path, default)
    else:
        return result

class GcpRequestException(Exception):
    pass

def remove_nones_from_dict(obj):
    new_obj = {}
    for key in obj:
        value = obj[key]
        if value is not None and value != {} and value != []:
            new_obj[key] = value

    # Blank dictionaries should return None or GCP API may complain.
    if not new_obj:
        return None
    return new_obj

# Handles the replacement of dicts with values -> the needed value for GCP API
def replace_resource_dict(item, value):
    if isinstance(item, list):
        items = []
        for i in item:
            items.append(replace_resource_dict(i, value))
        return items
    else:
        if not item:
            return item
        else:
            return item.get(value)

# Handles all authentication and HTTP sessions for GCP API calls.
class GcpSession(object):
    def __init__(self, module, product):
        self.module = module
        self.product = product
        self._validate()

    def get(self, url, body=None, **kwargs):
        """
        This method should be avoided in favor of full_get
        """
        kwargs.update({'json': body})
        return self.full_get(url, **kwargs)

    def post(self, url, body=None, headers=None, **kwargs):
        """
        This method should be avoided in favor of full_post
        """
        kwargs.update({'json': body, 'headers': headers})
        return self.full_post(url, **kwargs)

    def post_contents(self, url, file_contents=None, headers=None, **kwargs):
        """
        This method should be avoided in favor of full_post
        """
        kwargs.update({'data': file_contents, 'headers': headers})
        return self.full_post(url, **kwargs)

    def delete(self, url, body=None):
        """
        This method should be avoided in favor of full_delete
        """
        kwargs = {'json': body}
        return self.full_delete(url, **kwargs)

    def put(self, url, body=None):
        """
        This method should be avoided in favor of full_put
        """
        kwargs = {'json': body}
        return self.full_put(url, **kwargs)

    def patch(self, url, body=None, **kwargs):
        """
        This method should be avoided in favor of full_patch
        """
        kwargs.update({'json': body})
        return self.full_patch(url, **kwargs)

    def list(self, url, callback, params=None, array_name='items',
             pageToken='nextPageToken', **kwargs):
        """
        This should be used for calling the GCP list APIs. It will return
        an array of items

        This takes a callback to a `return_if_object(module, response)`
        function that will decode the response + return a dictionary. Some
        modules handle the decode + error processing differently, so we should
        defer to the module to handle this.
        """
        resp = callback(self.module, self.full_get(url, params, **kwargs))
        items = resp.get(array_name) if resp.get(array_name) else []
        while resp.get(pageToken):
            if params:
                params['pageToken'] = resp.get(pageToken)
            else:
                params = {'pageToken': resp[pageToken]}

            resp = callback(self.module, self.full_get(url, params, **kwargs))
            if resp.get(array_name):
                items = items + resp.get(array_name)
        return items

    # The following methods fully mimic the requests API and should be used.
    def full_get(self, url, params=None, **kwargs):
        kwargs['headers'] = self._set_headers(kwargs.get('headers'))
        try:
            return self.session().get(url, params=params, **kwargs)
        except getattr(requests.exceptions, 'RequestException') as inst:
            # Only log the message to avoid logging any sensitive info.
            self.module.fail_json(msg=inst.message)

    def full_post(self, url, data=None, json=None, **kwargs):
        kwargs['headers'] = self._set_headers(kwargs.get('headers'))

        try:
            return self.session().post(url, data=data, json=json, **kwargs)
        except getattr(requests.exceptions, 'RequestException') as inst:
            self.module.fail_json(msg=inst.message)

    def full_put(self, url, data=None, **kwargs):
        kwargs['headers'] = self._set_headers(kwargs.get('headers'))

        try:
            return self.session().put(url, data=data, **kwargs)
        except getattr(requests.exceptions, 'RequestException') as inst:
            self.module.fail_json(msg=inst.message)

    def full_patch(self, url, data=None, **kwargs):
        kwargs['headers'] = self._set_headers(kwargs.get('headers'))

        try:
            return self.session().patch(url, data=data, **kwargs)
        except getattr(requests.exceptions, 'RequestException') as inst:
            self.module.fail_json(msg=inst.message)

    def full_delete(self, url, **kwargs):
        kwargs['headers'] = self._set_headers(kwargs.get('headers'))

        try:
            return self.session().delete(url, **kwargs)
        except getattr(requests.exceptions, 'RequestException') as inst:
            self.module.fail_json(msg=inst.message)

    def _set_headers(self, headers):
        if headers:
            return self._merge_dictionaries(headers, self._headers())
        else:
            return self._headers()

    def session(self):
        return AuthorizedSession(
            self._credentials())

    def _validate(self):
        if not HAS_REQUESTS:
            self.module.fail_json(msg="Please install the requests library")

        if not HAS_GOOGLE_LIBRARIES:
            self.module.fail_json(msg="Please install the google-auth library")

        if self.module.params.get('service_account_email') is not None and self.module.params['auth_kind'] != 'machineaccount':
            self.module.fail_json(
                msg="Service Account Email only works with Machine Account-based authentication"
            )

        if (self.module.params.get('service_account_file') is not None or
                self.module.params.get('service_account_contents') is not None) and self.module.params['auth_kind'] != 'serviceaccount':
            self.module.fail_json(
                msg="Service Account File only works with Service Account-based authentication"
            )

    def _credentials(self):
        cred_type = self.module.params['auth_kind']
        if cred_type == 'application':
            credentials, project_id = google.auth.default(scopes=self.module.params['scopes'])
            return credentials
        elif cred_type == 'serviceaccount' and self.module.params.get('service_account_file'):
            path = os.path.realpath(os.path.expanduser(self.module.params['service_account_file']))
            return service_account.Credentials.from_service_account_file(path).with_scopes(self.module.params['scopes'])
        elif cred_type == 'serviceaccount' and self.module.params.get('service_account_contents'):
            try:
                cred = json.loads(self.module.params.get('service_account_contents'))
            except json.decoder.JSONDecodeError as e:
                self.module.fail_json(
                    msg="Unable to decode service_account_contents as JSON"
                )
            return service_account.Credentials.from_service_account_info(cred).with_scopes(self.module.params['scopes'])
        elif cred_type == 'machineaccount':
            return google.auth.compute_engine.Credentials(
                self.module.params['service_account_email'])
        else:
            self.module.fail_json(msg="Credential type '%s' not implemented" % cred_type)

    def _headers(self):
        if self.module.params.get('env_type'):
            return {
                'User-Agent': "Google-Ansible-MM-{0}-{1}".format(self.product, self.module.params.get('env_type'))
            }
        else:
            return {
                'User-Agent': "Google-Ansible-MM-{0}".format(self.product)
            }

    def _merge_dictionaries(self, a, b):
        new = a.copy()
        new.update(b)
        return new

class GcpModule(AnsibleModule):
    def __init__(self, *args, **kwargs):
        arg_spec = {}
        if 'argument_spec' in kwargs:
            arg_spec = kwargs['argument_spec']

        kwargs['argument_spec'] = self._merge_dictionaries(
            arg_spec,
            dict(
                project=dict(
                    required=False,
                    type='str',
                    fallback=(env_fallback, ['GCP_PROJECT'])),
                auth_kind=dict(
                    required=True,
                    fallback=(env_fallback, ['GCP_AUTH_KIND']),
                    choices=['machineaccount', 'serviceaccount', 'application'],
                    type='str'),
                service_account_email=dict(
                    required=False,
                    fallback=(env_fallback, ['GCP_SERVICE_ACCOUNT_EMAIL']),
                    type='str'),
                service_account_file=dict(
                    required=False,
                    fallback=(env_fallback, ['GCP_SERVICE_ACCOUNT_FILE']),
                    type='path'),
                service_account_contents=dict(
                    required=False,
                    fallback=(env_fallback, ['GCP_SERVICE_ACCOUNT_CONTENTS']),
                    no_log=True,
                    type='jsonarg'),
                scopes=dict(
                    required=False,
                    fallback=(env_fallback, ['GCP_SCOPES']),
                    type='list'),
                env_type=dict(
                    required=False,
                    fallback=(env_fallback, ['GCP_ENV_TYPE']),
                    type='str')
            )
        )

        mutual = []
        if 'mutually_exclusive' in kwargs:
            mutual = kwargs['mutually_exclusive']

        kwargs['mutually_exclusive'] = mutual.append(
            ['service_account_email', 'service_account_file', 'service_account_contents']
        )

        AnsibleModule.__init__(self, *args, **kwargs)

    def raise_for_status(self, response):
        try:
            response.raise_for_status()
        except getattr(requests.exceptions, 'RequestException') as inst:
            self.fail_json(msg="GCP returned error: %s" % response.json())

    def _merge_dictionaries(self, a, b):
        new = a.copy()
        new.update(b)
        return new

# This class does difference checking according to a set of GCP-specific rules.
# This will be primarily used for checking dictionaries.
# In an equivalence check, the left-hand dictionary will be the request and
# the right-hand side will be the response.

# Rules:
# Extra keys in response will be ignored.
# Ordering of lists does not matter.
#   - exception: lists of dictionaries are
#     assumed to be in sorted order.
class GcpRequest(object):
    def __init__(self, request):
        self.request = request

    def __eq__(self, other):
        return not self.difference(other)

    def __ne__(self, other):
        return not self.__eq__(other)

    # Returns the difference between a request + response.
    # While this is used under the hood for __eq__ and __ne__,
    # it is useful for debugging.
    def difference(self, response):
        return self._compare_value(self.request, response.request)

    def _compare_dicts(self, req_dict, resp_dict):
        difference = {}
        for key in req_dict:
            if resp_dict.get(key):
                difference[key] = self._compare_value(req_dict.get(key), resp_dict.get(key))

        # Remove all empty values from difference.
        sanitized_difference = {}
        for key in difference:
            if difference[key]:
                sanitized_difference[key] = difference[key]

        return sanitized_difference

    # Takes in two lists and compares them.
    # All things in the list should be identical (even if a dictionary)
    def _compare_lists(self, req_list, resp_list):
        # Have to convert each thing over to unicode.
        # Python doesn't handle equality checks between unicode + non-unicode well.
        difference = []
        new_req_list = self._convert_value(req_list)
        new_resp_list = self._convert_value(resp_list)

        # We have to compare each thing in the request to every other thing
        # in the response.
        # This is because the request value will be a subset of the response value.
        # The assumption is that these lists will be small enough that it won't
        # be a performance burden.
        for req_item in new_req_list:
            found_item = False
            for resp_item in new_resp_list:
                # Looking for a None value here.
                if not self._compare_value(req_item, resp_item):
                    found_item = True
            if not found_item:
                difference.append(req_item)

        difference2 = []
        for value in difference:
            if value:
                difference2.append(value)

        return difference2

    # Compare two values of arbitrary types.
    def _compare_value(self, req_value, resp_value):
        diff = None
        # If a None is found, a difference does not exist.
        # Only differing values matter.
        if not resp_value:
            return None

        # Can assume non-None types at this point.
        try:
            if isinstance(req_value, list):
                diff = self._compare_lists(req_value, resp_value)
            elif isinstance(req_value, dict):
                diff = self._compare_dicts(req_value, resp_value)
            elif isinstance(req_value, bool):
                diff = self._compare_boolean(req_value, resp_value)
            # Always use to_text values to avoid unicode issues.
            elif to_text(req_value) != to_text(resp_value):
                diff = req_value
        # to_text may throw UnicodeErrors.
        # These errors shouldn't crash Ansible and should be hidden.
        except UnicodeError:
            pass

        return diff

    # Compare two boolean values.
    def _compare_boolean(self, req_value, resp_value):
        try:
            # Both True
            if req_value and isinstance(resp_value, bool) and resp_value:
                return None
            # Value1 True, resp_value 'true'
            elif req_value and to_text(resp_value) == 'true':
                return None
            # Both False
            elif not req_value and isinstance(resp_value, bool) and not resp_value:
                return None
            # Value1 False, resp_value 'false'
            elif not req_value and to_text(resp_value) == 'false':
                return None
            else:
                return resp_value

        # to_text may throw UnicodeErrors.
        # These errors shouldn't crash Ansible and should be hidden.
        except UnicodeError:
            return None

    # Python (2 esp.) doesn't do comparisons between unicode + non-unicode well.
    # This leads to a lot of false positives when diffing values.
    # The Ansible to_text() function is meant to get all strings
    # into a standard format.
    def _convert_value(self, value):
        if isinstance(value, list):
            new_list = []
            for item in value:
                new_list.append(self._convert_value(item))
            return new_list
        elif isinstance(value, dict):
            new_dict = {}
            for key in value:
                new_dict[key] = self._convert_value(value[key])
            return new_dict
        else:
            return to_text(value)


# summarize multiple confidence intervals on an ARIMA forecast
from pandas import read_csv
from statsmodels.tsa.arima.model import ARIMA
# load data
series = read_csv('daily-total-female-births.csv', header=0, index_col=0, parse_dates=True, squeeze=True)
# split data into train and test setes
X = series.values
X = X.astype('float32')
size = len(X) - 1
train, test = X[0:size], X[size:]
# fit an ARIMA model
model = ARIMA(train, order=(5,1,1))
model_fit = model.fit()
result = model_fit.get_forecast()
forecast = result.predicted_mean
# summarize confidence intervals
intervals = [0.2, 0.1, 0.05, 0.01]
for a in intervals:
	ci = result.conf_int(alpha=a)
	print('%.1f%% Confidence Interval: %.3f between %.3f and %.3f' % ((1-a)*100, forecast, ci[0,0], ci[0,1]))


import os
import sys
from pprint import pprint
from collections import defaultdict
from array import array
import argparse
import ROOT as r

'''
This script calculates the BX scale factors to be applied
on train MC for data comparison. They are binned by BX and E-rec regions.
There are different histograms for different eta regions:
1 = all endcap
2 = rings 18-21
3 = rings 22-25
4 = rings 26-28
'''

parser = argparse.ArgumentParser()
parser.add_argument("-i", "--inputfile", type=str, help="Input file", required=True)
parser.add_argument("-o", "--outputfile", type=str, help="Outputfile", required=True)
parser.add_argument("-n", "--nbx", type=int, help="Number of BX", required=True)
args = parser.parse_args()

regions_names = {
    "1": "18_28",
    "2": "18_21",
    "3": "22_25",
    "4": "26_28"
}

with open(args.inputfile) as fi:
    lines = fi.readlines()

regions = defaultdict(dict)

for li in lines:
    region_et, nevents_bx = li.split(" ")
    nevents_bx = int(nevents_bx)
    region , et = region_et.split("_")
    et = int(et)

    if et not in regions[region]:
        regions[region][et] = []

    regions[region][et].append(nevents_bx)

# Calculate Scale factors
sf_regions = {}
for region, etregs in regions.items():
    new_etrs = {}
    for k, etr in etregs.items():
        s = sum(etr)
        bxsf = list(map(lambda k: k/s, etr))
        new_etrs[k] = bxsf
    sf_regions[region] = new_etrs

# Create one 2D histogram for each region
output = r.TFile(args.outputfile, "recreate")

for region, data in sf_regions.items():
    sfhisto = r.TH2F("bxsf_"+ regions_names[region], "", args.nbx, 0, args.nbx-1, len(data), 1, len(data))

    for et, sfs in data.items():
        for bx,sf in enumerate(sfs):
            bn = sfhisto.GetBin(bx+1, et)
            sfhisto.SetBinContent(bn, sf)
            print(et,bx,sf)
    sfhisto.Write()

output.Close()


'''

CNN+GRU

1. CNNEncoder: CNN feature extraction net

2. CNNClassifier: Simple CNN classifier to train CNNEncoder

3. CGNN: Final net to apply CNNEncoder and BiGRU
'''
from keras.models import Model, Sequential
from keras.layers import Conv2D, Dense, Input, Dropout, Flatten, GRU, MaxPool2D, Activation, BatchNormalization

def CNNEncoder(input_shape):
    model = Sequential()
    model.add(BatchNormalization(axis=1, name='bn_0'))

    # Conv block 1
    model.add(Conv2D(64, (3,3), strides=(1, 1), padding='same', name='conv_1'))
    model.add(BatchNormalization(axis=1, name='bn_1'))
    model.add(Activation('elu'))
    model.add(MaxPool2D(pool_size=(4, 2), strides=(4,2), name='pool_1'))
    model.add(Dropout(0.2, name='dropout_1'))

    # Conv block2
    model.add(Conv2D(128, (3,3), strides=(1, 1), padding='same', name='conv_2'))
    model.add(BatchNormalization(axis=1, name='bn_2'))
    model.add(Activation('elu'))
    model.add(MaxPool2D(pool_size=(5, 2), strides=(5,2), name='pool_2'))
    model.add(Dropout(0.2, name='dropout_2'))

    # Conv block3
    model.add(Conv2D(128, (3,3), strides=(1, 1), padding='same', name='conv_3'))
    model.add(BatchNormalization(axis=1, name='bn_3'))
    model.add(Activation('elu'))
    model.add(MaxPool2D(pool_size=(5, 4), strides=(5,4), name='pool_3'))
    model.add(Dropout(0.2, name='dropout_3'))

    # Conv block3
    model.add(Conv2D(128, (3,3), strides=(1, 1), padding='same', name='conv_4'))
    model.add(BatchNormalization(axis=1, name='bn_4'))
    model.add(Activation('elu'))
    model.add(MaxPool2D(pool_size=(5, 4), strides=(5,4), name='pool_4'))
    model.add(Dropout(0.2, name='dropout_4'))

    model.add(Flatten())

    return model

def CNNClassifier(input_shape):
    input = Input(input_shape)
    x = CNNEncoder(input_shape)(input)
    x = Dense(1, activation='relu')(x)
    model = Model(input,x)
    model.compile('Adam', 'mse', metrics='acc')
    return model

def CGNN(input_shape):
    input = Input(input_shape)
    x = CNNEncoder(input_shape)(input)
    Model(input, x)


# -*- encoding: utf-8 -*-

import odoo
import odoo.modules.registry
import ast

from odoo import http, _
from odoo.http import request
from odoo.addons.web.controllers.main import Home

import datetime
import json
import pytz
import os
from odoo.addons.student_portal.controllers.main import StudentPortal
import logging

_logger = logging.getLogger(__name__)

#----------------------------------------------------------
# OpenERP Web web Controllers
#----------------------------------------------------------

class StudentPortal(StudentPortal):

    # Main student Portal Profile
    @http.route(['/student/portal/profile'], type='http', auth="user", website=True)
    def student_portal_profile(self, **kw):
        partner = request.env.user.partner_id
        student_id = request.env['student.student'].sudo().search([('user_id','=',request.env.user.id)], limit=1)
        country_ids = request.env['res.country'].sudo().search([])
        state_ids = request.env['res.country.state'].sudo().search([])
        mother_tongue_ids = request.env['mother.toungue'].sudo().search([])
        general_survey_ids = request.env['general.survey'].sudo().search([])
        highest_qualification_ids = request.env['highest.qualification'].sudo().search([])
        values = {'student_profile': student_id,
                'gender':student_id.gender,
                'school_ids':student_id.sudo().school_id,
                'standard_ids': student_id.sudo().standard_id,
                'year_ids': student_id.sudo().year,
                'country_id': student_id.sudo().country_id,
                'country_ids': country_ids,
                'state_id': student_id.sudo().state_id,
                'state_ids': state_ids,
                'marital_status': student_id.maritual_status,
                'mother_tongue_ids': mother_tongue_ids,
                'mother_tongue_id': student_id.sudo().mother_tongue,
                'income':student_id.sudo().income,
                'general_survey_ids': general_survey_ids,
                'general_survey_id': student_id.sudo().general_survey_id,
                'highest_qualification_ids': highest_qualification_ids,
                'highest_qualification_id': student_id.sudo().highest_qualification_id,
                'references_ids': student_id.sudo().reference_ids,
                'parent_ids': student_id.sudo().parent_id,
                'education_background_ids': student_id.sudo().education_background_id,
                'family_ids': student_id.sudo().family_con_ids,
        }
        return request.render("student_portal.student_portal_profile_template", values)

    # Student Profile Update
    @http.route(['/student/profile/update'], type='http', auth="public", website=True, csrf=False)
    def student_profile_update(self, **post):
        partner = request.env.user.partner_id
        student_id = request.env['student.student'].sudo().search([('user_id','=',request.env.user.id)], limit=1)
        vals = {
                'name': post.get('first_name',False) or '',
                'gender': post.get('gender',False),
                'street':post.get('address1',False),
                'street2':post.get('address2',False),
                'state_id':post.get('state_ids',False) and int(post.get('state_ids',False)),
                'zip':post.get('zip',False),
                'country_id':post.get('country_ids',False) and int(post.get('country_ids',False)),
                'phone':post.get('phone',False),
                'mobile':post.get('mobile',False),
                'email':post.get('email',False),
                'contact_phone1':post.get('phone_no',False),
                'contact_mobile1':post.get('mobile_no',False),
                'nric':post.get('nric',False),
                'maritual_status': post.get('marital_status',False),
                'hp_no':post.get('hp_no',False),
                'occupation': post.get('occupation',False),
                'income': '' if post.get('income',False) == 'select_income' else post.get('income',False) ,
                'citizenship': post.get('citizenship',False),
                'remark': post.get('qualification_remark',False),
                'mother_tongue': post.get('mother_tongue_ids',False) and int(post.get('mother_tongue_ids',False)),
                }
        if student_id:
            student_id.sudo().write(vals)
        return request.redirect("/student/portal/profile")


import os
from django.template import Library, Node, TemplateSyntaxError
from google.appengine.ext import webapp
import logging

register = webapp.template.create_template_register()

def PageTree(pages, currentPage):
    return  { 'pageTree' : pages, 'currentPage': currentPage }

path = os.path.join(os.path.dirname(__file__), '../templates/edit/pageTree.html')
register.inclusion_tag(path)(PageTree)

def SitePageTree(pages, currentPage):
    return  { 'pageTree' : pages, 'currentPage': currentPage }

path = os.path.join(os.path.dirname(__file__), '../templates/pages/modules/sitePageTree.html')
register.inclusion_tag(path)(SitePageTree)

def Module(module, language):
    data = ''
    if module['data'].has_key(language):
        data = module['data'][language]
    return  { 'module' : module, 'data' : data, 'language' : language }

path = os.path.join(os.path.dirname(__file__), '../templates/edit/modules/module.html')
register.inclusion_tag(path)(Module)

def ifIn(value, list):
    if value in list:
        return True
    else:
        return False

register.filter('ifIn', ifIn)


# -*- coding: utf-8 -*-
"""
Created on Mon Oct 14 14:41:53 2019

@author: amanoels
"""

from __future__ import absolute_import, division, print_function, unicode_literals
# TensorFlow e tf.keras
import tensorflow as tf
from tensorflow import keras

# Librarie sauxiliares
import numpy as np
import matplotlib.pyplot as plt

print(tf.__version__)

# Baixando pacote fashion_mnist
fashion_mnist = keras.datasets.fashion_mnist

# Carregando dados para treinamento e testes
(train_images, train_labels), (test_images, test_labels) = fashion_mnist.load_data()

"""
Label 	Classe
0 	    Camisetas/Top (T-shirt/top)
1 	    Calça (Trouser)
2 	    Suéter (Pullover)
3 	    Vestidos (Dress)
4 	    Casaco (Coat)
5 	    Sandálias (Sandal)
6 	    Camisas (Shirt)
7 	    Tênis (Sneaker)
8 	    Bolsa (Bag)
9 	    Botas (Ankle boot) """

# A base de dados não traz os labels, sendo assim estão sendo armazenados aqui
class_names = ['T-shirt/top', 'Trouser', 'Pullover', 'Dress', 'Coat',
               'Sandal', 'Shirt', 'Sneaker', 'Bag', 'Ankle boot']

# Shape para determinar o dimensionamento
train_images.shape

# Labels com um conjunto de treinamento
len(train_labels)

# Cada label é um inteiro entre 0 e 9
train_labels

# Existem 10000 imagens no cojunto de teste
test_images.shape

# labels no conjunto de teste
len(test_labels)

# Os dados precisam ser pré-processados antes de treinar a rede. Verificando a primeira
# imagem percebemos que os pixels estão entre 0 e 255.
plt.figure()
plt.imshow(train_images[0])
plt.colorbar()
plt.grid(False)
plt.show()

# Estes valores precisam ser escalados no intervalor entre 0 e 1 antes de alimentar
# o modelo da rede neural para tal os valores devem ser divididos por 255.
train_images = train_images / 255.0
test_images = test_images / 255.0

# Para garantir que os dados estão no formato correto e prontos para construir e treinar
# a rede, apresento as 25 primeiras imagens.
plt.figure(figsize=(10,10))
for i in range(25):
    plt.subplot(5,5,i+1)
    plt.xticks([])
    plt.yticks([])
    plt.grid(False)
    plt.imshow(train_images[i], cmap=plt.cm.binary)
    plt.xlabel(class_names[train_labels[i]])
plt.show()

# As figuras estão sendo apresentadas e montadas corretamente, desta forma começo a construção
# do modelo

# Duas etapas principas
# 1 Montar as camadas
# 2 Compilar as camadas

# Modelagem
model = keras.Sequential([
        keras.layers.Flatten(input_shape=(28,28)),
        keras.layers.Dense(128, activation='relu'),
        keras.layers.Dense(10, activation='softmax')
])

# Compilação ( Função loss mede o erro, o otimizador aponta para o caminho correto,
# baseado nos resultados de loss e a métrica de medição é a acuracia.
model.compile(optimizer='adam',
              loss='sparse_categorical_crossentropy',
              metrics=['accuracy'])

# Treinando o modelo
model.fit(train_images, train_labels, epochs=50)

# Avaliação do modelo e sua acuracia.
test_loss, test_acc = model.evaluate(test_images,  test_labels, verbose=2)

print('\nTest accuracy:', test_acc)
# A acuracio não esta boa ainda, precisa ser ajustado, pois o modelo esta com overfiting

# Prevendo classificação
predictions = model.predict(test_images)

# Primeira posiçao da previsão, é um array de 10 posições
predictions[0]

# Buscando a maior confiana exitente neste array
np.argmax(predictions[0])
# Desta forma o modelo esta confiante de que esta imagem é uma "Ankle boot".

# Para validar que a classe é mesmo esta, vou checar a massa de testes
train_labels[0]

# Função de preparação das imagens
def plot_image(i, predictions_array, true_label, img):
  predictions_array, true_label, img = predictions_array[i], true_label[i], img[i]
  plt.grid(False)
  plt.xticks([])
  plt.yticks([])

  plt.imshow(img, cmap=plt.cm.binary)

  predicted_label = np.argmax(predictions_array)
  if predicted_label == true_label:
    color = 'blue'
  else:
    color = 'red'

  plt.xlabel("{} {:2.0f}% ({})".format(class_names[predicted_label],
                                100*np.max(predictions_array),
                                class_names[true_label]),
                                color=color)

def plot_value_array(i, predictions_array, true_label):
  predictions_array, true_label = predictions_array[i], true_label[i]
  plt.grid(False)
  plt.xticks([])
  plt.yticks([])
  thisplot = plt.bar(range(10), predictions_array, color="#777777")
  plt.ylim([0, 1])
  predicted_label = np.argmax(predictions_array)

  thisplot[predicted_label].set_color('red')
  thisplot[true_label].set_color('blue')

# Apresentação de informação
i = 0
plt.figure(figsize=(6,3))
plt.subplot(1,2,1)
plot_image(i, predictions, test_labels, test_images)
plt.subplot(1,2,2)
plot_value_array(i, predictions,  test_labels)
plt.show()

# Plotando a primeira previsão
num_rows = 5
num_cols = 3
num_images = num_rows*num_cols
plt.figure(figsize=(2*2*num_cols, 2*num_rows))
for i in range(num_images):
  plt.subplot(num_rows, 2*num_cols, 2*i+1)
  plot_image(i, predictions, test_labels, test_images)
  plt.subplot(num_rows, 2*num_cols, 2*i+2)
  plot_value_array(i, predictions, test_labels)
plt.show()

# Previsão para uma unica imagem
img = test_images[0]
print(img.shape)


def ivtk_scene(actors):
	from tvtk.tools import ivtk
	#创建一个带Crust (Python Shell)的窗口
	win = ivtk.IVTKWithCrustAndBrowser()
	win.open()
	win.scene.add_actor(actors)

	#修正错误
	dialog = win.control.centralWidget().widget(0).widget(0)
	from pyface.qt import QtCore
	dialog.setWindowFlags(QtCore.Qt.WindowFlags(0x00000000))
	dialog.show()
	return win

def event_loop():
	#开始界面消息循环
	from pyface.api import GUI
	gui = GUI()
	gui.start_event_loop()


#!/usr/bin/env python3
import socket
import logging
import sys
logging.basicConfig(format='%(levelname)s:%(message)s', stream=sys.stderr, level=logging.DEBUG)

HOST = "www.google.com"
PORT = 80
BUFFER_SIZE = 1024

# payload = """GET / HTTP/1.0
# Host: {HOST}
# """.format(HOST=HOST)
payload = "GET / HTTP/1.0\r\n\r\n"

def conn_socket(addr_tup):
    (family, socktype, proto, canonname, sockaddr) = addr_tup
    print(proto)
    try:
        s = socket.socket(family, socktype, proto)
        s.connect(sockaddr)
        s.sendall(payload.encode())
        #s.sendall(payload)

        full_data = b""
        while True:
            data = s.recv(BUFFER_SIZE)
            #print(data)
            if not data:
                break
            full_data += data

        #print(full_data)
    except Exception as e:
        print(e)
        pass
    finally:
        s.close()

def main():
    addr_info = socket.getaddrinfo(HOST, PORT, proto=socket.SOL_TCP)
    addr_tup = addr_info[0]
    logging.debug('addr_tup = {}'.format(addr_tup))

    conn_socket(addr_tup)

if __name__ == "__main__":
    main()


# initialize the scoring logic by loading the model
def init():
    import numpy
    import scipy
    from sklearn.linear_model import LogisticRegression

    global model
    import pickle
    # load model file
    f = open('model.pkl', 'rb')
    # deserialize it into a scikit-learn model
    model = pickle.load(f)
    f.close()

def run(inputString):
    import json
    import numpy
    try:
        input_list = json.loads(inputString)
    except ValueError:
        return "bad input: expecting a JSON encoded list of lists."
    input_array = numpy.array(input_list)
    if (input_array.shape != (1, 4)):
        return 'bad input: expecting a JSON encoded list of lists of shape (1,4).'

    # make prediction
    score = model.predict(input_array)[0]
    return str(score)

if __name__ == '__main__':
    import json
    init()
    print (run(json.dumps([[1,2,3,4]])))


import pandas as pd
import numpy as np
from tensorflow.keras.layers import SimpleRNN, Dense, Dropout, LSTM, Input
from tensorflow.keras.models import Sequential, Model
import matplotlib.pyplot as plt
from sklearn.preprocessing import MinMaxScaler

def create_window(data, window_size, features):
    window_data = np.array([])
    for i in range(data.shape[0] - window_size):
        window_data = np.append(window_data, data[i:i + window_size, :])
    window_data = window_data.reshape(-1, window_size, features)
    return window_data

window_size = 7
train = pd.read_csv('data/HYMTF.csv', sep=',')

x_data = train[['Close', 'Volume', 'Adj Close']].to_numpy()

scaler = MinMaxScaler()
x_scaled = scaler.fit(x_data)
x_data = x_scaled.fit_transform(x_data)

x_data = create_window(x_data, window_size, features=3)

train_target = train.shift(-window_size)
y_data = train_target['Close'][:-window_size].values.reshape(-1, 1)
y_scaled = scaler.fit(y_data)
y_data = y_scaled.fit_transform(y_data)
'''
return_sequences=True : ,x.shape==y.shape
return_sequences=False : x.shape=3,y.shape=2
'''
inputs = Input(batch_shape=(1, x_data.shape[1], x_data.shape[2]))
lstm = LSTM(6, return_sequences=True, stateful=True)(inputs)
lstm = LSTM(12, stateful=True)(lstm)
outputs = Dense(1, activation='sigmoid')(lstm)
model = Model(inputs=inputs, outputs=outputs)

model.compile(loss='mse', optimizer='rmsprop', metrics=['acc'])
model.fit(x_data, y_data, epochs=5)

y_data = y_scaled.inverse_transform(y_data)
predict = model.predict(x_data, verbose=1)
predict = y_scaled.inverse_transform(predict)

plt.plot(y_data[:500, :], color='B')
plt.plot(predict[:500, :], color='R')


from segmentation_models_pytorch.base.model import Model
from segmentation_models_pytorch.encoders import get_encoder

import torch.nn as nn
import torch
import torch.nn.functional as F
from segmentation.effnet_decoder import EfficientNetEncoder
# from segmentation.oc_unet_decoder import OCUnetDecoder
from segmentation.unet_decoder import UnetDecoder

class EncoderDecoder(Model):

    def __init__(self, encoder, decoder, activation):
        super().__init__()
        self.encoder = encoder
        self.decoder = decoder

        if callable(activation):
            self.activation = activation
        elif activation == 'softmax':
            self.activation = nn.Softmax(dim=1)
        elif activation == 'sigmoid':
            self.activation = nn.Sigmoid()
        else:
            raise ValueError('Activation should be "sigmoid" or "softmax"')

    def forward(self, x):
        x = self.encoder(x)
        x = self.decoder(x)
        return x

    def predict(self, x):
        if self.training:
            self.eval()

        with torch.no_grad():
            x = self.forward(x)
            x = self.activation(x)

        return x

class UnetWithClassifier(EncoderDecoder):
    """Unet_ is a fully convolution neural network for image semantic segmentation

    Args:
        encoder_name: name of classification model (without last dense layers) used as feature
            extractor to build segmentation model.
        encoder_weights: one of ``None`` (random initialization), ``imagenet`` (pre-training on ImageNet).
        decoder_channels: list of numbers of ``Conv2D`` layer filters in decoder blocks
        decoder_use_batchnorm: if ``True``, ``BatchNormalisation`` layer between ``Conv2D`` and ``Activation`` layers
            is used.
        classes: a number of classes for output (output shape - ``(batch, classes, h, w)``).
        activation: one of [``sigmoid``, ``softmax``, None]
        center: if ``True`` add ``Conv2dReLU`` block on encoder head (useful for VGG models)

    Returns:
        ``torch.nn.Module``: **Unet**

    .. _Unet:
        https://arxiv.org/pdf/1505.04597

    """

    def __init__(
            self,
            encoder_name='resnet34',
            encoder_weights='imagenet',
            decoder_use_batchnorm=True,
            decoder_channels=(256, 128, 64, 32, 16),
            classes=1,
            activation='sigmoid',
            center=False,  # usefull for VGG models
            use_oc_module=False,
    ):
        if 'efficientnet' in encoder_name:
            encoder = EfficientNetEncoder.from_pretrained(encoder_name)
        else:
            encoder = get_encoder(
                encoder_name,
                encoder_weights=encoder_weights
            )

        decoder = UnetDecoder(
            encoder_channels=encoder.out_shapes,
            decoder_channels=decoder_channels,
            final_channels=classes,
            use_batchnorm=decoder_use_batchnorm,
            center=center,
        )

        super().__init__(encoder, decoder, activation)
        self.linear = torch.nn.Linear(encoder.out_shapes[0], classes)

        self.name = 'u-{}'.format(encoder_name)

    def forward(self, seg_features):
        x=seg_features
        x = self.encoder(x)

        pool_x = F.adaptive_avg_pool2d(x[0], (1, 1)).reshape(x[0].shape[0], -1)
        cls_pred = self.linear(pool_x)

        x = self.decoder(x)
        return cls_pred, x

    def predict(self, seg_features):
        x=seg_features
        if self.training:
            self.eval()

        with torch.no_grad():
            cls_pred, x = self.forward(x)
            x = self.activation(x)

        return cls_pred, x

if __name__ == '__main__':
    ACTIVATION = 'sigmoid'
    model = UnetWithClassifier(encoder_name='efficientnet-b0', encoder_weights='imagenet', classes=4,
                               activation=ACTIVATION)
    # model = Unet(encoder_name='resnet18', encoder_weights='imagenet', classes=1, activation=ACTIVATION)
    model(torch.zeros(1, 3, 128, 128))


import json
import re
from os import path
from subprocess import Popen, PIPE

import powerconsul.common.logger as logger

class Check_Base(object):
    """
    Base class for a checked resource.
    """
    def __init__(self, resource):
        self.resource       = resource
        self.name           = None

        # Process/regex string filter to indicate all is well
        self.procStr        = POWERCONSUL.ARGS.get('procstr')
        self.procRe         = POWERCONSUL.ARGS.get('procre')

        # Noop file
        self.noopFile       = POWERCONSUL.ARGS.get('noopfile')

        # Parse the Consul service name and bootstrap cluster status
        POWERCONSUL.service = POWERCONSUL.ARGS.get('consulservice', required='Must supply a Consul servicename: powerconsul check <resource> -S <serviceName>')

        # Setup the logger
        POWERCONSUL.LOG = logger.create('check', service=POWERCONSUL.service, log_file='/var/log/powerconsul/check/{0}.{1}.log'.format(self.resource, POWERCONSUL.service))
        POWERCONSUL.LOG.info('=' * 20)

        # Bootstrap the cluster
        POWERCONSUL.CLUSTER.bootstrap()

    def checkNoop(self):
        """
        Look for the existence of a noop file, to indicate all checks should pass.
        """
        if self.noopFile and path.isfile(self.noopFile):
            POWERCONSUL.LOG.info('Noop file discovered [{0}], setting checks to passing state'.format(self.noopFile))
            return True
        return False

    def unlockClusterData(self):
        """
        Unlock cluster data if active nodes are healthy.
        """
        data = POWERCONSUL.CLUSTER.data.getAll()

        # Need to unlock
        if 'lock' in data:
            POWERCONSUL.putKV('{0}/{1}'.format(POWERCONSUL.CONFIG.get('local', 'clusterKey'), POWERCONSUL.service), {
                'active_nodes': data['active_nodes'],
                'standby_nodes': data['standby_nodes']
            }, all_dcs=True)
            POWERCONSUL.LOG.info('Unlocked cluster data...', method='unlockClusterData')

    def setPrimary(cls):
        """
        Swap the secondary servers to primary in cluster KV data in the event
        of a primary failure.
        """
        data = POWERCONSUL.CLUSTER.data.getAll()

        # Cluster data is locked
        if 'lock' in data and data['lock']:
            return POWERCONSUL.LOG.info('Cluster data is locked, not updating primary...', method='setPrimary')

        # If not updating cluster KV or not clustered at all
        if not POWERCONSUL.CLUSTER.updatekv or not POWERCONSUL.CLUSTER.hasStandby:
            return

        # Cluster key / new cluster data
        clusterKey = POWERCONSUL.CONFIG.get('local', 'clusterKey')
        newData    = { 'filter': {} }

        # Filter applied
        if 'filter' in data:
            for key, values in data['filter'].iteritems():

                # Group by nodes
                if 'active_nodes' in values:
                    newData['filter'][key] = {
                        'active_nodes': values['standby_nodes'],
                        'standby_nodes': values['active_nodes']
                    }

                # Group by datacenter
                if 'active_datacenter' in values:
                    newData['filter'][key] = {
                        'active_datacenter': values['standby_datacenter'],
                        'standby_datacenter': values['active_datacenter']
                    }

        # Statically defined primary/secondary nodes
        else:

            # Group by nodes
            if 'active_nodes' in data:
                newData = {
                    'active_nodes': data['standby_nodes'],
                    'standby_nodes': data['active_nodes']
                }

            # Group by datacenter
            if 'active_datacenter' in data:
                newData = {
                    'active_datacenter': data['standby_datacenter'],
                    'standby_datacenter': data['active_datacenter']
                }

        # Put the new cluster data
        POWERCONSUL.putKV('{0}/{1}'.format(clusterKey, POWERCONSUL.service), newData, all_dcs=True)

    def checkPS(self):
        """
        Look for a user supplied string in the process table. If found, assume the check should pass.
        """
        if self.procStr or self.procRe:
            pstab = Popen(['ps', 'aux'], stdout=PIPE)
            out   = pstab.communicate()

            # Process regex
            regex = None if not self.procRe else re.compile(self.procRe)

            # Look for the process string in the process table
            for line in out[0].split('\n'):

                # Ignore powerconsul process table entries
                if 'powerconsul' in line:
                    continue

                # Process string
                if (self.procStr) and (self.procStr in line):
                    POWERCONSUL.LOG.info('Discovered process filter string: [{0}], set state -> passing'.format(self.procStr), method='checkPS')
                    return True

                # Process regular expressions
                if (regex) and (regex.match(line)):
                    POWERCONSUL.LOG.info('Discovered process filter regex: [{0}], set state -> passing'.format(self.procRe), method='checkPS')
                    return True
        return False

    def setDNS(self, state):
        """
        Disable/enable this service in a DNS prepared query via tags.
        """
        try:
            serviceObj   = POWERCONSUL.API.agent.services()[POWERCONSUL.service]
            applyChanges = False

            # Enable DNS
            if state:
                if 'nodns' in serviceObj['Tags']:
                    applyChanges = True
                    serviceObj['Tags'].remove('nodns')

            # Disable DNS
            else:
                if not 'nodns' in serviceObj['Tags']:
                    applyChanges = True
                    serviceObj['Tags'].append('nodns')

            # Re-register the service
            if applyChanges:
                POWERCONSUL.LOG.info('enabled={0}'.format(('no' if ('nodns' in serviceObj['Tags']) else 'yes')), method='setDNS')

                # Make the API request
                POWERCONSUL.API.agent.service.register(POWERCONSUL.service,
                    service_id = serviceObj['ID'],
                    address    = serviceObj['Address'],
                    port       = serviceObj['Port'],
                    tags       = serviceObj['Tags'],
                    check      = json.loads(open('/etc/consul/service_{0}.json'.format(POWERCONSUL.service)).read())['service']['checks'][0]
                )

        # Failed to update DNS tag
        except Exception as e:
            POWERCONSUL.LOG.error('Failed to update DNS tag: {0}'.format(str(e)), method='setDNS')

    def byDatacenter(self):
        """
        Ensure a clustered resource state by datacenter.
        """
        if not POWERCONSUL.CLUSTER.datacenters.enabled:
            return None

        # Log the service check
        POWERCONSUL.LOG.info('active=[{0}], standby=[{1}], local={2}'.format(
            POWERCONSUL.CLUSTER.datacenters.active, POWERCONSUL.CLUSTER.datacenters.standby, POWERCONSUL.CLUSTER.datacenters.local
        ), method='ensure.byDatacenter')

        # Node is active
        if POWERCONSUL.CLUSTER.datacenters.local == POWERCONSUL.CLUSTER.datacenters.active:
            self.ensure(service, clustered=True)

        # Node is standby
        if POWERCONSUL.CLUSTER.datacenters.local == POWERCONSUL.CLUSTER.datacenters.standby:

            # Active nodes healthy/passing
            if POWERCONSUL.CLUSTER.activePassing(datacenters=[POWERCONSUL.CLUSTER.datacenters.active]):
                self.ensure(expects=False, clustered=True, active=False)

            # Active nodes critical
            self.setPrimary()
            self.ensure(expects=True, clustered=True, active=False)

    def byNodes(self):
        """
        Ensure a clustered resource state by nodes.
        """
        if not POWERCONSUL.CLUSTER.nodes.enabled:
            return None

        # Log the service check
        POWERCONSUL.LOG.info('active=[{0}], standby=[{1}], local={2}'.format(
            ','.join(POWERCONSUL.CLUSTER.nodes.active), ','.join(POWERCONSUL.CLUSTER.nodes.standby), POWERCONSUL.HOST
        ), method='ensure.byNodes')

        # Node is active
        if POWERCONSUL.CLUSTER.nodes.local in POWERCONSUL.CLUSTER.nodes.active:
            self.ensure(clustered=True)

        # Node is standby
        if POWERCONSUL.CLUSTER.nodes.local in POWERCONSUL.CLUSTER.nodes.standby:

            # Active nodes healthy/passing
            if POWERCONSUL.CLUSTER.activePassing(nodes=POWERCONSUL.CLUSTER.nodes.active):
                self.unlockClusterData()
                self.ensure(expects=False, clustered=True, active=False)

            # Active nodes critical
            self.setPrimary()
            self.ensure(expects=True, clustered=True, active=False)


'''
Created on 07 of September 2019
@author: Dennis
'''
from odoo import api, fields, models, tools, SUPERUSER_ID, _
from datetime import date, datetime, timedelta
from odoo.exceptions import UserError, ValidationError
import pandas as pd
import io
import base64
from odoo.osv import expression
from odoo.tools.safe_eval import safe_eval
import decimal
import logging
_logger = logging.getLogger("_name_")

def workbook_table_label(workbook):
    table_label = workbook.add_format()
    table_label.set_font_color('black')
    table_label.set_font_name('Arial')
    table_label.set_font_size(11)
    return table_label

def workbook_table_label_data(workbook):
    label_data = workbook.add_format()
    label_data.set_bold(True)
    label_data.set_font_color('black')
    label_data.set_font_name('Arial')
    label_data.set_font_size(12)
    label_data.set_center_across()
    label_data.set_align('left')
    return label_data

def workbook_table_header(workbook):
    table_header = workbook.add_format()
    table_header.set_bold(True)
    table_header.set_font_color('black')
    table_header.set_font_name('Arial')
    table_header.set_font_size(12)
    table_header.set_bg_color('#b5e9ff')
    table_header.set_center_across()
    table_header.set_align('vcenter')
    return table_header

def workbook_table_row_index(workbook):
    table_row = workbook.add_format()
    table_row.set_bold(True)
    table_row.set_font_color('black')
    table_row.set_font_name('Arial')
    table_row.set_font_size(11)
    table_row.set_bg_color('#cceeff')
    return table_row

def workbook_table_row(workbook):
    table_row = workbook.add_format()
    # table_row.set_bold(True)
    table_row.set_font_color('black')
    table_row.set_font_name('Arial')
    table_row.set_font_size(11)
    table_row.set_bg_color('#cceeff')
    table_row.set_num_format('#,##0.00_);(#,##0.00)')
    return table_row

def workbook_table_row_total(workbook):
    table_row = workbook.add_format()
    table_row.set_bold(True)
    table_row.set_font_color('black')
    table_row.set_font_name('Arial')
    table_row.set_font_size(11)
    table_row.set_bg_color('#cceeff')
    table_row.set_num_format('[$₱-3409]#,##0.00;[RED](-[$₱-3409]#,##0.00)')
    table_row.set_top(2)
    return table_row

class HRMSPayrollRegister(models.AbstractModel):
    _name = 'report.hrms_payroll.payroll_register'
    _inherit = 'report.report_xlsx.abstract'

    # @api.multi
    # def get_data(self, obj_data):
    #     payslip_data = []
    #     batch_ids = [i.id for i in obj_data.payslip_multi_batch_ids]
    #     # obj_data.payslip_multi_batch_ids.ids
    #     rec_domain = expression.AND([safe_eval(obj_data.domain)]) + [('slip_id.payslip_run_id', 'in', batch_ids)]
    #     for slip in self.env['hr.payslip.line'].search(rec_domain):
    #         payslip_data.append({
    #             'payslip': slip.slip_id,
    #             'employee': slip.slip_id.employee_id,
    #             'employee_name': slip.slip_id.employee_id.name,
    #             'employee_department': slip.slip_id.employee_id.department_id.name,
    #             'rule_category_name': slip.category_id.name,
    #             'salary_rule': slip.salary_rule_id,
    #             'salary_rule_name': slip.salary_rule_id.name,
    #             'salary_rule_code': slip.salary_rule_id.code,
    #             'salary_rule_sequence': slip.salary_rule_id.sequence,
    #             'amount': decimal.Decimal(format(slip.total, '.2f')),
    #         })
    #     return payslip_data

    @api.multi
    def get_data(self, obj_data):
        data = []
        if obj_data.batch_type == 'multi':
            rec_domain = [('slip_id.payslip_run_id', 'in', obj_data.payslip_multi_batch_ids.ids)]
        else:
            rec_domain = [('slip_id.payslip_run_id', '=', obj_data.payslip_batch_id.id)]
        if obj_data.employee_ids.ids:
            rec_domain += [('slip_id.employee_id', 'in', obj_data.employee_ids.ids)]
        rec_domain += expression.AND([safe_eval(obj_data.domain)])
        for slip in obj_data.env['hr.payslip.line'].search(rec_domain):
            if slip.total != 0:
                data.append({
                    'payslip': slip.slip_id,
                    'employee': slip.slip_id.employee_id,
                    'employee_name': slip.slip_id.employee_id.name,
                    'employee_department': slip.slip_id.employee_id.department_id.name,
                    'rule_category_name': slip.category_id.name,
                    'salary_rule': slip.salary_rule_id,
                    'salary_rule_name': slip.salary_rule_id.name,
                    'salary_rule_code': slip.salary_rule_id.code,
                    'salary_rule_sequence': slip.salary_rule_id.sequence,
                    'amount': slip.total,
                })
        # if not data:
        #     raise ValidationError(_('No valid data that matches your search criteria'))
        return data

    def generate_xlsx_report(self, workbook, data, line):
        table_label = workbook_table_label(workbook)
        table_label_data = workbook_table_label_data(workbook)
        table_label_data_datetime = table_label_data
        table_label_data_datetime.set_num_format('dd/mm/yyyy hh:mm AM/PM')
        table_header = workbook_table_header(workbook)
        table_row_index = workbook_table_row_index(workbook)
        table_row = workbook_table_row(workbook)
        table_row_total = workbook_table_row_total(workbook)
        for obj in line:
            payslip_data = self.get_data(line)
            # if not payslip_data:  raise ValidationError(_("Payslip is Empty"))
            payslip_register = workbook.add_worksheet("Payslip Register")
            payslip_register.set_landscape()
            payslip_register.set_paper(14)
            payslip_register.set_column('A:A', 20)
            payslip_register.set_column('B:ZZ', 12)
            payslip_register.write(0, 0, "Company", table_label)
            payslip_register.merge_range(0, 1, 0, 3, obj.company_id.name, table_label_data)
            if obj.batch_type == 'single':
                payslip_register.write(1, 0, "Payroll Batch", table_label)
                payslip_register.merge_range(1, 1, 1, 3, obj.payslip_batch_id.name, table_label_data)
                payslip_register.write(2, 0, "Cutoff", table_label)
                payslip_register.merge_range(2, 1, 2, 3, "%s - %s"%(obj.payslip_batch_id.date_start, obj.payslip_batch_id.date_end), table_label_data)
            else:
                payslip_register.write(1, 0, "Payroll Batches", table_label)
                batch_name = [i.name for i in obj.payslip_multi_batch_ids]
                payslip_register.merge_range(1, 1, 1, 3, str(batch_name), table_label_data)
                payslip_register.write(2, 0, "Cutoff", table_label)
                cutoff = ["%s - %s"%(i.date_start, i.date_end) for i in obj.payslip_multi_batch_ids]
                payslip_register.merge_range(2, 1, 2, 3, str(cutoff), table_label_data)
            payslip_register.write(1, 4, "Run By", table_label)
            payslip_register.merge_range(1, 5, 1, 7, obj.create_uid.name, table_label_data)
            payslip_register.write(2, 4, "Run Date", table_label)
            payslip_register.merge_range(2, 5, 2, 7, datetime.now()+timedelta(hours=8), table_label_data_datetime)
            df = pd.DataFrame(payslip_data).sort_values(by=['salary_rule_sequence'])

            # EMPLOYEE PAYROLL
            crosstab_df = pd.crosstab(index=[df.employee_department,df.employee_name], columns=[df.salary_rule_sequence, df.salary_rule_code, df.rule_category_name], values=df.amount, aggfunc='sum', margins=True).reset_index()
            header_cols = 0
            crosstab_df.drop(crosstab_df.columns[len(crosstab_df.columns)-1], axis=1, inplace=True)
            category = ''
            col_start = ''
            for i in crosstab_df:
                if i[0] != 'employee_department':
                    if category and category == i[2]:
                        payslip_register.merge_range(5, col_start, 5,header_cols, i[0] == 'employee_name' and "Employee" or i[2], table_header)
                    else:
                        category = i[2]
                        col_start = header_cols
                        if i[0] == 'employee_name': payslip_register.merge_range(5, header_cols, 6,header_cols, "Employee", table_header)
                        else: payslip_register.write(5, header_cols, i[2], table_header)
                    header_cols += 1
            header_cols = 0
            for i in crosstab_df:
                if i[0] != 'employee_department':
                    payslip_register.write(6, header_cols, i[1] == 'employee_name' and "Employee" or i[1], table_header)
                    header_cols += 1
            payslip_register.merge_range(4, 0, 4, header_cols, "EMPLOYEE PAYROLL", table_label_data)
            rules = crosstab_df.values.tolist()
            data_rows = 7
            for rec in rules:
                data_cols = 0
                del rec[0]
                if not rec[0]:
                    for line in rec:
                        try:
                            payslip_register.write(data_rows, data_cols, line, data_cols == 0 and table_row_index or table_row_total)
                        except:
                            payslip_register.write(data_rows, data_cols, 0.00, data_cols == 0 and table_row_index or table_row_total)
                        data_cols += 1
                else:
                    for line in rec:
                        try:
                            payslip_register.write(data_rows, data_cols, line, data_cols == 0 and table_row_index or table_row)
                        except:
                            payslip_register.write(data_rows, data_cols, 0.00, data_cols == 0 and table_row_index or table_row)
                        data_cols += 1
                data_rows += 1

            # DEPARTMENT PAYROLL SUMMARY
            data_rows += 1
            payslip_register.merge_range(data_rows, 0, data_rows, header_cols, "DEPARTMENT PAYROLL SUMMARY", table_label_data)
            crosstab_summary_df = pd.crosstab(index=[df.employee_department], columns=[df.salary_rule_sequence, df.salary_rule_code, df.rule_category_name], values=df.amount, aggfunc='sum', margins=True).reset_index()
            header_cols = 0
            data_rows += 1
            crosstab_summary_df.drop(crosstab_summary_df.columns[len(crosstab_summary_df.columns)-1], axis=1, inplace=True)
            category = ''
            col_start = ''
            for i in crosstab_summary_df:
                if category and category == i[2]:
                    payslip_register.merge_range(data_rows, col_start, data_rows,header_cols, i[0] == 'employee_department' and "DEPARTMENT" or i[2], table_header)
                else:
                    category = i[2]
                    col_start = header_cols
                    if i[0] == 'employee_name': payslip_register.merge_range(data_rows, header_cols, data_rows + 1,header_cols, "Employee", table_header)
                    else: payslip_register.write(data_rows, header_cols, i[2], table_header)
                header_cols += 1
            header_cols = 0
            data_rows += 1
            for i in crosstab_summary_df:
                    payslip_register.write(data_rows, header_cols, i[0] == 'employee_department' and "DEPARTMENT" or i[1], table_header)
                    header_cols += 1

            rules = crosstab_summary_df.values.tolist()
            data_rows += 1
            for rec in rules:
                data_cols = 0
                if rec[0] == "All":
                    rec[0] = ''
                    for line in rec:
                        try:
                            payslip_register.write(data_rows, data_cols, line, data_cols == 0 and table_row_index or table_row_total)
                        except:
                            payslip_register.write(data_rows, data_cols, 0.00, data_cols == 0 and table_row_index or table_row_total)
                        data_cols += 1
                else:
                    for line in rec:
                        # _logger.info('\n\n\nData: \ndata:\n%s'%(str(line)))
                        try:
                            payslip_register.write(data_rows, data_cols, line, data_cols == 0 and table_row_index or table_row)
                        except:
                            payslip_register.write(data_rows, data_cols, 0.00, data_cols == 0 and table_row_index or table_row)
                        data_cols += 1
                data_rows += 1

            # for im in payslip_data:
            #     # payslip_register.write(data_rows, 1, 0.00, data_cols == 0 and table_row_index or table_row)
            #     buf_image=io.BytesIO(base64.b64decode(im.get('employee').image))
            #     payslip_register.insert_image('B%s'%(data_rows), "any_name.png", {'image_data': buf_image})
            #     data_rows += 1


__author__ = 'Chi'

from time import time
from bin.headlinegeneration.utils.loginfor import loginformation
from gensim.models import word2vec
import re
import multiprocessing
import gensim
import os

def cleandata(rawdata):
    try:
        cleanr = re.compile('<.*>?>')
        cleantext = re.sub(cleanr, ' ', rawdata)
    except:
        pass
        #loginformation("", "debug", "Error occurs while cleaning data: " + rawdata)
        #loginformation("", "info", "Finished clean the data: " + rawdata)
    return cleantext

#生成迭代器，以防止数据太大，内存不够
class GetSentence(object):
    def __init__(self, dirname):
        self.dirname = dirname

    def __iter__(self):        #__iter__方法的对象是可迭代的。
        for file in os.listdir(self.dirname):
            filePath = self.dirname + '/' + file
            try:
                for line in open(filePath):
                    sline = line.strip()
                    if sline == "":
                        continue
                    rline = cleandata(sline)
                    yield rline.split(" ")
            except IOError:
                loginformation("", "info", "open file: " + self.dirname + '/' + file + " error ")
            else:
                loginformation("", "info", "finish the file: " + self.dirname + '/' + file)

def wordVectorTrainModel(trainDataPath, modelPath, vocabularyPath, word2VecOrgPath):
    begintime = time()
    sentences = GetSentence(trainDataPath)
    #对训练数据的参数配置
    model = gensim.models.Word2Vec(sentences,
                                   size = 100,
                                   window = 5,
                                   min_count = 1,
                                   workers = 4)
    loginformation("", "info", "The process is saving the model.")
    try:
        model.save(modelPath)
        model.wv.save_word2vec_format(word2VecOrgPath,
                                  vocabularyPath,
                                  binary=False)
    except:
        loginformation("", "info", "Error occurs while saving the word vector model!!")
    else:
        loginformation("", "info", "Finished the process of saving word vector model.")
    endtime = time()
    loginformation("", "info", "Total word vector training time is: " + (endtime - begintime))

#get the word vector of sentence after segment, requirement: space between word and word
def getSentenceVector(sentence, wordVectorModel, wordVectorModelDim):
    sentenceList = sentence.rstrip('\n').split("  ")
    sentenceWordVectorList = []
    for word in sentenceList:
        wordVector = []
        if(word != ' ' or word != ''):
            try:
                for i in range(wordVectorModelDim):
                    wordVector.append(str(wordVectorModel[word][i].strip))
            except KeyError:
                loginformation("", "debug", word + "not in the vocabulary !!!")
                for i in range(wordVectorModelDim):
                    wordVector.append("0.0")
                pass
            else:
                loginformation("", "info", "Get the vector of " + word)
        else:
            loginformation("", "info", "null word occrs")
        sentenceWordVectorList.append(wordVector)
    loginformation("", "info", "transfered sentence " + sentence + " to word vector.")
    return sentenceWordVectorList

if __name__ == "__main__":
    rootPath = os.path.abspath(".") + "/"
    trainDataPath = rootPath + "../../../../../Documents/weibocluster_segmentByPynlpir/"
    modelPath = rootPath + "../../../data/preprocess/word2vectormodel/dim100Window5Min1.model"
    vocabularyPath = rootPath + "../../../data/preprocess/wordVectorVocabulary/dim100Window5Min1Vocabulary"
    word2VecOrgPath = rootPath + "../../../data/preprocess/word2VecOrgPath/dim100Window5Min1Word2VecOrgPath"
    wordVectorTrainModel(trainDataPath, modelPath, vocabularyPath, word2VecOrgPath)