import torch
from data import MnistData
from networks import MnistModel, LSTM
from tqdm import tqdm
import pickle
import argparse
import numpy as np

def str2bool(v):
    if v.lower() in ('yes', 'true', 't', 'y', '1'):
        return True
    elif v.lower() in ('no', 'false', 'f', 'n', '0'):
        return False
    else:
        raise argparse.ArgumentTypeError('Boolean value expected.')

parser = argparse.ArgumentParser()

parser.add_argument('--cuda', type = str2bool, default = True, help = 'use gpu or not')
parser.add_argument('--epochs', type = int, default = 200)

parser.add_argument('--batch_size', type = int, default = 64)
parser.add_argument('--hidden_size', type = int, default = 100)
parser.add_argument('--input_size', type = int, default = 1)
parser.add_argument('--model', type = str, default = 'LSTM')
parser.add_argument('--train', type = str2bool, default = True)
parser.add_argument('--num_units', type = int, default = 6)
parser.add_argument('--rnn_cell', type = str, default = 'LSTM')
parser.add_argument('--key_size_input', type = int, default = 64)
parser.add_argument('--value_size_input', type = int, default =  400)
parser.add_argument('--query_size_input', type = int, default = 64)
parser.add_argument('--num_input_heads', type = int, default = 1)
parser.add_argument('--num_comm_heads', type = int, default = 4)
parser.add_argument('--input_dropout', type = float, default = 0.1)
parser.add_argument('--comm_dropout', type = float, default = 0.1)

parser.add_argument('--key_size_comm', type = int, default = 32)
parser.add_argument('--value_size_comm', type = int, default = 100)
parser.add_argument('--query_size_comm', type = int, default = 32)
parser.add_argument('--k', type = int, default = 4)

parser.add_argument('--size', type = int, default = 14)
parser.add_argument('--loadsaved', type = int, default = 0)
parser.add_argument('--log_dir', type = str, default = 'smnist_lstm_600')

args = vars(parser.parse_args())

log_dir = args['log_dir']
torch.manual_seed(10)
np.random.seed(10)
torch.cuda.manual_seed(10)

if args['model'] == 'LSTM':
	mode = LSTM
else:
	mode = MnistModel

def test_model(model, loader, func):

	accuracy = 0
	loss = 0
	model.eval()
	with torch.no_grad():
		for i in tqdm(range(loader.val_len())):
			test_x, test_y = func(i)
			test_x = model.to_device(test_x)
			test_y = model.to_device(test_y).long()

			probs  = model( test_x)

			preds = torch.argmax(probs, dim=1)
			correct = preds == test_y
			accuracy += correct.sum().item()

	accuracy /= 100.0
	return accuracy

def train_model(model, epochs, data):
	acc=[]
	lossstats=[]
	best_acc = 0.0
	ctr = 0

	test_acc = 0
	start_epoch=0
	ctr=0
	if args['loadsaved']==1:
		with open(log_dir+'/accstats.pickle','rb') as f:
			acc=pickle.load(f)
		with open(log_dir+'/lossstats.pickle','rb') as f:
			losslist=pickle.load(f)
		start_epoch=len(acc)-1
		best_acc=0
		for i in acc:
			if i[0]>best_acc:
				best_acc=i[0]
		ctr=len(losslist)-1
		saved = torch.load(log_dir + '/best_model.pt')
		model.load_state_dict(saved['net'])
	optimizer = torch.optim.Adam(model.parameters(), lr = 0.001)

	for epoch in range(start_epoch,epochs):

		print('epoch ' + str(epoch + 1))
		epoch_loss = 0.
		iter_ctr = 0.
		t_accuracy = 0
		norm = 0
		model.train()
		for i in tqdm(range(data.train_len())):
			iter_ctr+=1.
			inp_x, inp_y = data.train_get(i)
			inp_x = model.to_device(inp_x)
			inp_y = model.to_device(inp_y)

			output, l = model(inp_x, inp_y)

			optimizer.zero_grad()
			l.backward()
			optimizer.step()
			norm += model.grad_norm()
			epoch_loss += l.item()
			preds = torch.argmax(output, dim=1)

			correct = preds == inp_y.long()
			t_accuracy += correct.sum().item()

			ctr += 1

		v_accuracy1 = test_model(model, data, data.val_get1)
		v_accuracy2 = test_model(model, data, data.val_get2)
		v_accuracy3 = test_model(model, data, data.val_get3)

		print('best validation accuracy ' + str(best_acc))
		print('Saving best model..')
		state = {
	       'net': model.state_dict(),
	       'epoch':epoch,
	    'ctr':ctr,
	    'best_acc':best_acc
	    }
		with open(log_dir + '/best_model.pt', 'wb') as f:
			torch.save(state, f)
		print('epoch_loss: {}, val accuracy1: {}, val_accuracy2:{}, val_accuracy3:{}, train_acc: {}, grad_norm: {} '.format(epoch_loss/(iter_ctr), v_accuracy1, v_accuracy2, v_accuracy3, t_accuracy / 600, norm/iter_ctr))
		lossstats.append((ctr,epoch_loss/iter_ctr))
		acc.append((epoch,(v_accuracy1, v_accuracy2, v_accuracy3)))
		with open(log_dir+'/lossstats.pickle','wb') as f:
			pickle.dump(lossstats,f)
		with open(log_dir+'/accstats.pickle','wb') as f:
			pickle.dump(acc,f)

data = MnistData(args['batch_size'], (args['size'], args['size']), args['k'])
model = mode(args).cuda()

if args['train']:
	train_model(model, args['epochs'], data)
else:
	saved = torch.load(log_dir + '/best_model.pt')
	model.load_state_dict(saved['net'])
	v_acc = test_model(model, data)
	print('val_acc:'+str(v_acc))


"""File hodls function definitions for tf and idf computing."""
###################################################################
#                           Imports                               #
###################################################################
from math import log, sqrt
from collections import defaultdict

###################################################################
#                Global Variabls and Constants                    #
###################################################################

NUMBER_OF_FILES = 55393
TITLE_VALUE = 20
BOLD_VALUE = 5
HEADER_VALUE = 10

###################################################################
#                          Functions                              #
###################################################################

def calculateQueryNormalizedTfIdf(query_tokens: list[str], postings: list[list], nGramPostings: dict[tuple, list], frequencies: dict[str, int], nGrams: list[tuple[int, str, str]], nGramFrequencies: dict[tuple, int], token_idf_index) -> dict[str, int]:
    """Calculates normalized tf-idf for query tokens."""

    # Calculate tf-wt
    query_tf_wt = {}
    tokens = set(query_token for query_token in query_tokens if query_token in postings and postings[query_token])
    for token in tokens:
        query_tf_wt[token] = 1 + log(frequencies[token], 10)
    # Calcualte idf
    query_idf = {}
    for token in tokens:
        query_idf[token] = token_idf_index[token]

    # Only use top 20 idf's to search (for efficiency)
    if len(query_idf) > 20:
        for token, _ in sorted(query_idf.items(), key= lambda x: x[1], reverse=True)[10:]:
            query_idf.pop(token)

    # Claculate tf-idf
    query_weights = {}
    for token in query_idf.keys():
        query_weights[token] = query_tf_wt[token] * query_idf[token]

    # Normalize tf-idf
    query_normalized_scores = {}
    query_normalization_length = sqrt(sum([i**2 for i in query_weights.values()]))
    for token, weight in query_weights.items():
        query_normalized_scores[token] = weight/query_normalization_length

    # Calculate tf-wt for nGrams
    if nGrams:
        query_tf_wt = {}
        nGrams = [nGram for nGram, posting_list in nGramPostings.items() if posting_list]
        for nGram in nGrams:
            query_tf_wt[nGram] = 1 + log(nGramFrequencies[nGram], 10)

        # Calcualte idf for nGrams
        query_idf = {}
        for nGram in nGrams:
            query_idf[nGram] = log(NUMBER_OF_FILES/len(nGramPostings[nGram]), 10)

        # Claculate tf-idf for nGrams
        query_weights = {}
        for token in query_idf.keys():
            query_weights[token] = query_tf_wt[token] * query_idf[token]

        # Normalize tf-idf for nGrams
        query_nGram_normalized_scores = {}
        query_normalization_length = sqrt(sum([i**2 for i in query_weights.values()]))
        for token, weight in query_weights.items():
            query_nGram_normalized_scores[token] = weight/query_normalization_length
    else:
        query_nGram_normalized_scores = {}

    return query_normalized_scores, query_nGram_normalized_scores

def calculateDocumentNormalizedTfWt(postings: dict[str, list], nGramPostings: dict[tuple, list]) -> dict:
    """Calcualte normalized tf scores for each document."""
    document_term_scores = defaultdict(dict)
    for token, posting in postings.items():
        for docID, freq, _, title, bold, header in posting:
            # Calcualte tf-wt and add scores for if token was a title, bold, or header
            document_term_scores[docID][token] = 1 + log(freq, 10) + title * TITLE_VALUE + bold * BOLD_VALUE + header * HEADER_VALUE
        # Normalize Values
        document_term_scores[docID][token] = document_term_scores[docID][token]/sum(document_term_scores[docID].values())

    # Same but for N Grams
    for nGram, first_second_postings in nGramPostings.items():
        for posting in first_second_postings:
            for docID, freq, _, title, bold, header in posting:
                # Calcualte tf-wt and add scores for if nGram was a title, bold, or header
                document_term_scores[docID][nGram] = 1 + log(freq, 10) + title * TITLE_VALUE + bold * BOLD_VALUE + header * HEADER_VALUE
            # Normalize Values
            document_term_scores[docID][nGram] = document_term_scores[docID][nGram]/sum(document_term_scores[docID].values())
    return document_term_scores


from odoo import api, fields, models

from odoo.addons.ssi_decorator import ssi_decorator

class OutsourceWorkOutstandingBatch(models.Model):
    _name = "outsource_work_outstanding_batch"
    _inherit = [
        "mixin.transaction_confirm",
        "mixin.transaction_done",
        "mixin.transaction_cancel",
        "mixin.transaction_pricelist",
        "mixin.date_duration",
    ]
    _description = "Outsource Work Outstanding Batch"
    _approval_from_state = "draft"
    _approval_to_state = "done"
    _approval_state = "confirm"
    _after_approved_method = "action_done"

    # Mixin duration attribute
    _date_start_readonly = True
    _date_end_readonly = True
    _date_start_required = True
    _date_end_required = True
    _date_start_states_list = ["draft"]
    _date_start_states_readonly = ["draft"]
    _date_end_states_list = ["draft"]
    _date_end_states_readonly = ["draft"]

    # Attributes related to add element on view automatically
    _automatically_insert_view_element = True

    # Attributes related to add element on form view automatically
    _automatically_insert_multiple_approval_page = True

    _statusbar_visible_label = "open,draft,confirm,done"

    _policy_field_order = [
        "confirm_ok",
        "approve_ok",
        "reject_ok",
        "restart_approval_ok",
        "cancel_ok",
        "restart_ok",
        "done_ok",
        "manual_number_ok",
    ]
    _header_button_order = [
        "action_confirm",
        "action_approve_approval",
        "action_reject_approval",
        "action_done",
        "%(ssi_transaction_cancel_mixin.base_select_cancel_reason_action)d",
        "action_restart",
    ]

    # Attributes related to add element on search view automatically
    _state_filter_order = [
        "dom_draft",
        "dom_confirm",
        "dom_reject",
        "dom_done",
        "dom_cancel",
    ]

    _create_sequence_state = "done"

    pricelist_id = fields.Many2one(
        required=False,
    )
    type_id = fields.Many2one(
        string="Type",
        comodel_name="outsource_work_outstanding_type",
        required=True,
        ondelete="restrict",
        readonly=True,
        states={"draft": [("readonly", False)]},
    )
    date = fields.Date(
        string="Date",
        required=True,
        readonly=True,
        states={"draft": [("readonly", False)]},
    )
    date_due = fields.Date(
        string="Date Due",
        required=True,
        readonly=True,
        states={"draft": [("readonly", False)]},
    )
    detail_ids = fields.One2many(
        string="Outstanding Details",
        comodel_name="outsource_work_outstanding_batch_detail",
        inverse_name="batch_id",
        readonly=True,
        copy=True,
    )
    amount_untaxed = fields.Monetary(
        string="Untaxed",
        required=False,
        compute="_compute_total",
        store=True,
        currency_field="currency_id",
    )
    amount_tax = fields.Monetary(
        string="Tax",
        required=False,
        compute="_compute_total",
        store=True,
        currency_field="currency_id",
    )
    amount_total = fields.Monetary(
        string="Total",
        required=False,
        compute="_compute_total",
        store=True,
        currency_field="currency_id",
    )
    analytic_account_id = fields.Many2one(
        string="Analytic Account",
        comodel_name="account.analytic.account",
        readonly=True,
        states={
            "draft": [
                ("readonly", False),
            ],
        },
    )
    state = fields.Selection(
        string="State",
        selection=[
            ("draft", "Draft"),
            ("confirm", "Waiting for Approval"),
            ("done", "Done"),
            ("cancel", "Cancelled"),
        ],
        copy=False,
        default="draft",
        required=True,
        readonly=True,
    )

    @api.model
    def _get_policy_field(self):
        res = super(OutsourceWorkOutstandingBatch, self)._get_policy_field()
        policy_field = [
            "confirm_ok",
            "approve_ok",
            "done_ok",
            "cancel_ok",
            "reject_ok",
            "restart_ok",
            "restart_approval_ok",
            "manual_number_ok",
        ]
        res += policy_field
        return res

    @api.depends(
        "detail_ids",
        "detail_ids.outstanding_id",
        "detail_ids.outstanding_id.amount_untaxed",
        "detail_ids.outstanding_id.amount_tax",
        "detail_ids.outstanding_id.amount_total",
    )
    def _compute_total(self):
        for record in self:
            amount_untaxed = amount_tax = amount_total = 0.0
            for detail in record.detail_ids:
                amount_untaxed += detail.outstanding_id.amount_untaxed
                amount_tax += detail.outstanding_id.amount_tax
                amount_total += detail.outstanding_id.amount_total

            record.amount_untaxed = amount_untaxed
            record.amount_tax = amount_tax
            record.amount_total = amount_untaxed + amount_tax

    def action_populate(self):
        for record in self:
            record._populate()

    def action_clear(self):
        for record in self:
            record._unlink_detail()

    @ssi_decorator.post_confirm_action()
    def _post_confirm_action_10_confirm_outstanding(self):
        self.ensure_one()
        for detail in self.detail_ids:
            outstanding = detail.outstanding_id
            outstanding.action_populate()
            if outstanding.confirm_ok:
                outstanding.action_confirm()

    @ssi_decorator.post_approve_action()
    def _post_approve_action_10_approve_outstanding(self):
        self.ensure_one()
        for detail in self.detail_ids:
            outstanding = detail.outstanding_id
            if outstanding.approve_ok:
                outstanding.action_approve_approval()

    @ssi_decorator.post_reject_action()
    def _post_reject_action_10_reject_outstanding(self):
        self.ensure_one()
        for detail in self.detail_ids:
            outstanding = detail.outstanding_id
            if outstanding.reject_ok:
                outstanding.action_reject_approval()

    @ssi_decorator.post_restart_action()
    def _post_restart_action_10_restart_outstanding(self):
        self.ensure_one()
        for detail in self.detail_ids:
            outstanding = detail.outstanding_id
            if outstanding.restart_ok:
                outstanding.action_restart()

    @ssi_decorator.post_cancel_action()
    def _post_cancel_action_10_cancel_outstanding(self):
        self.ensure_one()
        for detail in self.detail_ids:
            outstanding = detail.outstanding_id
            if outstanding.cancel_ok:
                outstanding.action_cancel(self.cancel_reason_id)

    def _populate(self):
        self.ensure_one()
        Work = self.env["outsource_work"]
        Detail = self.env["outsource_work_outstanding_batch_detail"]
        self._unlink_detail()
        criteria = self._prepare_populate_domain()
        works = Work.search(criteria)
        partners = works.mapped("partner_id")
        for partner in partners:
            Detail.create(
                {
                    "batch_id": self.id,
                    "partner_id": partner.id,
                }
            )
        for detail in self.detail_ids:
            detail._create_outstanding()

    def _unlink_detail(self):
        self.ensure_one()
        for detail in self.detail_ids:
            detail.outstanding_id.unlink()
        self.detail_ids.unlink()

    def _prepare_populate_domain(self):
        self.ensure_one()
        result = [
            ("date", ">=", self.date_start),
            ("date", "<=", self.date_end),
            ("outstanding_id", "=", False),
            ("currency_id", "=", self.currency_id.id),
            ("state", "=", "done"),
        ]
        if self.analytic_account_id:
            result.append(("analytic_account_id", "=", self.analytic_account_id.id))
        return result


## -*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *

from Ui_ibmProveedores import *
from apoyo import *
import psycopg2,  psycopg2.extras

class ibmProveedores(QDialog, Ui_ibmProveedores):
    def __init__(self, cfg,  id_proveedores= None,  parent = None, name = None, modal = False):

        QDialog.__init__(self, parent)
        if name:
            self.setObjectName(name)
        self.setupUi(self)
        self.cfg=cfg
        self.reg=None
        self.id_proveedores=id_proveedores
        if self.id_proveedores!=None:
            self.lblTitulo.setText("Modificar proveedor")
            self.setWindowTitle("gnuOptics > Proveedores > Modificar")

            #consigue el registro de id_proveedores
            self.cfg.connect()
            cur = self.cfg.con.cursor()
            cur.execute("select * from proveedores where id_proveedores=%s", (id_proveedores, ))
            self.reg= cur.fetchone()
            cur.close()
            self.cfg.disconnect()
            self.txtProveedor.setText(s2q(self.reg['proveedor']))
            self.txtCIF.setText(s2q(self.reg['cif']))
            self.txtTelefono.setText(s2q(self.reg['telefono']))
            self.txtEmail.setText(s2q(self.reg['email']))
            self.txtDireccion.setText(s2q(self.reg['direccion']))
            self.txtCiudad.setText(s2q(self.reg['ciudad']))
            self.txtCodigoPostal.setText(s2q(self.reg['codigopostal']))
            self.txtPais.setText(s2q(self.reg['pais']))

    @pyqtSignature("")
    def on_cmdYN_accepted(self):

        if self.id_proveedores==None: #insertar
            self.cfg.connect()
            cur = self.cfg.con.cursor()
            cur.execute("insert into proveedores(proveedor, cif, telefono, email, direccion, ciudad, codigopostal, pais) values ( %s, %s, %s, %s, %s, %s, %s, %s)", (q2s(self.txtProveedor.text()), q2s(self.txtCIF.text()), q2s(self.txtTelefono.text()), q2s(self.txtEmail.text()), q2s(self.txtDireccion.text()), q2s(self.txtCiudad.text()), q2s(self.txtCodigoPostal.text()), q2s(self.txtPais.text())))
            self.cfg.con.commit()
            cur.close()
            self.cfg.disconnect()
            self.done(0)
        else: #modificar
            self.cfg.connect()
            cur = self.cfg.con.cursor()
            sql="update proveedores set proveedor=%s, cif=%s, telefono=%s, email=%s, direccion=%s, ciudad=%s, codigopostal=%s, pais=%s where id_proveedores=%s"
            data=(q2s(self.txtProveedor.text()), q2s(self.txtCIF.text()), q2s(self.txtTelefono.text()), q2s(self.txtEmail.text()), q2s(self.txtDireccion.text()), q2s(self.txtCiudad.text()), q2s(self.txtCodigoPostal.text()), q2s(self.txtPais.text()),  self.id_proveedores )
            cur.execute(sql, data )
            self.cfg.con.commit()
            cur.close()
            self.cfg.disconnect()
            self.done(0)

    @pyqtSignature("")
    def on_cmdYN_rejected(self):
        self.done(0)


#!/usr/bin/env python3
#
# An http server that conforms to:
# https://prometheus.io/docs/alerting/latest/configuration/#webhook_config
#
# Enables hume support for Prometheus' AlertManager
#
# Maybe include a nice AlertManager template...
# https://prometheus.io/blog/2016/03/03/custom-alertmanager-templates/
#
# Author: Buanzo

import argparse
from hume import Hume
import json
import time
import datetime
import webhook_listener
from pprint import pprint

__version__ = '0.1'
__version_str = 'Hume AlertManager Receiver v{} by Buanzo'.format(__version__)

def construct_hume(alert):
    labels = alert['labels']
    print('construct_hume')
    # OK, let's handle this
    # First, lets extract/construct level, msg, tags and task
    try:
        status = alert['status'].strip()
    except Exception:
        status = 'unknown_status'

    try:
        level = labels['severity']
    except Exception:
        level = 'warning'  # Sensible default? alpha software, people!

    try:
        #task = '{}[{}]'.format(labels['instance_name'], labels['ip'])
        task = labels['name']
    except Exception:
        if 'instance_name' in labels.keys():
            task = labels['instance_name']
        else:
            task = 'Alertmanager'

    tags = []
    try:
        tags.append(labels['alertname'])
    except Exception:
        pass

    try:
        tags.append(labels['job'])
    except Exception:
        pass

    try:
        tags.append(labels['type'])
    except Exception:
        pass

    try:
        tags.append(labels['region'])
    except Exception:
        pass

    try:
        tags.append(labels['flavor'])
    except Exception:
        pass

    try:
        startsAt = alert['startsAt']
    except Exception:
        d = datetime.datetime.utcnow()
        startsAt = '{}Z'.format(d.isoformat("T"))

    try:
#        summary = alert['annotations']['description']
        summary = alert['annotations']['summary']
    except Exception:
        summary = 'n/a'

# TODO: hume.msg = "STATUS: "+status+"\nDETAILS: "+annotations.summary
    try:
        status = alert['status']
    except Exception:
        status = 'n/a'
    msg = "Alert is {}.\n\n{}".format(status,
                                           summary)
    try:
        hostname = labels['instance'].split(':')[0]
    except Exception:
        hostname = 'n/a'

    extra = {}
    try:
        extra['instance_name'] = labels['instance_name']
    except Exception:
        extra = None

    humePkt = {'level': level,
               'msg': msg,
               'tags': tags,
               'task': task}
    if extra is not None:
        humePkt['extra'] = extra
    return(humePkt)

def process_alertmanager_request(request, *args, **kwargs):
    method = request.method
    cLength = int(request.headers['Content-Length'])
    cType = request.headers['Content-Type']
    if cType == 'application/json' and cLength > 0 and cLength < 65535:
        print('Decoding Body...')
        try:
            body = request.body.read(cLength)
        except Exception as exc:
            print(exc)
            return
        try:
            body = body.decode('utf8')
        except Exception as exc:
            print(exc)
            return
        try:
            jBody = json.loads(body)
        except Exception as exc:
            print(exc)
            return
    else:
        return
    # print('DECODED JSON BODY:')
    # pprint(jBody)
    #pprint(jBody['alerts'])
    for alert in jBody['alerts']:
        print('ALERTA:')
        pprint(alert)
        print('HUME:')
        humePkt = construct_hume(alert)
        pprint(humePkt)
    try:
        Hume(humePkt).send()
    except Exception as exc:
        print('Error sending hume:')
        print(exc)
    return

def run():
    parser = argparse.ArgumentParser()
    parser.add_argument('--version',
                        action='version',
                        version=__version_str)
    parser.add_argument('-l', '--listen',
                        default='127.0.0.1',
                        dest='host',
                        help='Listening IP for receiver. Default: 127.0.0.1.')
    parser.add_argument('-p', '--port',
                        default=8090,
                        type=int,
                        nargs=1,
                        dest='port',
                        help='Listening port for receiver. Default is 8090.')
    parser.add_argument('-d', '--debug',
                        default=False,
                        action='store_true',
                        dest='debug',
                        help='Enables debugging messages')
    parser.add_argument('-t', '--threadpoolsize',
                        default=10,
                        type=int,
                        nargs=1,
                        dest='threadPool',
                        help='Receiver threading pool size. Default 10.')
    handlers = {"POST": process_alertmanager_request}
    args = parser.parse_args()
    if args.debug:
        print('Running with args:')
        print('host={}'.format(args.host))
        print('port={}'.format(args.port))
        print('threadPoolSize={}'.format(args.threadPool))
    webhook_receiver = webhook_listener.Listener(host=args.host,
                                                 port=args.port,
                                                 debug=args.debug,
                                                 threadPool=args.threadPool,
                                                 handlers=handlers)
    webhook_receiver.start()

    try:
        while True:
            time.sleep(300)
    except KeyboardInterrupt:
        webhook_receiver.stop()

if __name__ == '__main__':
    run()


from webdriver_manager.chrome import ChromeDriverManager
from selenium import webdriver
from selenium.webdriver.common.by import By
import time
import json
from multiprocessing import Pool

options = webdriver.ChromeOptions()
options.headless = False

def write_to_json(_data):
    data = []
    try:
        with open("output.json", "r") as file:
            data = json.load(file)
    except:
        pass
    print(len(data))
    data.append(_data)
    with open("output.json", "w") as file:
        json.dump(data, file, indent=4)

def pagin():
    driver = webdriver.Chrome(ChromeDriverManager().install(), options=options)
    url = 'https://www.allpointsfps.com/search/?sort=score&mpp=300&pg=1'
    driver.get(url)
    paginat = driver.find_element(By.ID, 'ctl00_SearchBody_NavigationTop_lnkLast')
    paginat.click()
    time.sleep(5)
    pagesn = driver.find_elements(By.CLASS_NAME, 'hawk-pageActive')
    pages = pagesn[1].text
    driver.close()
    driver.quit()
    return int(pages)

def main(url):
    driver = webdriver.Chrome(ChromeDriverManager().install())
    driver.maximize_window()
    driver.get(url)
    items = driver.find_elements(by=By.CLASS_NAME, value='title-section')
    link_list = []
    for i in range(len(items)):
        link = items[i].find_element(By.TAG_NAME, 'a').get_attribute('href')
        link_list.append(link)
    for link in link_list:
        try:
            driver.get(link)
            name = driver.title
            price = driver.find_element(by=By.XPATH,
                value='/html/body/div[1]/div[1]/main/div/section[2]/section[2]/div[2]/div[2]/div/div[2]/span[2]').text
            description = driver.find_element(by=By.CLASS_NAME, value='description').text
            oem = driver.find_elements(by=By.CLASS_NAME, value='line-value.sku-value')[1].text
            manufacturerName = driver.find_elements(by=By.CLASS_NAME, value='line-label.sku-label')[1].text[:-2]
            try:
                image = driver.find_elements(by=By.CLASS_NAME, value='thumb')[0].get_attribute('src')
            except:
                image = 'null'
            to_json = {"distributor": "Object('5c5ebad9bb2e1f555e656e10')", "manufacturerName": manufacturerName,
                       "oem": oem,
                       "description": description, "image": image, "name": name, "price": price, "url": link,
                       "crossnew": []}
            try:
                crossnew = driver.find_element(by=By.CLASS_NAME, value='list-group')
                listg = crossnew.find_elements(by=By.CLASS_NAME, value='list-group-item.replaces-item')
                for i in range(len(listg)):
                    crossoae = listg[i].find_elements(by=By.CLASS_NAME, value='oem-sku')
                    crossn = listg[i].find_element(by=By.CLASS_NAME, value='oem-name')
                    aes = []
                    for j in crossoae:
                        ae = j.text
                        aes.append(ae)
                    to_json["crossnew"].append({"mn": crossn.text,
                        "oems": aes})
            except:
                crossnew = 'null'
                to_json["crossnew"].append(crossnew)
            write_to_json(to_json)
        except:
            pass

def links(pages):
    links_list = []
    for i in range(pages):
        links_list.append(f'https://www.allpointsfps.com/search/?sort=score&mpp=300&pg={i + 1}')
    return links_list

if __name__ == '__main__':
    thread = int(input("Enter quantity threads: "))
    n = pagin()
    arr = links(n)
    p = Pool(processes=thread)
    p.map(main, arr)

time.sleep(55)


import os
from setuptools import setup

VERSION = "0.1.2"
DESCRIPTION = "nose plugin for Kay framework testing"
README = os.path.join(os.path.dirname(__file__), "README.rst")
LONG_DESCRIPTION = open(README).read() + "\n\n"

setup(
    name = "NoseKay",
    version = VERSION,
    author = "Yuku Takahashi",
    author_email = "taka84u9@gmail.com",
    description = DESCRIPTION,
    long_description = LONG_DESCRIPTION,
    license = "BSD",
    entry_points = {
        "nose.plugins.0.10": ["nosekay = nosekay:NoseKay"]
    },
    keywords="nose kay-framework",
    classifiers = [
        "Development Status :: 3 - Alpha",
        "License :: OSI Approved :: BSD License",
		"Programming Language :: Python",
		"Intended Audience :: Developers",
		"Topic :: Software Development :: Testing",
    ],
    py_modules = ["nosekay"],
    install_requires = ["nose>=0.10.1"],
)


from PyDAQmx import *
import numpy as np
import time

class NIDAQ_USB:

    def __init__(self):
        return

    def stop(self):
        ###############################################################################
        # Cleanup
        if self.taskHandle:
            # DAQmx Stop Code
            print('Stopping task')
            DAQmxStopTask(self.taskHandle)
            DAQmxClearTask(self.taskHandle)

    def __del__(self):
        print('destructor')
        self.stop()

    def initialize(self, strDevice='Dev1', strChannels='ai0', Total_acquisition_time_in_seconds=1, fs=8e3):
        self.N_channels = len(strChannels)
        self.N_points = np.round(Total_acquisition_time_in_seconds*fs)

        ###############################################################################
        # Declaration of variable passed by reference
        self.taskHandle = TaskHandle()
        self.read = int32()
        ###############################################################################
        # Allocate memory for output:
        self.data_all = np.zeros((self.N_channels, self.N_points), dtype=np.float64)
#        buffer_size = self.data_all.size
        print(self.data_all.size)
        try:
            ###############################################################################
            # DAQmx Configure Code
            DAQmxCreateTask("",byref(self.taskHandle))

            # Create all the input channels
            # Values possible for input type (4th parameter):
            # DAQmx_Val_RSE
            # DAQmx_Val_NRSE
            # DAQmx_Val_Diff
            # DAQmx_Val_PseudoDiff
            for strCurrentChannel in strChannels:
                DAQmxCreateAIVoltageChan(self.taskHandle, strDevice + '/' + strCurrentChannel ,"", DAQmx_Val_RSE, -10.0, 10.0, DAQmx_Val_Volts, None)

            DAQmxCfgSampClkTiming(self.taskHandle, "", fs, DAQmx_Val_Rising, DAQmx_Val_FiniteSamps, int(self.data_all.size))

        except DAQError as err:
            ###############################################################################
            # Error handling
            print("DAQmx Error: %s" % err)
            raise

    def triggerSingleAcquisition(self):

        ###############################################################################
        # DAQmx Start Code
        DAQmxStartTask(self.taskHandle)
#        start_time_all = time.clock()

    def readData(self):
        ###############################################################################
        # DAQmx Read Code
        DAQmxReadAnalogF64(self.taskHandle, int(self.N_points), 10.0, DAQmx_Val_GroupByChannel, self.data_all, int(self.data_all.size), byref(self.read), None)
        return self.data_all
#
#
#
#

#
################################################################################
## Class test/usage example code:
#
#
## Configuration values:
#
#Total_acquisition_time_in_seconds = 1
#strDevice = 'Dev1'
##strChannels = ['ai0', 'ai1', 'ai2', 'ai3', 'ai6', 'ai5']
#strChannels = ['ai0', 'ai3']
#fs = 24e3
#
#nidaq = NIDAQ_USB()
#nidaq.initialize(strDevice, strChannels, Total_acquisition_time_in_seconds, fs)
#nidaq.triggerSingleAcquisition()
#data_all = nidaq.readData()
##nidaq.stop()
#
#figure
#for k in range(data_all.shape[0]):
#    plot(data_all[k, :])
#title('All data')
#


import re
import time
import urllib2
from trac.core import *
from trac.web.chrome import ITemplateProvider, add_script, add_stylesheet
from trac.web.main import IRequestFilter, IRequestHandler
from trac.ticket import TicketSystem
from trac.ticket.model import Ticket
from trac.config import ListOption, Option

class VisualizationModule(Component):
    implements(IRequestHandler, ITemplateProvider, IRequestFilter)

    SECTION = 'viz'
    DEFAULTS = {
        'source': 'table',
        'query': '',
        'selector': 'table.tickets.listing',
        'type': 'AreaChart',
        'options': 'width:600,height:400',
    }

    reports = ListOption(SECTION, 'reports', default=[],
            doc="List of report numbers to treat as queues")

    # ITemplateProvider methods
    def get_htdocs_dirs(self):
        from pkg_resources import resource_filename
        return [('viz', resource_filename(__name__, 'htdocs'))]

    def get_templates_dirs(self):
        from pkg_resources import resource_filename
        return [resource_filename(__name__, 'templates')]

    # IRequestFilter methods
    def pre_process_request(self, req, handler):
        return handler

    def post_process_request(self, req, template, data, content_type):
        if self._is_valid_request(req):
            add_stylesheet(req, 'viz/viz.css')
            add_script(req, 'viz/viz.js')
            add_script(req, '/viz/viz.html')
        return template, data, content_type

    # IRequestHandler methods
    def match_request(self, req):
        return req.path_info.startswith('/viz/')

    def process_request(self, req):
        data = self._get_data(req)
        return 'viz.html', data, 'text/javascript'

    # private methods
    def _is_valid_request(self, req):
        """Checks permissions and that page is visualizable."""
        if req.perm.has_permission('TICKET_VIEW') and \
          'action=' not in req.query_string and \
          self._get_section(req):
            return True
        return False

    def _get_section(self, req, check_referer=False):
        """Returns the trac.ini section that best matches the page url.
        There's a default section [viz] plus regex defined sections:

          [viz]
          reports = 11,12
          options = width:400,height:300

          [viz.report/12]
          options = colors:['red','orange']

          [viz.milestone]
          type = ColumnChart
          options = isStacked:true

        In this example, here are results for different page urls:

          /report/1      ->  None
          /report/11     ->  'viz'
          /report/12     ->  'viz.report/12'
          /milestone/m1  ->  'viz.milestone'
        """
        if check_referer:
            path = req.environ.get('HTTP_REFERER','')
        else:
            path = req.path_info

        # check regex sections
        for section in self.env.config.sections():
            if not section.startswith('%s.' % self.SECTION):
                continue
            section_re = re.compile(section[len(self.SECTION)+1:])
            if section_re.search(path):
                return section

        # check reports list
        report_re = re.compile(r"/report/(?P<num>[1-9][0-9]*)")
        match = report_re.search(req.path_info)
        if match:
            report = match.groupdict()['num']
            if report in self.reports:
                return self.SECTION

        return None

    def _get_data(self, req):
        """Return the template data for the given request url."""
        data = {}
        section = self._get_section(req, check_referer=True)

        # override [viz] with regex section
        for key,default in self.DEFAULTS.items():
            data[key] = self.env.config.get(self.SECTION,key,default) # [viz]
            if section != self.SECTION:
                data[key] = self.env.config.get(section,key,data[key])

        # redo options - make additive
        key,default = 'options',self.DEFAULTS['options']
        data[key] = self.env.config.get(self.SECTION,key,default) # [viz]
        if section != self.SECTION:
            options = self.env.config.get(section,key,data[key])
            if data[key] != options:
                data[key] = (data[key] + ',' + options).strip(',')

        return data


import numpy as np

def compute_numerial_gradient(cost_func, theta):
    #theta存放所有参数 包括所有特征向量和喜好向量的每一个分量
    numgrad = np.zeros(theta.size)
    perturb = np.zeros(theta.size)

    e = 1e-4
    #用弦的斜率（梯度）与切线的斜率（梯度）进行比较  来进行梯度检查 如果差不多 就说明没问题
    #对每个参数都进行梯度检查
    for p in range(theta.size):
        perturb[p] = e
        #返回弦两个端点的代价
        loss1, grad1 = cost_func(theta - perturb)
        loss2, grad2 = cost_func(theta + perturb)

        numgrad[p] = (loss2 - loss1) / (2 * e) #弦的斜率（梯度）
        perturb[p] = 0

    return numgrad


# -*- coding: utf-8 -*-
"""
Created on Fri Feb 14 12:13:38 2014

@author: jnd
"""

import numpy as np

data = np.random.randn(1e6)
while 1:
    data = np.fft.fft(data)


import streamlit as st
import time
import downloder
def main():
    title, mid, logo = st.columns([40,1,40])
    with title:
        st.title("Youtube")
        st.title("Downloader")
    with logo:
        st.image("logo.png")

    txt_input, btn = st.columns([10,1])

    txt =st.text_input("Enter URL")
    if 'state' not in st.session_state:
        st.session_state['state']=False
    if (st.button("Process link",on_click=callback) or st.session_state.state):
        if txt== '':
            st.warning('enter a url')
        else:
            with st.spinner("Processing..."):
                try:
                    url = downloder.Get_res(txt)
                    d_vid,aud, pic = st.columns([1,1,4])
                    with d_vid:
                        st.write("### Videos")
                        if url.r_144p()==None:
                            st.button(label="144p not available", disabled=True)
                        else:
                            if st.button(label="144p res"):
                                url.r_144p().download()
                                #st.experimental_rerun()

                        if url.r_360p()==None:
                            st.button(label="360p not available", disabled=True)
                        else:
                            if st.button(label="360p res"):
                                url.r_360p().download()

                        if url.r_720p()==None:
                            st.button(label="720p not available", disabled=True)
                        else:
                            if st.button(label="720p res"):
                                url.r_720p().download()
                    with aud:
                        st.write("### Audio")
                        if url.a_50()==None:
                            st.button(label="50kbps not available", disabled=True)
                        else:
                            if st.button(label="50kbps"):
                                url.a_50p().download()

                        if url.a_70()==None:
                            st.button(label="70kbps not available", disabled=True)
                        else:
                            if st.button(label="70kbps"):
                                url.a_70().download()

                        if url.a_128()==None:
                            st.button(label="128kbps not available", disabled=True)
                        else:
                            if st.button(label="120kbps"):
                                url.a_128().download()
                    with pic:
                        st.image(url.thumb_nail())
                        st.write(url.title())

                except:
                    st.warning("Enter a valid URL")

        st.success("Done")

def callback():
    st.session_state.state = True

if __name__ == '__main__':
    main()


""" Tests for showing different versions of the home page """

from django.core.urlresolvers import reverse

from common.session import create_consumer_in_session
from common.test_utils import EnhancedTestCase
from consumer.factories.consumer_factory import CONSUMER_FACTORY

class TestShowMarketHome(EnhancedTestCase):
    """ Test cases for Market Home. """
    urls = 'urls_local.urls_2'

    def test_get_show_home(self):
        """ No consumer in session and is not an ajax request. """
        response = self.client.get(reverse('home'))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, 'frm_consumer_registration')
        self.assertContains(response, 'frm_subscriber_registration')
        self.assertContains(response,
            "input type='hidden' name='csrfmiddlewaretoken'")
        self.assertContains(response, 'input name="email"')
        self.assertContains(response, 'input name="consumer_zip_postal"')
        self.assertContains(response, 'input name="mobile_phone_number"')
        self.assertContains(response, 'input name="subscriber_zip_postal"')
        self.assertContains(response, 'name="carrier"')

    def test_get_home_consumer(self):
        """ Consumer in session and is not an ajax request. """
        consumer = CONSUMER_FACTORY.create_consumer()
        create_consumer_in_session(self, consumer)
        self.assemble_session(self.session)
        response = self.client.get(reverse('home'), follow=True)
        self.assertEqual(response.status_code, 200)
        self.assertEquals(str(response.request['PATH_INFO']), '/hudson-valley/')
        self.assertContains(response, 'frm_consumer_registration')
        self.assertContains(response, 'frm_subscriber_registration')
        self.assertContains(response, consumer.email)
        self.assertContains(response, consumer.consumer_zip_postal)

    def test_home_post_con_reg(self):
        """ No consumer in session. Now post the consumer registration form
        with an ajax request with good data.
        """
        post_data = {'ajax_mode': 'consumer_reg',
            'email': 'will+validconsumer@10coupons.com',
            'consumer_zip_postal': '10990'}
        response = self.client.post(reverse('home'), post_data,
            HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertContains(response,
            '"is_already_registered": true')
        self.assertNotContains(response, 'errors')

    def test_home_post_con_reg_bad(self):
        """ No consumer in session. Now post the consumer registration form
        with an ajax request with bad data.
        """
        post_data = {'ajax_mode': 'consumer_reg',
            'email': 'NotValidEmail',
            'consumer_zip_postal': 'ABC'}
        response = self.client.post(reverse('home'), post_data,
            HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertNotContains(response,
            '"is_already_registered": true')
        self.assertContains(response,
            '"email": ["Enter a valid e-mail address."]')
        self.assertContains(response,
            '"consumer_zip_postal": ["Please enter a 5 digit zip"]')
        self.assertContains(response, 'errors')

    def test_home_post_sub_reg(self):
        """ Consumer in session. Now post the subscriber registration form
        with an ajax request with good data.
        """
        post_data = {'ajax_mode': 'subscriber_reg',
            'mobile_phone_number': '5555551010',
            'carrier': '7',
            'subscriber_zip_postal': '10990'}
        response = self.client.post(reverse('home'), post_data,
            HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertContains(response,
            '"is_already_registered": true')
        self.assertNotContains(response, 'errors')

    def test_home_post_sub_reg_bad(self):
        """ Consumer in session. Now post the subscriber registration form
        with an ajax request with bad data.
        """
        post_data = {'ajax_mode': 'subscriber_reg',
            'mobile_phone_number': 'ABCDEFGHIJ',
            'carrier': '',
            'subscriber_zip_postal': 'ABC'}
        response = self.client.post(reverse('home'), post_data,
            HTTP_X_REQUESTED_WITH='XMLHttpRequest')
        self.assertNotContains(response,
            '"is_already_registered": true')
        self.assertContains(response,
            '"mobile_phone_number": [" Please enter the 10 digit number of your cell phone"]')
        self.assertContains(response,
            '"subscriber_zip_postal": ["Please enter a 5 digit zip"]')
        self.assertContains(response,
            '"carrier": ["Select your cell phone service provider"]')
        self.assertContains(response, 'errors')


import json
from datetime import datetime, timedelta
import sys

# Load the JSON data from the file
with open('/home/trabajo/.ti-sheet') as f:
    data = json.load(f)

def calculate_total_time_per_month(data):
    # Initialize a dictionary to store total time per day
    total_time_per_day = {}

    # Get the current month
    current_month = datetime.utcnow().month

    # Iterate over the work entries
    for entry in data['work']:
        start_time = datetime.fromisoformat(entry['start'][:-1])

        # Check if the entry is within the current month
        if start_time.month == current_month:
            # Calculate the time difference in seconds
            end_time_str = entry.get('end', None)
            if end_time_str:
                end_time = datetime.fromisoformat(end_time_str[:-1])
            else:
                end_time = datetime.utcnow()

            time_difference = (end_time - start_time).total_seconds()

            # Extract the date (year-month-day) from the start time
            date = start_time.date()

            # Add the time difference to the total time for that day
            total_time_per_day[date] = total_time_per_day.get(date, 0) + time_difference

    return total_time_per_day

# Calculate total time for the current month
total_time_per_month = calculate_total_time_per_month(data)
total_time = 0

# Print the total time for each day in the current month
for date, total_time_day in list(total_time_per_month.items())[-int(sys.argv[1]):]:
    total_time += total_time_day
    print(f'{date.strftime("%d")}: {total_time_day/3600:.2f}h')

previous_time = list(total_time_per_month.items())[-(int(sys.argv[1])+1)][1]
last_time = list(total_time_per_month.items())[-1][1]

# The avr needs to include x items and cause we are excluding the last one, we must add one previous to the list
# I dont wanna my avr go down because the day is starting and the time is 0
total_time -= last_time
total_time += previous_time

average_time = total_time / int(sys.argv[1])
print(f'{sys.argv[1]}d: {average_time/3600:.2f}h')


# from PyQt5.QtWidgets import QSizePolicy
from PyQt5 import QtCore, QtGui, QtWidgets
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.figure import Figure
from IonSimulator import IonSimulator as IonSim
import numpy as np
import sys

class Ui_MainWindow(object):
    def setupUi(self, MainWindow):

        plotOffset = 20
        plotDPI = 100
        plotWidth = 8
        plotHeight = 6
        windowWidth = 960
        windowHeight = 640
        widgetYSpacing = 10
        fontSize = 12
        buttonWidth = 100
        buttonHeight = 50
        inputWidths = 80
        inputHeights = 20

        MainWindow.setObjectName("MainWindow")
        MainWindow.resize(windowWidth, windowHeight)

        font = QtGui.QFont()
        font.setPointSize(fontSize)

        self.centralwidget = QtWidgets.QWidget(MainWindow)
        self.centralwidget.setObjectName("centralwidget")
        MainWindow.setCentralWidget(self.centralwidget)

        plotWithOffset = plotOffset + plotWidth*plotDPI
        buttonXPos = plotWithOffset + (windowWidth - plotWithOffset - buttonWidth)/2
        buttonYPos = plotOffset
        self.simulateButton = QtWidgets.QPushButton(self.centralwidget)
        self.simulateButton.setGeometry(QtCore.QRect(buttonXPos, buttonYPos, buttonWidth, buttonHeight))
        self.simulateButton.setBaseSize(QtCore.QSize(0, 0))
        self.simulateButton.setFont(font)
        self.simulateButton.setObjectName("simulateButton")

        inputXPos = plotWithOffset + (windowWidth - plotWithOffset - inputWidths)/2
        inputYPos = buttonYPos + buttonHeight + widgetYSpacing
        self.massLabel = QtWidgets.QLabel(self.centralwidget)
        self.massLabel.setGeometry(QtCore.QRect(inputXPos, inputYPos, inputWidths, inputHeights))
        self.massLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.massLabel.setObjectName("massLabel")

        inputYPos += inputHeights + widgetYSpacing
        self.massInput = QtWidgets.QLineEdit(self.centralwidget)
        self.massInput.setGeometry(QtCore.QRect(inputXPos, inputYPos, inputWidths, inputHeights))
        self.massInput.setAlignment(QtCore.Qt.AlignCenter)
        self.massInput.setObjectName("massInput")

        inputYPos += inputHeights + widgetYSpacing
        self.chargeLabel = QtWidgets.QLabel(self.centralwidget)
        self.chargeLabel.setGeometry(QtCore.QRect(inputXPos, inputYPos, inputWidths, inputHeights))
        self.chargeLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.chargeLabel.setObjectName("chargeLabel")

        inputYPos += inputHeights + widgetYSpacing
        self.chargeInput = QtWidgets.QLineEdit(self.centralwidget)
        self.chargeInput.setGeometry(QtCore.QRect(inputXPos, inputYPos, inputWidths, inputHeights))
        self.chargeInput.setAlignment(QtCore.Qt.AlignCenter)
        self.chargeInput.setObjectName("chargeInput")

        inputYPos += inputHeights + widgetYSpacing
        self.fieldLabel = QtWidgets.QLabel(self.centralwidget)
        self.fieldLabel.setGeometry(QtCore.QRect(inputXPos, inputYPos, inputWidths, inputHeights))
        self.fieldLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.fieldLabel.setObjectName("fieldLabel")

        inputYPos += inputHeights + widgetYSpacing
        self.fieldInput = QtWidgets.QLineEdit(self.centralwidget)
        self.fieldInput.setGeometry(QtCore.QRect(inputXPos, inputYPos, inputWidths, inputHeights))
        self.fieldInput.setAlignment(QtCore.Qt.AlignCenter)
        self.fieldInput.setObjectName("fieldInput")

        inputYPos += inputHeights + widgetYSpacing
        self.delayLabel = QtWidgets.QLabel(self.centralwidget)
        self.delayLabel.setGeometry(QtCore.QRect(inputXPos, inputYPos, inputWidths, inputHeights))
        self.delayLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.delayLabel.setObjectName("delayLabel")

        inputYPos += inputHeights + widgetYSpacing
        self.delayInput = QtWidgets.QLineEdit(self.centralwidget)
        self.delayInput.setGeometry(QtCore.QRect(inputXPos, inputYPos, inputWidths, inputHeights))
        self.delayInput.setAlignment(QtCore.Qt.AlignCenter)
        self.delayInput.setObjectName("delayInput")

        inputYPos += inputHeights + widgetYSpacing
        self.rampLabel = QtWidgets.QLabel(self.centralwidget)
        self.rampLabel.setGeometry(QtCore.QRect(inputXPos, inputYPos, inputWidths, inputHeights))
        self.rampLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.rampLabel.setObjectName("rampLabel")

        inputYPos += inputHeights + widgetYSpacing
        self.rampInput = QtWidgets.QLineEdit(self.centralwidget)
        self.rampInput.setGeometry(QtCore.QRect(inputXPos, inputYPos, inputWidths, inputHeights))
        self.rampInput.setAlignment(QtCore.Qt.AlignCenter)
        self.rampInput.setObjectName("rampInput")

        inputYPos += inputHeights + widgetYSpacing
        self.fitLabel = QtWidgets.QLabel(self.centralwidget)
        self.fitLabel.setGeometry(QtCore.QRect(inputXPos, inputYPos, inputWidths, inputHeights))
        self.fitLabel.setAlignment(QtCore.Qt.AlignCenter)
        self.fitLabel.setObjectName("fitLabel")

        inputYPos += inputHeights + widgetYSpacing
        self.fitValue = QtWidgets.QLineEdit(self.centralwidget)
        self.fitValue.setGeometry(QtCore.QRect(inputXPos, inputYPos, inputWidths, inputHeights))
        self.fitValue.setAlignment(QtCore.Qt.AlignCenter)
        self.fitValue.setObjectName("fitValue")
        self.fitValue.setReadOnly(True)

        self.canvas = PlotCanvas(MainWindow,width=plotWidth, height=plotHeight)
        self.canvas.move(20,20)

        self.retranslateUi(MainWindow)
        QtCore.QMetaObject.connectSlotsByName(MainWindow)

    def retranslateUi(self, MainWindow):
        _translate = QtCore.QCoreApplication.translate
        MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow"))
        self.simulateButton.setText(_translate("MainWindow", "Simulate!"))
        self.massLabel.setText(_translate("MainWindow", "Mass"))
        self.chargeLabel.setText(_translate("MainWindow", "Charge"))
        self.fieldLabel.setText(_translate("MainWindow", "Field Strength"))
        self.delayLabel.setText(_translate("MainWindow", "Delay"))
        self.rampLabel.setText(_translate("MainWindow", "Ramp"))
        self.fitLabel.setText(_translate("MainWindow", "Fit"))

class PlotCanvas(FigureCanvas):

    def __init__(self, parent=None, width=1, height=1, dpi=100):
        fig = Figure(figsize=(width, height), dpi=dpi)
        FigureCanvas.__init__(self, fig)
        self.setParent(parent)
        self.axes = self.figure.add_subplot(111)

        FigureCanvas.updateGeometry(self)

    def plot(self,x,y,title,desc='r.',x_label='tof ($\mu$s)',y_label='mom (au)'):

        self.axes.plot(x,y,desc)
        self.axes.set_xlabel(x_label)
        self.axes.set_ylabel(y_label)
        self.axes.set_title(title)
        self.draw()

    def clear(self):
        self.axes.clear()

def simulate(simulator,ui):
    ui.canvas.clear()
    try:
        simulator.SetMass(int(ui.massInput.text()))
    except:
        ui.massInput.setText(str(simulator.particle_mass_amu))
    try:
        simulator.SetCharge(int(ui.chargeInput.text()))
    except:
        ui.chargeInput.setText(str(simulator.particle_charge_C))
    try:
        simulator.spectrometer.E_max = int(ui.fieldInput.text())
    except:
        ui.fieldInput.setText(str(simulator.spectrometer.E_max))
    try:
        simulator.spectrometer.delay = int(ui.delayInput.text())
    except:
        ui.delayInput.setText(str(eformat(simulator.spectrometer.delay,3,1)))
    try:
        simulator.spectrometer.ramp = int(ui.rampInput.text())
    except:
        ui.delayInput.setText(str(eformat(simulator.spectrometer.ramp,3,1)))

    simulator.Simulate()
    plot(simulator,ui)

def plot(simulator,ui):
    pz = simulator.Get_Pz_o()
    ui.canvas.plot(simulator.data['tof']*10**6,pz,'Mass: ' + str(simulator.particle_mass_amu))
    ui.canvas.plot(simulator.polyFitX*10**6,simulator.polyFitY,'Mass: ' + str(simulator.particle_mass_amu),'b-')

def eformat(f, prec, exp_digits):
    s = "%.*e"%(prec, f)
    mantissa, exp = s.split('e')
    return "%se%+0*d"%(mantissa, exp_digits+1, int(exp))

if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    MainWindow = QtWidgets.QMainWindow()
    ui = Ui_MainWindow()
    ui.setupUi(MainWindow)
    simulator = IonSim()
    ui.massInput.setText(str(simulator.particle_mass_amu))
    ui.chargeInput.setText(str(simulator.particle_charge_C))
    ui.fieldInput.setText(str(simulator.spectrometer.E_max))
    ui.delayInput.setText(str(eformat(simulator.spectrometer.delay,3,1)))
    ui.rampInput.setText(str(eformat(simulator.spectrometer.ramp,3,1)))
    ui.simulateButton.clicked.connect(lambda: simulate(simulator,ui))
    MainWindow.show()
    sys.exit(app.exec_())


import sys
from flask import make_response, request
from sqlalchemy import select, String
from sqlalchemy.orm import sessionmaker, Session
from sqlalchemy.sql import cast
from functools import wraps
from database.schema import Account, Loginsession

def get_accounts(session: Session):
    account_query = select(
        Account.user_id,
        Account.username,
        cast(Account.pass_hash, String).label("pass_hash"),
    )
    accounts = session.execute(account_query).all()

    return {"data": [dict(account) for account in accounts]}

def get_tokens(session: Session):
    session_query = select(
        cast(Loginsession.token, String).label("token"), Loginsession.user_id
    )
    login_sessions = session.execute(session_query).all()

    return {"data": [dict(login_session) for login_session in login_sessions]}

def get_user(session: Session) -> Account:
    token = request.cookies.get("token")
    if token == None:
        return None
    session_query = (
        select(Account)
        .join(Loginsession)
        .where(Loginsession.token == token.encode("utf-8"))
    )
    print(session_query, file=sys.stderr)
    this_session = session.execute(session_query).one_or_none()

    return this_session.Account

def check_loggedin_token(token, session: Session):
    if token is None:
        return False

    session_query = select(Loginsession).where(
        Loginsession.token == token.encode("utf-8")
    )
    this_session = session.execute(session_query).one_or_none()

    # return dict(this_session) if this_session is not None else None
    return this_session is not None

def login_required(MakeSession: sessionmaker):
    def _wrapped_decorator(func):
        @wraps(func)
        def _wrapper(*args, **kwargs):

            cookie_token = request.cookies.get("token")
            cookie_username = request.cookies.get("username")

            with MakeSession() as session:
                is_logged_in = check_loggedin_token(cookie_token, session)

            # or cookie_username != user_info.get('username'):
            if not is_logged_in:
                resp = make_response({"message": "Incorrect Auth Token"})
                resp.delete_cookie("token")
                resp.status_code = 401
                return resp
            return func(*args, **kwargs)

        return _wrapper

    return _wrapped_decorator


import random, bisect
"""
continous random variable X ~ [0, 1], f(x) = 1 and F(x) = x
Z_n = max of n samples of X
F_z(x) = p(max of n samples <= x) = F(x)^n
p_z(x) = dF_z/dx = nF(x)^{n - 1} * f(x)

p_z(x) = nx^{n - 1}
so E[x] = n/(n + 1)
"""
random.seed(1)
R, ITERS = 10, 10**5

def X() -> float:
    """ Sample the random variable X. """
    return random.uniform(0, 1)

def Z(X, iters: int=R) -> float:
    """ Sample the random variable Z. """
    return lambda: max(X() for i in range(iters))

def sample(X: list, F: list) -> float:
    """ Samples a value from a random variable. """
    p = random.random()
    return X[bisect.bisect(F, p) - 1]

def pz(z):
    """ pmf of Z """
    i = bisect.bisect(X, z)
    return pow(F[i], R) - pow(F[i - 1], R)

def E(X, iters: int=ITERS) -> float:
    """ Expected value by repeatedly sampling a random variable. """
    return sum(X() for i in range(iters))/iters

if __name__ == "__main__":
    ### continuous case
    print(E(Z(X)))
    print(R/(R + 1))

    ### discrete case
    X = [   1,    5,  10,   15,   16,   20,  30,   35,   50,  100]
    p = [0.05, 0.08, 0.1, 0.12, 0.17, 0.22, 0.1,  0.1, 0.05, 0.01]
    assert sum(p) == 1
    N = len(X)

    # cmf of X
    F = [0]*(N + 1)
    for i in range(N):
        F[i + 1] = F[i] + p[i]

    Fz = [0]*(N + 1)
    for i in range(N):
        Fz[i + 1] = Fz[i] + pz(X[i])

    # print(F)
    # print(Fz)
    # print([pow(f, R) for f in F])

    print(sum(pz(x)*x for x in X))
    print(E(Z(lambda: sample(X, F))))


from telegram.ext import ConversationHandler

from src.managers import IOassetsManager, LoggerManager, QuestManager, TimeManager
from src.templates import MessageTemplates
from . import ReusableComponents

def send_quest_image_start(update, context):
    ReusableComponents.log_command_accessed_timing(update)

    user_id = update.message.from_user.id
    username = update.message.from_user.username

    if not user_is_a_member(update):
        LoggerManager.general_logs(
            f"User {username} ({user_id}) is not a member!")

        update.message.reply_text(MessageTemplates.new_user_found_message)

        return ConversationHandler.END

    list_of_available_quests = get_list_of_available_quests_for_the_week()

    if len(list_of_available_quests) <= 0:
        update.message.reply_text(MessageTemplates.error_message)

        ReusableComponents.prompt_user_next_action(update)

        return ConversationHandler.END

    context.chat_data["quest_titles"] = list_of_available_quests

    update.message.reply_text(
        MessageTemplates.send_quest_image_message(list_of_available_quests))

    return 'QuestDescription'

def user_is_a_member(update):
    return ReusableComponents.check_membership_status(update)

def get_list_of_available_quests_for_the_week():
    date_today = TimeManager.get_current_date()

    return QuestManager.get_list_of_available_quest_titles_for_the_week(date_today)

# QuestDescription state
def display_quest_description(update, context):
    user_choice = update.message.text

    if is_invalid_user_choice(user_choice, context):
        update.message.reply_text(MessageTemplates.invalid_response_message)
        return 'QuestDescription'

    # Get quest description from database
    parsed_user_choice = int(user_choice) - 1
    selected_quest_title = context.chat_data["quest_titles"][parsed_user_choice][0]
    quest_description = QuestManager.get_list_of_available_quests_for_the_week(selected_quest_title)

    if not quest_description:
        username = update.message.from_user.username
        user_id = update.message.from_user.id

        LoggerManager.general_logs(f"Error occurred while {username} ({user_id}) is viewing quest description")

        return ConversationHandler.END

    update.message.reply_text(MessageTemplates.gen_quest_description_message(selected_quest_title, quest_description),
                              disable_web_page_preview=True)

    return 'ImageResponse'

def is_invalid_user_choice(user_choice, context):
    if not user_choice.isdigit():
        return True

    if int(user_choice) > len(context.chat_data["quest_titles"]) or int(user_choice) <= 0:
        return True

    return False

# ImageResponse state
def after_send_quest_image(update, context):
    photo_id = update.message.photo[0].file_id

    snapee_asst_id = IOassetsManager.get_snapee_asst_id()

    response_status = send_message_to_snapee_assistant(update, context, snapee_asst_id, photo_id)

    inform_user_about_sending_photo_result(update, response_status)

    return ConversationHandler.END

def send_message_to_snapee_assistant(update, context, snapee_asst_id, photo_id):
    user_id = update.message.from_user.id
    username = update.message.from_user.username

    LoggerManager.general_logs(
        f"Sending user {username} ({user_id})'s photo to snapeeassistant now.")

    try:
        context.bot.send_photo(snapee_asst_id,
                               photo=photo_id,
                               caption=f"User: {username} ({user_id})")
        return True

    except Exception as e:
        LoggerManager.exception_logs(e)
        LoggerManager.exception_logs(
            f"Something went wrong while sending user {username} ({user_id})'s photo to SnapeeAssistant")

def inform_user_about_sending_photo_result(update, response_status):
    if response_status:
        update.message.reply_text(MessageTemplates.quest_image_sent_message)

    else:
        update.message.reply_text(MessageTemplates.error_message)

    ReusableComponents.prompt_user_next_action(update)


"""
Review Question 11
Count the occurrences of each letter in a file
Prompt user to enter filename
"""

def count_letters(filename):
    count_letters = dict()
    upper = set("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
    lower = set("abcdefghijklmnopqrstuvwxyz")
    with open(filename, "r") as f:
        contents = f.read()
        for each_character in contents:
            if each_character in lower or each_character in upper:
                count_letters[each_character] = count_letters.get(each_character, 0) + 1
    print(count_letters)

def main():
    filename = input("Enter filename ")
    count_letters(filename)

if __name__ == "__main__":
    main()


#!/usr/bin/env python3
# -*- coding: utf-8 -*-

# Import required modules
from __future__ import print_function
import mlt
import time
import sys

# Start the mlt system
mlt.Factory().init( )

# Establish a profile
profile = mlt.Profile( )

# Create the producer
p = mlt.Producer( profile, sys.argv[1] )

if p:
	# Create the consumer
	c = mlt.Consumer( profile, "sdl" )

	# Turn off the default rescaling
	c.set( "rescale", "none" )

	# Connect the producer to the consumer
	c.connect( p )

	# Start the consumer
	c.start( )

	# Wait until the user stops the consumer
	while c.is_stopped( ) == 0:
		time.sleep( 1 )
else:
	# Diagnostics
	print("Unable to open ", sys.argv[ 1 ])


from openpyxl import Workbook
from openpyxl.styles import Alignment
from openpyxl.utils import get_column_letter
from openpyxl.writer.excel import save_virtual_workbook

from webapp.articles.models import ArticleModel

def convert_to_xls(article: ArticleModel) -> bytes:
    """
    Converts Article model to xls book
    """
    book: Workbook = Workbook()
    sheet = book.active

    article_dict = article.__dict__
    tags = ", ".join(article.get_relations("tags"))
    categories = ", ".join(article.get_relations("categories"))
    reference_images = ", ".join(article.get_relations("reference_images"))
    keys = [
        "unique_id",
        "state",
        "legal_language",
        "citation",
        "cfr40_part280",
        "local_regulation",
        "abstract",
        "updated_date",
        "effective_date",
    ]
    data = [article_dict[key] for key in keys]
    updated_date = article.updated_date
    if updated_date:
        data[-2] = updated_date
    effective_date = article.effective_date
    if effective_date:
        data[-1] = effective_date.strftime("%d/%m/%Y")
    data.insert(-2, tags)
    data.insert(-3, categories)
    data.insert(-4, reference_images)

    header = [
        "Unique ID",
        "State",
        "Regulation",
        "Citation",
        "40CFR 280 Part Federal Rule",
        "Legal Regulation",
        "Abstract",
        "Reference Images",
        "Categories",
        "Tags",
        "Updated Date",
        "Effective Date",
    ]
    sheet.title = article.title
    sheet.append(header)
    sheet.append(data)
    column = 1

    while column < len(data) + 1:
        i = get_column_letter(column)
        sheet.column_dimensions[i].width = 15
        for j in range(1, 13):
            sheet[f"{i}{j}"].alignment = Alignment(
                wrapText=True, vertical="top"
            )
        column += 1
    return save_virtual_workbook(book)


# https://www.codewars.com/kata/55aa075506463dac6600010d/train/python
# 1, 246, 2, 123, 3, 82, 6, 41 are the divisors of number 246.
# Squaring these divisors we get: 1, 60516, 4, 15129, 9, 6724, 36, 1681.
# The sum of these squares is 84100 which is 290 * 290.
#
# Task
# Find all integers between m and n (m and n integers with 1 <= m <= n)
# such that the sum of their squared divisors is itself a square.
#
# We will return an array of subarrays or of tuples (in C an array of Pair) or a string.
# The subarrays (or tuples or Pairs) will have two elements: first the number
# the squared divisors of which is a square and then the sum of the squared divisors.
#
# Example:
# list_squared(1, 250) --> [[1, 1], [42, 2500], [246, 84100]]
# list_squared(42, 250) --> [[42, 2500], [246, 84100]]

def list_squared(m, n):
    result = []
    for x in range(m, n + 1):
        dividers = set()
        if int(x ** 0.5) ** 2 == x:
            dividers.add(int(x ** 0.5))
        for d in range(1, int(x ** 0.5)+1):
            if x % d == 0:
                dividers.add(d)
                dividers.add(x // d)
        sum_dividers = sum(d ** 2 for d in dividers)
        if int(sum_dividers ** 0.5) ** 2 == sum_dividers:
            result.append([x, sum_dividers])
    return result

print(list_squared(1, 250))     # [[1, 1], [42, 2500], [246, 84100]]
print(list_squared(42, 250))    # [[42, 2500], [246, 84100]]
print(list_squared(250, 500))   # [[287, 84100]]


#!/usr/bin/env python

"""
This module provides the logging function.
"""
import os
import sys
import logging
import logging.handlers

class Logger(object):
    """The logger factory class. It is a template to help quickly create a log utility.
    Attributes:
    set_conf(log_file, use_stdout, log_level):
    this is a static method that returns a configured logger.
    get_logger(tag): this is a static method that returns a configured logger.
    """
    __loggers = {}

    __use_stdout = True
    __log_file = ""
    __log_level = logging.DEBUG

    @staticmethod
    def config(log_file, use_stdout, log_level):
        """set the config, where config is a ConfigParser object
        """
        Logger.__use_stdout = use_stdout
        Logger.__log_level = log_level
        dirname = os.path.dirname(log_file)
        if (not os.path.isfile(log_file)) and (not os.path.isdir(dirname)):
            try:
                os.makedirs(dirname)
            except OSError as e:
                print("create path '%s' for logging failed: %s" % (dirname, e))
                sys.exit()
        Logger.__log_file = log_file

    @staticmethod
    def get_logger(tag):
        """return the configured logger object
        """
        if tag not in Logger.__loggers:
            Logger.__loggers[tag] = logging.getLogger(tag)
            Logger.__loggers[tag].setLevel(Logger.__log_level)
            formatter = logging.Formatter(
                "[%(name)s][%(levelname)s] %(asctime)s "
                "%(filename)s:%(lineno)s %(message)s")
            file_handler = logging.handlers.TimedRotatingFileHandler(
                Logger.__log_file, when='H', interval=1, backupCount=0)
            file_handler.setLevel(Logger.__log_level)
            file_handler.setFormatter(formatter)
            file_handler.suffix = "%Y%m%d%H%M.log"
            Logger.__loggers[tag].addHandler(file_handler)
            if Logger.__use_stdout:
                stream_headler = logging.StreamHandler()
                stream_headler.setLevel(Logger.__log_level)
                stream_headler.setFormatter(formatter)
                Logger.__loggers[tag].addHandler(stream_headler)
        return Logger.__loggers[tag]


import os
import shutil

def search_and_delete(folder_path, target_folders):
    '''
    在{folder_path}下寻找目标目录并且删除.
    '''
    for root, dirs, files in os.walk(folder_path):
        '''
        递归地搜索以{folder_path}为根节点的整个文件树.
        For each directory in the directory tree rooted at top (including top
    itself, but excluding '.' and '..'), yields a 3-tuple

        dirpath, dirnames, filenames

    dirpath is a string, the path to the directory.  dirnames is a list of
    the names of the subdirectories in dirpath (including symlinks to directories,
    and excluding '.' and '..').
    filenames is a list of the names of the non-directory files in dirpath.
    Note that the names in the lists are just names, with no path components.
    To get a full path (which begins with top) to a file or directory in
    dirpath, do os.path.join(dirpath, name).
        '''
        for target_folder in target_folders:
            if target_folder in dirs:
                folder_to_delete = os.path.join(root, target_folder)
                shutil.rmtree(folder_to_delete)
                print(f"Deleted folder: {folder_to_delete}")

if __name__ == "__main__":
    # 定义要搜索和删除的目标文件夹列表
    is_backend_project = True
    is_frontend_project = False

    # 后端项目需要删除target文件夹
    if is_backend_project:
        target_folders = ['target']

    # 前端项目需要删除dist, node_modules
    if is_frontend_project:
        target_folders = ['dist', 'node_modules']

    # 定义包含项目的文件夹路径
    project_folder = '/Users/lyk/Projects/MyOfficialProjects/VolatileReborn copy'  # 替换为实际的文件夹路径

    # 调用函数搜索并删除目标文件夹
    search_and_delete(project_folder, target_folders)


import cv2
import numpy as np
from utils.functions import l2_distance

def ax2bgr(ax):
    canvas = ax.figure.canvas
    canvas.draw()
    data = np.frombuffer(canvas.tostring_rgb(), dtype=np.uint8)
    data = data.reshape(canvas.get_width_height()[::-1] + (3,))
    img = cv2.cvtColor(data, cv2.COLOR_RGB2BGR)
    return img

def data2img(data, size=300, color=True):
    img = process_img(data, smooth=False)
    h, w = img.shape
    # opencv: change (w, h) here
    img = cv2.resize(img, (size, int(size / w * h)))
    img = (img * 255).astype(np.uint8)
    if color:
        img = cv2.applyColorMap(img, cv2.COLORMAP_JET)
    return img

def process_img(img, smooth=True, eps=1e-16):
    img = (img - np.min(img)) / (np.max(img) - np.min(img) + eps)
    if smooth:
        img = cv2.GaussianBlur(img, (3, 3), sigmaX=1, sigmaY=0)
    return img

def render_env(ax, qs, q_preds=None, gs=None):
    # qs
    qs = np.array(qs)
    ax.plot(qs[:, 0], qs[:, 1], 'b', label='pos')
    ax.plot(qs[-1, 0], qs[-1, 1], 'xb')

    # q_preds
    if q_preds is not None:
        q_preds = np.array(q_preds)
        ax.plot(q_preds[:, 0], q_preds[:, 1], 'r', label='pred')
        ax.plot(q_preds[-1, 0], q_preds[-1, 1], 'xr')

        error = l2_distance(q_preds[-1, :], qs[-1, :])
        ax.set_title('error={:.2f}'.format(error))

    # gs
    if gs is not None:
        gs = np.array(gs)[:, 0, 5]
        idx = (gs > 0)
        ax.plot(qs[idx, 0], qs[idx, 1], 'or')

    ax.legend(loc='lower right')
    res = ax2bgr(ax)
    return res


'''

'''

#CODE
t = int(input())
for _ in range(t):
    n = int(input())
    arr = list(map(int,input().split()))
    curr = 0
    count = 0
    for i in range(n):
        if arr[i]>curr:
            count = count + (arr[i] - curr)
        curr = arr[i]
    print(count)


from random import randint
import matplotlib.pyplot as plt
import numpy as np

# Class for graph
# written in the spirit of dict of lists stroage type

class Graph:

    # storage of vertex data :
    # index of vertex -> some object
    verteces = []

    # dict for graph edges
    # key : index of vertex
    # value : list of adjecent indeces
    edges = {}

    # number of verteces in graph
    N = 0

    # graph initializer

    # if N is not provided empty graph is created
    # else random graph is generated, where each edge
    # has 50 % chance to appear
    # by deafault we store in each vertex its index number
    def __init__(self, N = None):

        self.edges = {}

        if N == None:
            self.N = 0
            self.verteces = []
            return

        self.verteces = list(range(N))

        for i in range(N):
            self.edges[i] = []

        for i in range(N):
            for k in range(i, N):
                if randint(0, 1):
                    self.edges[i].append(k)
                    self.edges[k].append(i)

        self.N = N

    # get info from node index
    def __getitem__(self, index):
        return self.verteces[index]

    def __len__(self):
        return self.N

    # add vertex to existing graph
    # info is an information stored in vertex
    def add_vertex(self, info):
        self.verteces.append(info)
        self.edges[self.N] = []
        self.N = self.N + 1

    # add edge between two existing verteces
    def add_edge(self, i, j):
        assert i < self.N, 'first vertex is not present in graph'
        assert j < self.N, 'second vertex is not present in graph'

        self.edges[i].append(j)
        self.edges[j].append(i)

    # plot function for graph
    # graph is plotted as equally distrubed over circle points with lines coresponding to edges
    # axes : matplotlib axes to which plot a graph
    # param_dict : parameter dictionary for lines plot (see ex. in jupiter notebook)
    # font_dict : parameter dictionary for text labels of nodes (see ex. in jupiter notebook)
    def plot(self, axes, param_dict, font_dict, acsent_nodes=None):

        assert self.N > 0 , 'Graph is empty'

        d_alpha = 2 * np.pi / self.N

        # plot edges and verteces
        for node in self.edges.keys():
            # if edges are present
            alpha = d_alpha * node
            if self.edges[node]:

                for neigh in self.edges[node]:
                    if neigh > node:
                        beta = neigh * d_alpha
                        axes.plot([np.cos(beta), np.cos(alpha)],
                                   [np.sin(beta), np.sin(alpha)],
                                    **param_dict)

            else:
                axes.plot(np.cos(alpha), np.sin(alpha),
                           **param_dict)

        if acsent_nodes != None:
            alpha = d_alpha * np.array(acsent_nodes)
            axes.plot(np.cos(alpha), np.sin(alpha),
                           color='k', marker='o', linestyle='',
                           markersize=18, label='selected_nodes')

        # plot node labels
        for node in self.edges.keys():
            alpha = d_alpha * node

            margin_step = 0.05 + font_dict['size'] * 0.0025

            axes.text( (1 + margin_step) * np.cos(alpha),
                       (1 + margin_step) * np.sin(alpha),
                      '{}'.format(node),
                      fontdict = font_dict)

        bd = 1 + 0.1 + font_dict['size'] * 0.0025
        axes.set_xlim([-bd, bd])
        axes.set_ylim([-bd, bd])


import numpy as np
from matplotlib import pyplot as plt

Y = np.array([2, 1,
3, 4,
5, 0,
7, 6,
9, 2 ])

Y = Y.reshape((5,2))
mu = Y.mean(axis=0)
Yc = Y - mu

#S = np.cov(Yc.T)
S = np.dot(Yc.T,Yc)/4

val, vet = np.linalg.eig(S)

F = np.dot(Yc, vet)

plt.figure()
plt.subplot(121, aspect='equal')
plt.plot(Y[:,0], Y[:,1], 'go')
plt.arrow(mu[0], mu[1], vet[0,0], vet[1,0], color='red')
plt.arrow(mu[0], mu[1], vet[0,1], vet[1,1], color='blue')

plt.subplot(122, aspect='equal')
plt.plot(F[:,0], F[:,1], 'ro')