import itertools
import sys
import os
from typing import Dict, Union, List

import numpy as np
import scipy.stats as stats
from collections import defaultdict

import pandas as pd

from .bt import BT
from .utils import same_top_n, tau_to_percent, percent_outliers

DEFAULT_CONFIG: Dict[str, Union[float, List[str], int, bool]] = {
    'compute_pairwise': True,
    'n_bootstrap': 100,
    'epsilon_bt': 1e-9,
    'pval_threshold': 0.05,
    'aggregations': ['Mean', 'Median', 'BT']
}

class Pairformance(object):
    """
    Pairformance(df=eval_df, config=config)

    Tool to perform paired evaluation of automatic systems.
    It takes a dataframe as input with systems as columns and the system scores on test instances as rows (one row per test instance).

    The pairformance tool takes the pairing into account and provide:
    - Estimates of `mean`, `median`, and `BT` scores for each system
    - Confidence intervals for each estimate with bootstrap resampling of the data
    - Statistical testing for each of the three aggregation mechanisms
    - Pairwise comparison between each system. In particular, `pairformance` can produce the probability that any system has better score than any other system.
    - Diagnostic of the disagreement between `mean`, `median`, and `BT` about the ordering of systems
    - Diagnostic of the score distributions (outliers, measures of the strength of the pairing, score variances across systems and instances)
    - Plotting facilities to view global estimates, pairwise estimates, and the pairing structure for each pair of systems

    Attributes
    ----------
    df : pd.DataFrame
        evaluation dataframe with system scores (one column per system, one row per test instance)
    config: dict
        dictionary with configuration parameters

    Methods
    -------
    eval() -> dict
        Compute the main evaluation. Runs the global estimates with bootstrap resamples for all aggregation mechanisms considered.
        Run the pairwise comparison estimate with bootstrap resamples if the configuration parameter `compute_pairwise` is True.

    prob_a_better_b(system_a: str, system_b: str, df: pd.DataFrame = None) -> [Float, Float]
        Compute the probability that one system is better than other (special case of BT with 2 systems)
        It also reports the p-value testing whether the probability is significantly above 0.5.

    diagnostic_aggregation_agreement(system_results: dict = None) -> dict:
        Computes disagreement measures between aggregation mechanisms considered in the config file.
        The disagreement measures are the ones discussed in the paper.

    diagnostic_system_scores(eval_df: pd.DataFrame) -> dict:
        Computes diagnostic statistics from the distribution of system scores

    print_global_results() -> pd.DataFrame:
        Prints the global estimates for each system and each aggregation mechanism.

    print_pairwise_results() -> dict:
        Prints the pairwise comparison for each system and each aggregation mechanism.
    """
    def __init__(self, df: pd.DataFrame, config: dict = DEFAULT_CONFIG):
        """
        Intialization of Pairformance with evaluation dataframe and configuration parameters.

        The following configuration parameters are available:
        `aggregations`: a list of aggregation mechanisms to consider
        `compute_pairwise`: whether to run the analyses for each pair of systems
        `epsilon_bt`: when the iterative algorithm of BT does not vary by more than epsilon_bt, we stop.
        `n_bootstrap`: number of bootstrap resample of the data to take to compute confidence intervals
        `pval_threshold`: percentile to use for confidence interval. Example: 0.05 gives the (5, 95) percentiles.

        :param df: evaluation dataframe with system scores (one column per system, one row per test instance)
        :param config: dictionary with configuration parameters
        """
        self.df = df
        self.config = config

        if self.config['compute_pairwise']:
            self.data_matrices = {}
            self.pval_matrices = {}
            self.orders_of_systems = {}

    def _bootstrap_global_eval(self, df: pd.DataFrame) -> dict:
        """
        Runs the global estimates for all systems and aggregations considered with bootstrap resamples.

        :param df: evaluation dataframe with system scores (one column per system, one row per test instance)
        :return: dictionary of dataframes with bootstrap resamples of global estimates.
        """
        global_eval = defaultdict(list)

        for _ in range(self.config['n_bootstrap']):
            resample_df = df.sample(frac=1, replace=True)

            if 'Mean' in self.config['aggregations']:
                global_eval['Mean'].append(resample_df.mean(axis=0))

            if 'Median' in self.config['aggregations']:
                global_eval['Median'].append(resample_df.median(axis=0))

            if 'BT' in self.config['aggregations']:
                bt_results = BT(resample_df)
                global_eval['BT'].append(pd.Series(dict(zip(df.columns, bt_results))))

        self.global_results = {method: pd.concat(data, axis=1).T
                               for method, data in global_eval.items()}
        return self.global_results

    def _bootstrap_pairwise_eval(self, df: pd.DataFrame) -> dict:
        """
        Runs the pairwise comparison for all systems and aggregations considered with bootstrap resamples.

        :param df: evaluation dataframe with system scores (one column per system, one row per test instance)
        :return: dictionary of dataframes with bootstrap resample estimates of the pairwise comparisons
        """
        pairwise_data = defaultdict(dict)

        for system_a, system_b in itertools.combinations(df.columns, 2):
            if 'BT' in self.config['aggregations']:
                bt_scores = BT(df[[system_a, system_b]])
                bt_best_sys = (system_a if bt_scores[0] >= bt_scores[1] else system_b)
                bt_worst_sys = (system_b if bt_scores[0] >= bt_scores[1] else system_a)
                bt_median_of_differences = (df[bt_best_sys] - df[bt_worst_sys]) > 0
                p_a_better_b = bt_scores[0] / (bt_scores[0] + bt_scores[1])
                p_b_better_a = bt_scores[1] / (bt_scores[0] + bt_scores[1])
            else:
                bt_median_of_differences = None

            pval_mean, pval_median, pval_bt = \
                Pairformance._statistical_testing(df[system_a], df[system_b], bt_median_of_differences)

            # A -> B: information relative to whether A is better than B
            pairwise_data[system_a][system_b] = {}
            pairwise_data[system_b][system_a] = {}
            if 'Mean' in self.config['aggregations']:
                means_df = self.global_results['Mean']
                pairwise_data[system_a][system_b]['Difference of Means'] = means_df[system_a].mean(axis=0) - means_df[
                    system_b].mean(axis=0)
                pairwise_data[system_a][system_b]['p-val (paired t-test)'] = pval_mean

                pairwise_data[system_b][system_a]['Difference of Means'] = means_df[system_b].mean(axis=0) - means_df[
                    system_a].mean(axis=0)
                pairwise_data[system_b][system_a]['p-val (paired t-test)'] = pval_mean

            if 'Median' in self.config['aggregations']:
                medians_df = self.global_results['Median']
                pairwise_data[system_a][system_b]['Difference of Medians'] = medians_df[system_a].mean(axis=0) - \
                                                                             medians_df[system_b].mean(axis=0)
                pairwise_data[system_a][system_b]['p-val (Mood\'s test)'] = pval_median

                pairwise_data[system_b][system_a]['Difference of Medians'] = medians_df[system_b].mean(axis=0) - \
                                                                             medians_df[system_a].mean(axis=0)
                pairwise_data[system_b][system_a]['p-val (Mood\'s test)'] = pval_median

            if 'BT' in self.config['aggregations']:
                pairwise_data[system_a][system_b]['BT: P(A > B)'] = p_a_better_b
                pairwise_data[system_a][system_b]['p-val (Sign test)'] = pval_bt

                pairwise_data[system_b][system_a]['BT: P(A > B)'] = p_b_better_a
                pairwise_data[system_b][system_a]['p-val (Sign test)'] = pval_bt

        self.pairwise_results = pairwise_data
        return self.pairwise_results

    def eval(self) -> dict:
        """
        Compute the main evaluation. Runs the global estimates with bootstrap resamples for all aggregation mechanisms considered.
        Run the pairwise comparison estimate with bootstrap resamples if the configuration parameter `compute_pairwise` is True.

        :return: dictionary with global_result or both global_results and pairwise_results.
        """
        # sets the attribute self.global_results
        self._bootstrap_global_eval(self.df)

        if not self.config['compute_pairwise']:
            return {'global-results': self.global_results}

        # sets the attribute self.pairwise_results
        self._bootstrap_pairwise_eval(self.df)

        for agg_choice in self.config['aggregations']:
            self._prepare_data_matrix(agg_choice)

        return {'pairwise-results': self.pairwise_results,
                'global-results': self.global_results}

    def _prepare_data_matrix(self, aggreagation_choice: str = 'BT'):
        """
        Inner data structure management to cleanly organize the results of bootstrap resamples in the pairwise setup.

        :param aggreagation_choice: a choice of aggregation mechanism
        :return:
        """
        if aggreagation_choice == 'Mean':
            stat_key = 'Difference of Means'
            pval_key = 'p-val (paired t-test)'
        elif aggreagation_choice == 'Median':
            stat_key = 'Difference of Medians'
            pval_key = 'p-val (Mood\'s test)'
        else:
            stat_key = 'BT: P(A > B)'
            pval_key = 'p-val (Sign test)'

        nb_systems = len(self.pairwise_results)
        data_matrix = np.zeros((nb_systems, nb_systems))
        pval_matrix = np.zeros((nb_systems, nb_systems))

        # Order systems by performance
        order_of_systems = []
        for system, matches in self.pairwise_results.items():
            order_of_systems.append((system, np.sum([v[stat_key] for _, v in matches.items()])))

        sorted_systems = sorted(order_of_systems, key=lambda t: t[1])
        sorted_systems = [t[0] for t in sorted_systems]
        order_of_systems = dict(zip(sorted_systems, list(range(len(sorted_systems)))))

        for system_a, idx_a in order_of_systems.items():
            for system_b, idx_b in order_of_systems.items():
                if system_a == system_b:
                    # default difference between itself
                    data_matrix[idx_a][idx_b] = \
                        (0. if aggreagation_choice in ['Mean', 'Median'] else 0.5)

                    # Not significant by default
                    pval_matrix[idx_a][idx_b] = 1.
                    continue

                data_pair = self.pairwise_results[system_a][system_b]
                data_matrix[idx_a][idx_b] = data_pair[stat_key]
                pval_matrix[idx_a][idx_b] = data_pair[pval_key]

        self.data_matrices[aggreagation_choice] = data_matrix
        self.pval_matrices[aggreagation_choice] = pval_matrix
        self.orders_of_systems[aggreagation_choice] = order_of_systems

    def prob_a_better_b(self,
                        system_a: str,
                        system_b: str,
                        df: pd.DataFrame = None) -> [float, float]:

        """
        Compute the probability that one system is better than other (special case of BT with 2 systems)
        It also reports the p-value testing whether the probability is significantly above 0.5.

        :param system_a: name of the system a
        :param system_b: name of system b
        :param df: evaluation dataframe with system scores (one column per system, one row per test instance)
        :return: (P_A_betterthan_B, p_value)
        """
        if df is None:
            assert hasattr(self, 'df'), "No dataframe is available"
            df = self.df

        assert system_a in df.columns and system_b in df.columns, \
            "at least one of the systems provided is not in the dataframe"

        try:
            comparison_res = self.pairwise_results[system_a][system_b]
            return comparison_res['BT: P(A > B)'], comparison_res['p-val (Sign test)']
        except Exception as e:
            pass

        bt_scores = BT(df[[system_a, system_b]])
        p_a_better_b = bt_scores[0] / (bt_scores[0] + bt_scores[1])

        best_sys = (system_a if bt_scores[0] >= bt_scores[1] else system_b)
        worst_sys = (system_b if bt_scores[0] >= bt_scores[1] else system_a)
        median_of_differences = (df[best_sys] - df[worst_sys]) > 0

        pval_bt = stats.binom_test(np.sum(median_of_differences),
                                   n=len(median_of_differences), p
                                   =0.5)

        return p_a_better_b, pval_bt

    def diagnostic_aggregation_agreement(self, system_results: dict = None) -> dict:
        """
        Computes disagreement measures between aggregation mechanisms considered in the config file.
        The disagreement measures are the ones discussed in the paper.

        :param system_results: global system results as outputed by Pairformance.print_global_results()
        :return: dictionary with agreement statistics
        """
        if system_results is None:
            orig_stdout = sys.stdout
            sys.stdout = open(os.devnull, 'w')
            system_results = self.print_global_results()
            sys.stdout.close()
            sys.stdout = orig_stdout

        print("\n\n===== Aggregation Agreement =====")
        print("\t {:^25} {:^15} {:^15} {:^15}".format("Pairs of Agg.",
                                                      "Percentage Aggr.",
                                                      "Same Sota",
                                                      "Same Top-3"))

        agreements = {}
        for pairs_of_agg in itertools.combinations(self.config['aggregations'], 2):
            agg_a, agg_b = pairs_of_agg
            tau_agreement = tau_to_percent(stats.kendalltau(system_results[agg_a], system_results[agg_b])[0])
            same_sota = same_top_n(system_results[agg_a], system_results[agg_b], 1)
            same_top_3 = same_top_n(system_results[agg_a], system_results[agg_b], 1)
            agreements[str(pairs_of_agg)] = {
                'Percentage-agreement': tau_agreement,
                'Same-sota': same_sota,
                'Same-top-3': same_top_3
            }
            pair = f"{agg_a} vs. {agg_b}"
            line = "\t {:^25} {:^15.2f} {:^15} {:^15}".format(pair,
                                                              tau_agreement,
                                                              str(same_sota),
                                                              str(same_top_3))
            print(line)

        return agreements

    @staticmethod
    def diagnostic_system_scores(eval_df: pd.DataFrame) -> dict:
        """
        Computes the following diagnostic statistics from the distribution of system scores:
        `global-outliers-percentage`: take the whole array of data and compute the percentage of outliers
        `per-system-outliers-percentage`: percentage of outliers for each system independently
        `mean-row-std`: measure the std per test instance, then average this std across test instances, i.e., how much variance is there across system
        `rank-std-across-rows`: computes the order of systems per test instance, and measure how much the ranking varies across test instances, i.e., how much variance is there across ranking of systems
        `std-of-row-means`: computes the mean score of each test instance (across systems) and measure the std across test instances, i.e., how much overall scores vary across test instances

        :param eval_df: evaluation dataframe with system scores (one column per system, one row per test instance)
        :return: dictionary with diagnostic statistics
        """

        # Compute % outliers on the whole dataframe
        overall_outlier_percent = percent_outliers(eval_df.to_numpy().flatten())

        # Compute % outliers per system
        outlier_per_system = {}
        for systems in eval_df.columns:
            outlier_per_system[systems] = \
                percent_outliers(eval_df[systems].to_numpy().flatten())

        # Compute score variance per row
        mean_row_std = eval_df.std(axis=1).mean()

        # Compute rank disagreement per instance average over instances
        rank_std_across_rows = eval_df.rank(axis=1).std(axis=0).to_dict()

        # Compute mean score per row variance
        std_of_row_means = eval_df.mean(axis=1).std()

        # Compute system pairwise harmony
        pairwise_harmony = {}
        for system_a, system_b in itertools.combinations(eval_df.columns, 2):
            key = f"{system_a}-{system_b}"
            pairwise_harmony[key] = stats.kendalltau(eval_df[system_a], eval_df[system_b])

        return {
            'global-outliers-percentage': overall_outlier_percent,
            'per-system-outliers-percentage': outlier_per_system,
            'mean-row-std': mean_row_std,
            'rank-std-across-rows': rank_std_across_rows,
            'std-of-row-means': std_of_row_means
        }

    @staticmethod
    def _statistical_testing(system_a_scores, system_b_scores, median_of_differences=None):
        """
        Computes statistical tests related to mean, median, and BT (if median_of_differences is not None).
        In particular, it computes the paired t-test, the Mood's median test, and the sign test.

        :param system_a_scores: list of scores
        :param system_b_scores: list of scores
        :param median_of_differences: list of differences
        :return: (p_value_t_test, p_value_mood_test, p_value_sign_test)
        """
        # Statistical testing related to mean
        _, p_value_t_test = stats.ttest_rel(system_a_scores, system_b_scores)

        # Statistical testing related to median
        _, p_value_mood_test, _, _ = stats.median_test(system_a_scores, system_b_scores)

        # Statistical testing related to BT scores
        if median_of_differences is not None:
            p_value_sign_test = stats.binom_test(np.sum(median_of_differences),
                                       n=len(median_of_differences),
                                       p=0.5)
        else:
            p_value_sign_test = None

        return p_value_t_test, p_value_mood_test, p_value_sign_test

    # Logging

    def print_global_results(self) -> pd.DataFrame:
        """
        Prints the global estimates for each system and each aggregation mechanism.
        It requires self.global_results to exists.
        This is done by first running eval().

        :return: a dataframe with the results printed to stdout.
        """

        assert hasattr(self, 'global_results'), " ".join(["self.global_results should exists,",
                                                          "please run .eval() first"])

        results = {}
        print("\n\n===== Global Results =====")
        for agg, aggregation_results in self.global_results.items():
            ci_type = "({:.0%} bootstrap CI)".format(1 - self.config['pval_threshold'])
            print("\n*** {} ***".format(agg))

            print("\t {:^15} {:^15} {:^15}".format("Systems", "Est. score", ci_type))

            #             print(" ".join([sys.rjust(20) for sys in aggregation_results.keys()]))
            for system, system_results in aggregation_results.items():
                estimated_score = system_results.mean()
                lo_CI = system_results.quantile(self.config['pval_threshold'])
                hi_CI = system_results.quantile(1 - self.config['pval_threshold'])
                ci = "({:.3f}, {:.3f})".format(lo_CI, hi_CI)
                line = "\t {:^15} {:^15.3f} {:^15}".format(system, estimated_score, ci)
                print(line)

                if system not in results:
                    results[system] = {}
                results[system][agg] = estimated_score

        return pd.DataFrame.from_dict(results, orient='index')

    def print_pairwise_results(self) -> dict:
        """
        Prints the pairwise comparison for each system and each aggregation mechanism.
        It requires self.pairwise_results to exists.
        This is done by first running eval() with the configuration parameter `compute_pairwise` set to True.

        :return: a dict object with the results printed to stdout.
        """

        assert hasattr(self, 'pairwise_results'), " ".join(["self.global_results should exists,",
                                                            "please run .eval() first with the configuration parameter",
                                                            "`compute_pairwise` set to True"])

        results = {}
        print("\n\n===== Pairwise Results =====")
        for system, system_comparisons in self.pairwise_results.items():
            print("\n*** {} ***".format(system))

            if len(system_comparisons.values()) == 0:
                return results

            top_line = "\t {:^20}".format("Systems [A vs. B]")
            for key_results in list(system_comparisons.values())[0].keys():
                top_line += " {:^20}".format(key_results)
            print(top_line)

            for compared_system, comparison_results in system_comparisons.items():
                systems_involved = "{} vs. {}".format(system, compared_system)
                line = "\t {:^20}".format(systems_involved)
                #                if systems_involved not in results:
                results[systems_involved] = comparison_results

                for k, result in comparison_results.items():
                    line += " {:^20.3f}".format(result)
                print(line)

        return results


from django.urls import path, include

from . import views

urlpatterns = [
    path('register/', views.register, name='register'),
    path('profile/<int:profile_id>/', views.profile_page, name='profile_page'),
    path('profile/<int:pk>/review/', views.CommentCreateView.as_view(), name='review'),
    path('profile/<int:user_id>/<int:pk>/', views.CommentDeleteView.as_view(), name='comment-delete'),
    path('profile/<int:profile_id>/edit/', views.edit_profile, name='edit_profile'),
    path('inbox/', views.inbox, name='inbox'),
    path('request/<int:pk>/', views.AskDetailView.as_view(), name='ask-detail'),
    path('request/<int:pk>/delete/', views.AskDeleteView.as_view(), name='ask-delete'),
    path('request/<int:pk>/complete/', views.AskCompleteView.as_view(), name='ask-complete'),
    path('request/<int:ask_id>/accept/', views.accept_ask, name='ask-accept'),
    path('request/<int:ask_id>/decline/', views.decline_ask, name='ask-decline'),
]


import random

import tornado.ioloop
import tornado.web

class MainHandler(tornado.web.RequestHandler):
    def get(self):
        cats = [
            {"image": "images/1.jpg", "name": "Шаурма"},
            {"image": "images/2.jpg", "name": "Пуля"},
            {"image": "images/3.jpeg", "name": "Кама"},
            {"image": "images/4.jpg", "name": "Ежжи"},
            {"image": "images/5.jpg", "name": "Барсик"},
        ]
        catOfTheDay = random.choice(cats)
        self.render("page.html", cat=catOfTheDay)

settings = [
    (r"/", MainHandler),
    (r'/images/(.*)', tornado.web.StaticFileHandler, {'path': 'images'})
]
app = tornado.web.Application(settings)
app.listen(8888)
tornado.ioloop.IOLoop.current().start()


##Write a program that reads the words in words.txt and stores them as
##keys in a dictionary. It doesn’t matter what the values are. Then you
##can use the in operator as a fast way to check whether a string is in the
##dictionary
dic = dict()
count = 0
fhand = open('words.txt')
for line in fhand:
    words = line.split()
    for word in words:
        lowerWord = word.lower()
        if lowerWord not in dic:
            dic[lowerWord] = count
            count = count + 1

inp = input('Enter a word to check if it is in words.txt: ')
lowerInp = inp.lower()
if lowerInp in dic:
    print(lowerInp, 'is in text')
else:
    print(lowerInp, 'is not in text')


fabric = [[0] * 1000 for i in range(1000)]
dict = {i : [] for i in range(1000*1000)}
for line in open("input").readlines():
    parts = line.split(' ')
    temp = parts[2].split(',')
    row = int(temp[0])
    col = int(temp[1][0:-1])
    temp = parts[3].split('x')
    for r in range(int(temp[0])):
        for c in range(int(temp[1])):
            fabric[row+r][col+c] += 1
            dict[(row+r)*1000+(col+c)].append(int(parts[0][1:]))

sum = 0
labels = set(range(1265))
for i in range(1000*1000):
    if len(dict[i]) > 1:
        for label in dict[i]:
            labels.discard(label-1)

print(list(labels)[0]+1)


#!/usr/bin/env python3

def advent05b(f):
    free = set(range(0, 1024))

    for line in f:
        binstring = line.replace('F','0').replace('B','1').replace('L','0').replace('R','1')
        free.remove(int(binstring, 2))

    for i in range(1024):
        if i not in free:
            break
        free.remove(i)

    for i in reversed(range(1024)):
        if i not in free:
            break
        free.remove(i)

    return free.pop()

if __name__ == '__main__':
    import sys
    print(advent05b(sys.stdin))


class Solution:
    def maxSubarraySumCircular(self, nums: List[int]) -> int:
        maxSum,minSum = nums[0],nums[0]
        curMax,curMin = 0,0
        totalSum = 0
        for num in nums:
            curMax = max(curMax+num,num)
            curMin = min(curMin+num,num)
            totalSum += num
            maxSum = max(maxSum,curMax)
            minSum = min(minSum,curMin)
        return max(totalSum-minSum,maxSum) if maxSum>0 else maxSum


from sequana.lazy import pylab
from sequana.lazy import pandas as pd
from sequana.utils.pandas import PandasReader
from sequana.viz.venn import plot_venn

import colorlog

logger = colorlog.getLogger(__name__)

__all__ = ["MACS3Reader", "PeakConsensus"]

class MACS3Reader:
    """This class reads output of macs3 tool

    ::

        from sequana import MACS3Reader
        mr = MACS3Reader(data)
        mr.df
        mr.plot_volcano()

    If input file ends in .xls, we assume this is a NAME_peaks.xls file. It is
    therefore a tabulated file where columns are:

    - chromosome name
    - start position of peak
    - end position of peak
    - length of peak region
    - absolute peak summit position
    - pileup height at peak summit
    - -log10(pvalue) for the peak summit (e.g. pvalue =1e-10, then this value should be 10)
    - fold enrichment for this peak summit against random Poisson distribution with local lambda,
    - -log10(qvalue) at peak summit

    Note that coordinates in XLS is 1-based which is different from BED format
    that follows. When --broad is enabled for broad peak calling, the pileup, p-value,
    q-value, and fold change in the XLS file will be the mean value across
    the entire peak region, since peak summit won't be called in broad peak calling mode.

    NAME_peaks.narrowPeak is BED6+4 format file which contains the peak locations
    together with peak summit, p-value, and q-value.

    The fifth column is the **score** calculate as int(-10*log10_pvalue) or
    int(-10*log10_pvalue) where log10-pvalue/log10-qvalue is the 8th or 9th column
    depending on whether -p (pvalue) or -q (qvalue) is used as score cutoff. The 7th
    columns stores the fold-change at peak summit. The 8th is -log10pvalue at peak summit
    and the 9th is -log10qvalue at peak summit. The 10th is the relative summit position
    to peak start equivalent to absolute peak summit position in the xls file.

    NAME_peaks.broadPeak is in BED6+3 format which is similar to narrowPeak file, except
    for missing the 10th column for annotating peak summits. This file and the
    gappedPeak file will only be available when --broad is enabled. Since in the
    broad peak calling mode, the peak summit won't be called, the values in the 5th,
    and 7-9th columns are the mean value across all positions in the peak region.
    Refer to narrowPeak if you want to fix the value issue in the 5th column

    .. reference:: https://github.com/macs3-project/MACS/blob/master/docs/callpeak.md
    """

    def __init__(self, filename):

        # .xls is not stuctured similarly to .narrowPeak
        if filename.endswith(".xls"):
            #
            self.df = PandasReader(filename, comment="#", sep="\t").df
            # narrow and broad files have this header in common and can be checked.
            for x in [
                "chr",
                "start",
                "end",
                "abs_summit",
                "-log10(pvalue)",
                "fold_enrichment",
                "-log10(qvalue)",
                "name",
            ]:
                # we could have also pileup depending on the user's options
                assert x in self.df.columns
            self.df["stop"] = self.df["end"]
        elif filename.endswith("narrowPeak"):
            columns = [
                "chr",
                "start",
                "stop",
                "name",
                "score",
                "NA",
                "fold_enrichment",
                "-log10(pvalue)",
                "-log10(qvalue)",
                "abs_summit_from_start",
            ]
            self.df = PandasReader(filename, header=None, sep="\t", columns=columns).df
        elif filename.endswith("broadPeak"):
            columns = [
                "chr",
                "start",
                "stop",
                "name",
                "score",
                "NA",
                "fold_enrichment",
                "-log10(pvalue)",
                "-log10(qvalue)",
            ]
            self.df = PandasReader(filename, header=None, sep="\t", columns=columns).df
        self.df["length"] = self.df["stop"] - self.df["start"]
        #

    def __len__(self):
        return len(self.df)

    def plot_volcano(self, plotly=False, marker_color="b", title=""):
        """Plots -log10 p-value versus fold change of all peaks"""

        if plotly:
            from plotly import express as px

            df = self.df.copy()
            df["log_adj_pvalue"] = self.df["-log10(pvalue)"]
            df["log2FoldChange"] = pylab.log2(self.df["fold_enrichment"])
            df["info"] = df["chr"] + ":" + df["start"].astype(str) + "-" + df["stop"].astype(str)

            fig = px.scatter(
                df,
                x="log2FoldChange",
                y="log_adj_pvalue",
                hover_name="info",
                log_y=False,
                color="length",
                height=600,
                title=title,
                labels={"log2_fold_enrichment": "log10 p-value"},
            )
            return fig

        pylab.scatter(
            pylab.log2(self.df["fold_enrichment"]),
            self.df["-log10(pvalue)"],
            marker="o",
            alpha=0.5,
            color=marker_color,
            lw=0,
            s=self.df["length"] / self.df["length"].max() * 400,
        )
        pylab.xlabel("Fold enrichment")
        pylab.ylabel("log10 pvalue")
        pylab.title(title)

class PeakConsensus:
    def __init__(self, f1, f2):
        self.df1 = MACS3Reader(f1).df
        self.df1["category"] = "first"
        self.df2 = MACS3Reader(f2).df
        self.df2["category"] = "second"
        self.df_merged = self.merge()

    def merge(self, overlap=0.2):
        df = pd.concat([self.df1, self.df2]).sort_values(["chr", "start"])
        # if overlap at least one base, we merge the peaks and label them with
        # common information, otherwise we report the original peak

        merged = []
        prev = None
        N1 = 0
        N2 = 0
        N12 = 0
        skip_next = True
        for k, current in df.iterrows():
            if skip_next:
                prev = current
                skip_next = False
                continue

            # if current overlaps the prev start or end, there is overlap
            # or if current included in prev there current and prev overlaps
            if current["start"] <= prev["start"] and current["stop"] >= prev["start"]:
                overlap = True
                N12 += 1
            elif current["start"] <= prev["stop"] and current["stop"] >= prev["stop"]:
                overlap = True
                N12 += 1
            elif current["start"] >= prev["start"] and current["stop"] <= prev["stop"]:
                overlap = True
                N12 += 1
            else:
                overlap = False
                if prev["name"].startswith("1_vs_6_7"):
                    N1 += 1
                elif prev["name"].startswith("2_vs_6_7"):
                    N2 += 1

            if overlap:
                m = min(current["start"], prev["start"])
                M = max(current["stop"], prev["stop"])
                data = current.copy()
                data["start"] = m
                data["stop"] = M
                data["category"] = "both"
                merged.append(data)
                skip_next = True
            else:
                m = min(current["start"], prev["start"])
                M = max(current["stop"], prev["stop"])
                merged.append(prev)
                skip_next = False

            prev = current
        df = pd.DataFrame(merged)
        df = df.reset_index(drop=True)
        return df

    def plot_venn(self, title="", labels=[]):

        plot_venn(
            (
                set(self.df_merged.query("category in ['first', 'both']").index),
                set(self.df_merged.query("category in ['second', 'both']").index),
            ),
            labels=(("first", "second")),
        )

    def to_saf(self, filename):
        """For now, all strand are categorised as strand + .
        strand not used in the pipeline for now."""
        df = self.df_merged.reset_index()
        df["strand"] = "+"
        df["GeneID"] = df["index"]
        df[["GeneID", "chr", "start", "stop", "strand", "category"]].to_csv(filename, sep="\t", index=None)

    def to_bed(self, filename):
        # output to be used by homer
        # annotatePeaks.pl file.bed file.fa -gid -gff file.gff
        # GeneID seems to have to start with Interval_ ??

        df = self.df_merged.reset_index()
        df["strand"] = "+"
        df["GeneID"] = ["Interval_{}".format(x) for x in df["index"]]
        mapper = {"both": 3, "first": 1, "second": 2}
        df["score"] = [mapper[x] for x in df["category"]]
        df[["chr", "start", "stop", "GeneID", "score", "strand"]].to_csv(filename, sep="\t", index=None, header=False)


'''
假设你是一位顺风车司机，车上最初有 capacity 个空座位可以用来载客。由于道路的限制，车 只能 向一个方向行驶（也就是说，不允许掉头或改变方向，你可以将其想象为一个向量）。

这儿有一份乘客行程计划表 trips[][]，其中 trips[i] = [num_passengers, start_location, end_location] 包含了第 i 组乘客的行程信息：

必须接送的乘客数量；
乘客的上车地点；
以及乘客的下车地点。
这些给出的地点位置是从你的 初始 出发位置向前行驶到这些地点所需的距离（它们一定在你的行驶方向上）。

请你根据给出的行程计划表和车子的座位数，来判断你的车是否可以顺利完成接送所有乘客的任务（当且仅当你可以在所有给定的行程中接送所有乘客时，返回 true，否则请返回 false）。

示例 1：

输入：trips = [[2,1,5],[3,3,7]], capacity = 4
输出：false
示例 2：

输入：trips = [[2,1,5],[3,3,7]], capacity = 5
输出：true
示例 3：

输入：trips = [[2,1,5],[3,5,7]], capacity = 3
输出：true

来源：力扣（LeetCode）
链接：https://leetcode-cn.com/problems/car-pooling
著作权归领扣网络所有。商业转载请联系官方授权，非商业转载请注明出处。

'''
class Solution(object):
    def carPooling(self, trips, capacity):
        """
        :type trips: List[List[int]]
        :type capacity: int
        :rtype: bool
        线段重合问题
        """
        n = len(trips)
        cur_people = [0]*1001
        for ind in range(n):
            cur_people[trips[ind][1]] += trips[ind][0] # ind time people add
            cur_people[trips[ind][2]] -= trips[ind][0] # ind time people minus
        for ind in range(1,1001):
            cur_people[ind] += cur_people[ind-1]
            if cur_people[ind] > capacity:
                return False
        return True


import cv2
import mediapipe as mp
import time

class handDetector():
    #Detection model initialization
    def __init__(self, mode=False, maxHands = 2, modelCom = 1, detectionCon = 0.5, trackCon=0.5 ):
        # static_image_mode = False,
        # max_num_hands = 2,
        # model_complexity = 1,
        # min_detection_confidence = 0.5,
        # min_tracking_confidence = 0.5

        self.mode = mode
        self.maxHands = maxHands
        self.modelCom = modelCom
        self.detectionCon = detectionCon
        self.trackCon = trackCon

        self.mpHands = mp.solutions.hands #Mediapipe hand detection
        self.hands = self.mpHands.Hands(self.mode,self.maxHands,self.modelCom,self.detectionCon,self.trackCon) #create an object for detect hands
        self.mpDraw = mp.solutions.drawing_utils #object for draw hand landmarks

    #hand detector method
    def findHands(self, img, draw=True):
        imgRGB = cv2.cvtColor(img, cv2.COLOR_BGR2RGB) #convert image to RGB
        self.results = self.hands.process(imgRGB) #call hands object

        #retrived and visualized hands info
        if self.results.multi_hand_landmarks:
            for handLMS in self.results.multi_hand_landmarks:
                #Check weather draw is True
                if draw:
                    self.mpDraw.draw_landmarks(img, handLMS, self.mpHands.HAND_CONNECTIONS) #visualized the hand landmarks

        return img

    #land mark position values extract
    def findPosition(self, img, handNo=0, draw=True):
        lmList = [] #landmark list

        if self.results.multi_hand_landmarks:
            myHand = self.results.multi_hand_landmarks[handNo]

            for id, lm in enumerate(myHand.landmark): #landmarks details/locations
                h, w, c = img.shape
                cx, cy = int(lm.x*w), int(lm.y*h) #position according to display pixles
                lmList.append([id,cx, cy])

                if draw:
                    cv2.circle(img, (cx,cy), 7, (0,0,255), cv2.FILLED)

        return lmList

def main():
    #define the webcam
    cap = cv2.VideoCapture(0)

    detector = handDetector() #call hand detector class

    pTime = 0 #varibles for calculate FPS
    cTime = 0

    while True:
        success, img = cap.read()
        img = detector.findHands(img) #call the method
        lmList = detector.findPosition(img)

        if len(lmList) !=0: #check weather any hand detected
            print(lmList[4])

        #Calculate the FPS
        cTime = time.time()
        fps = 1/(cTime-pTime)
        pTime = cTime
        cv2.putText(img, str(int(fps)), (10,70), cv2.FONT_HERSHEY_PLAIN , 3, (255,0,255), 3)

        cv2.imshow("Image", img)
        cv2.waitKey(1)

if __name__ == "__main__":
    main()


# pip install paho-mqtt
import paho.mqtt.client as mqtt # Import the MQTT library
import time # The time library is useful for delays

# Our "on message" event
def messageFunction (client, userdata, message):
    topic = str(message.topic)
    message = str(message.payload.decode("utf-8"))
    print(topic +" : "+ message)

ourClient = mqtt.Client("makerio_mqtt") # Create a MQTT client object & giva any name
ourClient.username_pw_set("etmhjbta","qCC5wB4eE6f0")
ourClient.connect("tailor.cloudmqtt.com", 13544) # Connect to the test MQTT broker
ourClient.subscribe("switch") # Subscribe to the topic AC_unit
ourClient.on_message = messageFunction # Attach the messageFunction to subscription
ourClient.loop_start() # Start the MQTT client

# # Main program loop
# while(1):
#     ourClient.publish("switch", "on") # Publish message to MQTT broker
#     time.sleep(1) # Sleep for a second
input()


import matplotlib.pyplot as plt
from casadi import cos, sin, pi, sqrt, linspace
import matplotlib
from pandas import read_csv
import numpy as np

def latexify(fig_width=None, fig_height=None):
    """Set up matplotlib's RC params for LaTeX plotting.
    Call this before plotting a figure.

    Parameters
    ----------
    fig_width : float, optional, inches
    fig_height : float,  optional, inches
    columns : {1, 2}
    """

    # code adapted from http://www.scipy.org/Cookbook/Matplotlib/LaTeX_Examples

    # Width and max height in inches for IEEE journals taken from
    # computer.org/cms/Computer.org/Journal%20templates/transactions_art_guide.pdf

    if fig_width is None:
        fig_width = 5  # width in inches

    if fig_height is None:
        golden_mean = (sqrt(5)-1.0)/2.0    # Aesthetic ratio
        fig_height = fig_width*golden_mean # height in inches

    params = {'backend': 'ps',
              'text.latex.preamble': r"\usepackage{gensymb} \usepackage{amsmath}",
              'axes.labelsize': 10, # fontsize for x and y labels (was 10)
              'axes.titlesize': 10,
              'legend.fontsize': 10, # was 10
              'xtick.labelsize': 10,
              'ytick.labelsize': 10,
              'text.usetex': True,
              'figure.figsize': [fig_width, fig_height],
              'font.family': 'serif'
    }

    matplotlib.rcParams.update(params)

def visualize_trajectory(x, y, phi, L, obstacles=None, save_fig=False, fig_name=None):
    latexify(fig_width=3, fig_height=3)
    marker_size = 5
    fig, ax = plt.subplots()
    ax.scatter(9, 9, marker='x')
    for (xk, yk, phik) in zip(x, y, phi):
        r_propeller_x = xk + L*cos(phik)
        r_propeller_y = yk + L*sin(phik)

        l_propeller_x = xk - L*cos(phik)
        l_propeller_y = yk - L*sin(phik)

        ax.scatter(xk, yk, marker_size, marker='s', color = 'black')
        ax.plot([xk, r_propeller_x], [yk, r_propeller_y], 'b')
        ax.plot([xk, l_propeller_x], [yk, l_propeller_y], 'b')

    if obstacles != None:
        for o in obstacles:
            px_obst_k = o[0][0]
            py_obst_k = o[0][1]
            r_obst_k = o[1]
            theta = linspace(0, 2*pi, 100)
            xobst1 = px_obst_k + r_obst_k*cos(theta)
            xobst2 = py_obst_k + r_obst_k*sin(theta)
            plt.plot(xobst1, xobst2, 'r')

    ax.set_xlim([0, 10])
    ax.set_ylim([0, 10])
    ax.set_xlabel('X (m)')
    ax.set_ylabel('Y (m)')
    ax.set_aspect(1)
    plt.show()

    if save_fig:
        fig.savefig(fig_name + '.svg', format='svg', dpi=1200)

def plot_controls(tgrid, u, save_fig=False, fig_name=None):
    latexify(fig_width=2, fig_height=1.5)
    fig, ax = plt.subplots()
    ax.step(tgrid[0:-1], u[0,:], where='post', label=r'$F_1$')
    ax.step(tgrid[0:-1], u[1,:], where='post', label=r'$F_2$')
    ax.set_xlabel(r'$k$ (iteration)')
    ax.set_ylabel(r'$F$ (N)')
    ax.legend()
    ax.grid()
    plt.show()

    if save_fig:
        fig.savefig(fig_name + '.svg', format='svg', dpi=1200)

def plot_pose(tgrid, pose, save_fig=False):
    latexify()
    fig, ax = plt.subplots()
    ax.plot(tgrid, pose[0,:], label=r'$x$')
    ax.plot(tgrid, pose[1,:], label=r'$y$')
    ax.plot(tgrid, pose[2,:], label=r'$\phi$')
    ax.set_xlabel(r'$t$ (sec)')
    ax.set_ylabel(r'$u$ (N)')
    ax.legend()
    ax.grid()
    plt.show()

    if save_fig:
        fig.savefig('drone_pose.svg', format='svg', dpi=1200)

def plot_RL_statistics(save_fig=False):
    latexify(fig_width=11, fig_height=3)

    # load trainig statistics
    sac_reward = read_csv('report/SAC7_reward.csv')
    td3_reward = read_csv('report/TD37_reward.csv')

    sac_actor_loss = read_csv('report/SAC7_actor_loss.csv')
    td3_actor_loss = read_csv('report/TD37_actor_loss.csv')

    sac_critic_loss = read_csv('report/SAC7_critic_loss.csv')
    td3_critic_loss = read_csv('report/TD37_critic_loss.csv')

    fig, ax = plt.subplots(1,3)
    ax[0].plot(1e-5*sac_reward.values[:,1], 1e-3*sac_reward.values[:,2], label='SAC')
    ax[0].plot(1e-5*td3_reward.values[:,1], 1e-3*td3_reward.values[:,2], label='TD3')
    ax[0].set_xlabel(r'time steps $\times\ 10^5$')
    ax[0].set_ylabel(r'episode return $\times\ 10^3$')
    ax[0].set_ylim(-14, -4)
    ax[0].legend()

    ax[1].plot(1e-5*sac_actor_loss.values[:,1], 1e-3*sac_actor_loss.values[:,2], label='SAC')
    ax[1].plot(1e-5*td3_actor_loss.values[:,1], 1e-3*td3_actor_loss.values[:,2], label='TD3')
    ax[1].set_xlabel(r'time steps $\times\ 10^5$')
    ax[1].set_ylabel(r'actor loss $\times\ 10^3$')
    ax[1].set_ylim(0, 8)
    ax[1].legend()

    ax[2].plot(1e-5*sac_critic_loss.values[:,1], 1e-4*sac_critic_loss.values[:,2], label='SAC')
    ax[2].plot(1e-5*td3_critic_loss.values[:,1], 1e-4*td3_critic_loss.values[:,2], label='TD3')
    ax[2].set_xlabel(r'time steps $\times\ 10^5$')
    ax[2].set_ylabel(r'critic loss $\times\ 10^4$')
    ax[2].set_ylim(-1, 25)
    ax[2].legend()

    plt.show()

    if save_fig:
        fig.savefig('report/RL_statistics.svg', format='svg', dpi=1200)

def plot_controls_RL(t_grid_td3, u_traj_td31, t_grid_sac, u_traj_sac1, save_fig=False):
    latexify(fig_width=2, fig_height=1.5)
    fig, ax = plt.subplots()
    ax.step(t_grid_td3[0:-1], u_traj_td31[:,0], where='post', label=r'$F_1$ TD3')
    ax.step(t_grid_td3[0:-1], u_traj_td31[:,1], where='post', label=r'$F_2$ TD3')
    ax.step(t_grid_sac[0:-1], u_traj_sac1[:,0], '--', where='post', label=r'$F_1$ SAC')
    ax.step(t_grid_sac[0:-1], u_traj_sac1[:,1], '--', where='post', label=r'$F_2$ SAC')
    ax.set_xlabel(r'$k$ (iteration)')
    ax.set_ylabel(r'$F$ (N)')
    ax.legend(loc='upper right')
    ax.grid()
    plt.show()
    if save_fig:
            fig.savefig('report/controls_RL.svg', format='svg', dpi=1200)

def visualize_trajectory_RL(x_traj_td31, x_traj_td32, x_traj_sac1, x_traj_sac2, L, save_fig=False):
    latexify(fig_width=3, fig_height=3)
    marker_size = 5
    fig, ax = plt.subplots()
    ax.scatter(9, 9, marker='x')
    for (xk, yk, phik) in zip(x_traj_td31[::15,0], x_traj_td31[::15,1], x_traj_td31[::15,2]):
        r_propeller_x = xk + L*np.cos(phik)
        r_propeller_y = yk + L*np.sin(phik)

        l_propeller_x = xk - L*np.cos(phik)
        l_propeller_y = yk - L*np.sin(phik)

        ax.scatter(xk, yk, marker_size, marker='s', color = 'black')
        ax.plot([xk, r_propeller_x], [yk, r_propeller_y], 'b')
        ax.plot([xk, l_propeller_x], [yk, l_propeller_y], 'b')

    for (xk, yk, phik) in zip(x_traj_td32[::15,0], x_traj_td32[::15,1], x_traj_td32[::15,2]):
        r_propeller_x = xk + L*np.cos(phik)
        r_propeller_y = yk + L*np.sin(phik)

        l_propeller_x = xk - L*np.cos(phik)
        l_propeller_y = yk - L*np.sin(phik)

        ax.scatter(xk, yk, marker_size, marker='s', color = 'black')
        ax.plot([xk, r_propeller_x], [yk, r_propeller_y], 'b')
        ax.plot([xk, l_propeller_x], [yk, l_propeller_y], 'b')

    for (xk, yk, phik) in zip(x_traj_sac1[::15,0], x_traj_sac1[::15,1], x_traj_sac1[::15,2]):
        r_propeller_x = xk + L*np.cos(phik)
        r_propeller_y = yk + L*np.sin(phik)

        l_propeller_x = xk - L*np.cos(phik)
        l_propeller_y = yk - L*np.sin(phik)

        ax.scatter(xk, yk, marker_size, marker='s', color = 'black')
        ax.plot([xk, r_propeller_x], [yk, r_propeller_y], 'r')
        ax.plot([xk, l_propeller_x], [yk, l_propeller_y], 'r')

    for (xk, yk, phik) in zip(x_traj_sac2[::15,0], x_traj_sac2[::15,1], x_traj_sac2[::15,2]):
        r_propeller_x = xk + L*np.cos(phik)
        r_propeller_y = yk + L*np.sin(phik)

        l_propeller_x = xk - L*np.cos(phik)
        l_propeller_y = yk - L*np.sin(phik)

        ax.scatter(xk, yk, marker_size, marker='s', color = 'black')
        ax.plot([xk, r_propeller_x], [yk, r_propeller_y], 'r')
        ax.plot([xk, l_propeller_x], [yk, l_propeller_y], 'r')

    ax.set_xlim([0, 10])
    ax.set_ylim([0, 10])
    ax.set_xlabel('X (m)')
    ax.set_ylabel('Y (m)')
    ax.set_aspect(1)
    plt.show()

    if save_fig:
            fig.savefig('report/trajectory_RL.svg', format='svg', dpi=1200)


__author__ = 'Anna Nikishova'

import os
import numpy as np
from scipy.interpolate import griddata
import matplotlib.pyplot as plt

def plot_res(prediction, original, name, num, out_color):
    plt.figure(figsize=(5, 11))
    axis1 = plt.subplot(311)
    plt.title('{} training sample of size: {}'.format(type_train, str(len(train_n))))
    plt.plot(prediction, '.', label='Linear interpolator', color=out_color)
    plt.plot(original, '.', label='Turbulence model', color='green')
    plt.xlabel('Run number')
    plt.ylabel('Prediction of {}'.format(name))
    plt.legend()
    plt.grid()
    # plt.yscale("log")
    plt.subplot(312)
    plt.plot(prediction- original, '.', color=out_color)
    plt.grid()
    # plt.yscale("log")
    plt.xlabel('Run number')
    plt.ylabel('Error')
    plt.subplot(313)
    plt.plot(np.fabs(prediction- original)/original * 100, '.', color=out_color)
    plt.grid()
    plt.xlabel('Run number')
    plt.ylabel('Relative error (%)')
    # plt.yscale("log")
    plt.tight_layout()
    plt.savefig('data/GP_prediction_' + name + '_' + type_train + '_' + str(len(train_n)) + '(linear).png',bbox_inches='tight', dpi=100)
    plt.show()
    plt.clf()

data = np.genfromtxt('data/AUG_gem_inoutput.txt', skip_header=1)
input_samples_all = data[:, 1:58]
output_samples_all = data[:, 58:]
input_dim = 8
N_runs = len(input_samples_all[:, 0])

names_in_outputs = ['time', 'Te-ft1', 'Te-ft2', 'Te-ft3', 'Te-ft4', 'Te-ft5', 'Te-ft6', 'Te-ft7', 'Te-ft8', 'dTe-ft1', 'dTe-ft2', 'dTe-ft3', 'dTe-ft4', 'dTe-ft5', 'dTe-ft6', 'dTe-ft7', 'dTe-ft8', 'Ti-ft1', 'Ti-ft2', 'Ti-ft3', 'Ti-ft4', 'Ti-ft5', 'Ti-ft6', 'Ti-ft7', 'Ti-ft8', 'dTi-ft1', 'dTi-ft2', 'dTi-ft3', 'dTi-ft4', 'dTi-ft5', 'dTi-ft6', 'dTi-ft7', 'dTi-ft8', 'ne-ft1', 'ne-ft2', 'ne-ft3', 'ne-ft4', 'ne-ft5', 'ne-ft6', 'ne-ft7', 'ne-ft8', 'dne-ft1', 'dne-ft2', 'dne-ft3', 'dne-ft4', 'dne-ft5', 'dne-ft6', 'dne-ft7', 'dne-ft8', 'q-ft1', 'q-ft2', 'q-ft3', 'q-ft4', 'q-ft5', 'q-ft6', 'q-ft7', 'q-ft8', 'B0', 'flux-Te-ft1', 'flux-Te-ft2', 'flux-Te-ft3', 'flux-Te-ft4', 'flux-Te-ft5', 'flux-Te-ft6', 'flux-Te-ft7', 'flux-Te-ft8', 'flux-Ti-ft1', 'flux-Ti-ft2', 'flux-Ti-ft3', 'flux-Ti-ft4', 'flux-Ti-ft5', 'flux-Ti-ft6', 'flux-Ti-ft7', 'flux-Ti-ft8', 'flux-ne-ft1', 'flux-ne-ft2', 'flux-ne-ft3', 'flux-ne-ft4', 'flux-ne-ft5', 'flux-ne-ft6', 'flux-ne-ft7', 'flux-ne-ft8']

num_output = 0
input_samples8 = input_samples_all[:, num_output::8]
output_samples = output_samples_all[:, num_output]

# Here I excluded the input paprameters that did not vary in the data set
input_samples = np.zeros((N_runs, 5))
input_samples[:,:4] = input_samples8[:,:4]
input_samples[:,4] = input_samples8[:,6]

N_tr = 1000
type_train = 'regular'#'random'#
if type_train == 'random':
    train_n = np.random.randint(0, N_runs, N_tr)
else:
    train_n = np.arange(0, N_runs, 5)

X = input_samples[train_n]
Y = output_samples[train_n]

start = 0
end = 300

prediction = griddata(X, Y, input_samples, method='linear')

plot_res(prediction, output_samples, names_in_outputs[58+num_output], '1', 'blue')


# Have the function TreeConstructor(strArr) take the array of strings stored in strArr, which will
# contain pairs of integers in the following format: (i1,i2), where i1 represents a child node in a
# tree and the second integer i2 signifies that it is the parent of i1. Your program should, if a binary
# tree can be formed, return the string true because a valid binary tree can be formed. If a proper binary
# tree cannot be formed with the integer pairs, then return the string false. All of the integers within
# the tree will be unique, which means there can only be one node in the tree with the given integer value.

import re
def TreeConstructor(strArr):
  parents = []
  children = []
  # We create a list of all the children and parents
  for string in strArr:
    vals = re.findall(r'\d+', string)
    children.append(vals[0])
    parents.append(vals[1])
  # if a child is the child of two different parents, then a valid binary tree cannot be made
  if len(children) != len(set(children)):
    return False
  par_count = {}
  # Also if a parents has more than two children, then a valid binary tree cannot be made
  for parent in parents:
    if parent in par_count:
      if par_count[parent] > 1:
        return False
      par_count[parent] += 1
    else:
      par_count[parent] = 1
  return True


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

from imio.helpers.content import get_schema_fields
from plone.dexterity.interfaces import IDexterityContent
from plone.restapi.interfaces import IFieldSerializer
from plone.restapi.serializer.converters import json_compatible
from plone.restapi.serializer.dxfields import ChoiceFieldSerializer
from plone.restapi.serializer.dxfields import CollectionFieldSerializer
from plonemeeting.restapi import logger
from plonemeeting.restapi.interfaces import IPMRestapiLayer
from zope.component import adapter
from zope.interface import implementer
from zope.schema.interfaces import IChoice
from zope.schema.interfaces import ICollection
from zope.schema.interfaces import IField
from zope.schema.interfaces import IVocabularyTokenized
from zope.schema.vocabulary import SimpleTerm

@adapter(IChoice, IDexterityContent, IPMRestapiLayer)
@implementer(IFieldSerializer)
class PMChoiceFieldSerializer(ChoiceFieldSerializer):
    """Override to take elephantvocabulary into account."""

    def __call__(self):
        # Binding is necessary for named vocabularies
        if IField.providedBy(self.field):
            self.field = self.field.bind(self.context)
        value = self.get_value()
        # XXX with elephanvocabulary, "real" vocab is stored on vocabulary.vocab
        vocab = getattr(self.field.vocabulary, "vocab", self.field.vocabulary)
        if value is not None and IVocabularyTokenized.providedBy(vocab):
            try:
                term = self.field.vocabulary.getTerm(value)
            # If not found, get it from the z3c.form that maybe uses a MissingTerms adapter...
            except LookupError:
                try:
                    view = self.context.restrictedTraverse("@@view")
                    view.update()
                    # widget_name is the field name prefixed with behavior if any
                    widget_name = [field for field in get_schema_fields(self.context, prefix=True)
                                   if field[1].__name__ == self.field.__name__][0][0]
                    widget = view.widgets[widget_name]
                    term = widget.terms.getTerm(value)
                except Exception:
                    # at worse use value as title
                    term = SimpleTerm(value, title=value)
            finally:
                value = {"token": term.token, "title": term.title}

        return json_compatible(value)

@adapter(ICollection, IDexterityContent, IPMRestapiLayer)
@implementer(IFieldSerializer)
class PMCollectionFieldSerializer(CollectionFieldSerializer):
    """Override to take elephantvocabulary into account."""

    def __call__(self):
        # Binding is necessary for named vocabularies
        if IField.providedBy(self.field):
            self.field = self.field.bind(self.context)
        value = self.get_value()
        value_type = self.field.value_type
        if value is not None and IChoice.providedBy(value_type):
            # XXX with elephanvocabulary, "real" vocab is stored on vocabulary.vocab
            vocab = getattr(value_type.vocabulary, "vocab", value_type.vocabulary)
            if IVocabularyTokenized.providedBy(vocab):
                values = []
                for v in value:
                    try:
                        term = value_type.vocabulary.getTerm(v)
                        values.append({u"token": term.token, u"title": term.title})
                    except LookupError:
                        logger.warning("Term lookup error: %r" % v)
                value = values
        return json_compatible(value)


from pacman.model.graphs.application import ApplicationSpiNNakerLinkVertex
from spynnaker.pyNN.external_devices_models.push_bot.ethernet import (
    PushBotEthernetSpeakerDevice)
from spynnaker.pyNN.models.common import PopulationApplicationVertex

class PushBotSpiNNakerLinkSpeakerDevice(
        PushBotEthernetSpeakerDevice, ApplicationSpiNNakerLinkVertex,
        PopulationApplicationVertex):
    """
    The speaker of a PushBot.
    """
    __slots__ = []

    default_parameters = {
        'n_neurons': 1, 'label': None,
        'board_address': None,
        'start_active_time': 50,
        'start_total_period': 100,
        'start_frequency': None,
        'start_melody': None}

    def __init__(
            self, speaker, protocol, spinnaker_link_id,
            n_neurons=default_parameters['n_neurons'],
            label=default_parameters['label'],
            board_address=default_parameters['board_address'],
            start_active_time=default_parameters['start_active_time'],
            start_total_period=default_parameters['start_total_period'],
            start_frequency=default_parameters['start_frequency'],
            start_melody=default_parameters['start_melody']):
        """
        :param PushBotSpeaker speaker: Which speaker device to control
        :param MunichIoSpiNNakerLinkProtocol protocol:
            The protocol instance to get commands from
        :param int spinnaker_link_id: The SpiNNakerLink connected to
        :param int n_neurons: The number of neurons in the device
        :param str label: The label of the device
        :param board_address:
            The IP address of the board that the device is connected to
        :type board_address: str or None
        :param int start_active_time: The "active time" to set at the start
        :param int start_total_period: The "total period" to set at the start
        :param int start_frequency: The "frequency" to set at the start
        :param int start_melody: The "melody" to set at the start
        """
        # pylint: disable=too-many-arguments
        super().__init__(
            speaker, protocol, start_active_time, start_total_period,
            start_frequency, start_melody)
        ApplicationSpiNNakerLinkVertex.__init__(
            self, spinnaker_link_id=spinnaker_link_id, n_atoms=n_neurons,
            board_address=board_address, label=label)


import numpy as np
import quicksort_swx as qsort

class qnode:#queue node,actually, a tree node
    def __init__(self,coord):
        self.Coord=coord
        self.lc=None#left child
        self.rc=None#right child
        self.pr=None#parent
        self.leaf=None#point to leaf of status tree for circle event, None for site event
        self.cnt=None#lowpnt of the circle event
class node_q:
    def __init__(self,qnode):
        self.pre=None
        self.next=None
        self.qnode=qnode

def genBST(sortedsites):#generate BST using sorted events
    len1=sortedsites.shape[0]#length of the sites list
    #print("len1: ",len1)
    if len1==1:
        root=qnode(sortedsites[0,:])
        return root
    elif len1==2:
        root=qnode(sortedsites[0,:])
        root.rc=qnode(sortedsites[1,:])
        root.rc.pr=root
        return root
    else:
        mid=int((len1+1)/2)
        #print("mid",mid)
        root=qnode(sortedsites[mid-1,:])
        root.lc=genBST(sortedsites[0:mid-1,:])
        root.rc=genBST(sortedsites[mid:len1,:])
        root.lc.pr=root
        root.rc.pr=root
        return root

class queue_tree:
    def __init__(self,node_q):
        self.head=node_q
        self.tail=node_q
    def insert(self,node_q):#when insert a node, the queue should not be empty
        node_q.next=self.tail
        self.tail.pre=node_q
        self.tail=node_q
    def popout(self):
        self.head=self.head.pre

def printtree(root):#print the tree rooted at "root": using breadth first search
    qt1=queue_tree(node_q(root))
    while qt1.head is not None:
        print(qt1.head.qnode.Coord)
        # if qt1.head.qnode.pr is not None:
        #     print("pr.lc? pr.rc?",(qt1.head.qnode.pr.lc==qt1.head.qnode)or(qt1.head.qnode.pr.rc==qt1.head.qnode))
        if qt1.head.qnode.lc is not None:
            qt1.insert(  node_q(qt1.head.qnode.lc)  )
        if qt1.head.qnode.rc is not None:
            qt1.insert(  node_q(qt1.head.qnode.rc)  )
        qt1.popout()

def cmpsites(site1,site2):#compare qnode
    if (site1.Coord[1] > site2.Coord[1]) or \
       ((site1.Coord[1] == site2.Coord[1]) and (site1.Coord[0] < site2.Coord[0])):
         return True #site1>site2
    else:
         return False #site1<site2

class queue_v:#queue for computing voronoi diagram
    def __init__(self,sites):#use n sites to initialize Q
        indexes=np.arange(0,len(sites))
        sortedsites,sortedindexes=qsort.quicksort(sites,indexes)
        newsites=np.zeros([len(sites),3])#third indexes show the index 0: highest site 1:second highest
        newsites[:,2]=np.arange(len(sites))
        newsites[:, 0:2]=sortedsites
        print("sortedsites: ",newsites)
        root=genBST( np.flip(newsites,0))#  sortedsites
        # print("Initial Q: ")
        printtree(root)
        # print("end of initial Q:")
        self.root=root  #pointer to the root
        #find the largest node
        self.sortedlist=np.copy(newsites)
        p=root
        while True:
            if p.rc is None:
                break
            p=p.rc
        print("outq of initial Q: ",p.Coord)
        self.outq=p    #point to the largest element
    def insert(self,event):#operate on qtree,event is q qnode
        current=self.root
        if current is None:
            print("current is None!")
            self.root=event
            self.outq=event
        else:
            while True :
                if cmpsites(current,event) is True:#event<current
                    if current.lc is None:
                        event.pr=current
                        current.lc=event
                        break
                    else:
                        current=current.lc
                else:  #event>current
                     if current.rc is None:
                        event.pr=current
                        current.rc=event
                        break
                     else:
                        current=current.rc
        #update the top element in the queue
            if self.outq.rc is not None:
                self.outq=self.outq.rc
    def delete(self,event):
        #check if event is root
        if event.pr is None:#event is self.root
            print("delete:event is root")
            if event.rc is None and event.lc is None:
                print("event.pr.rc is None and event.pr.lc is None")
            if  event.lc is None and event.rc is None: #event has no child
                self.root=None
                print("(event.lc==None) and (event.rc==None)")
            elif event.lc is None: #has one child:left child
                self.root=event.rc
                event.rc.pr = None
                print("delete line129")
            elif event.rc is None: #has one child:right child
                print("delete line131")
                self.root=event.lc
                event.lc.pr=None
            else:#has two children
                print("has two children")
            # #find the smallest element/leaf in the right subtree,this element will be the new root
                p=event.rc
                while True:
                    if p.lc is not None:
                        p=p.lc
                    else:#p is what we want to replace event,break
                        if p.rc is None:
                            if p.pr != event:
                                p.pr.lc=None
                        else:
                            if p.pr!=event:
                                p.pr.lc=p.rc
                        p.lc = event.lc#operations to replace event with p
                        event.lc.pr = p
                        if event.rc!=p:
                            p.rc = event.rc
                            event.rc.pr = p
                        p.pr = None
                        self.root = p
                        print("Found p: ",p.Coord)
                        break
        else:#event is not self.root
            print("event is not Root",event.Coord)
            if (event.lc is None) and (event.rc is None): #event has no child
                # left child or right
                if event.pr.lc==event:#left child
                    event.pr.lc=None
                else:
                    event.pr.rc=None
                    # print("line157")
            elif event.lc is None: #has one child
                event.rc.pr = event.pr
                if event.pr.lc==event:
                    event.pr.lc=event.rc
                else:
                    event.pr.rc=event.rc
                    # print("line164")
            elif event.rc is None: #has one child
                # if event.rc is None:
                #     if event.pr.lc is not None:
                #         print("line171",event.pr.lc.Coord)
                #     if event.pr.rc is not None:
                #         print("line171", event.pr.rc.Coord)
                #     print(event.pr.lc,event.pr.rc,event,event.lc.Coord)
                event.lc.pr=event.pr
                if event.pr.lc==event:
                    event.pr.lc=event.lc
                else:
                    event.pr.rc=event.lc
                if event.pr.rc is not None:
                    print("event.pr.rc.Coord",event.pr.rc.Coord)
            else:#has two children    #find the smallest element in the right subtree
                p=event.rc
                while True:
                    if p.lc is not None:
                        p=p.lc
                    else:
                        if p.rc is None:
                            if p.pr != event:
                                p.pr.lc=None
                        else:
                            if p.pr!=event:
                                p.pr.lc=p.rc
                        p.lc = event.lc  # operations to replace event with p
                        event.lc.pr = p
                        if event.rc!=p:
                            p.rc = event.rc
                            event.rc.pr = p
                        p.pr = event.pr
                        if event.pr.lc==event:
                            event.pr.lc=p
                        else:
                            event.pr.rc = p
                        break
                print("line187")
        #update outq:finding max node

        p = self.root
        n=1
        if p is not None:
            while n<100:
                n=n+1
                if p.rc is None:
                    break
                p = p.rc
                print(p.Coord)
        else:
            print("outq is None")
        if n>90:
            print("delete line206", self.root.Coord, p.rc, p.rc.rc)
        self.outq = p
        # print("p",p.Coord)

    def printall(self):
        printtree(self.root)

#    def search(self,event):
##    def printall(self):#print all nodes


from functools import wraps
import subprocess

_SELECTIONS = {
    '+': 'clipboard',
    '*': 'primary',
}

def _store_selection(data, selection):
    with subprocess.Popen(['xclip',
                           '-selection', selection],
                          stdin=subprocess.PIPE) as xclip:
        xclip.stdin.write(str(data).encode())

def _load_selection(selection):
    with subprocess.Popen(['xclip',
                           '-selection', selection,
                           '-o'], stdout=subprocess.PIPE) as xclip:
        return xclip.stdout.read().decode()

class RPNError(Exception):
    pass

def wrap_user_errors(fmt):
    '''
    Ugly hack decorator that converts exceptions to warnings.

    Passes through RPNErrors.
    '''
    def decorator(f):
        @wraps(f)
        def wrapper(*args, **kwargs):
            try:
                return f(*args, **kwargs)
            except RPNError:
                raise
            except Exception as e:
                raise RPNError(fmt.format(*args, **kwargs), e)
        return wrapper
    return decorator


import time
from collections import deque
n, k = list(map(int, input().split()))

def circularize(i):
    dq = deque()
    for i in range(1, n+1):
        dq.append(i)
    return dq

def solution(n, k):
    circle = circularize(n)
    i = 0
    answer = deque()
    while len(circle):
        if i+1 == k:
            answer.append(circle.popleft())
            i = -1
        else:
            circle.append(circle.popleft())
        i += 1
    return '<' + ', '.join(map(str, answer)) + '>'

s = time.time()
print(solution(n, k))
print(time.time()-s)


def podio_olimpico(tempo_chegada1, tempo_chegada2, tempo_chegada3):
    t1 = int(tempo_chegada1)
    t2 = int(tempo_chegada2)
    t3 = int(tempo_chegada3)

    if (t1 < t2 and t1 < t3) and (t2 < t3):
        return print("1 -", t1, "minutos\n2 -", t2, "minutos\n3 -", t3, "minutos")

    elif (t1 < t2 and t1 < t3) and (t2 > t3):
        return print("1 -", t1, "minutos\n2 -", t3, "minutos\n3 -", t2, "minutos")

    elif (t2 < t1 and t2 < t3) and (t1 < t3):
        return print("1 -", t2, "minutos\n2 -", t1, "minutos\n3 -", t3, "minutos")

    elif (t2 < t1 and t2 < t3) and (t1 > t3):
        return print("1 -", t2, "minutos\n2 -", t3, "minutos\n3 -", t1, "minutos")

    elif (t3 < t1 and t3 < t2) and (t1 < t2):
        return print("1 -", t3, "minutos\n2 -", t1, "minutos\n3 -", t2, "minutos")

    elif (t3 < t1 and t3 < t2) and (t1 > t2):
        return print("1 -", t3, "minutos\n2 -", t2, "minutos\n3 -", t1, "minutos")

##Atualização


from helper.SimulationJob import SimulationJob
from math import exp, sqrt
import pandas as pd
import numpy as np
import matplotlib
import matplotlib.pyplot as plt
from os import path

matplotlib.use("qt5agg")

# case: P = 1, D = 1-w^2 for different values of lambda and mean opinion

def inv_dist(w, m, lam):
    res = (1 + w) ** (-2 + (m / (2 * lam)))
    res = res * (1 - w) ** (-2 - (m / (2 * lam)))
    res = res * exp(-((1 - m * w) / (lam * (1 - w**2))))
    return res

for lmb in [0.1, 0.5, 1, 2]:
    for mn in [-0.5, -0.1, 0]:
        # Parameter initialization
        lamb = lmb
        mean_opinion = mn
        nagents = 20000
        t_horiz = 1300

        # theta_std = 0.1
        # gamma = (theta_std ** 2) / lamb
        gamma = 0.005
        theta_std = sqrt(gamma * lamb)
        print(f"gamma= {gamma}")
        print(f"theta_std = {theta_std}")

        # compute reference solution as described p. 241
        resolution = 1000
        x = np.linspace(-0.99, 1, num=resolution, endpoint=False)
        y = [inv_dist(s, mean_opinion, lamb) for s in x]
        data = [x, y]
        data = np.transpose(data)
        reference = pd.DataFrame(data=data, columns=["w", "g_inf(w)"])

        # run MC simulation
        sim = SimulationJob(
            gamma,
            theta_std,
            lambda g, w: (1 - g) / (1 + abs(w)),
            lambda w: 1,
            lambda w: (1 - w**2),  # P&T p. 241
            mean_opinion,
            t_horiz,
            nagents,
            uniform_theta=True,
        )
        sim.run()
        result_df = pd.Series(sim.result, name="opinion")

        # Generate histogram data
        counts, bins = np.histogram(result_df, bins=np.linspace(-1, 1, 200))
        bins = 0.5 * (bins[:-1] + bins[1:])

        # Scaling of reference solution
        mean_sim_result = np.mean(counts)
        mean_ref_result = np.mean(reference["g_inf(w)"])
        reference["g_inf(w)"] = (mean_sim_result / mean_ref_result) * reference[
            "g_inf(w)"
        ]

        fig = plt.figure()
        plt.bar(x=bins, height=counts, width=2 / len(bins))
        plt.plot(reference["w"], reference["g_inf(w)"], "r")
        plt.suptitle(f"Steady Opinion Profile for P = 1 and D = 1- w^2")
        plt.title(f"lambda= {lamb}, n= {nagents} and {t_horiz} simulated time units")
        plt.xlabel("Opinion []")
        plt.ylabel("Count []")
        plt.savefig(
            path.join(
                "experiment-data",
                f"experiment-3-uniform-theta-lambda-{lamb}-mean-{mean_opinion}-nagents-{nagents}-t-horiz-{t_horiz}.png",
            )
        )


import os
from PIL import Image
from PIL import ImageFont
from PIL import ImageDraw
import uuid

def get_file_path_with_type(file_path, file_type):
    file_paths = []
    root_dir = os.walk(file_path)

    for sub_dir, folder_name, file_list in root_dir:
        for file_name in file_list:
            file_path = os.path.join(sub_dir, file_name)
            if file_type in file_path:
                file_paths.append(file_path)
    file_paths = sorted(file_paths)
    return file_paths

if __name__ == "__main__":
    src_folder = 'xxxxx'

    img_paths = get_file_path_with_type(src_folder, '.JPG')

    for im in img_paths:
        src = Image.open(im).convert('RGBA')
        mask = Image.new('RGBA', src.size, (0, 0, 0, 0))
        """ set font """
        font = ImageFont.truetype('c:/windows/Fonts/msyh.ttc', 25)
        rst = ImageDraw.Draw(mask)
        rst.text((int(mask.size[0] / 2) - 50,
                  mask.size[1] - 60),
                 "©shelly", font=font,
                 fill=(192, 192, 192, 192))
        dst = Image.alpha_composite(src, mask)
        name = str(uuid.uuid4()) + '.png'
        path = os.path.join(src_folder, name)
        dst.save(path)


# -*- coding: utf-8 -*-
''' Interaction diagram computation. Home made test.'''
from __future__ import print_function
from __future__ import division

import geom
import xc

from materials.ehe import EHE_materials
from materials.sia262 import SIA262_materials
from materials.sections.fiber_section import def_simple_RC_section

__author__= "Luis C. Pérez Tato (LCPT) and Ana Ortega (AOO)"
__copyright__= "Copyright 2015, LCPT and AOO"
__license__= "GPL"
__version__= "3.0"
__email__= "l.pereztato@gmail.com"

areaFi6= SIA262_materials.section_barres_courantes[6e-3]
areaFi8= SIA262_materials.section_barres_courantes[8e-3]
areaFi10= SIA262_materials.section_barres_courantes[10e-3]
areaFi12= SIA262_materials.section_barres_courantes[12e-3]
areaFi14= SIA262_materials.section_barres_courantes[14e-3]
areaFi16= SIA262_materials.section_barres_courantes[16e-3]
areaFi18= SIA262_materials.section_barres_courantes[18e-3]
areaFi20= SIA262_materials.section_barres_courantes[20e-3]
areaFi22= SIA262_materials.section_barres_courantes[22e-3]
areaFi26= SIA262_materials.section_barres_courantes[26e-3]
areaFi30= SIA262_materials.section_barres_courantes[30e-3]
areaFi34= SIA262_materials.section_barres_courantes[34e-3]
areaFi40= SIA262_materials.section_barres_courantes[40e-3]

concrete= EHE_materials.HA30
concrete.alfacc=0.85    # f_maxd= 0.85*fcd concrete long term compressive strength factor (normally alfacc=1)

reinfSteel= EHE_materials.B500S

sccData= def_simple_RC_section.RCRectangularSection(name= "sccData", sectionDescr= "Prueba.", concrType= concrete, depth= 0.5, width= 1.0, reinfSteelType= reinfSteel)
sccData.negatvRebarRows= def_simple_RC_section.LongReinfLayers([def_simple_RC_section.ReinfRow(rebarsDiam=40e-3, rebarsSpacing=0.15,width=1.0,nominalCover=0.25-0.19)])
sccData.positvRebarRows= def_simple_RC_section.LongReinfLayers([def_simple_RC_section.ReinfRow(rebarsDiam=6e-3, rebarsSpacing=0.15,width=1.0,nominalCover=0.25-0.19)])
#sccData.setMainReinfNeg(40e-3,areaFi40,0.15,0.25-0.19)
#sccData.setMainReinfPos(6e-3,areaFi6,0.15,0.25-0.19)

feProblem= xc.FEProblem()
feProblem.logFileName= "/tmp/erase.log" # Don't print(warnings.)
feProblem.errFileName= "/tmp/erase.err" # Don't print(errors.)

preprocessor=  feProblem.getPreprocessor
sccData.defRCSection(preprocessor, 'd')
param= xc.InteractionDiagramParameters()
diag= sccData.defInteractionDiagramNMy(preprocessor)

fcELU13= diag.getCapacityFactor(geom.Pos2d(136.78e3,24.71e3))
fcELU14= diag.getCapacityFactor(geom.Pos2d(1197.13e3,65.98e3))

''' Test to be replaced LCPT 02/10/2015'''
ratio1= abs(fcELU13-0.777283365776)
ratio2= abs(fcELU14-4.4411488676)

'''
sccData.plot(preprocessor) # Display section geometry
print("fcELU13= ", fcELU13)
print("ratio1= ", ratio1)
print("fcELU14= ", fcELU14)
print("ratio2= ", ratio2)
'''

feProblem.errFileName= "cerr" # Display errors if any.
import os
from misc_utils import log_messages as lmsg
fname= os.path.basename(__file__)
if((abs(ratio1)<1e-2) & (abs(ratio2)<1e-2)):
    print('test '+fname+': ok.')
else:
    lmsg.error(fname+' ERROR.')

# # Graphic output.
# from postprocess.reports import graph_material
# interactionDiagramGraphic= graph_material.InteractionDiagramGraphic(title= 'Test')
# interactionDiagramGraphic.setupGraphic(diag)
# interactionDiagramGraphic.show()


from django.conf.urls import url

from pages import views as views_pages

urlpatterns = [
    url(r'^search/$',
        views_pages.SearchOfferView.as_view(), name='search'),
    url(r'^contacts/$',
        views_pages.OfficeListView.as_view(), name='contacts'),
    url(r'^workshop/$',
        views_pages.BlogListView.as_view(), name='blog'),
    url(r'^workshop/(?P<pk>[0-9a-f-]+)/$',
        views_pages.BlogDetailView.as_view(), name='blog_detail'),
    url(r'^catalog/(?P<path>[-\w\/]+)/$',
        views_pages.catalog_view, name='catalog'),
     url(r'catalog',
         views_pages.TagsView.as_view(), name='tags'),
    url(r'^(?P<slug>[-\w]+)/$',
        views_pages.PageView.as_view(), name='static'),
]


from django.shortcuts import render
from . models import *

# Create your views here.
def matricula(request):
    if request.POST:
        nova_matricula = Matricula()
        nova_matricula.dataInicio = request.POST.get('data')
        nova_matricula.dataFinal = request.POST.get('data2')
        try:
            instituicao = Instituicao.objects.get(pk = request.POST.get('instituicao'))
            pessoa = Pessoa.objects.get(pk = request.POST.get('pessoa'))
            curso = Curso.objects.get(pk = request.POST.get('curso'))
            nova_matricula.instituicao = instituicao
            nova_matricula.pessoa = pessoa
            nova_matricula.curso = curso
            nova_matricula.save()
        except Instituicao.DoesNotExist:
            print('Instituição não encontrado')
        except Pessoa.DoesNotExist:
            print('Pessoa não encontrado')
        except Curso.DoesNotExist:
            print('Ocupacao não encontrada')
        except Exception as e:
            print('Erro de integridade:', e)

    matriculas = {
        'instituicao':Instituicao.objects.all(),
        'curso':Curso.objects.all(),
        'pessoa':Pessoa.objects.all(),
    }

    return render(request, 'matricula/matricula.html', matriculas)

def cidade(request):
    cidades = {
        'cidade':Cidade.objects.all()
    }

    return render(request, 'cidade/cidade.html', cidades)

def pessoa(request):
    pessoas = {
        'pessoa':Pessoa.objects.all()
    }

    return render(request, 'pessoa/pessoa.html', pessoas)

def areasaber(request):
    areassaberes = {
        'areasaber':AreaSaber.objects.all()
    }

    return render(request, 'areasaber/areasaber.html', areassaberes)

def instituicao(request):
    instituicoes = {
        'instituicao':Instituicao.objects.all()
    }

    return render(request, 'instituicao/instituicao.html', instituicoes)

def curso(request):
    cursos = {
        'curso':Curso.objects.all()
    }

    return render(request, 'curso/curso.html', cursos)

def disciplina(request):
    disciplinas = {
        'disciplina':Disciplina.objects.all()
    }

    return render(request, 'disciplina/disciplina.html', disciplinas)

def matriculado(request):
    matriculados = {
        'matriculado':Matricula.objects.all()
    }

    return render(request, 'matricula/matriculado.html', matriculados)

def avaliacao(request):
    avaliacoes = {
        'avaliacao':Avaliacao.objects.all()
    }

    return render(request, 'avaliacao/avaliacao.html', avaliacoes)

def frequencia(request):
    frequencias = {
        'frequencia':Frequencia.objects.all()
    }

    return render(request, 'frequencia/frequencia.html', frequencias)

def periodoturma(request):
    periodoturmas = {
        'periodoturma':PeriodoTurma.objects.all()
    }

    return render(request, 'periodo/periodoturma.html', periodoturmas)

def ocorrencia(request):
    ocorrencias = {
        'ocorrencia':Ocorrencia.objects.all()
    }

    return render(request, 'ocorrencia/ocorrencia.html', ocorrencias)

def disciplinacurso(request):
    disciplinacursos = {
        'disciplinacurso':DisciplinaCurso.objects.all()
    }

    return render(request, 'disciplina/disciplinacurso.html', disciplinacursos)


import sys

import subprocess

commands = []

# isoforms_fasta = sys.argv[2]
# left_fq = sys.argv[3]
# right_fq = sys.argv[4]

# commands.append('bwa index {}'.format(isoforms_fasta))
# commands.append('bwa mem -t 16 {} {} {} > aln-pe.bwamem.sam'.format(isoforms_fasta, left_fq, right_fq))
# commands.append('samtools view -b aln-pe.bwamem.sam > aln-pe.bwamem.bam')
# commands.append('samtools sort aln-pe.bwamem.bam > aln-pe.bwamem.sortedByCoord.bam')
# commands.append('samtools index aln-pe.bwamem.sortedByCoord.bam')

names_txt = sys.argv[1]

filename = names_txt.split('.')[0]

with open(names_txt, 'r') as fin:
    names = fin.read().splitlines()
print('seqnames: {}\n'.format(names))

for seqname in names:
    commands.append('samtools view -h -b aln-pe.bwamem.sortedByCoord.bam {name}_transcript > {name}.bam'.format(name=seqname))
    commands.append('samtools sort -n {name}.bam -o {name}.sortedByName.bam'.format(name=seqname))
    commands.append('bedtools bamtofastq -i {name}.sortedByName.bam -fq left.{name}.fastq -fq2 right.{name}.fastq'.format(name=seqname))
    commands.append('bedtools bamtofastq -i {name}.sortedByName.bam -fq left.{name}.fastq -fq2 right.{name}.fastq'.format(name=seqname))

lefts = ['left.{}.fastq'.format(name) for name in names]
commands.append('cat {} > left.{}.fastq'.format(' '.join(lefts), filename))

rights = ['right.{}.fastq'.format(name) for name in names]
commands.append('cat {} > right.{}.fastq'.format(' '.join(rights), filename))

for cmd in commands:
    print(cmd + ':\n')
    subprocess.call(cmd, shell=True)
    print('\n')


import argparse
import os
import numpy as np
import tensorflow as tf  # version 1.15.4
import multiprocessing
import tqdm
import pickle
from keras.preprocessing.sequence import pad_sequences

parser = argparse.ArgumentParser(description='PyTorch ImageNet Training')
parser.add_argument(
    '--audioset-dir', metavar='AUDIOSET_DIR',
    help='Specify path to ../audioset/audioset_v1_embeddings/',
)

def read_data(path, include_times=False):
    result = [[], [], []]
    if include_times:
        result += [[], []]
    for example in tf.python_io.tf_record_iterator(path):
        tf_example = tf.train.Example.FromString(example)
        vid_id = tf_example.features.feature['video_id'].bytes_list.value[
            0].decode(encoding='UTF-8')
        label = tf_example.features.feature['labels'].int64_list.value
        if include_times:
            result[3].append(tf_example.features.feature[
                                 'start_time_seconds'].float_list.value)
            result[4].append(tf_example.features.feature[
                                 'end_time_seconds'].float_list.value)
        tf_seq_example = tf.train.SequenceExample.FromString(example)
        tf_feature = tf_seq_example.feature_lists.feature_list[
            'audio_embedding'].feature
        n_frames = len(tf_feature)
        audio_frames = []
        # Iterate through frames.
        for i in range(n_frames):
            hexembed = tf_feature[i].bytes_list.value[0].hex()
            arrayembed = [int(hexembed[i:i + 2], 16) for i in
                          range(0, len(hexembed), 2)]
            audio_frames.append(arrayembed)
        result[0].append(vid_id)
        result[1].append(list(label))
        result[2].append(np.stack(audio_frames).astype(np.uint8))
    return result

def pad(feature_matrix, maxlen=10):
    return pad_sequences(feature_matrix.T, maxlen=maxlen).T.astype(np.uint8)

def preprocess_data(path, prefix='bal_train'):
    fns = [path + fn for fn in os.listdir(path)]
    with multiprocessing.Pool(multiprocessing.cpu_count()) as p:
        results = list(tqdm.tqdm(p.imap(read_data, fns), total=len(fns)))

    print('\nAll files read in. Now post-processing.')
    video_ids = [v for r in results for v in r[0]]
    labels = [l for r in results for l in r[1]]
    features = [f for r in results for f in r[2]]
    del results  # Free memory
    # Make all inputs exactly the same shape.
    print("Padding with 0 to make all features shape (10,128) of type uint8.")
    with multiprocessing.Pool(multiprocessing.cpu_count()) as p:
        features = list(tqdm.tqdm(p.imap(pad, features), total=len(features)))

    print('Saving pickled results.')
    with open(prefix + '_features.p', 'wb') as wf:
        pickle.dump(features, wf, pickle.HIGHEST_PROTOCOL)
    with open(prefix + '_video_ids.p', 'wb') as wf:
        pickle.dump(video_ids, wf, pickle.HIGHEST_PROTOCOL)
    with open(prefix + '_labels.p', 'wb') as wf:
        pickle.dump(labels, wf, pickle.HIGHEST_PROTOCOL)

    print('Preprocessing complete.')

def main(audioset_dir):
    for kind in ["eval", "bal_train", "unbal_train"]:
        preprocess_data(audioset_dir + kind + "/", prefix=kind)

if __name__ == '__main__':
    arg_parser = parser.parse_args()
    if arg_parser.audioset_dir is None:
        parser.error("Specify the path to the audioset embeddings "
                     "directory.\nFor example, if the data is stored in "
                     "'/datasets/audioset/audioset_v1_embeddings/' "
                     "you should call this script like this:\npython "
                     "audioset_preprocessing.py --audioset-dir "
                     "'/datasets/audioset/audioset_v1_embeddings/'")
    main(audioset_dir=arg_parser.audioset_dir)


"""
1번.

Min Heap 자료구조를 이용하면 최대값을 O(logN)의 시간복잡도로 찾을 수 있다. Min Heap을 이용하면 우선순위 값이 낮은 자료를 먼저 출력하는 Priority Queue를 구현할 수 있다. Min Heap을 이용한 Priority Queue는 아래와 같은 특징을 가진다.

Min Heap을 이용한 Priority Queue의 특징
자료를 입력하는 동작과 출력하는 동작 모두 O(logN)으로 이루어진다.
우선순위 값이 낮은 자료를 먼저 출력하되, 우선순위 값이 같은 자료끼리는 순서를 고려하지 않는다.
다음과 같은 Method들을 구현한다.
is_empty(): Queue가 비어있으면 True, 비어있지 않으면 False를 출력한다.
put(): Priority Queue에 자료를 입력한다. 자료는 길이가 2인 Tuple로, (우선순위, 자료) 형태로 입력받는다.
get(): Priority Queue에서 자료를 출력한다. 출력한 데이터는 Priority Queue에서 삭제한다. 더이상 출력할 데이터가 없는 경우 None을 출력한다.
peek(): Priority Queue에서 자료를 출력한다. 출력한 데이터는 Priority Queue에 그대로 유지한다. 더이상 출력할 데이터가 없는 경우 None을 출력한다.
"""
class PriorityQueue:
    def __init__(self):
        self.tree = [None]

    def is_empty(self):
        return len(self.tree) == 1

    def put(self, data):
        self.tree.append(data)
        curr = len(self.tree) - 1
        parent = curr // 2
        while parent > 0:
            if self.tree[curr][0] > self.tree[parent][0]:
                return
            self.tree[curr], self.tree[parent] = self.tree[parent], self.tree[curr]
            curr = parent
            parent = curr // 2

    def get(self):
        if self.is_empty() is True:
            return None
        data = self.tree[1]
        self.tree[1] = self.tree[-1]
        self.tree = self.tree[:-1]
        curr = 1
        while curr < len(self.tree):
            left = curr * 2
            right = curr * 2 + 1
            if left < len(self.tree) and right < len(self.tree):
                if self.tree[left][0] < self.tree[right][0]:
                    if self.tree[left][0] < self.tree[curr][0]:
                        self.tree[curr], self.tree[left] = self.tree[left], self.tree[curr]
                        curr = left
                else:
                    if self.tree[right][0] < self.tree[curr][0]:
                        self.tree[curr], self.tree[right] = self.tree[right], self.tree[curr]
                        curr = right

            elif left < len(self.tree) and self.tree[left][0] < self.tree[curr][0]:
                self.tree[curr], self.tree[left] = self.tree[left], self.tree[curr]
                curr = left
            elif right < len(self.tree) and self.tree[right][0] < self.tree[curr][0]:
                self.tree[curr], self.tree[right] = self.tree[right], self.tree[curr]
                curr = right
            else:
                break
        return data

    def peek(self):
        if self.is_empty() is True:
            return None
        return self.tree[1]

pq = PriorityQueue()
pq.put((0, 'a'))
pq.put((5, 'b'))
pq.put((2, 'c'))
pq.put((1, 'd'))
pq.put((3, 'e'))
pq.put((4, 'f'))

print(pq.get())
print(pq.get())
print(pq.get())
print(pq.get())
print(pq.get())
print(pq.get())
print(pq.get())
"""
2번.
오름차순으로 정렬된 N개의 정수를 가진 List가 주어져있을 때,
해당 List에 존재하는 서로 다른 값이 몇 가지인지 알아내는 알고리즘을 구현하라.
알고리즘의 제약사항은 아래와 같다. (알고리즘은 1 <= N <= 10000에서 테스트된다.)

추가 메모리 사용은 O(1)으로 제한된다. 따라서 set()와 dict() 등의 자료구조를 사용할 수 없다.
알고리즘의 시간복잡도는 O(N) 이하로 제한된다.
"""

def countUniques(a):

    count = 1

    for i in range(len(a) - 1) :
        for j in range(i+1, len(a)):
            if a[i] != a[j] :
                count += 1
                break
            else :
                break
    return count

# Test code
print(countUniques([-1, 1, 1, 1, 1, 4, 4, 4, 4, 10, 14, 14])) # 5
print('------')
print(countUniques([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1])) # 2
print('------')
print(countUniques([0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 2, 3])) # 4

print('------')

"""
3번
N개의 문자열로 이루어진 List에서 전체 문자열이 앞 n개 문자열이 같다고 할때,
가장 큰 n을 출력하는 알고리즘을 구현하라.
(즉, 주어진 모든 문자열의 앞의 몇개의 문자가 일치하는지 출력하라)
"""

def solution(a):
    count = 0
    w = a[0]
    for idx, c in enumerate(w):
        is_match = True
        for w_ in a:
            if c != w_[idx]:
                is_match = False
                break
        if is_match is True:
            count += 1
        else:
            break
    return count

print(solution(['abcd', 'abce', 'abchg', 'abcfwqw', 'abcdfg'])) # 3
print(solution(['abcd', 'gbce', 'abchg', 'abcfwqw', 'abcdfg'])) # 0

"""
4번
자연수 중, 각 자리수를 제곱한 것을 더하는 과정을 반복했을 때 1으로 끝나는 수를 '행복한 수'라고 한다.
'행복한 수'가 아닌 경우 이 과정이 1에 도달하지 못하고 같은 수열이 반복되는 무한 루프에 빠지게 된다.
자연수를 입력받았을 때 '행복한 수'인지 판별하는 알고리즘을 작성하라.

'행복한 수'를 찾는 과정의 예

  19이 행복한 수인지 확인하는 과정
  1^2 + 9^2 = 82
  8^2 + 2^2 = 68
  6^2 + 8^2 = 100
  1^2 + 0^2 + 0^2 = 1 --> True
"""

def solution(n):
    def calc_value(m):
        val = 0
        for c in str(m):
            val += int(c) ** 2
        return val

    hist = set()
    while n != 1:
        hist.add(n)
        n = calc_value(n)
        if n in hist:
            return False
    return True

print(solution(19)) # True
print(solution(61)) # False