#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018 Brno University of Technology FIT
# Author: Jan Profant <jan.profant@phonexia.com>
# All Rights Reserved

import os
import sys
import ctypes
import logging
import argparse
import multiprocessing

import numpy as np

from vbdiar.kaldi.utils import read_txt_matrix
from vbdiar.vad import get_vad
from vbdiar.utils import mkdir_p
from vbdiar.utils.utils import Utils
from vbdiar.embeddings.embedding import extract_embeddings
from vbdiar.scoring.diarization import Diarization
from vbdiar.scoring.normalization import Normalization
from vbdiar.kaldi.xvector_extraction import KaldiXVectorExtraction
from vbdiar.features.segments import get_segments, get_num_segments
from vbdiar.kaldi.mfcc_features_extraction import KaldiMFCCFeatureExtraction

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

CDIR = os.path.dirname(os.path.realpath(__file__))

def _process_files(dargs):
    """

    Args:
        dargs:

    Returns:

    """
    fns, kwargs = dargs
    ret = []
    for fn in fns:
        ret.append(process_file(file_name=fn, **kwargs))
    return ret

def process_files(fns, wav_dir, vad_dir, out_dir, features_extractor, embedding_extractor, max_size,
                  tolerance, wav_suffix='.wav', vad_suffix='.lab.gz', n_jobs=1):
    """ Process all files from list.

    Args:
        fns (list): name of files to process
        wav_dir (str): directory with wav files
        vad_dir (str): directory with vad files
        out_dir (str|None): output directory
        features_extractor (Any): intialized object for feature extraction
        embedding_extractor (Any): initialized object for embedding extraction
        max_size (int): maximal size of window in ms
        tolerance (int): accept given number of frames as speech even when it is marked as silence
        wav_suffix (str): suffix of wav files
        vad_suffix (str): suffix of vad files
        n_jobs (int): number of jobs to run in parallel

    Returns:
        List[EmbeddingSet]
    """
    kwargs = dict(wav_dir=wav_dir, vad_dir=vad_dir, out_dir=out_dir, features_extractor=features_extractor,
                  embedding_extractor=embedding_extractor, tolerance=tolerance, max_size=max_size,
                  wav_suffix=wav_suffix, vad_suffix=vad_suffix, )
    if n_jobs == 1:
        ret = _process_files((fns, kwargs))
    else:
        pool = multiprocessing.Pool(n_jobs)
        ret = pool.map(_process_files, ((part, kwargs) for part in Utils.partition(fns, n_jobs)))
    return [item for sublist in ret for item in sublist]

def process_file(wav_dir, vad_dir, out_dir, file_name, features_extractor, embedding_extractor,
                 max_size, tolerance, wav_suffix='.wav', vad_suffix='.lab.gz'):
    """ Process single audio file.

    Args:
        wav_dir (str): directory with wav files
        vad_dir (str): directory with vad files
        out_dir (str): output directory
        file_name (str): name of the file
        features_extractor (Any): intialized object for feature extraction
        embedding_extractor (Any): initialized object for embedding extraction
        max_size (int): maximal size of window in ms
        tolerance (int): accept given number of frames as speech even when it is marked as silence
        wav_suffix (str): suffix of wav files
        vad_suffix (str): suffix of vad files

    Returns:
        EmbeddingSet
    """
    logger.info('Processing file {}.'.format(file_name.split()[0]))
    num_speakers = None
    if len(file_name.split()) > 1:  # number of speakers is defined
        file_name, num_speakers = file_name.split()[0], int(file_name.split()[1])

    wav_dir, vad_dir = os.path.abspath(wav_dir), os.path.abspath(vad_dir)
    if out_dir:
        out_dir = os.path.abspath(out_dir)

    # extract features
    _, features = features_extractor.audio2features(os.path.join(wav_dir, '{}{}'.format(file_name, wav_suffix)))

    # load voice activity detection from file
    vad, _, _ = get_vad('{}{}'.format(os.path.join(vad_dir, file_name), vad_suffix), features.shape[0])

    # parse segments and split features
    features_dict = {}
    for seg in get_segments(vad, max_size, tolerance):
        start, end = get_num_segments(seg[0]), get_num_segments(seg[1])
        if seg[0] > features.shape[0] - 1 or seg[1] > features.shape[0] - 1:
            raise ValueError('Unexpected features dimensionality - check VAD input or audio.')
        features_dict['{}_{}'.format(start, end)] = features[seg[0]:seg[1]]

    # extract embedding for each segment
    embedding_set = extract_embeddings(features_dict, embedding_extractor)
    embedding_set.name = file_name
    embedding_set.num_speakers = num_speakers

    # save embeddings if required
    if out_dir is not None:
        mkdir_p(os.path.join(out_dir, os.path.dirname(file_name)))
        embedding_set.save(os.path.join(out_dir, '{}.pkl'.format(file_name)))

    return embedding_set

def set_mkl(num_cores=1):
    """ Set number of cores for mkl library.

    Args:
        num_cores (int): number of cores
    """
    try:
        mkl_rt = ctypes.CDLL('libmkl_rt.so')
        mkl_rt.mkl_set_dynamic(ctypes.byref(ctypes.c_int(0)))
        mkl_rt.mkl_set_num_threads(ctypes.byref(ctypes.c_int(num_cores)))
    except OSError:
        logger.warning('Failed to import libmkl_rt.so, it will not be possible to use mkl backend.')

if __name__ == '__main__':
    parser = argparse.ArgumentParser('Extract embeddings used for diarization from audio wav files.')

    # required
    parser.add_argument('-l', '--input-list', help='list of input files without suffix',
                        action='store', required=True)
    parser.add_argument('-c', '--configuration', help='input configuration of models',
                        action='store', required=True)

    # not required
    parser.add_argument('--audio-dir',
                        help='directory with audio files in .wav format - 8000Hz, 16bit-s, 1c', required=False)
    parser.add_argument('--vad-dir',
                        help='directory with lab files - Voice/Speech activity detection', required=False)
    parser.add_argument('--in-emb-dir',
                        help='input directory containing embeddings', required=False)
    parser.add_argument('--out-emb-dir',
                        help='output directory for storing embeddings', required=False)
    parser.add_argument('--norm-list',
                        help='list of normalization files without suffix', required=False)
    parser.add_argument('--in-rttm-dir',
                        help='input directory with rttm files', required=False)
    parser.add_argument('--out-rttm-dir',
                        help='output directory for storing rttm files', required=False)
    parser.add_argument('-wav-suffix',
                        help='wav file suffix', required=False)
    parser.add_argument('-vad-suffix',
                        help='Voice Activity Detector file suffix', required=False)
    parser.add_argument('-rttm-suffix',
                        help='rttm file suffix', required=False)
    parser.add_argument('--min-window-size',
                        help='minimal window size for embedding clustering in ms', type=int, required=False)
    parser.add_argument('--max-window-size',
                        help='maximal window size for extracting embedding in ms', type=int, required=False)
    parser.add_argument('--vad-tolerance',
                        help='tolerance critetion for ignoring frames of silence', type=float, required=False)
    parser.add_argument('-j', '--num-threads',
                        help='number of processor threads to use', required=False, type=int, default=1)
    parser.add_argument('--max-num-speakers',
                        help='maximal number of speakers', required=False)
    parser.set_defaults(max_num_speakers=10)
    parser.set_defaults(wav_suffix='.wav')
    parser.set_defaults(vad_suffix='.lab.gz')
    parser.set_defaults(rttm_suffix='.rttm')
    parser.set_defaults(min_window_size=1000)
    parser.set_defaults(max_window_size=3000)
    parser.set_defaults(vad_tolerance=0)
    args = parser.parse_args()

    logger.info('Running `{}`.'.format(' '.join(sys.argv)))

    set_mkl(1)

    # initialize extractor
    config = Utils.read_config(args.configuration)

    config_mfcc = config['MFCC']
    config_path = os.path.abspath(config_mfcc['config_path'])
    if not os.path.isfile(config_path):
        raise ValueError('Path to MFCC configuration `{}` not found.'.format(config_path))
    features_extractor = KaldiMFCCFeatureExtraction(
        config_path=config_path, apply_cmvn_sliding=config_mfcc['apply_cmvn_sliding'],
        norm_vars=config_mfcc['norm_vars'], center=config_mfcc['center'], cmn_window=config_mfcc['cmn_window'])

    config_embedding_extractor = config['EmbeddingExtractor']
    embedding_extractor = KaldiXVectorExtraction(
        nnet=os.path.abspath(config_embedding_extractor['nnet']), use_gpu=config_embedding_extractor['use_gpu'],
        min_chunk_size=config_embedding_extractor['min_chunk_size'],
        chunk_size=config_embedding_extractor['chunk_size'],
        cache_capacity=config_embedding_extractor['cache_capacity'])

    config_transforms = config['Transforms']
    mean, lda, use_l2_norm = \
        config_transforms.get('mean'), config_transforms.get('lda'), config_transforms.get('use_l2_norm')

    files = [line.rstrip('\n') for line in open(args.input_list)]

    # extract embeddings
    if args.in_emb_dir is None:
        if args.audio_dir is None:
            raise ValueError('At least one of `--in-emb-dir` or `--audio-dir` must be specified.')
        if args.vad_dir is None:
            raise ValueError('`--audio-dir` was specified, `--vad-dir` must be specified too.')
        embeddings = process_files(
            fns=files, wav_dir=args.audio_dir, vad_dir=args.vad_dir, out_dir=args.out_emb_dir,
            features_extractor=features_extractor, embedding_extractor=embedding_extractor,
            max_size=args.max_window_size, tolerance=args.vad_tolerance, wav_suffix=args.wav_suffix,
            vad_suffix=args.vad_suffix, n_jobs=args.num_threads)
    else:
        embeddings = args.in_emb_dir

    # initialize normalization
    if args.norm_list is not None:
        norm = Normalization(norm_list=args.norm_list, audio_dir=args.audio_dir,
                             in_rttm_dir=args.in_rttm_dir, in_emb_dir=args.in_emb_dir,
                             out_emb_dir=args.out_emb_dir, min_length=args.min_window_size,
                             embedding_extractor=embedding_extractor, features_extractor=features_extractor,
                             wav_suffix=args.wav_suffix, rttm_suffix=args.rttm_suffix, n_jobs=args.num_threads)
    else:
        norm = None

    # load transformations if specified
    if not norm:
        if mean:
            with open(mean) as f:
                mean = np.fromstring(f.readline().replace('[', '').replace(']', ''), sep=' ')
    else:
        mean = norm.mean
    if lda:
        # from some reason, matrix with kaldi transformation has 1 extra column
        lda = read_txt_matrix(lda).values()[0][:, :-1]

    # run diarization
    diar = Diarization(args.input_list, embeddings, embeddings_mean=mean, lda=lda, use_l2_norm=use_l2_norm, norm=norm)
    scores = diar.score_embeddings(args.min_window_size, args.max_num_speakers)

    if args.in_rttm_dir:
        diar.evaluate(scores=scores, in_rttm_dir=args.in_rttm_dir, collar_size=0.25, evaluate_overlaps=False)

    if args.out_rttm_dir is not None:
        diar.dump_rttm(scores, args.out_rttm_dir)


import shlex
from subprocess import Popen, PIPE
import sys
from . import util

def shell_exec(command, cwd=None):
    """execute commands and return stdout"""
    if isinstance(command, list):
        command_list = command
    else:
        command_list = shlex.split(command)
    try:
        proc = Popen(command_list,
                     stdin=PIPE,
                     stdout=PIPE,
                     stderr=PIPE,
                     cwd=cwd)
        stdout, err = proc.communicate()
        if proc.returncode == 0:
            # If command exit code is 0, assume stderr is informational only.
            # This probably won't work forever, but fits most of our current
            # use cases.
            err = None
        return util.ensure_string(stdout), err
    except FileNotFoundError:
        write_missing_binary_error()
        sys.exit(1)
    except BaseException as e:
        raise e

def write_missing_binary_error():
    sys.stderr.write("""qri command-line binary not found. It is either not installed, or PATH needs to be assigned. Please get the latest release from https://github.com/qri-io/qri, then run this command again.\n""")

def write_missing_cloud_api(method):
    sys.stderr.write("""Cloud API cannot "{}", and qri command-line binary not found. You can either `get` using cloud, or install the qri command-line binary. To do that, please get the latest release from https://github.com/qri-io/qri, assign your PATH, then run this command again.\n""".format(method))


import sys
from PyQt5.QtCore import QCoreApplication, Qt
from PyQt5.QtGui import QIcon, QColor
from PyQt5.QtWidgets import QApplication, QWidget, QMainWindow, QPushButton, QAction, QMessageBox, QVBoxLayout, QTabWidget, QFormLayout
from PyQt5.QtWidgets import QCalendarWidget, QFontDialog, QColorDialog, QTextEdit, QFileDialog
from PyQt5.QtWidgets import QCheckBox, QProgressBar, QComboBox, QLabel, QStyleFactory, QLineEdit, QInputDialog, QHBoxLayout, QGridLayout

class window(QMainWindow):

    def __init__(self):
        super(window, self).__init__()
        self.setGeometry(500, 500, 480, 320)
        self.setWindowTitle('PyQT5 Tabs demo')
        self.home()

    def home(self):
        self.table_widget = MyTabWidget(self)
        self.setCentralWidget(self.table_widget)

        self.show()

class MyTabWidget(QTabWidget):
    def __init__(self, parent):
        super(QWidget, self).__init__(parent)
        self.layout = QGridLayout(self)
        # self.layout.setSpacing(2)

        self.tabs = QTabWidget()
        self.tab1 = QWidget()
        self.tab2 = QWidget()

        self.tabs.addTab(self.tab1, 'Process Raw Data')
        self.tabs.addTab(self.tab2, 'Generate Sign Off')

################ tab 1
        self.tab1.layout = QGridLayout(self)
        nameLabel = QLabel('Raw File Path:')
        self.textbox = QLineEdit()
        btnSelect = QPushButton('...')
        btnSelect.clicked.connect(self.select_file)
        btnQuit = QPushButton('Quit')
        btnQuit.clicked.connect(self.close_application)
        btnRun1 = QPushButton('Run')
        btnRun1.clicked.connect(self.fn1)

        self.tab1.layout.addWidget(nameLabel, 0, 0)
        self.tab1.layout.addWidget(self.textbox, 0, 1)
        self.tab1.layout.addWidget(btnSelect, 0, 2)
        self.tab1.layout.addWidget(btnQuit, 3, 0)
        self.tab1.layout.addWidget(btnRun1, 0, 3)
        self.tab1.setLayout(self.tab1.layout)

################ tab 2
        self.tab2.layout = QGridLayout(self)
        nameLabel1 = QLabel('Processed File Path:')
        self.textbox1 = QLineEdit()
        btnSelect1 = QPushButton('...')
        btnSelect1.clicked.connect(self.select_file1)
        nameLabel2 = QLabel('Total Jobs Path:')
        self.textbox2 = QLineEdit()
        btnSelect2 = QPushButton('...')
        btnSelect2.clicked.connect(self.select_file2)
        btnRun2 = QPushButton('Run')
        btnRun2.clicked.connect(self.fn2)
        btnQuit2 = QPushButton('Quit')
        btnQuit2.clicked.connect(self.close_application)

        self.tab2.layout.addWidget(nameLabel1, 0, 0)
        self.tab2.layout.addWidget(self.textbox1, 0, 1)
        self.tab2.layout.addWidget(btnSelect1, 0, 2)
        self.tab2.layout.addWidget(nameLabel2, 1, 0)
        self.tab2.layout.addWidget(self.textbox2, 1, 1)
        self.tab2.layout.addWidget(btnSelect2, 1, 2)
        self.tab2.layout.addWidget(btnRun2, 2, 1)
        self.tab2.layout.addWidget(btnQuit2, 3, 0)
        self.tab2.setLayout(self.tab2.layout)

############### add tabs to Widget
        self.layout.addWidget(self.tabs)
        self.setLayout(self.layout)

    def select_file(self):
        self.file_name, _ = QFileDialog.getOpenFileName(self, 'Open File', options=QFileDialog.DontUseNativeDialog)
        self.textbox.setText(self.file_name)

    def select_file1(self):
        self.file_name1, _ = QFileDialog.getOpenFileName(self, 'Open File', options=QFileDialog.DontUseNativeDialog)
        self.textbox1.setText(self.file_name1)

    def select_file2(self):
        self.file_name2, _ = QFileDialog.getOpenFileName(self, 'Open File', options=QFileDialog.DontUseNativeDialog)
        self.textbox2.setText(self.file_name2)

    def close_application(self):
        choice = QMessageBox.question(self, 'Message',
                                     "Are you sure to quit?", QMessageBox.Yes |
                                     QMessageBox.No, QMessageBox.No)

        if choice == QMessageBox.Yes:
            # print('quit application')
            sys.exit()
        else:
            pass

    def fn1(self):
        pass

    def fn2(self):
        pass

if __name__ == '__main__':

    def run():
        app = QApplication(sys.argv)
        Gui = window()
        sys.exit(app.exec_())

    run()


#coding: utf-8
# +-------------------------------------------------------------------
# | 宝塔Linux面板
# +-------------------------------------------------------------------
# | Copyright (c) 2015-2099 宝塔软件(http://bt.cn) All rights reserved.
# +-------------------------------------------------------------------
# | Author: 黄文良 <287962566@qq.com>
# +-------------------------------------------------------------------
import system,psutil,time,public,db,os,sys,json
os.chdir('/www/server/panel')
sm = system.system();
taskConfig = json.loads(public.ReadFile('config/task.json'))

oldEdate = None

from BTPanel import cache

def control_init():
    sql = db.Sql().dbfile('system')
    csql = '''CREATE TABLE IF NOT EXISTS `load_average` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`pro` REAL,
`one` REAL,
`five` REAL,
`fifteen` REAL,
`addtime` INTEGER
)'''
    sql.execute(csql,())
    public.M('sites').execute("alter TABLE sites add edate integer DEFAULT '0000-00-00'",());
    public.M('sites').execute("alter TABLE sites add type_id integer DEFAULT 0",());

    sql = db.Sql()
    csql = '''CREATE TABLE IF NOT EXISTS `site_types` (
`id` INTEGER PRIMARY KEY AUTOINCREMENT,
`name` REAL,
`ps` REAL
)'''
    sql.execute(csql,())
    filename = '/www/server/nginx/off'
    if os.path.exists(filename): os.remove(filename)
    try:
        init_file = '/etc/init.d/bt'
        src_file = '/www/server/panel/init.sh'
        md51 = public.md5(init_file)
        md52 = public.md5(src_file)
        if md51 != md52:
            import shutil
            shutil.copyfile(src_file,init_file)
    except:pass
    public.writeFile('/var/bt_setupPath.conf','/www')
    clean_session()

#清理多余的session文件
def clean_session():
    try:
        session_path = r'/dev/shm/session_py' + str(sys.version_info[0])
        if not os.path.exists(session_path): return False
        now_time = time.time()
        p_time = 86400
        for fname in os.listdir(session_path):
            filename = os.path.join(session_path,fname)
            if not os.path.exists(filename): continue
            modify_time = os.path.getmtime(filename)
            if (now_time - modify_time) > p_time: os.remove(filename)
        return True
    except:return False

#监控任务
def control_task():

    global sm,taskConfig
    if not taskConfig['control']['open']: return False
    day = taskConfig['control']['day'];
    if day < 1:

        return False

    sql = db.Sql().dbfile('system')

    #取当前CPU Io
    cpuUsed = sm.get_cpu_percent()
    memUsed = get_mem_used()

    #取当前网络Io
    networkInfo = sm.GetNetWork(False)

    #取磁盘Io
    if os.path.exists('/proc/diskstats'):
        diskInfo = sm.get_io_info()

    addtime = int(time.time())
    deltime = addtime - (day * 86400)

    data = (cpuUsed,memUsed,addtime)
    sql.table('cpuio').add('pro,mem,addtime',data)
    sql.table('cpuio').where("addtime<?",(deltime,)).delete();

    data = (networkInfo['up'],networkInfo['down'],networkInfo['upTotal'],networkInfo['downTotal'],networkInfo['downPackets'],networkInfo['upPackets'],addtime)
    sql.table('network').add('up,down,total_up,total_down,down_packets,up_packets,addtime',data)
    sql.table('network').where("addtime<?",(deltime,)).delete();

    if os.path.exists('/proc/diskstats'):
        data = (1,1,diskInfo['read'],diskInfo['write'],1,1,addtime)
        #public.writeFile('/tmp/1.txt',str((time.time(),data)) + "\n",'a+')
        sql.table('diskio').add('read_count,write_count,read_bytes,write_bytes,read_time,write_time,addtime',data)
        sql.table('diskio').where("addtime<?",(deltime,)).delete();

    #LoadAverage
    load_average = sm.GetLoadAverage(None)
    lpro = round((load_average['one'] / load_average['max']) * 100,2)
    if lpro > 100: lpro = 100;
    sql.table('load_average').add('pro,one,five,fifteen,addtime',(lpro,load_average['one'],load_average['five'],load_average['fifteen'],addtime))

#取内存使用率
def get_mem_used():
    mem = psutil.virtual_memory()
    memInfo = {'memTotal':mem.total/1024/1024,'memFree':mem.free/1024/1024,'memBuffers':mem.buffers/1024/1024,'memCached':mem.cached/1024/1024}
    tmp = memInfo['memTotal'] - memInfo['memFree'] - memInfo['memBuffers'] - memInfo['memCached']
    tmp1 = memInfo['memTotal'] / 100
    return int(tmp / tmp1)

#软件安装任务
def install_task():
    if cache.get('install_task'): return True
    if cache.get('install_exists'): return True
    sql = db.Sql()
    sql.table('tasks').where("status=?",('-1',)).setField('status','0')
    taskArr = sql.table('tasks').where("status=?",('0',)).field('id,type,execstr').order("id asc").select();
    cache.set('install_exists',True)
    cache.delete('install_task')
    logPath = '/tmp/panelExec.log'
    for value in taskArr:
        start = int(time.time());
        if not sql.table('tasks').where("id=?",(value['id'],)).count(): continue;
        sql.table('tasks').where("id=?",(value['id'],)).save('status,start',('-1',start))
        if value['type'] == 'download':
            import downloadFile
            argv = value['execstr'].split('|bt|')
            downloadFile.downloadFile().DownloadFile(argv[0],argv[1])
        elif value['type'] == 'execshell':
           os.system(value['execstr'] + " > " + logPath + " 2>&1")
        end = int(time.time())
        sql.table('tasks').where("id=?",(value['id'],)).save('status,end',('1',end))
    cache.delete('install_exists')

#网站到期处理
def site_end_task():
    global oldEdate
    if not oldEdate: oldEdate = public.readFile('data/edate.pl')
    if not oldEdate: oldEdate = '0000-00-00'
    mEdate = time.strftime('%Y-%m-%d',time.localtime())
    if oldEdate == mEdate: return False
    edateSites = public.M('sites').where('edate>? AND edate<? AND (status=? OR status=?)',('0000-00-00',mEdate,1,u'正在运行')).field('id,name').select()
    import panelSite,common
    siteObject = panelSite.panelSite()
    for site in edateSites:
        get = common.dict_obj()
        get.id = site['id']
        get.name = site['name']
        siteObject.SiteStop(get)
    oldEdate = mEdate
    public.writeFile('data/edate.pl',mEdate)

#PHP守护
def php_safe_task():
    if not os.path.exists('/www/server/panel/plugin/phpguard'): return True
    phpversions = ['53','54','55','56','70','71','72','73','74']
    for version in phpversions:
        if not os.path.exists('/etc/init.d/php-fpm-'+version): continue;
        if check_php_version(version): continue;
        if start_php_version(version):
            public.WriteLog('PHP守护程序','检测到PHP-' + version + '处理异常,已自动修复!')

#处理指定PHP版本
def start_php_version(version):
    fpm = '/etc/init.d/php-fpm-'+version
    if not os.path.exists(fpm): return False;

    #尝试重载服务
    os.system(fpm + ' reload');
    if check_php_version(version): return True;

    #尝试重启服务
    cgi = '/tmp/php-cgi-'+version
    pid = '/www/server/php'+version+'/php-fpm.pid';
    os.system('pkill -9 php-fpm-'+version)
    time.sleep(0.5);
    if not os.path.exists(cgi): os.remove(cgi)
    if not os.path.exists(pid): os.remove(pid)
    os.system(fpm + ' start');
    if check_php_version(version): return True;

    #检查是否正确启动
    if os.path.exists(cgi): return True;

#检查指定PHP版本
def check_php_version(version):
    url = 'http://127.0.0.1/phpfpm_'+version+'_status';
    result = public.httpGet(url);
    #检查nginx
    if result.find('Bad Gateway') != -1: return False;
    #检查Apache
    if result.find('Service Unavailable') != -1: return False;
    if result.find('Not Found') != -1: check_phpinfo();

    #检查Web服务是否启动
    if result.find('Connection refused') != -1:
        global isTask
        if os.path.exists(isTask):
            isStatus = public.readFile(isTask);
            if isStatus == 'True': return True;
        filename = '/etc/init.d/nginx';
        if os.path.exists(filename): os.system(filename + ' start');
        filename = '/etc/init.d/httpd';
        if os.path.exists(filename): os.system(filename + ' start');
    return True;

#检测PHPINFO配置
def check_phpinfo():
    php_versions = ['53','54','55','56','70','71','72','73','74'];
    setupPath = '/www/server';
    path = setupPath +'/panel/vhost/nginx/phpinfo.conf';
    if not os.path.exists(path):
        opt = "";
        for version in php_versions:
            opt += "\n\tlocation /"+version+" {\n\t\tinclude enable-php-"+version+".conf;\n\t}";

        phpinfoBody = '''server
{
    listen 80;
    server_name 127.0.0.2;
    allow 127.0.0.1;
    index phpinfo.php index.html index.php;
    root  /www/server/phpinfo;
%s
}''' % (opt,);
        public.writeFile(path,phpinfoBody);

    path = setupPath + '/panel/vhost/apache/phpinfo.conf';
    if not os.path.exists(path):
        opt = "";
        for version in php_versions:
            opt += """\n<Location /%s>
    SetHandler "proxy:unix:/tmp/php-cgi-%s.sock|fcgi://localhost"
</Location>""" % (version,version);

        phpinfoBody = '''
<VirtualHost *:80>
DocumentRoot "/www/server/phpinfo"
ServerAdmin phpinfo
ServerName 127.0.0.2
%s
<Directory "/www/server/phpinfo">
    SetOutputFilter DEFLATE
    Options FollowSymLinks
    AllowOverride All
    Order allow,deny
    Allow from all
    DirectoryIndex index.php index.html index.htm default.php default.html default.htm
</Directory>
</VirtualHost>
''' % (opt,);
        public.writeFile(path,phpinfoBody);

class JobsConfig:
    JOBS = []
    SCHEDULER_API_ENABLED = True
    def __init__(self):
        global taskConfig
        self.JOBS = taskConfig['JOBS']


def check_all(x):
    check = []
    for i in range(len(attacker)):
        if deffender[i] == x:
            check.append(attacker[i])
    return check

def check_all_deff(x):
    check = []
    for i in range(len(attacker)):
        if attacker[i] == x:
            check.append(deffender[i])
    return check

def reku(arguments, arguments_in, arguments_out):
    for j in range(len(arguments)):
        args_two = arguments.copy()
        arg_in_two = arguments_in.copy()
        arg_out_two = arguments_out.copy()
        arg_in_two.append(args_two[j])
        args_two.remove(args_two[j])
        bul = True
        while bul:
            bul = False
            i = 0
            while i < len(args_two):
                check = check_all(args_two[i])
                if any(x in arg_in_two for x in check):
                    arg_out_two.append(args_two[i])
                    args_two.remove(args_two[i])
                    bul = True
                else:
                    i += 1
            i = 0
            while i < len(args_two):
                check = check_all_deff(args_two[i])
                if any(x in arg_in_two for x in check):
                    arg_out_two.append(args_two[i])
                    args_two.remove(args_two[i])
                    bul = True
                else:
                    i += 1

            i = 0
            while i < len(args_two):
                check = check_all(args_two[i])
                if all(x in arg_out for x in check):
                    arg_in_two.append(args_two[i])
                    args_two.remove(args_two[i])
                    bul = True
                else:
                    i += 1

        if len(args_two) != 0:
            reku(args_two, arg_in_two, arg_out_two)
        else:
            prefered.append(arg_in_two)

f = [x.strip() for x in open("dung2.txt", 'r').readlines()]
args = f[1].split(',')
a = f[-1].split('),(')
a[0] = a[0][1:4]
a[-1] = a[-1][0:3]
attacker = []
deffender = []
for i in range(len(a)):
    attacker.append(a[i].split(',')[0])
    deffender.append(a[i].split(',')[1])
# for i in range(len(a)):
#     print(attacker[i], deffender[i])
arg_in = []
arg_out = []

i = 0
while i < len(args):
    if args[i] not in deffender:
        arg_in.append(args[i])
        args.remove(args[i])
    else:
        i += 1

bul = True
while bul:
    bul = False
    i = 0
    while i < len(args):
        check = check_all(args[i])
        if any(x in arg_in for x in check):
            arg_out.append(args[i])
            args.remove(args[i])
            bul = True
        else:
            i += 1
    i = 0
    while i < len(args):
        check = check_all(args[i])
        if all(x in arg_out for x in check):
            arg_in.append(args[i])
            args.remove(args[i])
            bul = True
        else:
            i += 1
print("Grounded:", arg_in)
prefered = []
if len(args) != 0:
    reku(args, arg_in, arg_out)

prefered = list(sorted(x) for x in prefered)
prefered = list(set(str(x) for x in prefered))
for i in range(len(prefered)):
    print("Prefered:", prefered[i])

Wstęp do systemów sztucznej inteligencji/lab03/rekurencja.py


import canopen

from controller_ps2 import *

class f124():
    def __init__(self, net, node, eds):
        self.rpm_scale = 5120000/1875
        self.motor_mode_dict = {'pulse':-1,'immediate speed':-3, 'torque':4, 'localtion':1, 'speed':3, 'home':6, 'interpolation':7, 'ecan_location':8, 'ecan_speed':9, 'ecan_torque':10}
        self.motor_status_list = ['Ready_on', 'Switched_on', 'Operatetion_enable', 'Fault', 'Voltage_enable', 'Quick_stop', 'Switchon_disable', 'Warning', 'Manunfacture0', 'Remote', 'Target_reached', 'Intlim_active', 'Setpoint_Ack', 'Fllowing_Error', 'Commutation_found', 'Reference_Found']
        self.motor_control_dict = {'enable_speed':0x0F, 'enable_localtion':0x2F, 'disable':0x06, 'reset':'0x86'}

        self.node = net.add_node(node, eds)
    def set_node_status(self, state):
        self.node.state = state
    def set_motor_mode(self, mode):
        self.node.sdo['Modes_of_operation'].raw = self.motor_mode_dict[mode]
    def set_motor_speed(self, speed):
        self.node.sdo['Target_velocity'].raw = speed*self.rpm_scale
    def get_motor_speed(self):
        return self.node.sdo['Velocity_actual_value'].raw/self.rpm_scale
    def set_motor_control(self, state):
        self.node.sdo['Controlword'].raw = self.motor_control_dict[state]
    def get_motor_state(self):
        return self.node.sdo['Statusword'].raw
    def set_motor_direct(self, dir=0):
        self.node.sdo['Polarity'].raw = dir

async def motion_control(q):
    network = canopen.Network()
    network.connect(channel='can0', bustype='socketcan')
#    network.connect(channel=0 , bustype='canalystii', bitrate=500000)
    motor1 = f124(network, 1, 'KINCO-JDFD.EDS')
    motor2 = f124(network, 2, 'KINCO-JDFD.EDS')

    motor1.node.sdo['Controlword'].raw = 0x86
    motor2.node.sdo['Controlword'].raw = 0x86
#    time.sleep(0.5)
#    motor2.set_motor_control('disable')
#    motor2.set_motor_control('reset')
    motor1.set_motor_direct(1)
    motor1.set_motor_mode('speed')
    #motor1.set_motor_direct(1)
    motor2.set_motor_mode('speed')
    motor1.node.sdo['Profile_acceleration'].raw = 163.84*40
    motor1.node.sdo['Profile_deceleration'].raw = 163.84*40
    motor2.node.sdo['Profile_acceleration'].raw = 163.84*40
    motor2.node.sdo['Profile_deceleration'].raw = 163.84*40
    motor1.set_motor_speed(0)
    motor2.set_motor_speed(0)
    motor1.set_motor_control('enable_speed')
    motor2.set_motor_control('enable_speed')
    print('motor init ok')
    while True:
        command = await q.get()
        print('left_motor_speed: {}, right_motor_speed: {}'.format(command[0],command[1]))
        motor1.set_motor_speed(command[0])
        motor2.set_motor_speed(command[1])
        await asyncio.sleep(0.005)

async def joystick_control(event_queue, command_q):
    motor1_speed = 0
    motor2_speed = 0
    diff = 0
    event_q = event_queue
    speed_up = 1
    while True:
        event = await event_q.get()
        #event_q.task_done()
        #print(event)

        if(event[0] == 3):
            if(event[1] == 1):
                motor1_speed = 127-event[2]
            elif(event[1] == 5):
                motor2_speed = 127-event[2]
            elif(event[1] == 2):
                diff = event[2]-127
            command_q.put_nowait([(motor1_speed*10+diff*abs(motor1_speed)/31.75+3*diff)*speed_up, (motor1_speed*10-diff*abs(motor1_speed)/31.75-3*diff)*speed_up])
        elif(event[0] == 1):
            if(event[1] == 0x127):
                speed_up = event[2]*1.36+1
                #speed_up = event[2]+1
            #elif(event[1] == 0x126):
            #    speed_up = speed_up + (speed_up-2)event[2]*1.18
            #print(motor1_speed, motor2_speed)
            command_q.put_nowait([(motor1_speed*10+diff*abs(motor1_speed)/31.75+3*diff)*speed_up, (motor1_speed*10-diff*abs(motor1_speed)/31.75-3*diff)*speed_up])
            #print('command_q size: {}'.format(command_q.qsize()))
        #await asyncio.sleep(0.01)
if __name__ == "__main__":
    dev = find_device()
    q = asyncio.Queue()
    command_q = asyncio.Queue()
    loop = asyncio.get_event_loop()
    tasks = [asyncio.Task(read_event(dev, q)), asyncio.Task(motion_control(command_q)), asyncio.Task(joystick_control(q, command_q))]
    #tasks = [asyncio.Task(read_event(dev, q)), asyncio.Task(joystick_control(q, command_q))]
    loop.run_until_complete(asyncio.wait(tasks))


import math
from leaf import Leaf
from huffman import Huffman

class ARHC:

    """
    Implementation of Adaptive Run-length Huffman Compressor.

    :param prob1: Probability of one.
    """

    def __init__(self, prob1):
        self.prob1 = prob1

    def calculateOptimalRunLength(self):
        """ Calculate the optimal run-length. """
        return max(1, int(round(math.log(0.5) /
                         math.log(1 - self.prob1.getPredictive1()))))

    def buildSymbols(self, runLength):
        """ Build an alphabet encoding run-lengths. """
        symbols = [Leaf(
            '0' * runLength,
            pow(1 - self.prob1.getPredictive1(), runLength)
        )]
        for i in range(runLength):
            symbols.append(Leaf(
                '0' * i + '1',
                pow(1 - self.prob1.getPredictive1(), i) *
                    self.prob1.getPredictive1()
            ))
        return symbols

    def buildHuffman(self, bitsLeft):
        """ Build a Huffman symbol code from an alphabet that encodes
            run-lengths. """
        runLength = min(bitsLeft, self.calculateOptimalRunLength())
        symbols = self.buildSymbols(runLength)
        self.huffman = Huffman(symbols)

    def compress(self, inStream, outStream):
        """ Compress the contents of a stream and write the compressed
            contents to another stream. """
        inStream.observeRead(self.prob1.observe)
        while inStream.bitsLeftToRead() > 0:
            self.buildHuffman(inStream.bitsLeftToRead())
            outStream.write(self.huffman.encode(inStream))

    def decompress(self, inStream, outStream):
        """ Decompress the contents of a stream and write the decompressed
            contents to another stream. """
        outStream.observeWrite(self.prob1.observe)
        while outStream.bitsLeftToWrite() > 0:
            self.buildHuffman(outStream.bitsLeftToWrite())
            outStream.write(self.huffman.decode(inStream))


#!/usr/bin/python
def repeatingKeyXOR(plaintext,key):
    pt, k, result = list(plaintext), list(key), ''
    for i in range(len(pt)):
        cipher = chr(ord(pt[i]) ^ ord(k[i%len(k)]))
        result += hex(ord(cipher))[2:]
    return result

def main():
    key = "ICE"
    plaintext = "Burning 'em, if you ain't quick and nimble\nI go crazy when I hear a cymbal"
    ciphertext = repeatingKeyXOR(plaintext,key)

    print("Plaintext =", plaintext)
    print("Key =", key)
    print("Ciphertext =", ciphertext)

if __name__ == "__main__":
    main()


"""
1. Put your game's name as the parameter in the settings_dir line
2. List your game's options and saved state necessities in the settings dict
3. "from settings import *" in other files and refer to settings['screen_width']
	or something.
4. Call save_settings() whenever you update the settings dictionary.
5. There is no step 5, because everything is loaded automatically at startup.

If you add settings that aren't in the save file and would be overwritten by the
loading step, then add the following lines to your game, run it once, and then
remove them:
settings = default_settings()
save_settings()
"""
import pyglet.resource, os, pickle

settings_dir = pyglet.resource.get_settings_path('gw0rp')
settings_path = os.path.join(settings_dir, 'Preferences.txt')

def set(k, v):
    global settings
    settings[k] = v
    globals().update(settings)

def save():
	"""Pickle settings dictionary to the appropriate location"""

	if not os.path.exists(settings_dir):
	    os.makedirs(settings_dir)
	settings_file = open(settings_path,'w')
	pickle.dump(settings,settings_file)
	settings_file.close()
	globals().update(settings)

settings = dict(
	fullscreen = False,
	music_volume = 1.0,
	sound_volume = 1.0,
	save_dir = os.path.join(settings_dir, 'Saved Games'),
	first_launch = True
)

if os.path.exists(settings_path):
	try:
	    settings.update(pickle.load(open(settings_path,'r')))
	except:
	    save()
else:
    try:
        os.makedirs(settings_dir)
    except:
        pass #Windows is being stupid.

if not os.path.exists(settings['save_dir']):
    os.makedirs(os.path.join(settings['save_dir'], 'Autosave'))

globals().update(settings)


from __future__ import print_function

import densenet
import numpy as np
import sklearn.metrics as metrics

from keras.datasets import cifar10
from keras.utils import np_utils
from keras.preprocessing.image import ImageDataGenerator
from keras.optimizers import Adam
from keras.callbacks import ModelCheckpoint
from keras import backend as K

batch_size = 64
nb_classes = 10
nb_epoch = 150

img_rows, img_cols = 32, 32
img_channels = 3

img_dim = (img_channels, img_rows, img_cols) if K.image_dim_ordering() == "th" else (img_rows, img_cols, img_channels)
depth = 40
nb_dense_block = 3
growth_rate = 12
nb_filter = 16
dropout_rate = 0.0 # 0.0 for data augmentation

model = densenet.create_dense_net(nb_classes, img_dim, depth, nb_dense_block, growth_rate, nb_filter,
                                  dropout_rate=dropout_rate)
print("Model created")

model.summary()
optimizer = Adam(lr=1e-4) # Using Adam instead of SGD to speed up training
model.compile(loss='categorical_crossentropy', optimizer=optimizer, metrics=["accuracy"])
print("Finished compiling")
print("Building model...")

(trainX, trainY), (testX, testY) = cifar10.load_data()

Y_train = np_utils.to_categorical(trainY, nb_classes)
Y_test = np_utils.to_categorical(testY, nb_classes)

generator = ImageDataGenerator(featurewise_center=True,
                               featurewise_std_normalization=True,
                               rotation_range=10,
                               width_shift_range=5./32,
                               height_shift_range=5./32)

generator.fit(trainX, seed=0, augment=True)

test_generator = ImageDataGenerator(featurewise_center=True,
                                    featurewise_std_normalization=True)

test_generator.fit(testX, augment=True, seed=0)

# Load model
model.load_weights("weights/DenseNet-40-12-CIFAR10.h5")
print("Model loaded.")

model.fit_generator(generator.flow(trainX, Y_train, batch_size=batch_size), samples_per_epoch=len(trainX), nb_epoch=nb_epoch,
                   callbacks=[ModelCheckpoint("weights/DenseNet-40-12-CIFAR10.h5", monitor="val_acc", save_best_only=True,
                                              save_weights_only=True)],
                   validation_data=test_generator.flow(testX, testY, batch_size=batch_size),
                   nb_val_samples=testX.shape[0], verbose=1)

scores = model.evaluate_generator(test_generator.flow(testX, testY, nb_epoch), testX.shape[0])
print("Accuracy = %f" % (100 * scores[1]))
print("Error = %f" % (100 - 100 * scores[1]))


__author__ = 'hazel'

class Solution:
    # @param matrix, a list of lists of integers
    # @param target, an integer
    # @return a boolean
    def searchMatrix(self, matrix, target):
        i, j = 0, len(matrix) - 1
        while i < len(matrix) and j >= 0:
            if target < matrix[i][j]:
                j -= 1
            elif target > matrix[i][j]:
                i += 1
            else:
                return True
        return False


"""Main module."""
import time as _time
from threading import Thread as _Thread
from copy import deepcopy as _dcopy

import numpy as _np
import scipy.optimize as _scyopt

from mathphys.functions import save_pickle as _save_pickle

from siriuspy.namesys import SiriusPVName as _PVName
from siriuspy.clientconfigdb import ConfigDBClient as _ConfigDBClient
from siriuspy.devices import StrengthConv, PowerSupply, CurrInfoSI, \
    Trigger, Event, EVG, RFGen, Tune, FamBPMs
from siriuspy.sofb.csdev import SOFBFactory
import pyaccel as _pyaccel

from ..utils import ParamsBaseClass as _ParamsBaseClass, \
    ThreadedMeasBaseClass as _ThreadBaseClass

class ACORMParams(_ParamsBaseClass):
    """."""

    def __init__(self):
        """."""
        super().__init__()
        self.nr_points = 5500
        self.acq_rate = 'FAcq'
        self.timeout_bpms = 10  # [s]
        self.ch_kick = 5  # [urad]
        self.cv_kick = 5  # [urad]
        self.rf_kick = 5  # [Hz]
        self.delay_corrs = 50e-3  # [s]
        self.delay_rf = 200e-3  # [s]
        self.exc_duration = 5  # [s]
        self.exc_rf = 4  # [s]

        freqs = self.find_primes(16, start=120)
        self.ch_freqs = freqs[1::2][:6]
        self.cv_freqs = freqs[::2][:8]
        self.nr_sectors_per_acq = 1
        self.sectors_to_measure = _np.arange(1, 21)
        self.meas_bpms_noise = True
        self.meas_rf_line = True

    def __str__(self):
        """."""
        ftmp = '{0:24s} = {1:9.3f}  {2:s}\n'.format
        dtmp = '{0:24s} = {1:9d}  {2:s}\n'.format
        stmp = '{0:24s} = {1:9s}  {2:s}\n'.format

        stg = ''
        stg += dtmp('nr_points', self.nr_points, '')
        stg += stmp('acq_rate', self.acq_rate, '')
        stg += ftmp('timeout_bpms', self.timeout_bpms, '[s]')
        stg += ftmp('ch_kick', self.ch_kick, '[urad]')
        stg += ftmp('cv_kick', self.cv_kick, '[urad]')
        stg += ftmp('rf_kick', self.rf_kick, '[Hz]')
        stg += ftmp('delay_corrs', self.delay_corrs, '[s]')
        stg += ftmp('delay_rf', self.delay_rf, '[s]')
        stg += ftmp('exc_duration', self.exc_duration, '[s]')
        stg += ftmp('exc_rf', self.exc_rf, '[s]')
        stg += stmp('ch_freqs', str(self.ch_freqs), '[Hz]')
        stg += stmp('cv_freqs', str(self.cv_freqs), '[Hz]')
        stg += dtmp('nr_sectors_per_acq', self.nr_sectors_per_acq, '')
        stg += stmp('sectors_to_measure', str(self.sectors_to_measure), '')
        stg += stmp('meas_bpms_noise', str(self.meas_bpms_noise), '')
        stg += stmp('meas_rf_line', str(self.meas_rf_line), '')
        return stg

    @staticmethod
    def find_primes(n_primes, start=3):
        """."""
        primes = []
        i = start
        while True:
            for j in range(3, int(_np.sqrt(i))+1, 2):
                if not i % j:
                    break
            else:
                if i % 2:
                    primes.append(i)
            i += 1
            if len(primes) >= n_primes:
                break
        return _np.array(primes)

# TODO: Ideas for analisys:
# - try to use naff with prior filtering of data,  and making an algorithm to
#   find the frequencies closest to the desired ones
# -
class MeasACORM(_ThreadBaseClass):
    """."""

    def __init__(self, params=None, isonline=True):
        """."""
        params = ACORMParams() if params is None else params
        super().__init__(
            params=params, target=self._do_measure, isonline=isonline)
        self.bpms = dict()

        self.sofb_data = SOFBFactory.create('SI')
        self.configdb = _ConfigDBClient(config_type='si_orbcorr_respm')
        if self.isonline:
            self._create_devices()

    def load_and_apply(self, fname: str):
        """Load and apply `data` and `params` from pickle file.

        Args:
            fname (str): name of the pickle file. Extension is not needed.

        """
        super().load_and_apply(fname)
        if isinstance(self.data, list):
            self.data = {'magnets': self.data}

    @staticmethod
    def fitting_matrix(tim, freqs, num_cycles=None):
        """Create the matrix used for fitting of fourier components.

        The ordering of the matrix is the following:
           mat[i, 2*j] = cos(2*pi*freqs[j]*tim[i])
           mat[i, 2*j+1] = sin(2*pi*freqs[j]*tim[i])

        Args:
            tim (numpy.ndarray): array with times
            freqs (numpy.ndarray): array with frequencies to fit.
            num_cycles (numpy.ndarray, optional): number of cycles of each
                frequency. If not provided, all data range will be considered.

        Returns:
            numpy.ndarray: fitting matrix (len(tim), 2*len(freqs))

        """
        mat = _np.zeros((tim.size, 2*freqs.size))
        arg = 2*_np.pi*freqs[None, :]*tim[:, None]
        cos = _np.cos(arg)
        sin = _np.sin(arg)

        if num_cycles is not None:
            cond = arg > 2*_np.pi*num_cycles[None, :]
            cos[cond] = 0
            sin[cond] = 0
        mat[:, ::2] = cos
        mat[:, 1::2] = sin
        return mat

    @classmethod
    def fit_fourier_components(cls, data, freqs, dtim, num_cycles=None):
        """Fit Fourier components in signal for the given frequencies.

        Args:
            data (numpy.ndarray, NxM): signal to be fitted consisting of M
                columns of data.
            freqs (numpy.ndarray, K): K frequencies to fit Fourier components.
            dtim (numpy.ndarray, N): time vector for data columns.
            num_cycles (num.ndarray, K): number of cycles of each frequency.
                If not provided, all data range will be considered.

        Returns:
            numpy.ndarray, KxM: Fourier amplitudes.
            numpy.ndarray, KxM: Fourier phases (phase==0 means pure sine).
            numpy.ndarray, KxM: Fourier cosine coefficients.
            numpy.ndarray, KxM: Fourier sine coefficients.

        """
        tim = _np.arange(data.shape[0]) * dtim

        mat = cls.fitting_matrix(tim, freqs, num_cycles)
        coeffs, *_ = _np.linalg.lstsq(mat, data, rcond=None)

        cos = coeffs[::2]
        sin = coeffs[1::2]
        amps = _np.sqrt(cos**2 + sin**2)
        phases = _np.arctan2(cos, sin)
        return amps, phases, cos, sin

    @staticmethod
    def fit_fourier_components_naff(data, freqs0, dtim):
        """Not implemented properly yet. Please don't use this."""
        freqs = _np.zeros((len(freqs0), data.shape[1]))
        fourier = _np.zeros((len(freqs0), data.shape[1]), dtype=complex)

        for i in range(data.shape[1]):
            datum = data[:, i]
            fre, four = _pyaccel.naff.naff_general(
                datum, nr_ff=len(freqs0), is_real=True)
            fre = _np.abs(fre)
            idx = _np.argsort(fre)
            fre = fre[idx]
            four = four[idx]
            freqs[:, i] = fre/dtim
            fourier[:, i] = four

        amps = _np.abs(fourier)
        phases = _np.angle(fourier)
        cos = fourier.real
        sin = fourier.imag

        return amps, phases, cos, sin

    @staticmethod
    def calc_correlation(arr1, arr2):
        """Return the linear correlation between respective columns.

        Args:
            arr1 (numpy.ndarray, NxM): first array
            arr2 (numpy.ndarray, NxM): second array

        Returns:
            numpy.ndarray, M: correlation of the ith column of arr1 with ith
                column of arr2.

        """
        corr = (arr1 * arr2).sum(axis=0)
        corr /= _np.linalg.norm(arr1, axis=0)
        corr /= _np.linalg.norm(arr2, axis=0)
        return _np.abs(corr)

    def save_loco_input_data(self, respmat_name: str, overwrite=False):
        """Save in `.pickle` format a dictionary with all LOCO input data.

        Args:
            respmat_name (str): Name of the response matrix. A matrix with
                this name will be saved in configdb.
            overwrite (bool, optional): whether to overwrite existing files.
                Defaults to False.

        """
        bpms_data = self.data['bpms_noise']
        bpms_anly = self.analysis['bpms_noise']
        data = dict()
        data['timestamp'] = bpms_data['timestamp']
        data['rf_frequency'] = bpms_data['rf_frequency']
        data['tunex'] = bpms_data['tunex']
        data['tuney'] = bpms_data['tuney']
        data['stored_current'] = bpms_data['stored_current']
        data['bpm_variation'] = bpms_anly['bpm_variation']
        data['orbmat_name'] = respmat_name
        mat = self.save_respmat_to_configdb(respmat_name)
        data['respmat'] = mat

        _save_pickle(data, f'loco_input_{respmat_name:s}', overwrite=overwrite)

    def save_respmat_to_configdb(self, name: str):
        """Save response matrix to ConfigDb Server.

        Args:
            name (str): name of the matrix to saved.

        Returns:
            numpy.ndarray, 320x281: response matrix. Missing data is filled
                with zeros.

        """
        mat = self.build_respmat()
        self.configdb.insert_config(name, mat)
        return mat

    def build_respmat(self):
        """Build response matrix from previously analysed data.

        Returns:
            numpy.ndarray, 320x281: response matrix. Missing data is filled
                with zeros.

        """
        sofb = self.sofb_data
        mat = _np.zeros((2*sofb.nr_bpms, sofb.nr_corrs), dtype=float)
        anls = self.analysis['magnets']
        for anly in anls:
            mat[:sofb.nr_bpms, anly['mat_idcs']] = anly['mat_colsx']
            mat[sofb.nr_bpms:, anly['mat_idcs']] = anly['mat_colsy']

        anl = self.analysis['rf']
        mat[:sofb.nr_bpms, -1] = anl['mat_colx']
        mat[sofb.nr_bpms:, -1] = anl['mat_coly']
        return mat

    def process_data(
            self, mag_idx_ini=None, mag_min_freq=None, mag_max_freq=None,
            rf_transition_length=10):
        """Process measured data.

        Args:
            mag_idx_ini ([type], optional): initial index of orbit waveform
                where magnets excitation start. Defaults to None.
            mag_min_freq ([type], optional): Frequencies below this value will
                be filtered out before fitting of magnets excitation.`None`
                means no high pass filter will be applied. Defaults to `None`.
            mag_max_freq ([type], optional): Frequencies above this value will
                be filtered out before fitting of magnets excitation. `None`
                means no low pass filter will be applied. Defaults to `None`.
            rf_transition_length (int, optional): Number of indices to ignore
                right before or after RF frequency changes in RF line
                measurements. Defaults to 10.

        """
        self.analysis['magnets'] = self._process_data_magnets(
            self.data['magnets'], mag_idx_ini, mag_min_freq, mag_max_freq)
        rf_data = self.data.get('rf')
        if rf_data is not None:
            self.analysis['rf'] = self._process_data_rf(
                rf_data, rf_transition_length)
        bpms_data = self.data.get('bpms_noise')
        if bpms_data is not None:
            self.analysis['bpms_noise'] = self._process_data_bpms_noise(
                bpms_data)

    def get_magnets_data(self, chs_used, cvs_used):
        """Get magnet related data.

        Args:
            chs_used (list, tuple): CHs used in excitation.
            cvs_used (list, tuple): CVs used in excitation.

        Returns:
            dict: `chs_used` and `cvs_used` related data.

        """
        data = {
            'ch_names': [], 'ch_amplitudes': [], 'ch_offsets': [],
            'ch_kick_amplitudes': [], 'ch_kick_offsets': [],
            'ch_frequency': [], 'ch_num_cycles': [], 'ch_cycle_type': [],
            'cv_names': [], 'cv_amplitudes': [], 'cv_offsets': [],
            'cv_kick_amplitudes': [], 'cv_kick_offsets': [],
            'cv_frequency': [], 'cv_num_cycles': [], 'cv_cycle_type': [],
            }
        for cmn in chs_used:
            data['ch_names'].append(cmn)
            cm = self.devices[cmn]
            conv = self.devices[cmn+':StrengthConv'].conv_current_2_strength
            data['ch_amplitudes'].append(cm.cycle_ampl)
            data['ch_offsets'].append(cm.cycle_offset)
            data['ch_kick_amplitudes'].append(conv(cm.cycle_ampl))
            data['ch_kick_offsets'].append(conv(cm.cycle_offset))
            data['ch_frequency'].append(cm.cycle_freq)
            data['ch_num_cycles'].append(cm.cycle_num_cycles)
            data['ch_cycle_type'].append(cm.cycle_type_str)

        for cmn in cvs_used:
            data['cv_names'].append(cmn)
            cm = self.devices[cmn]
            conv = self.devices[cmn+':StrengthConv'].conv_current_2_strength
            data['cv_amplitudes'].append(cm.cycle_ampl)
            data['cv_offsets'].append(cm.cycle_offset)
            data['cv_kick_amplitudes'].append(conv(cm.cycle_ampl))
            data['cv_kick_offsets'].append(conv(cm.cycle_offset))
            data['cv_frequency'].append(cm.cycle_freq)
            data['cv_num_cycles'].append(cm.cycle_num_cycles)
            data['cv_cycle_type'].append(cm.cycle_type_str)

        trig = self.devices['trigcorrs']
        data['corrs_trig_delay_raw'] = trig.delay_raw
        data['corrs_trig_delta_delay_raw'] = trig.delta_delay_raw
        return data

    def get_bpms_data(self):
        """Get all BPM related data relevant for the measurements.

        Returns:
            dict: BPMs data.

        """
        orbx, orby = self.bpms.get_mturn_orbit(return_sum=False)
        bpm0 = self.bpms.devices[0]
        rf_freq = self.devices['rfgen'].frequency

        data = dict()
        data['orbx'] = orbx
        data['orby'] = orby
        data['bpms_acq_rate'] = bpm0.acq_channel_str
        data['bpms_sampling_frequency'] = self.bpms.get_sampling_frequency(
            self.devices['rfgen'].frequency, data['bpms_acq_rate'])
        data['bpms_nrsamples_pre'] = bpm0.acq_nrsamples_pre
        data['bpms_nrsamples_post'] = bpm0.acq_nrsamples_post
        data['bpms_trig_delay_raw'] = self.devices['trigbpms'].delay_raw
        data['bpms_switching_mode'] = bpm0.switching_mode_str
        data['bpms_switching_frequency'] = self.bpms.get_switching_frequency(
            rf_freq)
        return data

    def get_general_data(self):
        """Get general purpose data.

        Returns:
            dict: general purpose data.

        """
        data = dict()
        data['timestamp'] = _time.time()
        data['rf_frequency'] = self.devices['rfgen'].frequency
        data['stored_current'] = self.devices['currinfo'].current
        data['tunex'] = self.devices['tune'].tunex
        data['tuney'] = self.devices['tune'].tuney
        return data

    # ------------------ Auxiliary Methods ------------------

    def _create_devices(self):
        # Create objects to convert kicks to current
        t00 = _time.time()
        print('Creating kick converters  -> ', end='')
        self.devices.update({
            n+':StrengthConv': StrengthConv(n, 'Ref-Mon')
            for n in self.sofb_data.ch_names})
        self.devices.update({
            n+':StrengthConv': StrengthConv(n, 'Ref-Mon')
            for n in self.sofb_data.cv_names})
        print(f'ET: = {_time.time()-t00:.2f}s')

        # Create objects to interact with correctors
        t00 = _time.time()
        print('Creating correctors       -> ', end='')
        self.devices.update({
            nme: PowerSupply(nme) for nme in self.sofb_data.ch_names})
        self.devices.update({
            nme: PowerSupply(nme) for nme in self.sofb_data.cv_names})
        print(f'ET: = {_time.time()-t00:.2f}s')

        # Create object to get stored current
        t00 = _time.time()
        print('Creating General Devices  -> ', end='')
        self.devices['currinfo'] = CurrInfoSI()
        # Create RF generator object
        self.devices['rfgen'] = RFGen()
        # Create Tune object:
        self.devices['tune'] = Tune(Tune.DEVICES.SI)
        print(f'ET: = {_time.time()-t00:.2f}s')

        # Create BPMs trigger:
        t00 = _time.time()
        print('Creating Timing           -> ', end='')
        self.devices['trigbpms'] = Trigger('SI-Fam:TI-BPM')
        # Create Correctors Trigger:
        self.devices['trigcorrs'] = Trigger('SI-Glob:TI-Mags-Corrs')
        # Create event to start data acquisition sinchronously:
        self.devices['evt_study'] = Event('Study')
        self.devices['evg'] = EVG()
        print(f'ET: = {_time.time()-t00:.2f}s')

        # Create BPMs
        t00 = _time.time()
        print('Creating BPMs             -> ', end='')
        self.bpms = FamBPMs(FamBPMs.DEVICES.SI)
        self.devices['fambpms'] = self.bpms
        print(f'ET: = {_time.time()-t00:.2f}s')

    # ---------------- Data Measurement methods ----------------

    def _do_measure(self):
        if self.params.meas_bpms_noise:
            self.data['bpms_noise'] = self._do_measure_bpms_noise()

        if self._stopevt.is_set():
            print('Stopping...')
            return

        if self.params.meas_rf_line:
            self.data['rf'] = self._do_measure_rf_line()

        if self._stopevt.is_set():
            print('Stopping...')
            return

        self.data['magnets'] = self._do_measure_magnets()

    def _do_measure_bpms_noise(self):
        elt = _time.time()

        print('Measuring BPMs Noise:')

        t00 = _time.time()
        print('    Configuring BPMs...', end='')
        ret = self._config_bpms(self.params.nr_points)
        if ret < 0:
            print(f'BPM {-ret-1:d} did not finish last acquisition.')
        elif ret > 0:
            print(f'BPM {ret-1:d} is not ready for acquisition.')
        self._config_timing(self.params.delay_corrs)
        print(f'Done! ET: {_time.time()-t00:.2f}s')

        t00 = _time.time()
        print('    Sending Trigger signal...', end='')
        self.bpms.mturn_reset_flags_and_update_initial_timestamps(
            consider_sum=False)
        self.devices['evt_study'].cmd_external_trigger()
        print(f'Done! ET: {_time.time()-t00:.2f}s')

        # Wait BPMs PV to update with new data
        t00 = _time.time()
        print('    Waiting BPMs to update...', end='')
        ret = self.bpms.mturn_wait_update(
            timeout=self.params.timeout_bpms, consider_sum=False)
        if ret:
            print(
                'Problem: timed out waiting BPMs update. '
                f'Error code: {ret:d}')
        print(f'Done! ET: {_time.time()-t00:.2f}s')

        # get data
        data = self.get_general_data()
        data.update(self.get_bpms_data())

        elt -= _time.time()
        elt *= -1
        print(f'    Elapsed Time: {elt:.2f}s')
        return data

    def _do_measure_rf_line(self):
        elt = _time.time()
        print('Measuring RF Line:')

        t00 = _time.time()
        print('    Configuring BPMs...', end='')
        ret = self._config_bpms(self.params.nr_points)
        if ret < 0:
            print(f'BPM {-ret-1:d} did not finish last acquisition.')
        elif ret > 0:
            print(f'BPM {ret-1:d} is not ready for acquisition.')
        self._config_timing(self.params.delay_corrs)
        print(f'Done! ET: {_time.time()-t00:.2f}s')

        t00 = _time.time()
        print('    Sending Trigger signal...', end='')
        self.bpms.mturn_reset_flags_and_update_initial_timestamps(
            consider_sum=False)
        self.devices['evt_study'].cmd_external_trigger()

        t00 = _time.time()
        print('    Sweep RF...', end='')
        thr = _Thread(
            target=self._sweep_rf,
            args=(self.params.rf_kick, self.params.exc_rf),
            daemon=True)

        _time.sleep(self.params.delay_rf)
        thr.start()
        print(f'Done! ET: {_time.time()-t00:.2f}s')

        # Wait BPMs PV to update with new data
        t00 = _time.time()
        print('    Waiting BPMs to update...', end='')
        ret = self.bpms.mturn_wait_update(
            timeout=self.params.timeout_bpms, consider_sum=False)
        if ret:
            print(
                'Problem: timed out waiting BPMs update. '
                f'Error code: {ret:d}')
        print(f'Done! ET: {_time.time()-t00:.2f}s')

        # get data
        data = self.get_general_data()
        data.update(self.get_bpms_data())
        data['rf_kick'] = self.params.rf_kick

        elt -= _time.time()
        elt *= -1
        print(f'    Elapsed Time: {elt:.2f}s')
        return data

    def _sweep_rf(self, rf_kick, exc_duration):
        rfgen = self.devices['rfgen']
        freq0 = rfgen.frequency
        rfgen.frequency = freq0 - rf_kick
        _time.sleep(exc_duration/2)
        rfgen.frequency = freq0 + rf_kick
        _time.sleep(exc_duration/2)
        rfgen.frequency = freq0

    def _do_measure_magnets(self):
        elt0 = _time.time()
        data_mags = []

        print('Measuring Magnets:')

        # Shift correctors so first corrector is 01M1
        chs_shifted = self._shift_list(self.sofb_data.ch_names, 1)
        cvs_shifted = self._shift_list(self.sofb_data.cv_names, 1)

        # set operation mode to slowref
        if not self._change_corrs_opmode('slowref'):
            print('Problem: Correctors not in SlowRef mode.')
            return data_mags

        exc_duration = self.params.exc_duration
        ch_kick = self.params.ch_kick
        cv_kick = self.params.cv_kick
        freqh = self.params.ch_freqs
        freqv = self.params.cv_freqs
        nr_points = self.params.nr_points
        nr_secs_acq = self.params.nr_sectors_per_acq
        secs_to_meas = self.params.sectors_to_measure
        nr_secs = len(secs_to_meas)

        loop_size = nr_secs // nr_secs_acq
        loop_size += 1 if nr_secs % nr_secs_acq else 0
        for itr in range(loop_size):
            elt = _time.time()

            secs = secs_to_meas[itr*nr_secs_acq:nr_secs_acq*(itr+1)]
            if len(list(set(secs))) < len(secs):
                print('Problem: Same sectors in same acquisition.')
                break

            print(f'Sectors: '+', '.join(f'{s:02d}:' for s in secs))
            chs_slc, cvs_slc = [], []
            freqhe, freqve = [], []
            for sec in secs:
                chs_slc.extend(chs_shifted[(sec-1)*6:sec*6])
                cvs_slc.extend(cvs_shifted[(sec-1)*8:sec*8])
                freqhe.extend(freqh)
                freqve.extend(freqv)

            t00 = _time.time()
            print('    Configuring BPMs and timing...', end='')
            ret = self._config_bpms(nr_points * len(secs))
            if ret < 0:
                print(f'BPM {-ret-1:d} did not finish last acquisition.')
            elif ret > 0:
                print(f'BPM {ret-1:d} is not ready for acquisition.')
            self._config_timing(self.params.delay_corrs, secs)
            print(f'Done! ET: {_time.time()-t00:.2f}s')

            # configure correctors
            t00 = _time.time()
            print('    Configuring Correctors...', end='')
            self._config_correctors(chs_slc, ch_kick, freqhe, exc_duration)
            self._config_correctors(cvs_slc, cv_kick, freqve, exc_duration)
            print(f'Done! ET: {_time.time()-t00:.2f}s')

            # set operation mode to cycle
            t00 = _time.time()
            print('    Changing Correctors to Cycle...', end='')
            if not self._change_corrs_opmode('cycle', chs_slc + cvs_slc):
                print('Problem: Correctors not in Cycle mode.')
                break
            print(f'Done! ET: {_time.time()-t00:.2f}s')

            # send event through timing system to start acquisitions
            t00 = _time.time()
            print('    Sending Timing signal...', end='')
            self.bpms.mturn_reset_flags_and_update_initial_timestamps(
                consider_sum=False)
            self.devices['evt_study'].cmd_external_trigger()
            print(f'Done! ET: {_time.time()-t00:.2f}s')

            # Wait BPMs PV to update with new data
            t00 = _time.time()
            print('    Waiting BPMs to update...', end='')
            ret = self.bpms.mturn_wait_update(
                timeout=self.params.timeout_bpms, consider_sum=False)
            if ret:
                print(
                    'Problem: timed out waiting BPMs update. '
                    f'Error code: {ret:d}')
                break
            print(f'Done! ET: {_time.time()-t00:.2f}s')

            # get data for each sector separately:
            data = self.get_general_data()
            data.update(self.get_bpms_data())
            orbx = data.pop('orbx')
            orby = data.pop('orby')
            for i, _ in enumerate(secs):
                datas = _dcopy(data)
                datas['orbx'] = orbx[i*nr_points:(i+1)*nr_points]
                datas['orby'] = orby[i*nr_points:(i+1)*nr_points]
                chs_s = chs_slc[i*6:(i+1)*6]
                cvs_s = cvs_slc[i*8:(i+1)*8]
                datas.update(self.get_magnets_data(
                    chs_used=chs_s, cvs_used=cvs_s))
                data_mags.append(datas)

            # set operation mode to slowref
            t00 = _time.time()
            print('    Changing Correctors to SlowRef...', end='')
            if not self._wait_cycle_to_finish(chs_slc + cvs_slc):
                print('Problem: Cycle still not finished.')
                break
            if not self._change_corrs_opmode('slowref', chs_slc + cvs_slc):
                print('Problem: Correctors not in SlowRef mode.')
                break
            print(f'Done! ET: {_time.time()-t00:.2f}s')

            elt -= _time.time()
            elt *= -1
            print(f'    Elapsed Time: {elt:.2f}s')
            if self._stopevt.is_set():
                print('Stopping...')
                break

        # set operation mode to slowref
        if not self._change_corrs_opmode('slowref'):
            print('Problem: Correctors not in SlowRef mode.')
            return data_mags

        elt0 -= _time.time()
        elt0 *= -1
        print(f'Finished!!  ET: {elt0/60:.2f}min')
        return data_mags

    # ---------------- Data Processing methods ----------------

    def _process_data_rf(self, rf_data, transition_length=10):
        def _fitting_model(tim, *params):
            idx1, idx2, idx3, amp1, amp2 = params
            y = _np.zeros(tim.size)
            y[int(idx1):int(idx2)] = amp1
            y[int(idx2):int(idx3)] = amp2
            return y

        anly = dict()

        fsamp = self.data['bpms_sampling_frequency']
        dtim = 1/fsamp
        anly['fsamp'] = fsamp
        anly['dtim'] = dtim

        orbx = rf_data['orbx'].copy()
        orby = rf_data['orby'].copy()
        orbx -= orbx.mean(axis=0)
        orby -= orby.mean(axis=0)

        tim = _np.arange(orbx.shape[0]) * dtim
        anly['time'] = tim

        # fit average horizontal orbit to find transition indices
        exc_dur = self.params.exc_rf
        dly = self.params.delay_rf
        rf_kick = rf_data['rf_kick']
        idx1 = (tim > dly).nonzero()[0][0]
        idx2 = (tim > (exc_dur/2+dly)).nonzero()[0][0]
        idx3 = (tim > (exc_dur+dly)).nonzero()[0][0]
        etax_avg = 0.033e6  # average dispersion function, in [um]
        amp1 = -rf_kick * etax_avg / 1.7e-4 / 499665400
        amp2 = rf_kick * etax_avg / 1.7e-4 / 499665400
        par0 = [idx1, idx2, idx3, amp1, amp2]
        par, _ = _scyopt.curve_fit(
            _fitting_model, tim, orbx.mean(axis=1), p0=par0)
        idx1, idx2, idx3, amp1, amp2 = par
        idx1 = int(idx1)
        idx2 = int(idx2)
        idx3 = int(idx3)
        par = idx1, idx2, idx3, amp1, amp2
        anly['params_fit_init'] = par0
        anly['params_fit'] = par
        anly['idx1'] = idx1
        anly['idx2'] = idx2
        anly['idx3'] = idx3
        anly['amp1'] = amp1
        anly['amp2'] = amp2
        anly['transition_length'] = transition_length

        sec1_ini = idx1 + transition_length
        sec1_fin = idx2 - transition_length
        sec2_ini = idx2 + transition_length
        sec2_fin = idx3 - transition_length
        anly['sec1_ini'] = sec1_ini
        anly['sec1_fin'] = sec1_fin
        anly['sec2_ini'] = sec2_ini
        anly['sec2_fin'] = sec2_fin

        orbx_neg = orbx[sec1_ini:sec1_fin].mean(axis=0)
        orby_neg = orby[sec1_ini:sec1_fin].mean(axis=0)
        orbx_pos = orbx[sec2_ini:sec2_fin].mean(axis=0)
        orby_pos = orby[sec2_ini:sec2_fin].mean(axis=0)
        anly['orbx_neg'] = orbx_neg
        anly['orby_neg'] = orby_neg
        anly['orbx_pos'] = orbx_pos
        anly['orby_pos'] = orby_pos
        anly['mat_colx'] = (orbx_pos - orbx_neg) / rf_kick / 2
        anly['mat_coly'] = (orby_pos - orby_neg) / rf_kick / 2
        return anly

    def _process_data_bpms_noise(self, bpms_data):
        sofb = self.sofb_data
        anly = dict()

        fsamp = self.data['bpms_sampling_frequency']
        dtim = 1/fsamp
        freqs0 = _np.r_[self.params.ch_freqs, self.params.cv_freqs]
        anly['fsamp'] = fsamp
        anly['dtim'] = dtim
        anly['freqs0'] = freqs0

        orbx = bpms_data['orbx'].copy()
        orby = bpms_data['orby'].copy()
        orbx -= orbx.mean(axis=0)
        orby -= orby.mean(axis=0)

        tim = _np.arange(orbx.shape[0]) * dtim
        anly['time'] = tim

        ampx, *_ = self.fit_fourier_components(orbx, freqs0, dtim)
        ampy, *_ = self.fit_fourier_components(orby, freqs0, dtim)
        anly['noisex'] = ampx
        anly['noisey'] = ampy

        sch = len(self.params.ch_freqs)
        scv = len(self.params.cv_freqs)

        ampx_ch = ampx[:sch].T
        ampy_ch = ampy[:sch].T
        ampx_cv = ampx[sch:].T
        ampy_cv = ampy[sch:].T

        anly['noisex_ch'] = ampx_ch
        anly['noisey_ch'] = ampy_ch
        anly['noisex_cv'] = ampx_cv
        anly['noisey_cv'] = ampy_cv

        match = _np.zeros((2*sofb.nr_bpms, sch))
        matcv = _np.zeros((2*sofb.nr_bpms, scv))
        match[:sofb.nr_bpms] = ampx_ch
        match[sofb.nr_bpms:] = ampy_ch
        matcv[:sofb.nr_bpms] = ampx_cv
        matcv[sofb.nr_bpms:] = ampy_cv

        match = _np.roll(_np.tile(match, 20), -1)
        matcv = _np.roll(_np.tile(matcv, 20), -1)
        mat = _np.zeros((2*sofb.nr_bpms, sofb.nr_corrs))
        mat[:, :sofb.nr_ch] = match
        mat[:, sofb.nr_ch:sofb.nr_chcv] = matcv

        ampx_rf = orbx.std(axis=0)
        ampy_rf = orby.std(axis=0)
        anly['noisex_rf'] = ampx_rf
        anly['noisey_rf'] = ampy_rf
        mat[:sofb.nr_bpms, -1] = ampx_rf
        mat[sofb.nr_bpms:, -1] = ampy_rf

        anly['bpm_variation'] = mat
        return anly

    def _process_data_magnets(
            self, magnets_data, idx_ini=None, min_freq=None, max_freq=None):
        """."""
        sofb = self.sofb_data
        corr2idx = {name: i for i, name in enumerate(sofb.ch_names)}
        corr2idx.update({name: 120+i for i, name in enumerate(sofb.cv_names)})

        analysis = []
        for data in magnets_data:
            anly = dict()
            fsamp = self.data['bpms_sampling_frequency']
            dtim = 1/fsamp
            ch_freqs = _np.array(data['ch_frequency'])
            cv_freqs = _np.array(data['cv_frequency'])
            freqs0 = _np.r_[ch_freqs, cv_freqs]
            anly['fsamp'] = fsamp
            anly['dtim'] = dtim
            anly['freqs0'] = freqs0

            ch_ncycles = _np.array(data['ch_num_cycles'])
            cv_ncycles = _np.array(data['cv_num_cycles'])
            num_cycles = _np.r_[ch_ncycles, cv_ncycles]
            anly['num_cycles'] = num_cycles

            ch_amps = _np.array(data['ch_kick_amplitudes'])
            cv_amps = _np.array(data['cv_kick_amplitudes'])
            kicks = _np.r_[ch_amps, cv_amps]
            anly['kicks'] = kicks

            ch_idcs = _np.array([corr2idx[name] for name in data['ch_names']])
            cv_idcs = _np.array([corr2idx[name] for name in data['cv_names']])
            idcs = _np.r_[ch_idcs, cv_idcs]
            anly['mat_idcs'] = idcs

            orbx = data['orbx'].copy()
            orby = data['orby'].copy()
            orbx -= orbx.mean(axis=0)
            orby -= orby.mean(axis=0)

            tim = _np.arange(orbx.shape[0]) * dtim
            if idx_ini is None:
                # TODO: This logic is broken when more than one sector is
                # excited per BPM acquisition, because in this case the
                # deltaDelay variable is set, while delayRaw is kept as zero.
                delay = 4/data['rf_frequency']
                delay *= data['corrs_trig_delay_raw']
                idx_ini = (tim >= delay).nonzero()[0][0]
            anly['time'] = tim
            anly['idx_ini'] = idx_ini

            orbx = orbx[idx_ini:]
            orby = orby[idx_ini:]

            if min_freq is not None and max_freq is not None:
                min_freq = min_freq or 0
                max_freq = max_freq or fsamp/2
                dftx = _np.fft.rfft(orbx, axis=0)
                dfty = _np.fft.rfft(orby, axis=0)
                freq = _np.fft.rfftfreq(orbx.shape[0], d=dtim)
                idcs = (freq < min_freq) | (freq > max_freq)
                dftx[idcs] = 0
                orbx = _np.fft.irfft(dftx, axis=0)
                orby = _np.fft.irfft(dfty, axis=0)
            anly['min_freq'] = min_freq
            anly['max_freq'] = max_freq

            ampx, phasex, cosx, sinx = self.fit_fourier_components(
                orbx, freqs0, dtim, num_cycles)
            ampy, phasey, cosy, siny = self.fit_fourier_components(
                orby, freqs0, dtim, num_cycles)

            signx = _np.ones(ampx.shape)
            signx[_np.abs(phasex) > (_np.pi/2)] = -1
            signy = _np.ones(ampy.shape)
            signy[_np.abs(phasey) > (_np.pi/2)] = -1

            anly['ampx'] = ampx
            anly['ampy'] = ampy
            anly['phasex'] = phasex
            anly['phasey'] = phasey
            anly['cosx'] = cosx
            anly['cosy'] = cosy
            anly['sinx'] = sinx
            anly['siny'] = siny
            anly['signx'] = signx
            anly['signy'] = signy
            anly['mat_colsx'] = (signx * ampx / kicks[:, None]).T
            anly['mat_colsy'] = (signy * ampy / kicks[:, None]).T
            analysis.append(anly)
        return analysis

    # ----------------- BPMs related methods -----------------------

    def _config_bpms(self, nr_points):
        return self.bpms.mturn_config_acquisition(
            acq_rate=self.params.acq_rate,
            nr_points_before=0, nr_points_after=nr_points,
            repeat=False, external=True)

    # ----------------- Timing related methods -----------------------

    def _config_timing(self, cm_delay, sectors=None):
        trigbpm = self.devices['trigbpms']
        trigcorr = self.devices['trigcorrs']
        evt_study = self.devices['evt_study']
        evg = self.devices['evg']

        trigbpm.delay = 0.0
        trigbpm.nr_pulses = 1
        trigbpm.source = 'Study'

        trigcorr.nr_pulses = 1
        trigcorr.source = 'Study'
        ftim = self.devices['rfgen'].frequency / 4  # timing base frequency
        dly = int(cm_delay * ftim)

        # configure event Study to be in External mode
        evt_study.delay = 0
        evt_study.mode = 'External'

        # update event configurations in EVG
        evg.cmd_update_events()

        if sectors is None:
            trigcorr.delay_raw = dly
            print('Done!')
            return

        trigcorr.delay_raw = 0
        # Calculate delta_delay for correctors to be as close as possible to a
        # multiple of the the sampling period to ensure repeatability of
        # experiment along the sectors excited during single acquisition:
        fsamp = FamBPMs.get_sampling_frequency(
            self.devices['rfgen'].frequency, self.params.acq_rate)
        secs_delta_dly = _np.arange(len(sectors), dtype=float)
        secs_delta_dly *= self.params.nr_points / fsamp
        secs_delta_dlyr = _np.round(secs_delta_dly * ftim)

        delta_delay_raw = _np.zeros(trigcorr.delta_delay_raw.size)
        low_level = [_PVName(n) for n in trigcorr.low_level_triggers]
        for sec, ddlyr in zip(sectors, secs_delta_dlyr):
            # Find all low level triggers of this sector and set their delay:
            for j, llt in enumerate(low_level):
                if llt.sub.startswith(f'{sec:02d}'):
                    delta_delay_raw[j] = ddlyr + dly
        trigcorr.delta_delay_raw = delta_delay_raw

    # ----------------- Correctors related methods -----------------------

    def _config_correctors(self, corr_names, kick, freq_vector, exc_duration):
        """."""
        for i, cmn in enumerate(corr_names):
            cmo = self.devices[cmn]
            conv = self.devices[cmn+':StrengthConv'].conv_strength_2_current
            cmo.cycle_type = cmo.CYCLETYPE.Sine
            cmo.cycle_freq = freq_vector[i]
            cmo.cycle_ampl = conv(kick)
            cmo.cycle_offset = cmo.currentref_mon
            cmo.cycle_theta_begin = 0
            cmo.cycle_theta_end = 0
            cmo.cycle_num_cycles = int(exc_duration * freq_vector[i])

    def _change_corrs_opmode(self, mode, corr_names=None, timeout=10):
        """."""
        opm_sel = PowerSupply.OPMODE_SEL
        opm_sts = PowerSupply.OPMODE_STS
        mode_sel = opm_sel.Cycle if mode == 'cycle' else opm_sel.SlowRef
        mode_sts = opm_sts.Cycle if mode == 'cycle' else opm_sts.SlowRef

        if corr_names is None:
            corr_names = self.sofb_data.ch_names + self.sofb_data.cv_names

        for cmn in corr_names:
            cmo = self.devices[cmn]
            cmo.opmode = mode_sel

        interval = 0.2
        for _ in range(int(timeout/interval)):
            okk = True
            corrname = ''
            for cmn in corr_names:
                cmo = self.devices[cmn]
                oki = cmo.opmode == mode_sts
                if not oki:
                    corrname = cmn
                okk &= oki
            if okk:
                return True
            _time.sleep(interval)

        print(corrname)
        return False

    def _wait_cycle_to_finish(self, corr_names=None, timeout=10):
        if corr_names is None:
            corr_names = self.sofb_data.ch_names + self.sofb_data.cv_names

        for cmn in corr_names:
            cmo = self.devices[cmn]
            if not cmo.wait_cycle_to_finish(timeout=timeout):
                return False
        return True

    @staticmethod
    def _shift_list(lst, num):
        """."""
        return lst[-num:] + lst[:-num]


var = []
print("ingresar")
entr = input()
entra = int(entr)
salida = 0

def operacion(a,b,c):
        suma = 0
        for i in range(c):
                suma += a + i*b
        var.append(suma)

for n in range(0,entra):
	entrada = input()
	entrada2 = entrada.split()
	for f in range(0,len(entrada2)):
		entrada2[f] = int(entrada2[f])
	operacion(entrada2[0],entrada2[1],entrada2[2])
print(*var,sep=' ')


import pygame
import blits
import time

pygame.init()
WS =(1000, 500)
screen = pygame.display.set_mode(WS)
frame_rate =  20
clock = pygame.time.Clock()
pygame.init()
font = pygame.font.SysFont("bitstreamverasans", 30)
def main() :
    global screen
    snakeobj = blits.snake(screen , WS)
    run = True
    while run  :
        run = snakeobj.operate(pygame.event.get())
        clock.tick(frame_rate)
        screen.blit(font.render(str(snakeobj.len - 1), True, (0,0,255)), (0, 0))
        pygame.display.flip()
        screen.fill([0 , 0 ,0])

    game_score = font.render("Score " + str(snakeobj.len - 1) ,  True, (60,130,120))
    while True :
        for event in pygame.event.get() :
            if event.type == pygame.QUIT:
                exit()
        screen.blit(game_score, (0 , 0 ))
        pygame.display.flip()

if __name__ == "__main__" :
    main()