import csv
import psycopg2
import sys

conn = None
cursor = None

def create_csv(directory, name, header, list):
    """Writes the csv file.
    inputs: directory: string for the target directory for the csv
            name: string for the name of the csv file
            header: list of column names
            list: list of rows to be turned into a csv"""

    with open('{0}/{1}.csv'.format(directory, name), 'a', newline='') as f:
        writer = csv.writer(f)
        writer.writerow(header)
        writer.writerows(list)

def connect_to_db(dbname):
    """Connects to the specific database."""

    # Define our connection string
    conn_string = "dbname='{0}' host='127.0.0.1' port=5432".format(dbname)

	# get a connection, if a connect cannot be made an exception will be raised here
    global conn
    conn = psycopg2.connect(conn_string)

	# conn.cursor will return a cursor object, you can use this cursor to perform queries
    global cursor
    cursor = conn.cursor()

def main():
    dbname = sys.argv[1]
    directory = sys.argv[2]

    connect_to_db(dbname)

    # Writes users.csv
    cursor.execute("SELECT username, password, title, active FROM users JOIN user_is ON (users.user_pk = user_is.user_fk) JOIN roles ON (user_is.role_fk = roles.role_pk)")
    user_list = cursor.fetchall()
    create_csv(directory, 'users', ['username', 'password', 'role', 'active'], user_list)

    # Writes facilities.csv
    cursor.execute("SELECT facility_code, common_name FROM facilities")
    facility_list = cursor.fetchall()
    create_csv(directory, 'facilities', ['fcode', 'common_name'], facility_list)

    # Writes assets.csv
    cursor.execute("SELECT DISTINCT ON (asset_pk) asset_pk, asset_tag, description, facility_code, arrive_dt, disposed FROM assets JOIN asset_at ON (assets.asset_pk = asset_at.asset_fk) JOIN facilities ON (asset_at.facility_fk = facilities.facility_pk) ORDER BY asset_pk, arrive_dt")
    assets = cursor.fetchall()
    asset_list = []
    for row in assets:
        # Asset not disposed.
        if not row[5]:
            asset_list.append([row[1], row[2], row[3], row[4], 'NULL'])
        # Asset has been disposed.
        else:
            # Figure out the date of disposal.
            cursor.execute("SELECT DISTINCT ON (asset_pk) asset_pk, asset_tag, description, facility_code, depart_dt, disposed FROM assets JOIN asset_at ON (assets.asset_pk = asset_at.asset_fk) JOIN facilities ON (asset_at.facility_fk = facilities.facility_pk) WHERE asset_pk = {0} ORDER BY asset_pk, depart_dt DESC".format(row[0]))
            date = cursor.fetchall()[0][4]
            asset_list.append([row[1], row[2], row[3], row[4], date])
    create_csv(directory, 'assets', ['asset_tag', 'description', 'facility', 'acquired', 'disposed'], asset_list)

    # Writes transfers.csv
    cursor.execute("SELECT asset_tag, use1.username, request_dt, usea.username, approve_dt, facs.facility_code, facd.facility_code, load_dt, unload_dt FROM transfers LEFT JOIN facilities facs ON (transfers.source_facility_fk = facs.facility_pk) LEFT JOIN facilities facd ON (transfers.destination_facility_fk = facd.facility_pk) JOIN assets ON (transfers.asset_fk = assets.asset_pk) LEFT JOIN users use1 ON (transfers.request_user_fk = use1.user_pk) LEFT JOIN users usea ON (transfers.approve_user_fk = usea.user_pk) JOIN in_transit ON (transfers.transfer_pk = in_transit.transfer_fk)")
    transfers_list = cursor.fetchall()
    create_csv(directory, 'transfers', ['asset_tag', 'request_by', 'request_dt', 'approve_by', 'approve_dt', 'source', 'destination', 'load_dt', 'unload_dt'], transfers_list)

if __name__ == "__main__":
    main()


from django.shortcuts import render,HttpResponse,redirect
from django.utils.safestring import mark_safe
from django.core.paginator import Paginator

from app01.models import Person
# Create your views here.

def index(request):
    # return HttpResponse("Welcome to mysite")
    return render(request,'index.html')
def test(request):
    # data=['hello','world']
    # return render(request,'test.html',{'data':data})

    data={'k1':'hello','k2':'world'}
    return render(request,'test.html',{'data':data})
def ormtest(request):
    '''
    :param request:
    :return:

    新增用户
    Person.objects.create(name='scott',age=10)
    Person.objects.create(name='jack', age=20)
    <QuerySet [<Person: Person object (1)>, <Person: Person object (2)>, <Person: Person object (3)>, <Person: Person object (4)>]>
    '''
    data=Person.objects.all()
    return render(request, 'test.html', {'data': data})
def list_user(request):

    if request.method == 'GET':
        # 获取所有数据
        objects = Person.objects.all()
        # 每页10条数据
        paginator = Paginator(objects, 5)
        # 获取第一页的数据
        page_number = request.GET.get('page')
        page_obj = paginator.get_page(page_number)
        return render(request, 'list_user.html', {'page_obj': page_obj})

    print(request.POST)
    data=request.POST.get('jump-page')
    print(data)
    print('*******************')
    # 获取所有数据
    objects = Person.objects.all()
    # 每页10条数据
    paginator = Paginator(objects, 5)
    # 获取第一页的数据
    page_number = request.GET.get('page')
    page_obj = paginator.get_page(page_number)

    return render(request, 'list_user.html', {'page_obj': page_obj})

    # return render(request, 'list_user.html', {'data': data,'page_string':page_string,'total_page':total_page})

#####添加用户，这里基于modelform来处理
# Django ModelForm修改默认的控件属性
# https://blog.csdn.net/weixin_30254435/article/details/99050157
from django.forms import ModelForm
class Add_user_modelfrom(ModelForm):
    class Meta:
        model=Person
        # fields = ['name', 'age', ]
        fields='__all__'

#      <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
    def __init__(self, *args, **kwargs):
        super(Add_user_modelfrom, self).__init__(*args, **kwargs)
        for field_name in self.base_fields:
            field = self.base_fields[field_name]
            field.widget.attrs.update({'class': "form-control", 'id': 'exampleInput'})

def add_user(request):
    print(request.method)
    if request.method == 'GET':
        form=Add_user_modelfrom()
        return render(request,'add_user.html',{'form':form})
    form=Add_user_modelfrom(request.POST)
    form.save()
    return redirect('/list/user/')

def delete_user(request):
    '''
    :param request:
    :return:
     借助 ?id= 获取 key来删除
     https://blog.csdn.net/MaxineZhou/article/details/104971307
    '''
    id=request.GET.get('id')
    data=Person.objects.get(id=id).delete()
    print(data)
    return redirect('/list/user')

from django.forms import ModelForm
class Modify_user_modelfrom(ModelForm):
    class Meta:
        model=Person
        # fields = ['name', 'age', ]
        fields='__all__'

#      <input type="email" class="form-control" id="exampleInputEmail1" placeholder="Email">
    def __init__(self, *args, **kwargs):
        super(Modify_user_modelfrom, self).__init__(*args, **kwargs)
        for field_name in self.base_fields:
            field = self.base_fields[field_name]
            field.widget.attrs.update({'class': "form-control", 'id': 'exampleInput'})

def modify_user(request,uid):
    '''
    :param request:
    :return:
    '''
    data = Person.objects.filter(id=uid).first()
    print(data)
    if request.method == 'GET':
        form=Modify_user_modelfrom(instance=data)
        return render(request,'modify.html',{'form':form})

    else:
        form= Modify_user_modelfrom(request.POST,instance=data)
        if form.is_valid():
            form.save()
            return redirect('/list/user')


## BELOW HERE STORED FOR ARCHIVAL PURPOSES...
## snapshot # - # - # - # - # - # - # - # - # - # - # - # - # - # - # - # - #

def build_tick_labels(bins):
    labels = ['%d' % bins[0]]
    for x, y in zip(bins[:-1], bins[1:]):
        if y - x == 1:
            labels.append('%d' % y)
        else:
            labels.append('%d-%d' % (x + 1, y))
    labels.append('%d+' % (bins[-1] + 1))
    return labels

def plot_state_snapshot(ax, props, time, state_labels, age_cutoffs):
    x = np.arange(len(age_cutoffs) + 1)
    plots = []
    b = np.zeros(len(x))
    for i, label in enumerate(state_labels):
        plots.append(ax.bar(x, props[label], color=colors[i],
                            bottom=b, align='center', lw=0))
        b += props[label]
    #    legend([p[0] for p in plots], state_labels, bbox_to_anchor=(1.05, 1), loc=2, borderaxespad=0.)
    #    leg = ax.legend([p[0] for p in plots], state_labels)
    ax.set_xlim(-0.4, len(x) - 0.6)
    ax.set_xticks(list(range(len(x))))
    ax.xaxis.set_ticks_position('none')
    ax.set_xticklabels(build_tick_labels(age_cutoffs), size='x-small')
    ax.set_xlabel('Age group (years)')
    ax.set_ylim((0, 100))
    ax.set_ylabel('Percentage')
    ax.set_yticklabels(['%d%%' % z for z in range(0, 120, 20)], size='x-small')
    ax.set_title('year %03d day %03d' % (time / 365, time % 365))

def plot_states(ax, props, times, logscale=False, marker=-1, pop_size=-1):
    xvals = np.arange(times['st'], times['et'])

    print("************* SUPERCEDED BY output_timeseries")

    if marker > 0:
        ax.vlines(marker, 0.0005, 1, color='g')
    leg_labels = []
    for i, p in enumerate(props):
        yvals = list(p[2][times['si']:times['ei']])
        if len(yvals) < len(xvals):
            yvals.extend([0] * (len(xvals) - len(yvals)))
        ax.plot(xvals, yvals, color=colors[i])
        leg_labels.append(p[0])
    if logscale:
        ax.set_yscale('log')
        ymin = 1.0 / pop_size if pop_size > 0 else 0.0001
        ax.set_ylim((ymin, 1.0))
    leg = ax.legend(leg_labels, bbox_to_anchor=(0., 1.02, 1., .102), loc=3,
                    ncol=len(props), mode="expand", borderaxespad=0.)

    ax.set_ylabel('Fraction of population')

def output_state_snapshot(data,
                          start_index, end_index, start_time, end_time,
                          t_dur, years_per_tick, logscale,
                          snapshot, time, state_labels, age_cutoffs, ofile):
    """
    Plots four graphs:
    1. disease states by age (bars)
    2. disease states over time (current time marked by line)
    3. disease states of household containing children
    4. disease states of households not containing children

    Can be stitched together to make movie of outbreak.
    """

    # for each snapshot, bin individiuals by age and state
    cutoffs = list(age_cutoffs) + [2000]
    all_bins = {}
    kids_bins = {}
    nokids_bins = {}
    for label in state_labels:
        all_bins[label] = np.zeros(len(cutoffs))
        kids_bins[label] = np.zeros(len(cutoffs))
        nokids_bins[label] = np.zeros(len(cutoffs))
    for cur_ind in snapshot:
        index = 0
        while cur_ind['age'] >= cutoffs[index]:
            index += 1
        all_bins[cur_ind['state'].label][index] += 1
        if cur_ind['hh_type'].endswith('kids'):
            kids_bins[cur_ind['state'].label][index] += 1
        else:
            nokids_bins[cur_ind['state'].label][index] += 1

    all_props = convert_counts_to_props(all_bins, cutoffs)
    kids_props = convert_counts_to_props(kids_bins, cutoffs)
    nokids_props = convert_counts_to_props(nokids_bins, cutoffs)

    # plot figure
    fig = plt.figure()
    ax = fig.add_subplot(221)
    plot_state_snapshot(ax, all_props, time, state_labels, age_cutoffs)
    ax = fig.add_subplot(222)
    plot_states(ax, data, start_index, end_index, start_time, end_time,
                t_dur, logscale, marker=time)
    #    setup_x_axis(ax, start_time, end_time, years_per_tick)
    ax = fig.add_subplot(223)
    plot_state_snapshot(ax, kids_props, time, state_labels, age_cutoffs)
    ax = fig.add_subplot(224)
    plot_state_snapshot(ax, nokids_props, time, state_labels, age_cutoffs)
    fig.savefig(ofile)

def plot_ab_snapshot(ax, snapshot, binsize=5):
    binned = []
    cur_bin = []
    for i, x in list(snapshot.items()):
        #        print i, x
        cur_bin.extend(x)
        if i % binsize == 0:
            binned.append(cur_bin)
            cur_bin = []
        #    print binned

    ax.boxplot(binned, positions=list(range(0, len(binned))))  #, widths=3)
    ax.set_xlabel('Age')
    ax.set_ylabel('Antibody level')

def bin_ab_level(snapshot, cutoffs=(5, 62.5, 125),
                 bins=(1, 2, 3, 4, 5, 6, 7, 8, 9, 14, 19, 24, 34, 44, 59, 74)):
    cutoffs = list(cutoffs) + [10000]
    bins = list(bins) + [2000]
    counts = np.zeros((len(bins), len(cutoffs)))
    for cur_age, ab_levels in list(snapshot.items()):
        i = 0
        while cur_age >= bins[i]:
            i += 1
        for ab in ab_levels:
            j = 0
            while ab >= cutoffs[j]:
                j += 1
            counts[i][j] += 1

    return counts

def build_ab_legend_labels(cutoffs):
    """
    Create a list of series labels based upon cutoffs as follows:
    ['<c[0]', 'c[0]--c[1]-1', ..., 'c[n-1]--c[n]-1', 'c[n]+']
    """

    labels = ['<%g EU/mL' % cutoffs[0]]
    labels += ['%g to <%g EU/mL' % (x, y) for x, y in zip(cutoffs[:-1], cutoffs[1:])]
    labels += [''.join(('\\u2265', '%g EU/mL' % cutoffs[-1]))]
    return labels

def plot_ab_snapshot_bars(ax, counts, time, cutoffs=(5, 62.5, 125),
                          bins=(1, 2, 3, 4, 5, 6, 7, 8, 9, 14, 19, 24, 34, 44, 59, 74),
                          colours=('#ff0000', '#ffa500', '#ffff00', '#9acd32')):
    x = np.arange(len(counts))
    plots = []
    b = np.zeros((len(counts)))
    for i in range(len(cutoffs) + 1):
        plots.append(ax.bar(x, counts[:, i], color=colours[i], bottom=b, align='center'))
        b += counts[:, i]
    leg = ax.legend([p[0] for p in plots], build_ab_legend_labels(cutoffs), mode='expand',
                    ncol=4, bbox_to_anchor=(0., -.16, 1., .102), loc=8, handletextpad=0.3, markerscale=0.5)
    leg.get_frame().set_alpha(0.0)
    plt.setp(leg.get_texts(), fontsize='x-small')
    ax.set_xticks(list(range(len(bins) + 1)))
    ax.xaxis.set_ticks_position('none')
    ax.set_xticklabels(build_tick_labels(bins), size='x-small')
    ax.set_xlim((-0.4, len(bins) + 0.4))
    ax.set_xlabel('Age group (years)')
    ax.set_yticklabels(['%d%%' % x for x in range(0, 120, 20)], size='x-small')
    ax.set_ylim((0, 100))
    ax.set_ylabel('Percentage positive')
    ax.set_title('Antibody levels by age group (day %d)' % time)

def output_ab_snapshot(ss, ofile, cutoffs=(0.2, 0.5, 0.8)):
    """
    Plot a snapshot of antibody levels (by age?)
    """

    counts = bin_ab_level(ss[1], cutoffs)
    sums = np.array([[float(sum(x))] for x in counts])
    props = counts / sums * 100

    fig = plt.figure()
    ax = fig.add_subplot(111)
    plot_ab_snapshot_bars(ax, props, ss[0], cutoffs)
    fig.savefig(ofile)

def output_immunity_ratio(snapshots, state_labels, age_cutoffs, ofile):
    cutoffs = list(age_cutoffs) + [2000]

    kids_bins = {}
    nokids_bins = {}

    ratios = []

    for snapshot in snapshots:
        for label in state_labels:
            kids_bins[label] = np.zeros(len(cutoffs))
            nokids_bins[label] = np.zeros(len(cutoffs))

        for cur_ind in snapshot[1]:
            index = 0
            while cur_ind['age'] >= cutoffs[index]:
                index += 1
            if cur_ind['hh_type'].endswith('kids'):
                kids_bins[cur_ind['state'].label][index] += 1
            else:
                nokids_bins[cur_ind['state'].label][index] += 1

        kids_props = convert_counts_to_props(kids_bins, cutoffs)
        nokids_props = convert_counts_to_props(nokids_bins, cutoffs)

        cur_ratios = [x / y for x, y in zip(kids_props['R'], nokids_props['R'])]

        ratios.append(cur_ratios)

    of = file(ofile, 'w')
    for row in ratios:
        of.write(','.join([str(x) for x in row]))
        of.write('\n')
    of.close()

def output_heatmap(data, x_param, y_param, ofile, zlog=False):
    # compute boundaries of each heatmap cell such that actual parameter
    # value occupies the centre of the cell
    # NB: may not be the most legitimate way to display this info... (?)
    x_values = [np.mean([x, y]) \
                for x, y in zip(x_param['values'][:-1], x_param['values'][1:])]
    x_values.insert(0, x_values[0] - (x_values[1] - x_values[0]))
    x_values.append(x_values[-1] + (x_values[-1] - x_values[-2]))
    y_values = [np.mean([x, y]) \
                for x, y in zip(y_param['values'][:-1], y_param['values'][1:])]
    y_values.insert(0, y_values[0] - (y_values[1] - y_values[0]))
    y_values.append(y_values[-1] + (y_values[-1] - y_values[-2]))

    X, Y = np.meshgrid(np.array(x_values), np.array(y_values))

    fig = plt.figure()
    ax = fig.add_subplot(111)
    norm = LogNorm() if zlog else None
    img = ax.pcolor(X, Y, np.array(data), cmap='jet', norm=norm)
    ax.set_xlabel(x_param['name'])
    ax.set_ylabel(y_param['name'])

    ax.set_xlim((x_values[0], x_values[-1]))
    ax.set_ylim((y_values[0], y_values[-1]))

    fig.colorbar(img)
    fig.savefig(ofile)

def get_y_err(contour, cur):
    pass

def output_contour(data, x_param, y_param, ofile, zlog=False, contour_values=None, tgt_value=None, plot_values=None,
                   title=None):
    """
    Produce a contour map and, incidentally, calculate the y values corresponding to a target
    contour line for each value of x_param.

    TODO: These two functionalities should be separated.
    """

    x_values = x_param['values']
    y_values = y_param['values']

    fig = plt.figure()
    ax = fig.add_subplot(111)
    norm = LogNorm() if zlog else None

    if not contour_values: contour_values = 15

    img = ax.contourf(np.array(x_values), np.array(y_values), np.array(data), contour_values, cmap=plt.cm.rainbow,
                      vmax=abs(data).max(), vmin=-abs(data).max(), norm=norm)
    fig.colorbar(img)

    img = ax.contour(np.array(x_values), np.array(y_values), np.array(data), contour_values, linewidths=0.5, colors='k')
    ax.set_xlabel(x_param['name'])
    ax.set_ylabel(y_param['name'])

    y_fits = {}

    # if contour values and target value have been specified, find corresponding y
    # values for each x value
    contour_values = img.levels
    print((type(contour_values)))
    print(contour_values)
    print(tgt_value)
    if tgt_value in contour_values:
        i_tgt = [contour_values.tolist().index(tgt_value)]

        if not plot_values: plot_values = x_values

        for i, cur_x in enumerate(plot_values):
            # fn returns the distance between the current x, y location and the contour
            # line corresponding to the target R0 value
            fn = lambda cur_y: img.find_nearest_contour(cur_x, cur_y, i_tgt, pixel=False)[-1]
            best_y = fmin(fn, [0.1])
            y_fits[cur_x] = best_y[0]

            # plot intersections
            ax.plot((cur_x, cur_x), (0.005, best_y), 'w')
            ax.plot((0, cur_x), (best_y, best_y), 'w')

    if title:
        ax.set_title(title)

    fig.savefig(ofile)

    return y_fits

def output_outbreak_sizes(data, R0_values, ofile):
    # plot the distribution of epidemic outbreak sizes for various values of R0

    fig = plt.figure()
    ax = fig.add_subplot(111)

    for cur_R0_value, cur_data in zip(R0_values, data):
        print(cur_data)
        hist, bin_edges = np.histogram(cur_data, bins=101, range=(0.0, 1.0))
        hist = np.array(hist, dtype=np.float32) / float(sum(hist))
        print(hist)
        print(bin_edges)
        ax.plot([(x + y) / 2.0 for x, y in zip(bin_edges[:-1], bin_edges[1:])],
                hist, label='R0=%g' % cur_R0_value)

    leg = ax.legend()
    ax.set_xlabel('Outbreak size (proportion of population)')
    ax.set_ylabel('Proportion of runs')
    leg.get_frame().set_alpha(0.0)
    fig.savefig(ofile)


# RectangleArea.py
# CSCI 220 - Lab 01 - 1/13/14
# Author: Jake Hennessy
#
# Purpose: The purpose of this program is to calculate the area of a rectangle.

def main():
    length = eval(input("Enter the length: "))
    width = eval(input("Enter the width: "))
    area = length * width
    print ("Area =", area, "units squared.")

main()


'''
    SystemLab-Design Version 20.01
    Primary author: Marc Verreault
    E-mail: marc.verreault@systemlabdesign.com
    Copyright © 2019-2020 SystemLab Inc. All rights reserved.

    NOTICE================================================================================
    This file is part of SystemLab-Design 20.01.

    SystemLab-Design 20.01 is free software: you can redistribute it
    and/or modify it under the terms of the GNU General Public License
    as published by the Free Software Foundation, either version 3 of the License,
    or (at your option) any later version.

    SystemLab-Design 20.01 is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with SystemLab-Design 20.01.  If not, see <https://www.gnu.org/licenses/>.
    ======================================================================================

    SystemLab module for port analyzer(GUI) classes: SignalDigital
'''

import os
import config
gui_ui_path = config.root_path

import sys # MV 20.01.r2 24-Feb-20
import traceback # MV 20.01.r2 24-Feb-20

# MV 20.01.r1 29-Oct-2019
# Import config_port_viewers as cfg_digital
import importlib
cfg_port_viewers_path = str('syslab_config_files.config_port_viewers')
cfg_digital = importlib.import_module(cfg_port_viewers_path)
cfg_special_path = str('syslab_config_files.config_special')
cfg_special = importlib.import_module(cfg_special_path)

import numpy as np
import matplotlib

from PyQt5 import QtCore, QtGui, uic, QtWidgets
import matplotlib.pyplot as plt
# Method for embedding Matplotlib canvases into Qt-designed QDialog interfaces
# Ref: https://matplotlib.org/gallery/user_interfaces/embedding_in_qt_sgskip.html
# Accessed: 11 Feb 2019
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
from matplotlib.backends.backend_qt5agg import NavigationToolbar2QT as NavigationToolbar

qtDigitalPortDataViewerFile = os.path.join(gui_ui_path, 'syslab_gui_files', 'DigitalDataViewer.ui')
qtDigitalPortDataViewerFile = os.path.normpath(qtDigitalPortDataViewerFile)
Ui_PortDataWindow_Digital, QtBaseClass = uic.loadUiType(qtDigitalPortDataViewerFile)

#import matplotlib as mpl
matplotlib.rcParams['figure.dpi'] = 80

# MV 20.01.r3 15-Jun-20
style_spin_box = """QSpinBox {color: darkBlue; background: white;
                              selection-color: darkBlue;
                              selection-background-color: white;}"""

class DigitalPortDataAnalyzer(QtWidgets.QDialog, Ui_PortDataWindow_Digital):
    '''
    Digital signal format:
    portID(0), signal_type(1), symbol_rate(2), bit_rate(3), order(4),
    time_array(5), discrete_array(6)

    '''
    def __init__(self, signal_data, fb_name, port_name, direction, design_settings):
        QtWidgets.QDialog.__init__(self)
        Ui_PortDataWindow_Digital.__init__(self)
        self.setupUi(self)
        syslab_icon = set_icon_window()
        self.setWindowIcon(syslab_icon)
        self.setWindowFlags(self.windowFlags()|QtCore.Qt.WindowMinimizeButtonHint)
        self.setStyleSheet(cfg_special.global_font) # MV 20.01.r1 17-Dec-2019
        self.fb_name = fb_name
        self.port_name = port_name
        self.direction = direction

        # MV 20.01.r3 15-Jun-20 Set iteration to reflect main application setting
        # (iterators spin box)
        self.signals = signal_data
        current_iter = int(design_settings['current_iteration'])
        if (current_iter - 1) <= len(self.signals):
            self.iteration = current_iter
        else:
            self.iteration = int(len(self.signals))

        # MV 20.01.r3 13-Jun-20 Added functional block and port data info to
        # Window title box
        self.setWindowTitle('Digital signal data analyzer (' +
                             str(self.fb_name) + ', Port: ' +
                             str(self.port_name) + ', Dir: ' +
                             str(self.direction) + ')')

        iterations = len(signal_data)
        self.spinBoxTime.setMaximum(iterations)
        self.spinBoxTime.setValue(self.iteration) # MV 20.01.r3 15-Jun-20
        self.spinBoxTime.lineEdit().setAlignment(QtCore.Qt.AlignCenter) # MV 20.01.r3 15-Jun-20
        self.spinBoxTime.setStyleSheet(style_spin_box) # MV 20.01.r3 15-Jun-20
        self.spinBoxFreq.setMaximum(iterations)
        self.spinBoxFreq.setValue(self.iteration) # MV 20.01.r3 15-Jun-20
        self.spinBoxFreq.lineEdit().setAlignment(QtCore.Qt.AlignCenter) # MV 20.01.r3 15-Jun-20
        self.spinBoxFreq.setStyleSheet(style_spin_box) # MV 20.01.r3 15-Jun-20
        self.totalIterationsTime.setText(str(iterations))
        self.totalIterationsFreq.setText(str(iterations))
        self.spinBoxTime.valueChanged.connect(self.valueChangeTime)
        self.spinBoxFreq.valueChanged.connect(self.valueChangeFreq)
        self.displayUnitInterval.toggled.connect(self.checkSignalChangedSequence)
        self.displayTime.toggled.connect(self.checkSignalChangedSequence)

        #Plot settings (Time/Freq major/minor grids)
        self.checkBoxMajorGrid.stateChanged.connect(self.checkSignalChangedSequence)
        self.checkBoxMinorGrid.stateChanged.connect(self.checkSignalChangedSequence)
        self.checkBoxMajorGridFreq.stateChanged.connect(self.checkSignalChangedFreq)
        self.checkBoxMinorGridFreq.stateChanged.connect(self.checkSignalChangedFreq)

        self.actionSeqWindow.clicked.connect(self.updateTimeAxis)
        self.actionFreqWindow.clicked.connect(self.updateFreqAxis)
        self.checkBoxDisplayNegFreq.stateChanged.connect(self.checkSignalChangedFreq)

        #Signal data tab (dataFrameSignal)=====================================
        #Iterations group box
        iterations = len(signal_data)
        self.spinBoxSignalData.setMaximum(iterations)
        self.totalIterationsSignalData.setText(str(iterations))
        self.spinBoxSignalData.valueChanged.connect(self.iterationChangeSignalData)
        #Domain setting group box
        self.radioButtonSigFreq.toggled.connect(self.updateSignalData)
        self.radioButtonSigTime.toggled.connect(self.updateSignalData)

        #X-axis signal format group box
        self.radioButtonUnitSignalData.toggled.connect(self.updateSignalData)
        self.radioButtonTimeSignalData.toggled.connect(self.updateSignalData)
        #Adjust samples group box
        self.actionSetIndicesSignalData.clicked.connect(self.updateSignalData)
        #View settings group box
        self.linewidthSignalData.setText(str(60))
        self.actionSetLinewidthSignalData.clicked.connect(self.updateSignalData)

        #Setup initial data for iteration 1 (default)
        #self.iteration = 1  #MV 20.01.r3 13-Jun-20
        #self.signals = signal_data #MV 20.01.r3 13-Jun-20
        self.total_samples = design_settings['num_samples']
        self.sample_rate = design_settings['sampling_rate']
        self.sampling_period = design_settings['sampling_period']
        signal_default = self.signals[self.iteration]
        self.time = signal_default[5] #Sampled time array
        self.discrete = signal_default[6] #Digital samples
        self.seq_length = len(self.discrete) #Length of data sequence (number of symbols)
        self.units = np.linspace(1, self.seq_length, self.seq_length, dtype = 'int') #Unit interval
        self.totalSamples.setText(str(format(self.total_samples, '0.3E')))
        self.totalBits.setText(str(format(self.seq_length, '0.3E')))
        self.totalSymbols.setText(str(format((self.seq_length/signal_default[4]), '0.3E')))
        self.bitRate.setText(str(format(signal_default[3], '0.3E')))
        self.symbolRate.setText(str(format(signal_default[2], '0.3E')))
        self.symbolOrder.setText(str(signal_default[4]))

        self.samples_per_bit = int(round(self.sample_rate/signal_default[3]))
        self.samplesBit.setText(str(format(self.samples_per_bit, '0.3E')))
        self.samples_per_symbol = int(round(self.sample_rate/signal_default[2]))
        self.samplesSymbol.setText(str(format(self.samples_per_symbol, '0.3E')))

        self.discrete_time = []

        for sym in range(0,self.seq_length):
            i = 0
            while i < int(self.samples_per_symbol):
                self.discrete_time.append(self.discrete[sym])
                i += 1

        #Setup frequency domain analysis================================================
        # REF:  Fast Fourier Transform in matplotlib,
        # An example of FFT audio analysis in matplotlib and the fft function.
        # Source: https://plot.ly/matplotlib/fft/(accessed 20-Mar-2018)
        self.totalSamplesFreq.setText(str(format(self.total_samples, '0.3E')))
        self.samplingPeriod.setText(str(format(self.sampling_period, '0.3E')))
        self.samplingRate.setText(str(format(self.sample_rate, '0.3E')))

        self.n = int(len(self.discrete_time))
        T = self.n/self.sample_rate
        k = np.arange(self.n)
        self.frq = k/T # Positive/negative freq (double sided)
        self.frq_pos = self.frq[range(int(self.n/2))] # Positive freq only (single sided)

        #FFT computation
        self.Y = np.fft.fft(self.discrete_time)/self.n
        self.Y_pos = self.Y[range(int(self.n/2))]
        # MV 20.01.r3 20-Jul-20: Folding of spectrum
        self.Y_pos = self.Y_pos*np.sqrt(2)
        self.Y_pos[0] = self.Y_pos[0]/np.sqrt(2) # DC component is not doubled
        #===============================================================================

        #Setup background colors for frames
        color = QtGui.QColor(cfg_digital.digital_frame_background_color) # MV 20.01.r1 29-Oct-19
        p = self.graphFrame.palette()
        p.setColor(self.graphFrame.backgroundRole(), color)
        self.graphFrame.setPalette(p)
        p2 = self.dataFrame.palette()
        p2.setColor(self.dataFrame.backgroundRole(), color)
        self.dataFrame.setPalette(p2)
        p3 = self.graphFrameFreq.palette()
        p3.setColor(self.graphFrameFreq.backgroundRole(), color)
        self.graphFrameFreq.setPalette(p3)
        p4  = self.dataFrameFreq.palette()
        p4.setColor(self.dataFrameFreq.backgroundRole(), color)
        self.dataFrameFreq.setPalette(p4)

        #Setup matplotlib figures and toolbars
        self.graphLayout = QtWidgets.QVBoxLayout()
        # MV 20.01.r1 29-Oct-19 Added new feature to select figure area background color
        self.figure = plt.figure(facecolor = cfg_digital.digital_time_fig_back_color)
        self.figure.set_tight_layout(True)
        self.canvas = FigureCanvas(self.figure)
        self.toolbar = NavigationToolbar(self.canvas, self.tab_sequence)
        self.graphLayout.addWidget(self.canvas)
        self.graphLayout.addWidget(self.toolbar)
        self.graphFrame.setLayout(self.graphLayout)

        self.graphLayoutFreq = QtWidgets.QVBoxLayout()
        # MV 20.01.r1 29-Oct-19 Added new feature to select figure area background color
        self.figure_freq = plt.figure(facecolor = cfg_digital.digital_freq_fig_back_color)
        self.canvas_freq = FigureCanvas(self.figure_freq)
        self.toolbar_freq = NavigationToolbar(self.canvas_freq, self.tab_freq)
        self.graphLayoutFreq.addWidget(self.canvas_freq)
        self.graphLayoutFreq.addWidget(self.toolbar_freq)
        self.graphFrameFreq.setLayout(self.graphLayoutFreq)

        self.tabData.setCurrentWidget(self.tab_freq)
        self.plot_freq_domain(0)
        self.figure_freq.set_tight_layout(True)
        self.tabData.setCurrentWidget(self.tab_sequence)
        self.plot_sequence(0)

        #Prepare default data for signal data viewer===================================
        self.totalSamplesSignalData.setText(str(format(self.seq_length, 'n')))
        self.minIndexSignalData.setText(str(1))
        self.maxIndexSignalData.setText(str(format(self.seq_length, 'n')))
        self.updateSignalData()
        #Return to sequence tab
        self.tabData.setCurrentWidget(self.tab_sequence)

    def valueChangeTime(self):
        new_iteration = int(self.spinBoxTime.value())
        signal_updated = self.signals[new_iteration]

        self.time = signal_updated[5] #Sampled time array
        self.discrete = signal_updated[6] #Digital samples
        self.seq_length = len(self.discrete) #Length of data sequence (number of bits/symbols)
        self.units = np.linspace(1, self.seq_length, self.seq_length, dtype = 'int') #Unit interval
        self.totalSamples.setText(str(format(self.total_samples, '0.3E')))
        self.totalBits.setText(str(format(self.seq_length, '0.3E')))
        self.totalSymbols.setText(str(format((self.seq_length/signal_updated[4]), '0.3E')))
        self.bitRate.setText(str(format(signal_updated[3], '0.3E')))
        self.symbolRate.setText(str(format(signal_updated[2], '0.3E')))
        self.symbolOrder.setText(str(signal_updated[4]))

        self.samples_per_bit = int(round(self.sample_rate/signal_updated[3]))
        self.samplesBit.setText(str(format(self.samples_per_bit, '0.3E')))
        self.samples_per_symbol = int(round(self.sample_rate/signal_updated[2]))
        self.samplesSymbol.setText(str(format(self.samples_per_symbol, '0.3E')))

        self.discrete_time = []
        for sym in range(0,self.seq_length):
            i = 0
            while i < int(self.samples_per_symbol):
                self.discrete_time.append(self.discrete[sym])
                i += 1

        self.tabData.setCurrentWidget(self.tab_sequence)
        self.plot_sequence(0)
        self.canvas.draw()

    def checkSignalChangedSequence(self):
        self.tabData.setCurrentWidget(self.tab_sequence)
        self.plot_sequence(0)
        self.canvas.draw()

    def updateTimeAxis(self):
        self.plot_sequence(1)
        self.canvas.draw()

    def plot_sequence(self, time_axis_adjust):
        try:
            self.figure.clf() #MV Rel 20.01.r1 15-Sep-19
            # MV 20.01.r1 Added new feature to select plot area background color
            # MV 20.01.r1 29-Oct-19 Added new feature to select plot area background color
            back_color = cfg_digital.digital_time_plot_back_color
            ax = self.figure.add_subplot(111, facecolor = back_color)
            ax.clear()

            if time_axis_adjust == 1:
                start_unit = self.minUnit.text()
                end_unit = self.maxUnit.text()
                ax.set_xlim(float(start_unit), float(end_unit))

            # MV 20.01.r1 Linked plot settings to config file variables (to provide ability to
            # manage look and feel of plots)
            if self.displayTime.isChecked() == 1:
                ax.plot(self.time, self.discrete_time,
                        color = cfg_digital.digital_time_signal_color,
                        linestyle = cfg_digital.digital_time_signal_linestyle,
                        linewidth= cfg_digital.digital_time_signal_linewidth,
                        marker = cfg_digital.digital_time_signal_marker,
                        markersize = cfg_digital.digital_time_signal_markersize)
                ax.set_xlabel('Time (sec)')
            if self.displayUnitInterval.isChecked() == 1:
                ax.plot(self.units, self.discrete,
                        color = cfg_digital.digital_time_signal_color,
                        linestyle = cfg_digital.digital_time_signal_linestyle,
                        linewidth= cfg_digital.digital_time_signal_linewidth,
                        marker = cfg_digital.digital_time_signal_marker,
                        markersize = cfg_digital.digital_time_signal_markersize)
                ax.set_xlabel('Symbol index')

            # MV 20.01.r1 15-Sep-19 (Cleaned up title - was getting too long & causing
            # issues with tight layout)
            ax.set_title('Sequence data (' + str(self.fb_name) + ', Port:' + str(self.port_name) +
                                              ', Dir:' + str(self.direction) + ')')

            ax.set_ylabel('Discrete value (a.u.)')
            ax.set_aspect('auto')
            ax.format_coord = self.format_coord_seq

            # MV 20.01.r1
            if self.checkBoxMajorGrid.checkState() == 2:
                ax.grid(True)
                ax.grid(which='major',
                             linestyle = cfg_digital.digital_time_maj_grid_linestyle,
                             linewidth = cfg_digital.digital_time_maj_grid_linewidth,
                             color = cfg_digital.digital_time_maj_grid_color)

            if self.checkBoxMinorGrid.checkState() == 2:
                ax.minorticks_on()
                ax.grid(which='minor',
                             linestyle = cfg_digital.digital_time_min_grid_linestyle,
                             linewidth = cfg_digital.digital_time_min_grid_linewidth,
                             color = cfg_digital.digital_time_min_grid_color)

            # MV 20.01.r1 3-Nov-2019 Color settings for x and y-axis labels and tick marks
            ax.xaxis.label.set_color(cfg_digital.digital_time_labels_axes_color)
            ax.yaxis.label.set_color(cfg_digital.digital_time_labels_axes_color)
            ax.tick_params(axis='both', which ='both',
                                colors=cfg_digital.digital_time_labels_axes_color)

        except: # MV 20.01.r2 24-Feb-20
            e0 = sys.exc_info() [0]
            e1 = sys.exc_info() [1]
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Warning)
            syslab_icon = set_icon_window()
            msg.setWindowIcon(syslab_icon)
            msg.setText('Error plotting digital sequence')
            msg.setInformativeText(str(e0) + ' ' + str(e1))
            msg.setInformativeText(str(traceback.format_exc()))
            msg.setStyleSheet("QLabel{height: 150px; min-height: 150px; max-height: 150px;}")
            msg.setStyleSheet("QLabel{width: 500px; min-width: 400px; max-width: 500px;}")
            msg.setWindowTitle("Plotting error (Digital port viewer)")
            msg.setStandardButtons(QtWidgets.QMessageBox.Ok)
            rtnval = msg.exec()
            if rtnval == QtWidgets.QMessageBox.Ok:
                msg.close()

    def format_coord_seq(self, x, y):
        return 'Time/Samples=%0.7E, Mag=%0.7E' % (x, y)

    def valueChangeFreq(self):
        new_iteration = int(self.spinBoxFreq.value())
        signal_updated = self.signals[new_iteration]

        self.discrete = signal_updated[6] #Digital samples
        self.seq_length = len(self.discrete) #Length of data sequence (number of bits/symbols)
        self.totalSamples.setText(str(format(self.total_samples, '0.3E')))

        self.samples_per_symbol = int(round(self.sample_rate/signal_updated[2]))

        self.totalSamplesFreq.setText(str(format(self.total_samples, '0.3E')))
        self.samplingPeriod.setText(str(format(self.sampling_period, '0.3E')))
        self.samplingRate.setText(str(format(self.sample_rate, '0.3E')))

        self.discrete_time = []
        for sym in range(0,self.seq_length):
            i = 0
            while i < int(self.samples_per_symbol):
                self.discrete_time.append(self.discrete[sym])
                i += 1

        self.Y = np.fft.fft(self.discrete_time)/self.n # fft computing and normalization
        self.Y_pos = self.Y[range(int(self.n/2))]
        # MV 20.01.r3 20-Jul-20: Folding of spectrum
        self.Y_pos = self.Y_pos*np.sqrt(2)
        self.Y_pos[0] = self.Y_pos[0]/np.sqrt(2) # DC component is not doubled
        self.tabData.setCurrentWidget(self.tab_freq)
        self.plot_freq_domain(0)
        self.canvas_freq.draw()

    def checkSignalChangedFreq(self):
        self.tabData.setCurrentWidget(self.tab_freq)
        self.plot_freq_domain(0)
        self.canvas_freq.draw()

    def updateFreqAxis(self):
        self.plot_freq_domain(1)
        self.canvas_freq.draw()

    def plot_freq_domain(self, freq_axis_adjust):
        try:
            self.figure_freq.clf() #MV Rel 20.01.r1 15-Sep-19
            # MV 20.01.r1 Added new feature to select plot area background color
            # MV 20.01.r1 29-Oct-19 Added new feature to select plot area background color
            back_color = cfg_digital.digital_freq_plot_back_color
            af = self.figure_freq.add_subplot(111, facecolor = back_color)
            af.clear()

            if freq_axis_adjust == 1:
                start_freq = self.minFreq.text()
                end_freq = self.maxFreq.text()
                af.set_xlim(float(start_freq), float(end_freq))

            # MV 20.01.r1 Linked plot settings to config file variables (to provide ability to
            # manage look and feel of plots)
            if self.checkBoxDisplayNegFreq.checkState() == 2:
                af.plot(self.frq, abs(self.Y),
                        color = cfg_digital.digital_freq_signal_color,
                        linestyle = cfg_digital.digital_freq_signal_linestyle,
                        linewidth= cfg_digital.digital_freq_signal_linewidth,
                        marker = cfg_digital.digital_freq_signal_marker,
                        markersize = cfg_digital.digital_freq_signal_markersize)
            else:
                af.plot(self.frq_pos, abs(self.Y_pos),
                        color = cfg_digital.digital_freq_signal_color,
                        linestyle = cfg_digital.digital_freq_signal_linestyle,
                        linewidth= cfg_digital.digital_freq_signal_linewidth,
                        marker = cfg_digital.digital_freq_signal_marker,
                        markersize = cfg_digital.digital_freq_signal_markersize)

            # MV 20.01.r1 15-Sep-19 (Cleaned up title - was getting too long & causing
            # issues with tight layout)
            af.set_title('Freq data (' + str(self.fb_name) + ', Port:' + str(self.port_name) +
                                              ', Dir:' + str(self.direction) + ')')

            af.set_xlabel('Freq (Hz)')
            af.set_ylabel('|Y(freq)|')
            af.set_aspect('auto')
            af.format_coord = self.format_coord_freq

            # MV 20.01.r1
            if self.checkBoxMajorGridFreq.checkState() == 2:
                af.grid(True)
                af.grid(which='major',
                             linestyle = cfg_digital.digital_freq_maj_grid_linestyle,
                             linewidth = cfg_digital.digital_freq_maj_grid_linewidth,
                             color = cfg_digital.digital_freq_maj_grid_color)

            if self.checkBoxMinorGridFreq.checkState() == 2:
                af.minorticks_on()
                af.grid(which='minor',
                             linestyle = cfg_digital.digital_freq_min_grid_linestyle,
                             linewidth = cfg_digital.digital_freq_min_grid_linewidth,
                             color = cfg_digital.digital_freq_min_grid_color)

            # MV 20.01.r1 3-Nov-2019 Color settings for x and y-axis labels and tick marks
            af.xaxis.label.set_color(cfg_digital.digital_freq_labels_axes_color)
            af.yaxis.label.set_color(cfg_digital.digital_freq_labels_axes_color)
            af.tick_params(axis='both', which ='both',
                                colors=cfg_digital.digital_freq_labels_axes_color)

        except: # MV 20.01.r2 24-Feb-20
            e0 = sys.exc_info() [0]
            e1 = sys.exc_info() [1]
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Warning)
            syslab_icon = set_icon_window()
            msg.setWindowIcon(syslab_icon)
            msg.setText('Error plotting frequency domain sequence')
            msg.setInformativeText(str(e0) + ' ' + str(e1))
            msg.setInformativeText(str(traceback.format_exc()))
            msg.setStyleSheet("QLabel{height: 150px; min-height: 150px; max-height: 150px;}")
            msg.setStyleSheet("QLabel{width: 500px; min-width: 400px; max-width: 500px;}")
            msg.setWindowTitle("Plotting error (Digital port viewer)")
            msg.setStandardButtons(QtWidgets.QMessageBox.Ok)
            rtnval = msg.exec()
            if rtnval == QtWidgets.QMessageBox.Ok:
                msg.close()

    def format_coord_freq(self, x, y):
        return 'Freq=%0.7E, Mag=%0.7E' % (x, y)

    '''Signal data tab========================================================'''
    def iterationChangeSignalData(self):
        new_iteration = int(self.spinBoxSignalData.value())
        signal_updated = self.signals[new_iteration]

        self.time = signal_updated[5] #Sampled time array
        self.discrete = signal_updated[6] #Digital samples
        self.seq_length = len(self.discrete) #Length of data sequence (number of bits/symbols)
        self.units = np.linspace(1, self.seq_length, self.seq_length, dtype = 'int') #Unit interval

        self.samples_per_bit = int(round(self.sample_rate/signal_updated[3]))
        self.samples_per_symbol = int(round(self.sample_rate/signal_updated[2]))

        self.discrete_time = []
        for sym in range(0,self.seq_length):
            i = 0
            while i < int(self.samples_per_symbol):
                self.discrete_time.append(self.discrete[sym])
                i += 1

        self.Y = np.fft.fft(self.discrete_time)/self.n # fft computing and normalization

        self.updateSignalData()

    def updateSignalData(self):
        try:
            self.tabData.setCurrentWidget(self.tab_signal)
            self.signalBrowser.clear()

            #Signal data (base data)
            self.font_bold = QtGui.QFont("Arial", 8, QtGui.QFont.Bold)
            self.font_normal = QtGui.QFont("Arial", 8, QtGui.QFont.Normal)
            self.signalBrowser.setCurrentFont(self.font_bold)
            self.signalBrowser.setTextColor(QtGui.QColor('#007900'))
            i = int(self.spinBoxSignalData.value())
            self.signalBrowser.append('Signal data (digital) - Iteration '+str(i))
            self.signalBrowser.setCurrentFont(self.font_normal)
            self.signalBrowser.setTextColor(QtGui.QColor('#000000'))

            #Signal data title
            self.signalBrowser.setCurrentFont(self.font_bold)
            if (self.radioButtonUnitSignalData.isChecked() == 1
                and self.radioButtonSigTime.isChecked() == 1):
                self.signalBrowser.append('Signal data (symbol index, discrete value ):')
            elif (self.radioButtonUnitSignalData.isChecked() == 1
                and self.radioButtonSigTime.isChecked() == 1):
                self.signalBrowser.append('Signal data (index, time (s), discrete value ):')
            else:
                self.signalBrowser.append('Signal data (index, freq (Hz), Y):')
            self.signalBrowser.setCurrentFont(self.font_normal)

            # Adjust for new index range (if required)
            if self.radioButtonUnitSignalData.isChecked() == 1:
                self.totalSamplesSignalData.setText(str(format(self.seq_length, 'n')))
                self.minIndexSignalData.setText(str(1))
                self.maxIndexSignalData.setText(str(format(self.seq_length, 'n')))
            else:
                self.totalSamplesSignalData.setText(str(format(self.total_samples, 'n')))
                self.minIndexSignalData.setText(str(1))
                self.maxIndexSignalData.setText(str(format(self.total_samples, 'n')))

            self.start_index = int(self.minIndexSignalData.text())
            self.end_index = int(self.maxIndexSignalData.text()) + 1
            index_array = np.arange(self.start_index, self.end_index, 1)
            array_size = self.end_index - self.start_index

            #Prepare structured array for string output to text browser
            if (self.radioButtonUnitSignalData.isChecked() == 1
                and self.radioButtonSigTime.isChecked() == 1):
                data = np.zeros(array_size, dtype={'names':('index', 'y'),
                                                   'formats':('i4', 'i4')})
            elif (self.radioButtonUnitSignalData.isChecked() == 1
                and self.radioButtonSigTime.isChecked() == 1):
                data = np.zeros(array_size, dtype={'names':('index', 'x', 'y'),
                                                   'formats':('i4', 'f8', 'i4')})
            else:
                data = np.zeros(array_size, dtype={'names':('index', 'x', 'y'),
                                                   'formats':('i4', 'f8', 'c16')})
            data['index'] = index_array

            if self.radioButtonSigTime.isChecked() == 1:
                if self.radioButtonUnitSignalData.isChecked() == 1:
                    data['y'] = self.discrete[self.start_index-1:self.end_index-1]
                else:
                    data['x'] = self.time[self.start_index-1:self.end_index-1]
                    data['y'] = self.discrete_time[self.start_index-1:self.end_index-1]
            else:
                data['x'] = self.frq[self.start_index-1:self.end_index-1]
                data['y'] = self.Y[self.start_index-1:self.end_index-1]

            self.linewidth = 60
            if self.linewidthSignalData.text():
                self.linewidth = int(self.linewidthSignalData.text())

            self.signalBrowser.append(np.array2string(data, max_line_width = self.linewidth))

            cursor = self.signalBrowser.textCursor()
            cursor.setPosition(0)
            self.signalBrowser.setTextCursor(cursor)

        except: # MV 20.01.r2 24-Feb-20
            e0 = sys.exc_info() [0]
            e1 = sys.exc_info() [1]
            msg = QtWidgets.QMessageBox()
            msg.setIcon(QtWidgets.QMessageBox.Warning)
            syslab_icon = set_icon_window()
            msg.setWindowIcon(syslab_icon)
            msg.setText('Error displaying signal data')
            msg.setInformativeText(str(e0) + ' ' + str(e1))
            msg.setInformativeText(str(traceback.format_exc()))
            msg.setStyleSheet("QLabel{height: 150px; min-height: 150px; max-height: 150px;}")
            msg.setStyleSheet("QLabel{width: 500px; min-width: 400px; max-width: 500px;}")
            msg.setWindowTitle("Plotting error (Digital port viewer)")
            msg.setStandardButtons(QtWidgets.QMessageBox.Ok)
            rtnval = msg.exec()
            if rtnval == QtWidgets.QMessageBox.Ok:
                msg.close()

    '''Close event====================================================================='''
    def closeEvent(self, event):
        plt.close(self.figure)
        plt.close(self.figure_freq)

'''FUNCTIONS================================================================'''
def set_icon_window():
    icon_path = os.path.join(config.root_path, 'syslab_gui_icons', 'SysLabIcon128.png')
    icon_path = os.path.normpath(icon_path)
    icon = QtGui.QIcon()
    icon.addFile(icon_path)
    return icon

'''========================================================================='''


"""
Вам дана область карты https://stepik.org/media/attachments/lesson/266078/mapcity.osm

Пройдите по первым ста node в этой области и выведите для каждого три числа:
id, широту (атрибут lat) и долготу (атрибут lon).

Числа для каждого node выводите в отдельной строке, разделяя одним пробелом.
Обрабатывать node нужно в том же порядке, в котором они встречаются во входном файле.

Если вы все делаете правильно, то ваш ответ должен начинаться со строк:

60276311 55.5695795 37.5764692
60276312 55.5682232 37.5754573
"""
from urllib.request import urlopen, urlretrieve
from bs4 import BeautifulSoup

resp = urlopen('https://stepik.org/media/attachments/lesson/266078/mapcity.osm')
xml = resp.read().decode('utf8')
soup = BeautifulSoup(xml, 'lxml')

for node in soup.find_all('node', limit=100):
    print(node['id'], node['lat'], node['lon'])


import random
import numpy as np
class asignatura:
    def __init__(self,ramo, semestre):
        self.ramo = ramo
        self.semestre = semestre
    def getRamo(self):
        return self.ramo

    def getSemestre(self):
        return self.semestre

    def setRamo(self, ramo):
        self.ramo = ramo

    def setSemestre(self, semestre):
        self.semestre = semestre

    def getData(self):
        return self.ramo, self.semestre

import numpy as np

def h_aleatoria3(datos):
    np.random.seed()
    dias = np.array(['1', '2', '3', '4', '5'])
    semana = [[], [], [], [], []]
    horario = {}
    for dia_ in dias:
        horario[dia_] = {}
    bloques = 4
    asignaturas = []
    for sem in datos:
        for asig in datos[sem]['asignaturas']:
            tmp = asignatura(asig, sem)
            asignaturas.append(tmp)
    for dia_ in horario:
        for i in range(bloques):
            horario[dia_][i + 1] = []

    #print(horario)
    while asignaturas:
        #print("Asignaturas: ", len(asignaturas))
        dia = np.random.choice(dias)  # Usando np.random.choice en lugar de random.choice
        #print("DIAAAAA: ", dia)
        bloques = np.random.choice(list(range(1, 5))).__int__()
        tmp = np.random.choice(asignaturas)
        semTmp = tmp.getSemestre()
        #print("Dia: ", dia, "Bloque: ", bloques, "Semestre: ", semTmp)
        if semTmp not in semana[int(dia) - 1]:
            horario[dia][bloques].append(tmp)
            semana[int(dia) - 1].append(semTmp)
            asignaturas.remove(tmp)

        elif semTmp in semana[int(dia) - 1] and len(semana[int(dia) - 1]) < 10:
            validar = True
            count = 0
            while validar:
                if not asignaturas:
                    validar = False
                    break
                tmp_ = np.random.choice(asignaturas)
                semTmp_ = tmp_.getSemestre()
                if semTmp_ not in semana[int(dia) - 1]:
                    horario[dia][bloques].append(tmp_)
                    semana[int(dia) - 1].append(semTmp_)
                    asignaturas.remove(tmp_)
                    validar = False
                    break
                elif count == 10:
                    validar = False
                    #print("No se pudo asignar")
                    break
                else:
                    count += 1
                    validar = True
    #print(len(asignaturas))
    return horario
def h_aleatoria2(datos):
    dias = ['Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes']
    horario = {}
    for dia in dias:  #con esto asigno los dias de la semana de la libreta
        horario[dia] = {}
    bloques =  4
    #creamos un arreglo con todas las asignaturas
    asignaturas = []
    for sem in datos:

        for asig in datos[sem]['asignaturas']:
            tmp = asignatura(asig, sem)
            asignaturas.append(tmp)
    for dias in horario:
        #Creamos los bloques
        for i in range(bloques):
            horario[dias][i+1] = []

    for dias in horario:
        semDia = []
        for bloque in horario[dias]:
            for i in range(0,4):
                if asignaturas == []:
                    break
                tmp = random.choice(asignaturas)
                semTmp = tmp.getSemestre()
                if semTmp not in semDia:
                    horario[dias][bloque].append(tmp)
                    semDia.append(semTmp)
                    asignaturas.remove(tmp)
                elif semTmp in semDia and len(semDia) < 10:
                    validar = True
                    while(validar):
                        if asignaturas == []:
                            break
                        tmp_ = random.choice(asignaturas)
                        semTmp_ = tmp_.getSemestre()
                        if semTmp_ not in semDia:
                            horario[dias][bloque].append(tmp_)
                            #print("Dia:", dias , "bloque: ", bloque , "Semestres: ", semDia, "Asignaturas: ", len(asignaturas))
                            semDia.append(semTmp_)
                            asignaturas.remove(tmp_)
                            validar = False
                            break
                        else:
                            validar = True
    return horario
#heuristica por orden de malla.
def  heuristica_3(datos):
    dias = ['Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes']
    horario = {}
    for dia in dias:  #con esto asigno los dias de la semana de la libreta
        horario[dia] = {}
    bloques =  4
    asignaturas = []
    for sem in datos:
        for asig in datos[sem]['asignaturas']:
            tmp = asignatura(asig, sem)
            asignaturas.append(tmp)
    for dias in horario:
        #Creamos los bloques
        for i in range(bloques):
            horario[dias][i] = []

    for i in range(0,4):
        for dias in horario:
            if asignaturas == []:
                break
            else:
                horario[dias][i].append(asignaturas.pop())
    return horario

def heuristica_4(datos):
    dias = ['Lunes', 'Martes', 'Miercoles', 'Jueves', 'Viernes']
    horario = {}
    for dia in dias:  #con esto asigno los dias de la semana de la libreta
        horario[dia] = {}
    bloques =  4
    asignaturas = []
    for sem in datos:
        for asig in datos[sem]['asignaturas']:
            tmp = asignatura(asig, sem)
            asignaturas.append(tmp)
    for dias in horario:
        #Creamos los bloques
        for i in range(bloques):
            horario[dias][i] = []


from configparser import ConfigParser
import sys
import random
import pickle
import os
from time import time
import pygmo as pg
import numpy as np
from tengp_eval.utils import get_keijzer_data
from tengp_eval.utils.function_sets import keijzer_fixed_funset

def run(algos, output_dir, configs_dir, default_ini=None):
    random.seed(42)
    pg.set_global_rng_seed(42)

    np.warnings.filterwarnings('ignore')

    if not os.path.exists(output_dir):
        os.makedirs(output_dir)

    start = time()

    for bench_id in  range(1,16):

        x_train, y_train, x_test, y_test = get_keijzer_data(random, bench_id)
        print(bench_id, x_test.shape)

        chosen_run = algos[0]

#        if x_test.shape[0] > 10000:
#            print('volim si coevoluciu')
#            chosen_run = algos[1]

        cp = ConfigParser()

        if default_ini:
            cp.read(os.path.join(configs_dir, default_ini))
        else:
            cp.read(os.path.join(configs_dir, f'hp-keijzer{bench_id}.ini'))

        max_trials = 50

        all_logs = []

        for i in range(max_trials):
            print(f'keijzer{bench_id}-{i}')
            log = chosen_run(cp, x_test, y_test, keijzer_fixed_funset)
            all_logs.append(log)

        with open(os.path.join(output_dir, f'keijzer{bench_id}.log'), 'wb') as f:
            pickle.dump(all_logs, f)

    print(f'finised, wall time: {time() - start}')

if __name__ == '__main__':

    output_dir = sys.argv[2]
    configs_dir = sys.argv[3]
    default_ini = None
    if len(sys.argv) == 5:
        default_ini = sys.argv[4]

    if sys.argv[1] == 'pso':
        from .pso import RUNNERS
    elif sys.argv[1] == 'sa':
        from .sa import RUNNERS

    algos = RUNNERS

    run(algos, output_dir, configs_dir, default_ini)


""" Tests for DeterministicLearner """
# pylint: disable=redefined-outer-name
import pytest
import numpy as np

from deeprl.learners import DeterministicLearner

@pytest.fixture
def agent_step_ret():
    """ agent 'step' return value fixture """
    return np.random.randn(1)

@pytest.fixture
def env_step_ret():
    """ environment step return value """
    return (np.array([0, 0]), 0, False, None)

@pytest.fixture
def learner(mocker, continuous_env, agent_step_ret):
    """ learner fixture """
    learner_path = 'deeprl.learners.deterministic_learner.'
    mocker.patch(learner_path + 'EpochLogger.save_config')
    mocker.patch(learner_path + 'EpochLogger.log')
    mocker.patch(learner_path + 'EpochLogger.setup_tf_saver')
    agent = mocker.Mock()
    agent.step.return_value = agent_step_ret
    agent.build_graph.return_value = {'foo': 'bar'}
    return DeterministicLearner(agent, env=continuous_env)

def test_episode_step_testing_false(mocker, learner):
    """ smoke test episode step """
    mocker.patch.object(learner, 'logger')
    obs = learner.env.reset()
    ret = learner.episode_step(obs, 0, False, 0, 0, 0, testing=False)
    ret_obs, ret_rew, ret_is_term, ret_ep_len, ret_ep_ret, ret_epoch_ctr = ret
    assert ret_ep_len == 1
    learner.logger.store.assert_not_called()
    assert ret_epoch_ctr == 1
    assert learner.buffer.buf # ensure buffer was initialized

def test_episode_step_testing_true(mocker, learner):
    """ smoke test episode step """
    mocker.patch.object(learner, 'logger')
    mocker.patch.object(learner, 'buffer')
    obs = learner.env.reset()
    ret = learner.episode_step(obs, 0, False, 0, 0, 0, testing=True)
    ret_obs, ret_rew, ret_is_term, ret_ep_len, ret_ep_ret, ret_epoch_ctr = ret
    assert ret_ep_len == 1
    learner.logger.store.assert_not_called() # no logging during testing
    assert ret_epoch_ctr == 0
    # no buffer storage during testing
    learner.buffer.store.assert_not_called()

def test_play_episodes_reached_epoch_len(mocker, learner):
    """ test play_eposide when epoch end is reached """
    learner.logger = mocker.Mock()
    learner.epoch_len = 2
    ret_ep_len, _, _ = learner.play_episode()
    assert ret_ep_len == 2
    learner.logger.store.assert_not_called()

def test_play_episode_max_ep_len(mocker, learner, env_step_ret):
    """ test play_episode when the max_ep_len is reached """
    learner.max_ep_len = 2
    learner.logger = mocker.Mock()
    learner.env.step = mocker.Mock(return_value=env_step_ret)
    ret_ep_len, _, ret_epoch_ctr = learner.play_episode()
    assert ret_ep_len == 2
    assert ret_epoch_ctr == 2
    learner.logger.store.assert_called_once_with(EpLen=2, EpRet=0.)
    assert learner.buffer.ptr == 2

def test_play_episode_episode_ends(mocker, learner, env_step_ret):
    """ test play_episode when the episode terminates """
    learner.logger = mocker.Mock()
    # episode reaches termial state on fourth step
    learner.env.reset = mocker.Mock(return_value=env_step_ret[0])
    learner.env.step = mocker.Mock(
        side_effect=[env_step_ret,
                     env_step_ret,
                     env_step_ret,
                     (np.array([0, 0]), 2., True, None)]) # last one is terminal!
    ret_ep_len, ret_ep_ret, _ = learner.play_episode()
    assert ret_ep_len == 4
    # note the return should include the reward from the last step!!!
    assert ret_ep_ret == 2.
    learner.logger.store.assert_called_once_with(EpRet=2., EpLen=4)

def test_test_epoch_smoke(learner):
    """ smoke test test_epoch method """
    learner.test_epoch(1)


from random import randint
com = randint(0, 10)
count = 0
user = 11
while com != user:
    count += 1
    user = int(input('Digite seu palpite: '))
    if user > com:
        print('Seu chute foi muito alto! Tente um número menor,')
    elif user < com:
        print('Seu chute foi muito baixo. Tente um número maior')
print('Você acertou!!! Você precisou de {} tentativas para acertar.'.format(count))


import dash
import dash_core_components as dcc
import dash_html_components as html
import plotly.express as px
import pandas as pd
import json
import requests

from urllib import response
from urllib.request import urlopen
from flask_login.utils import login_required
import pandas as pd
import numpy as np
from dash import Dash, dash_table

# assume you have a "long-form" data frame
# see https://plotly.com/python/px-arguments/ for more options

def kpi2_solve_month_r():
    url = 'https://g43bee37532bd29-dblab1.adb.eu-frankfurt-1.oraclecloudapps.com/ords/tip/kpi2/incsolved/'
    data_oracle = requests.get(url).json()['items']
    data_oracle= pd.DataFrame(data_oracle)
    return data_oracle

def kpi3_solve_monthprior_r():
    url = 'https://g43bee37532bd29-dblab1.adb.eu-frankfurt-1.oraclecloudapps.com/ords/tip/kpi3/raisedpriority/'
    data_oracle = requests.get(url).json()['items']
    data_oracle= pd.DataFrame(data_oracle)
    critical = data_oracle[data_oracle['priority']=='Crítica']
    alta = data_oracle[data_oracle['priority']=='Alta']
    media = data_oracle[data_oracle['priority']=='Media']
    baja = data_oracle[data_oracle['priority']=='Baja']
    return critical, alta, media, baja

def kpi4_cause_incident_b(): #incident type and number
    url = 'https://g43bee37532bd29-dblab1.adb.eu-frankfurt-1.oraclecloudapps.com/ords/tip/kpi4/backcause'
    data_oracle = requests.get(url).json()['items']
    data_oracle= pd.DataFrame(data_oracle)
    return data_oracle

def kpi7_incident_b():
    url= 'https://g43bee37532bd29-dblab1.adb.eu-frankfurt-1.oraclecloudapps.com/ords/tip/kpi7/incidentstatus/'
    data_oracle = requests.get(url).json()['items']
    data_oracle= pd.DataFrame(data_oracle)
    return data_oracle

def kpi8_cause_incident_c(): #incident type and number
    url= 'https://g43bee37532bd29-dblab1.adb.eu-frankfurt-1.oraclecloudapps.com/ords/tip/kpi8/cc/'
    data_oracle = requests.get(url).json()['items']
    data_oracle= pd.DataFrame(data_oracle)
    return data_oracle

def kpi9_priority_closed(): #number of incidences month and priority
    url= 'https://g43bee37532bd29-dblab1.adb.eu-frankfurt-1.oraclecloudapps.com/ords/tip/kpi9/closeprio/'
    data_oracle = requests.get(url).json()['items']
    data_oracle= pd.DataFrame(data_oracle)
    critical = data_oracle[data_oracle['priority']=='Crítica']
    alta = data_oracle[data_oracle['priority']=='Alta']
    media = data_oracle[data_oracle['priority']=='Media']
    baja = data_oracle[data_oracle['priority']=='Baja']
    return critical, alta, media, baja

def create_dash_application(flask_app):
    dash_app = dash.Dash(server=flask_app, name="Dashboard", url_base_pathname="/raised/")

    df2= kpi2_solve_month_r()
    df3= kpi3_solve_monthprior_r()

    dash_app.layout = html.Div(
        children=[
            html.H1(children="Raised Dashboard"),
            html.Div(html.H4("Number of Incidents per Month")),
            dcc.Graph(
                id="kpi2-graph",
                figure=px.bar(df2, x="month", y="incidences_number", barmode="group"),
            ),
            dcc.Graph(
                figure={
                    'data': [
                        {'x': df3[0]['month'], 'y': df3[0]['incidences_number'], 'type': 'bar', 'name': 'Critical'},
                        {'x': df3[1]['month'], 'y': df3[1]['incidences_number'], 'type': 'bar', 'name': 'Alto'},
                        {'x': df3[2]['month'], 'y': df3[2]['incidences_number'], 'type': 'bar', 'name': 'Medio'},
                        {'x': df3[3]['month'], 'y': df3[3]['incidences_number'], 'type': 'bar', 'name': 'Bajo'},
                    ],
                    'layout': {
                        'title': 'Incidents Solved by Priority'
                    }
                }
            )
        ]
    )

    dash_app = dash.Dash(server=flask_app, name="Dashboard", url_base_pathname="/backlog/")
    df4= kpi4_cause_incident_b()
    df7= kpi7_incident_b()

    dash_app.layout = html.Div(
        children=[
            html.H1(children="Backlog Dashboard"),
            html.Div(html.H4("Incidents Status")),
            dcc.Graph(
                id="kpi7-graph",
                figure=px.bar(df7, x="incident_status", y="incident_status_number", barmode="group"),
            ),

            html.Div(html.H4("Number of Incidents by Type")),
            dash_table.DataTable(
                id='kpi4',
                columns=[
                    {"name": i, "id": i, "deletable": True, "selectable": True} for i in df4.columns
                ],
                data=df4.to_dict('records'),
                editable=False,
                sort_action="native",
                sort_mode="multi",
                row_deletable=False,
                fixed_columns=True,
                selected_columns=[],
                selected_rows=[],
                page_current= 0,
                page_size= 15

            )
        ]
    )

    dash_app = dash.Dash(server=flask_app, name="Dashboard", url_base_pathname="/close/")
    df8= kpi8_cause_incident_c()
    df9= kpi9_priority_closed()

    dash_app.layout = html.Div(
        children=[
            html.H1(children="Closed Dashboard"),
            dcc.Graph(
                figure={
                    'data': [
                        {'x': df9[0]['month'], 'y': df9[0]['incidences_number'], 'type': 'bar', 'name': 'Critical'},
                        {'x': df9[1]['month'], 'y': df9[1]['incidences_number'], 'type': 'bar', 'name': 'Alto'},
                        {'x': df9[2]['month'], 'y': df9[2]['incidences_number'], 'type': 'bar', 'name': 'Medio'},
                        {'x': df9[3]['month'], 'y': df9[3]['incidences_number'], 'type': 'bar', 'name': 'Bajo'},
                    ],
                    'layout': {
                        'title': 'Incidents Solved by Priority'
                    }
                }
            ),

            html.Div(html.H4("Number of Incidents by Type")),
            dash_table.DataTable(
                id='kpi8',
                columns=[
                    {"name": i, "id": i, "deletable": True, "selectable": True} for i in df8.columns
                ],
                data=df4.to_dict('records'),
                editable=False,
                sort_action="native",
                sort_mode="multi",
                row_deletable=False,
                fixed_columns=True,
                selected_columns=[],
                selected_rows=[],
                page_current= 0,
                page_size= 15
            )

        ]
    )

    return dash_app


import requests
import re
from requests.exceptions import RequestException
from urllib.parse import urlencode
import json
from bs4 import BeautifulSoup
from hashlib import md5
import os
from multiprocessing import Pool

def get_page_index(keyword,offset):
    data = {
        'aid': 24,
        'app_name': 'web_search',
        'offset': offset,
        'format': 'json',
        'keyword': '街拍',
        'autoload': 'true',
        'count': 20,
        'en_qc': 1,
        'cur_tab': 1,
        'from': 'search_tab',
        'pd': 'synthesis',
        'timestamp': 1571118951322
    }
    header = {
        'cookie': '__tasessionId=ampozol5g1563806844189; tt_webid=671649' +
                  '9234256455175; WEATHER_CITY=%E5%8C%97%E4%BA%AC; UM_distinctid=16c' +
                  '1a26e5e12df-040ada0c1d8081-c343162-100200-16c1a26e5e428c; CNZZDAT' +
                  'A1259612802=945869726-1563806204-https%253A%252F%252Fwww.google.c' +
                  'om%252F%7C1563806204; tt_webid=6716499234256455175; csrftoken=46' +
                  'a41d4141000920aea9354904736a2d; s_v_web_id=2b8f7242614ce9f3dd7cbf' +
                  '26d932530d',
        'host': 'www.toutiao.com',
        'referer': 'https://www.toutiao.com/search/?keyword=%E8%A1%97%E6%8B%8D',
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit' +
                      '/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36',
        'x-requested-with': 'XMLHttpRequest'
    }
    url = 'https://www.toutiao.com/api/search/content/?'+urlencode(data)
    try:
        response = requests.get(url,headers=header)
        response.encoding = 'utf-8'
        if response.status_code == 200:
            print("====request successful====")
            return response.text
        else:
            print(response.status_code)
            return None
    except RequestException:
        print('请求发生错误')
        return None

def parse_page_index(html):
    print('====parse page====')
    data = json.loads(html)
    if data and 'data' in data.keys():
        for item in data.get('data'):
            title = item.get('title')
            image_list = item.get('image_list')
            if image_list is not None:
                for image in image_list:
                    yield {
                        'title': title,
                        'image': image
                    }
    else:
        print('parse error')

# def get_detail_page(url):
#     try:
#         response = requests.get(url)
#         if response.status_code == 200:
#             return response.text
#         else:
#             return None
#     except RequestException:
#         print('get detail error!!!')
#         return None

# def parse_detail_page(html,url):
#     soup = BeautifulSoup(html,'lxml')
#     result = soup.select('title')
#     title = result[0].get_text() if result else ''
#     pattern = re.compile('gallery:\s+JSON.parse\("(.*?)"\)',re.S)
#     f_result = re.search(pattern,html)
#     print('f_result is ' + str(f_result))

def save_image(item):
    if not os.path.exists(item.get('title')):
        os.mkdir(item.get('title'))
    try:
        response = requests.get(item.get('image').get('url'))
        if response.status_code == 200:
            filepath = '{0}/{1}.{2}'.format(item.get('title'),md5(response.content).hexdigest(),'jpg')
            if not os.path.exists(filepath):
                with open(filepath,'wb') as f:
                    f.write(response.content)
                    f.close()
    except RequestException:
        print('save Error')

def main(offset):
    html = get_page_index('街拍', offset)
    image_list = parse_page_index(html)
    for item in image_list:
        print(item)
        save_image(item)

if __name__ == '__main__':
    groups = [x*20 for x in range(1,11)]
    pool = Pool()
    pool.map(main,groups)


import numpy as np
import matplotlib.pyplot as plt
import matplotlib.animation as animation
#%reset
#%matplotlib qt

#Inspired by FDheat.pdf, problem_set_fd_implicit.pdf

#grid, conditions
nx = 200
xmin = 0
xmax = 10
L = xmax-xmin
dx = L/(nx-1) #FDheat.pdf, prolly cause we count a node at x=0, count it as 1
nt = 200
nite = 400
a = 0.15
#dt = 0.5*dx**2/a #this is approx 0.02
dt = 1

r = a*dt/dx**2
#FDheat.pdf
#alpha*dt/dx**2<1/2, gives condition on t...

x = np.linspace(xmin,xmax,nx)

p = np.zeros((nt+1,nx))
xi = np.zeros((nite+1,nx))
rx = np.zeros((nite+1,nx))
p[0,:] = np.exp(-(x-5)**2) #should learn to do the cosine hill, for better behaviour at boundary x=0,L

#This is finite difference, based on self paper
A = (1+2*r)*np.eye(nx)+(-r)*np.eye(nx,k=1)+(-r)*np.eye(nx,k=-1)
A[0,0] = 1
A[0,1] = 0
A[-1,-1] = 1
A[-1,-2] = 0
Ainv = np.linalg.inv(A)

#diagonal matrix, for inversion iteration
Adiag = (1+2*r)*np.eye(nx)
Adiag[0,0] = 1
Adiag[-1,-1] = 1
#Matrix L^-1
Adiaginv = np.linalg.inv(Adiag)

fig = plt.figure()
ax = fig.gca()
ax.set_xlim(0,L)
ax.set_ylim(0,1.1)
ax.set_xlabel('x')
ax.set_ylabel('y')
ax.set_title('implicit Heat Equation,dt={}'.format(dt))
#ax.plot(x,p)
line, = ax.plot([],[])

def animate(i): #i increment with 1 each step

	#Here we do the actual calculation, need to change np.dot(Ainv,p)
	#first, x_1 = L^-1 * b
	xi[0,:] = np.dot(Adiaginv,p[i,:])
	#first, r_0 = b-L*x_1
	rx[0,:] = p[i,:]-np.dot(A,xi[0,:])
	#iterating x_2 = x_1 + L^-1*r_0
	for k in range(nite):
		#update x
		xi[k+1,:] = xi[k,:] + np.dot(Adiaginv,rx[k,:])
		#update r
		rx[k+1,:] = p[i,:]-np.dot(A,xi[k+1,:])

	p[i+1,:] = xi[-1,:]
	#p[i+1,:] = np.dot(Ainv,p[i,:])
	#ax.plot(x,p)
	line.set_data(x,p[i+1,:])
	if i == 3:
		plt.savefig('heat.png', bbox_inches='tight')
	return line

anim = animation.FuncAnimation(fig,animate, frames = nt, interval=500)#,blit=False)

plt.show()


# https://velog.io/@enchantee/%EB%B0%B1%EC%A4%80-1005-Python-kvth6jbu

import sys
from collections import deque

INPUT = sys.stdin.readline

def acm_craft(goal: int) -> int:
    queue, dp = deque(), [0 for _ in range(NUM + 1)]

    # 진입 차수가 0인 것을 찾아 큐에 넣음
    for i in range(1, NUM + 1):
        if IN_DEGREE[i] == 0:
            queue.append(i)
            dp[i] = BUILD_TIME[i]

    # 진입 차수를 줄여가며 건설 비용 갱신
    while queue:
        b = queue.popleft()
        for i in GRAPH[b]:
            IN_DEGREE[i] -= 1
            dp[i] = max(dp[b] + BUILD_TIME[i], dp[i])
            if IN_DEGREE[i] == 0:
                queue.append(i)

    return dp[goal]

if __name__ == "__main__":
    T = int(INPUT())
    for _ in range(T):
        NUM, RULE_NUM = map(int, INPUT().split())
        BUILD_TIME = [0] + list(map(int, INPUT().split()))
        GRAPH = [[] for _ in range(NUM + 1)]
        IN_DEGREE = [0 for _ in range(NUM + 1)]
        for _ in range(RULE_NUM):
            B1, B2 = map(int, INPUT().split())
            GRAPH[B1].append(B2)
            IN_DEGREE[B2] += 1
        GOAL = int(INPUT())
        print(acm_craft(GOAL))


import pandas as pd
import nltk
import spacy
from nltk.stem import PorterStemmer

# Load NLTK and spaCy models
nltk.download('punkt')
nlp = spacy.load('en_core_web_sm')

# Load the CSV dataset
df = pd.read_csv('storeTransactions.csv')  # Replace with your dataset file path

# Function for stemming using NLTK
def stem_text(text):
    stemmer = PorterStemmer()
    words = nltk.word_tokenize(text)
    stemmed_words = [stemmer.stem(word) for word in words]
    return ' '.join(stemmed_words)

# Function for lemmatization using spaCy
def lemmatize_text(text):
    doc = nlp(text)
    lemmatized_words = [token.lemma_ for token in doc]
    return ' '.join(lemmatized_words)

# Apply stemming and lemmatization to all columns
for column in df.columns:
    if df[column].dtype == 'O':  # Check if the column contains text data
        df[f'{column}_stemmed'] = df[column].apply(stem_text)
        df[f'{column}_lemmatized'] = df[column].apply(lemmatize_text)

# Save the processed dataset to a new CSV file
df.to_csv('sample_superstore_processed.csv', index=False)  # Change the output file path as needed


import pytest

from otx.algorithms.classification.tasks import ClassificationTrainTask
from otx.algorithms.common.tasks import BaseTask
from otx.api.configuration.configurable_parameters import ConfigurableParameters
from otx.api.entities.datasets import DatasetEntity
from otx.api.entities.label_schema import LabelSchemaEntity
from otx.api.entities.metrics import NullPerformance
from otx.api.entities.model import ModelConfiguration, ModelEntity
from tests.test_suite.e2e_test_system import e2e_pytest_unit
from tests.unit.algorithms.classification.test_helper import (
    DEFAULT_CLS_TEMPLATE,
    init_environment,
    setup_configurable_parameters,
)

@pytest.fixture
def otx_model():
    model_configuration = ModelConfiguration(
        configurable_parameters=ConfigurableParameters(header="header", description="description"),
        label_schema=LabelSchemaEntity(),
    )
    return ModelEntity(train_dataset=DatasetEntity(), configuration=model_configuration)

class TestOTXClsTaskTrain:
    @pytest.fixture(autouse=True)
    def setup(self, otx_model, tmp_dir_path) -> None:
        hyper_parameters, model_template = setup_configurable_parameters(DEFAULT_CLS_TEMPLATE)
        self.task_env, self.dataset = init_environment(params=hyper_parameters, model_template=model_template)
        self.model = otx_model
        self.cls_train_task = ClassificationTrainTask(self.task_env, output_path=str(tmp_dir_path))

    @e2e_pytest_unit
    def test_save_model(self, mocker):
        mocker.patch("torch.load", return_value="")
        self.cls_train_task.save_model(self.model)

        assert self.model.get_data("weights.pth")
        assert self.model.get_data("label_schema.json")

    @e2e_pytest_unit
    def test_train(self, mocker):
        from otx.algorithms.common.adapters.mmcv.hooks import OTXLoggerHook

        # generate some dummy learning curves
        mock_lcurve_val = OTXLoggerHook.Curve()
        mock_lcurve_val.x = [0, 1]
        mock_lcurve_val.y = [0.1, 0.2]
        # patch training process
        mocker.patch.object(BaseTask, "_run_task", return_value={"final_ckpt": ""})
        self.cls_train_task._learning_curves = {"val/accuracy_top-1": mock_lcurve_val}
        mocker.patch.object(ClassificationTrainTask, "save_model")
        self.cls_train_task.train(self.dataset, self.model)

        assert self.model.performance != NullPerformance()
        assert self.model.performance.score.value == 0.2

    @e2e_pytest_unit
    def test_cancel_training(self):
        self.cls_train_task.cancel_training()

        assert self.cls_train_task._should_stop is True


# A Hunter is derived from both a Mobile_Simulton and a Pulsator; it updates
#   like a Pulsator, but it also moves (either in a straight line
#   or in pursuit of Prey), and displays as a Pulsator.

from prey import Prey
from pulsator import Pulsator
from mobilesimulton import Mobile_Simulton
from math import atan2
import model

class Hunter(Pulsator,Mobile_Simulton):
  #  radius_constant = 200
    def __init__(self,x,y):
        Pulsator.__init__(self,x,y)
        width,height = self.get_dimension()
        variable_one = 0
        variable_two = 5
        Mobile_Simulton.__init__(self,x,y,width,height,variable_one,variable_two)
        self.randomize_angle()
        #self._new_x = x
        #self._new_y = y

    def update(self):#,model):
        new_list = []
        m = Pulsator.update(self)
       # self.set_location(self._new_x, self._new_y)
       # v = ((self._new_x, self._new_y))
      #  new_thing = model.find(lambda u : isinstance(u,Prey) and self.distance(u.get_location()) <= 200)#.contains((v)))
        new_thing  = model.find(lambda object : self.distance(object.get_location()) <= 200 and isinstance(object,Prey))
        if new_thing:
            for x in new_thing:
                new_list.append((self.distance(x.get_location()),x))
            new = min(new_list)
            first = self.get_location()
            second = new[1].get_location()
            first_variable = second[1] - first[1]
            second_variable = second[0] -first[0]

            self.set_angle(atan2(first_variable,second_variable))
        self.move()
        return m


"""
8 - Faça um programa que leia 2 notas de um aluno, verifique se as notas
são válidas e exiba na tela a média destas notas. Uma nota válida deve ser,
obrigatoriamente, um valor entre 0.00 e 10.00, onde caso a nota não possua um
valor válido, este fato deve ser informado ao usuário e o programa termina.
"""
sair = 0
print('\nAs perguntas serão feitas 5 vezes.\n')

while (sair < 5):

    nota1 = float(input("Digite a primeira nota: "))
    nota2 = float(input("Digite a segunda nota: "))
    media = (nota1 + nota2) / 2

    if nota1 <= 0.00 or nota1 >= 10.00:
        print('A primeira nota é inválida')

    elif nota2 <= 0.00 or nota2 >= 10.00:
        print('A segunda nota é inválida')

    elif media < 7.00:
        print(f'Voê não foi aprovado a sua média foi: {media}')

    else:
        print(f'A sua média é {media}')

    sair = sair + 1# Sem esse código, a condição de parada não será atingida,
    #gerando o que é chamado de loop infinito.

Exercicios Estruturas Logicas e Condicionais/exercicio 08 usando while.py


import torch
import torch.nn as nn
import torch.nn.functional as F

class LSTM(nn.Module):
    def __init__(
        self,
        input_size=8,
        sequence_num=31,
        lstm_dim=128,
        num_layers=2,
        output_size=1
    ):
        super().__init__()

        self.lstm = nn.LSTM(
            input_size,
            lstm_dim,
            num_layers,
            batch_first=True,
            bidirectional=True
        )
        # 维度？
        self.bn1 = nn.BatchNorm1d(lstm_dim*sequence_num*2)
        self.linear1 = nn.Linear(lstm_dim*sequence_num*2, 1)

    def forward(self,x):
        # 层的输出，结果和损失
        lstm_out, _ = self.lstm(x)
        # 除了第一批维，其余 flatten
        x = lstm_out.reshape(lstm_out.shape[0], -1)
        # 线性层之前的批归一化
        x = self.linear1(self.bn1(x))
        return x


from ast import arg
from cgitb import text
from functools import wraps

def information_decorator(func):
    @wraps(func)
    def inner(*args, **kwargs):
       print("func name: ",func.__name__)
       print("args: ",args)
       print("kargs: ",kwargs)
       res = func(*args, **kwargs)
       print("return value: ",res)
       print("return type: ",type(res))
       return res
    return inner

@information_decorator
def add4(w, x, y, z):
  return w+x

age = 0
text = ""
add4(1, 2, age=3, text="hello")


import requests
import random
from django.core.files import File
from django.core.files.temp import NamedTemporaryFile
from filer.models import Image

from dshop.models import ProductDefault, \
    ProductCategory, \
    ProductFilter, \
    ProductVariable, \
    ProductVariableVariant, \
    Attribute, \
    AttributeValue, \
    ProductBrand

def get_image():
    url = 'https://www.d-modules.com/static/img/logo-dmodules-black.png'
    try:
        r = requests.get(url)
    except Exception:
        r = requests.get(
                'https://miro.medium.com/max/2800/0*xMaFF2hSXpf_kIfG.jpg'
            )
    image_temp_file = NamedTemporaryFile(delete=True)
    image_temp_file.write(r.content)
    image_temp_file.flush()
    f = File(image_temp_file, name='image.png')
    img = Image.objects.create(
        original_filename='image',
        file=f,
        name='image'
    )
    return img

def filter_p():
    filt = ProductFilter.objects.create(name='ALL')
    return filt

def product_brand(data=None):
    if not data:
        data = {
            'name': 'D-Mart',
            'logo': get_image(),
            'order': 1
        }
    brand, created = ProductBrand.objects.get_or_create(**data)
    return brand

def category(data=None):
    if not data:
        data = {'name': 'Vegetable'}
    cat, created = ProductCategory.objects.get_or_create(**data)
    return cat

def attribute(name="KG"):
    attr, created = Attribute.objects.get_or_create(name=name)
    return attr

def attribute_value(attr, values=[1, 5]):
    value_list = []
    for val in values:
        attr_value, created = AttributeValue.objects.get_or_create(
                                  attribute=attr, value=val
                              )
        value_list.append(attr_value)
    return value_list

def product(filter_p, category, data=None):

    try:
        if not data:
            data = {
                'product_name': 'Capsicum',
                'product_code': 'caps',
                'slug': 'capsicum',
                'unit_price': 100.00,
                'quantity': 100,
                'order': 0,
                'caption': 'Capsicum'
            }
        product = ProductDefault.objects.create(**data)

        if category:
            product.categories.add(category)
        if filter_p:
            product.filters.add(filter_p)
    except Exception as e:
        return type(e)

    return product

def product_variable(data=None):

    try:
        if not data:
            data = {
                'product_name': 'Capsicum',
                'slug': 'capsicum-123',
                'order': 0,
                'caption': 'Capsicum'
            }
        product = ProductVariable.objects.create(**data)
    except Exception as e:
        return type(e)
    return product

def product_variant(product, data=None):

    try:
        if not data:
            data = {
                'product': product,
                'product_code': '00001',
                'unit_price': 10,
                'quantity': 100,
            }
        product_variant = ProductVariableVariant.objects.create(**data)
    except Exception as e:
        return type(e)

    return product_variant

def attach_attribute(product_v, attribute):

    try:
        if not product_v or not attribute:
            return None

        product_v.attribute.add(attribute)
    except Exception as e:
        return type(e)

    return True

def clear_data():
    ProductVariable.objects.all().delete()
    ProductCategory.objects.all().delete()
    ProductBrand.objects.all().delete()
    Attribute.objects.all().delete()

def create_data():
    clear_data()
    for i in range(1, 5):
        data = {
            'name': 'Brand ' + str(i),
            'logo': get_image(),
            'order': i
        }
        product_brand(data)
        category({'name': "Category " + str(i)})

    for cat in ProductCategory.objects.all():
        data = {
            'parent': cat,
            'name': 'Child 1: ' + cat.name
        }
        category(data)
        data = {
            'parent': cat,
            'name': 'Child 2: ' + cat.name
        }
        category(data)

    attr = attribute('Color')
    attribute_value(attr, ['Red', 'Blue', 'Green'])
    attr = attribute('Size')
    attribute_value(attr, ['S', 'M', 'L', 'XL'])

    product_counter = 1
    b_counter = 0
    for cat in ProductCategory.objects.all().order_by('id'):
        brand = ProductBrand.objects.all().order_by('id')[b_counter]
        data = {
            'product_name': 'Product ' + str(product_counter),
            'order': product_counter,
            'brand': brand,
            'caption': 'Test Product ' + str(product_counter)
        }
        product = product_variable(data)
        price = random.randint(10, 50)
        quantity = random.randint(5, 25)
        data = {
            'product': product,
            'product_code': ''.join(random.sample('0123456789', 5)),
            'unit_price': price,
            'quantity': quantity,
        }
        product_variant(product, data)

        product.categories.add(cat)
        product_counter += 1

        data = {
            'product_name': 'Product ' + str(product_counter),
            'order': product_counter,
            'brand': brand,
            'caption': 'Test Product ' + str(product_counter)
        }
        product = product_variable(data)
        price = random.randint(10, 50)
        quantity = random.randint(5, 25)
        data = {
            'product': product,
            'product_code': ''.join(random.sample('0123456789', 5)),
            'unit_price': price,
            'quantity': quantity,
        }
        product_variant(product, data)

        product.categories.add(cat)
        product_counter += 1
        b_counter += 1
        if b_counter == 4:
            b_counter = 0


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

import random

import probdist
import const

class PacketMorpher( object ):
    """Provides an interface to morph large chunks of bytes to a given target
    probability distribution. This is implemented by naively sampling the
    target probability distribution."""

    def __init__( self, dist=None ):
        """Initialize the PacketMorpher with a discrete probability
        distribution. If none is given, a distribution is randomly
        generated."""

        self.dist = dist if dist else \
                probdist.RandProbDist(lambda: random.randint(const.HDR_LENGTH, const.MTU))

    def morph( self, dataLen ):
        """Based on `dataLen', the length of the data to morph, this function
        returns a chopper function which is used to chop the data as well as
        the length of padding which is appended to the last protocol
        message."""

        breakPoints = []
        lastBreakPoint = 0
        progress = 0

        while progress < dataLen:
            newBreakPoint = progress + self.dist.randomSample()
            breakPoints.append((lastBreakPoint, newBreakPoint))
            lastBreakPoint = newBreakPoint
            progress = newBreakPoint

        paddingLen = progress - dataLen
        breakPoints.append((lastBreakPoint, progress))

        chopper = lambda data: [data[x:y] for (x, y) in breakPoints]

        return (chopper, paddingLen)

    def randomSample( self ):
        """Return a random sample of the stored probability distribution."""

        return self.dist.randomSample()


import pygame

from src.gui.Board import Board
from src.gui.Settings import Settings
from src.gui.TrainBoard import TrainBoard

# game constants
FPS = 30
WIDTH = 600
HEIGHT = 400

class Main:
    running = True

    def __init__(self):
        pygame.init()
        pygame.display.set_caption("Tic Tac Toe")
        self.clock = pygame.time.Clock()
        self.main_surface = pygame.display.set_mode((WIDTH, HEIGHT))
        self.settings_surface = Settings(self.main_surface)
        self.board_surface = Board(self.main_surface)
        self.train_board_surface = TrainBoard(self.main_surface, self.settings_surface.board_shape)

        self.current_screen = self.settings_surface.generate_surface()

    # main pygame loop
    def pygame_loop(self):
        while self.running:
            mouse_position = pygame.mouse.get_pos()
            events = pygame.event.get()

            if self.current_screen == "SETTINGS":
                self.settings_surface.handle_typing(events, mouse_position)

            for event in events:
                if event.type == pygame.QUIT:
                    self.running = False
                elif event.type == pygame.MOUSEBUTTONDOWN and self.current_screen == "SETTINGS":
                    self.current_screen = self.settings_surface.handle_clicks(mouse_position, [self.train_board_surface,
                                                                                self.board_surface])
                elif event.type == pygame.MOUSEBUTTONDOWN and self.current_screen == "TRAIN_BOARD":
                    self.current_screen = self.train_board_surface.handle_clicks(mouse_position, [self.settings_surface,
                                                                                self.board_surface])
                elif event.type == pygame.MOUSEBUTTONDOWN and self.current_screen == "BOARD":
                    self.current_screen = self.board_surface.handle_clicks(mouse_position, self.settings_surface)

            pygame.display.flip()
            self.clock.tick(FPS)

if __name__ == '__main__':
    Main().pygame_loop()


# -*- coding: utf-8 -*-

import sys

def crack(prices):
    if not prices or len(prices) < 2:
        return None

    min_price = prices[0]
    max_diff = -sys.maxsize

    for p in prices[1:]:
        if p - min_price > max_diff:
            max_diff = p - min_price
        if p < min_price:
            min_price = p

    return max_diff

if __name__ == '__main__':
    inputs = [
        [ 9, 11, 8, 5, 7, 10 ],
    ]

    for prices in inputs:
        print('\n Input: {}'.format(prices))

        max_profit = crack(prices)

        print(' Output: {}'.format(max_profit))


from django.core.management.base import BaseCommand, CommandError
from profiles.models import *

class Command(BaseCommand):
    help = 'delete profiles that\'s in wrong format'

    def handle(self, *args, **options):
        print("Total of {} profiles".format(len(Profile.objects.all())))
        for p in Profile.objects.all():
            for exp in p.experience_set.all():
                if not exp.company:
                    print("Deleting {} profile".format(p.username))
                    p.delete()
                    break


import osa
from math import ceil

def get_values(path):
    with open(path, 'r') as f:
        data = f.readlines()

    return data

def get_cost_rub(path):
    data = get_values(path)
    money_spent = 0

    for line in data:
        amount, currency = line.split()[1:]
        converted = convert_curr(amount, currency)
        money_spent += converted

    return ceil(money_spent)

def get_avg_temps(path):
    data = get_values(path)
    temps = []

    for line in data:
        amount = line.split()[0]
        temps.append(float(amount))

    avg_temp = convert_temp(sum(temps) / len(temps))
    return '{:.2f}'.format(avg_temp)

def get_sum_dist(path):
    data = get_values(path)
    dist_travelled = 0

    for line in data:
        distance = float(line.split()[1].replace(',', ''))
        dist_travelled += distance

    return '{:.2f}'.format(convert_dist(dist_travelled))

# конверции
def convert_curr(value, from_currency):
    client = osa.Client('http://fx.currencysystem.com/'
                        'webservices/CurrencyServer4.asmx?WSDL')
    conversion = from_currency, 'RUB'

    return client.service.ConvertToNum(None, *conversion, value, False)

def convert_temp(value):
    client = osa.Client('http://www.webservicex.net/'
                        'ConvertTemperature.asmx?WSDL')
    conversion = 'degreeFahrenheit', 'degreeCelsius'

    return client.service.ConvertTemp(value, *conversion)

def convert_dist(value):
    client = osa.Client('http://www.webservicex.net/length.asmx?WSDL')
    conversion = 'Miles', 'Kilometers'

    return client.service.ChangeLengthUnit(value, *conversion)

def main():
    print('Средняя температура:', get_avg_temps('temps.txt'), 'C')
    print('Сумма цен билетов:', get_cost_rub('currencies.txt'), 'руб.')
    print('Суммарное расстояние:', get_sum_dist('travel.txt'), 'км.')

main()


import numpy as np
import matplotlib.pyplot as plt

def example_function(x):
    return np.sin(x)

x0=0
x1=2*np.pi
delta_x=0.01

fxn_values=[]
x_values=[]

x=x0

while x<x1:
    new_f=example_function(x)
    x_values.append(x)
    fxn_values.append(new_f)
    x+=delta_x

plt.plot(x_values,fxn_values)
plt.show()