from tkinter import *
import pygame

class Pomodoro(object):

    def __init__(self, master):
        self.master = master
        self.master.geometry('300x200')

        self.master.columnconfigure(0, weight=1)
        self.master.rowconfigure(0, weight=1)
        self.master.title('Pomodoro')

        self.menuBar = Menu(master)

        # Definingo opções
        self.optionMenu = Menu(self.menuBar, tearoff=0)

        self.menuConfigTempo = Menu(self.menuBar, tearoff=0)
        self.optionMenu.add_command(label='Config. time', accelerator='Ctrl+t', compound=LEFT, command=self.configTimeWindow)

        self.soundMenuOptions = Menu(self.menuBar, tearoff=0)
        self.optionMenu.add_cascade(label='Alarms',  menu=self.soundMenuOptions)

        self.alarmsOptions = {'1. Firestation Bell': 'sounds/firestation_bell.wav',
                           '2. Burglar Bell': 'sounds/burglar_bell.wav'}

        self.alarm = StringVar()
        self.alarm.set('1. Firestation Bell')

        for k in sorted(self.alarmsOptions):
            self.soundMenuOptions.add_radiobutton(label=k, variable=self.alarm, command=self.sound)

        self.menuBar.add_cascade(label='Options', menu=self.optionMenu)

        self.infoMenu = Menu(self.menuBar, tearoff=0)
        self.infoMenu.add_command(label='Info', accelerator='Ctrl+I', compound=LEFT, command=self.telaInfo)
        self.menuBar.add_cascade(label='File', menu=self.infoMenu)

        self.master.config(menu=self.menuBar)

        self.frame_show()

    def configTime(self):
        self.initTimePomodoro = self.entry_var.get()
        self.labelClock['text'] = ("%.2f" % self.initTimePomodoro)
        self.toplevel.destroy()

    def configTimeWindow(self):
        self.toplevel = Toplevel(self.master)
        self.entry_var = DoubleVar()
        self.entryTime = Entry(self.toplevel, textvariable=self.entry_var)
        self.entryTime.grid()

        self.btnSetTime = Button(self.toplevel, text='Ok', command=self.configTime)
        self.btnSetTime.grid()

    def telaInfo(self):
        toplevelInfo = Toplevel(self.master)
        toplevelInfo.geometry('100x50')
        self.labelInfo = Label(toplevelInfo, text='Simple pomodoro timer')
        self.labelInfo.grid()

    def sound(self):
        self.som_nome = self.alarm.get()
        self.som_escolhido = self.alarmsOptions.get(self.som_nome)

    def frame_show(self):
        self.frame = Frame(self.master, bg='green')
        self.frame.grid(row=0, column=0, sticky='WE')
        self.frame.columnconfigure(0, weight=1)

        self.initTimePomodoro = 25.00
        self.timePomodoro = 25.00

        self.labelClock = Label(self.frame, text=("%.2f" % self.timePomodoro))
        self.labelClock['font'] = 'Helvetica 80 bold'
        self.labelClock.grid(sticky='we')

        self.btnStart = Button(self.frame, text='Start', command=self.startPomodoro)
        self.btnStart.grid(row=1, sticky='we')

        self.btnCancel = Button(self.frame, text='Cancel', command=self.cancelPomodoro)
        self.btnCancel.grid(row=2, sticky='we')
        self.statusCancel = False

    def startPomodoro(self):
        self.statusCancel = False
        self.timePomodoro = self.initTimePomodoro
        self.labelClock['text'] = ('%.2f' % self.timePomodoro)
        self.ticClock()

    def cancelPomodoro(self):
        self.statusCancel = True

    def ticClock(self):
        if self.timePomodoro < 0.01:
            self.labelClock['text'] = ('0.00')
            pygame.init()
            audio = pygame.mixer.Sound(self.alarmsOptions.get(self.alarm.get()))
            self.master.lift()
            audio.play()
        elif (self.statusCancel == True):
            print (self.initTimePomodoro)
            self.labelClock['text'] = ('%.2f' % self.initTimePomodoro)
        else:
            self.timePomodoro = self.timePomodoro - 0.01
            self.labelClock['text'] = ('%.2f' % self.timePomodoro)
            self.master.after(1000, self.ticClock)

def main():
    root = Tk()
    app = Pomodoro(root)
    root.mainloop()

if __name__ == '__main__':
    main()


import re
from .CodeBuilder import CodeBuilder

class Templite(object):
    def __init__(self, text, *context):
        """Construct a templite with the given 'text'
        context are dictionaries of values to use for future rendering
        These are good for filters and global values
        """
        self.context = {}
        self.context.update(context)

        self.all_vars = set()
        self.loop_vars = set()

        code = CodeBuilder()

        code.add_line("def render_function(context,do_dots):")
        code.indent()
        vars_code = code.add_section()
        code.add_line("result=[]")
        code.add_line("append_result = result.append")
        code.add_line("extend_result = result.extend")
        code.add_line("to_str = str")

        buffered = []

        def flush_output():
            """Force buffered to the code builder."""
            if len(buffered) == 1:
                code.add_line("append_result(%s)", buffered[0])
            elif len(buffered) > 1:
                code.add_line("extend_result(%s)", ",".join(buffered))
            else:
                del buffered[:]

        ops_stack = []
        tokens = re.split(r"(?s)({{.*?}}|{%.*?%}|{#.*?#})", text)

        for token in tokens:
            if token.startswith('{#'):
                continue
            if token.startswith('{{'):
                # a expression for evaluate
                expr = self._expr_code(token[2:-2].strip())
                buffered.append("to_str(%s)" % expr)
            elif token.startswith('{%'):
                # action tag;split into words and parse further.
                flush_output()
                words = token[2:-2].strip().split()
                if words[0] == 'if':
                    if len(words) != 2:
                        self._syntax_error("don't understand if", token)
                    ops_stack.append('if')
                    code.add_line('if %s:' % self._expr_code(words[1]))
                    code.indent()
                elif words[0] == 'for':
                    if len(words) != 3:
                        self._syntax_error("don't understand for", token)
                    ops_stack.append('for')
                    self._variable(words[1], self.loop_vars)
                    code.add_line('for c_% in %s:' % (words[1], self._expr_code(words[3])))
                    code.indent()
                elif words[0] == 'end':
                    if len(words) != 1:
                        self._syntax_error("don't understand end", token)
                    end_what = words[0][3:]
                    if not ops_stack:
                        self._syntax_error("has no if or for before end", token)
                    start_what = ops_stack.pop()
                    if start_what != end_what:
                        self._syntax_error("start is different of the end", end_what)
                    code.dedent()
                else:
                    self._syntax_error("error tag", words[0])


import tkinter as tk
from tkinter import ttk
import matplotlib.pyplot as plt
import Funciones

root = tk.Tk()
root.title("Proyecto energetica 2020-1")
style = ttk.Style()
style.configure("BW.TLabel", justify='LEFT')
root.geometry('660x230')

# --------------Start Code Here  'Matrices'------------------------------------------------------------

# --------------Start Function 'Graficadoras'--------------------------------------------------------------------------

def graf_recuperados(t, n, alpha, betha, p, tq, tp):

    casos_diarios = list()
    dia = list()
    for i in range(0, t+1):
        rec_nor, rec_crit = Funciones.recuperados(i, n, alpha, betha, p, tq, tp)
        rec_total = rec_nor+rec_crit
        casos_diarios.append(rec_total)
        dia.append(i)

    plt.ion()
    plt.figure('Recuperados')
    plt.scatter(dia, casos_diarios)
    plt.show()

def graf_infectados(t, n, alpha, betha, p):

    casos_diarios = list()
    dia = list()
    for i in range(0, t+1):
        inf_nor, inf_crit = Funciones.infectados(i, n, alpha, betha, p)
        inf_total = inf_nor + inf_crit
        casos_diarios.append(inf_total)
        dia.append(i)

    plt.ion()
    plt.figure('Infectados')
    plt.scatter(dia, casos_diarios)
    plt.show()

def graf_recuperados_crit(t, n, alpha, betha, p, tp):

    casos_diarios = list()
    dia = list()
    for i in range(0, t+1):
        rec_crit = Funciones.recuperados_criticos(i, n, alpha, betha, p, tp)
        casos_diarios.append(rec_crit)
        dia.append(i)

    plt.ion()
    plt.figure('Recuperados Criticos')
    plt.scatter(dia, casos_diarios)
    plt.show()

def graf_infectados_crit(t, n, alpha, betha, p):

    casos_diarios = list()
    dia = list()
    for i in range(0, t+1):
        inf_crit = Funciones.infectados_criticos(i, n, alpha, betha, p)
        casos_diarios.append(inf_crit)
        dia.append(i)

    plt.ion()
    plt.figure('Infectados Criticos')
    plt.scatter(dia, casos_diarios)
    plt.show()

def grafica_casos_totales(t, n, alpha, betha, p):

    casos_tot = list()
    cont_casos_totales = 0
    dia = list()
    for i in range(0, t+1):
        inf_nor, inf_crit = Funciones.infectados(i, n, alpha, betha, p)
        inf_total = inf_nor + inf_crit
        cont_casos_totales += inf_total
        casos_tot.append(cont_casos_totales)
        dia.append(i)
    plt.ion()
    plt.figure('Casos totales')
    plt.scatter(dia, casos_tot)
    plt.show()

def grafica_activos_por_dia(t, n, alpha, betha, p, tq, tp):

    casos_tot = list()
    dia = list()
    cont_act = 0
    for i in range(0, t+1):
        activos = Funciones.activos_diario(i, n, alpha, betha, p, tq, tp)
        sum_casos_diarios = activos[0] - activos[1]
        cont_act += sum_casos_diarios
        casos_tot.append(cont_act)
        dia.append(i)

    plt.ion()
    plt.figure('Activos')
    plt.scatter(dia, casos_tot)
    plt.show()

# --------------End Function 'Graficadoras'-----------------------------------------

# --------------End Code Here------------------------------------------------------------------------------------------

# --------------Start Code Here  'Variables'---------------------------------
# Columna 2

dia_de_evaluacion = tk.IntVar(root, value=120)
poblacion_critica = tk.DoubleVar(root, value=0.3)
parametro_de_forma = tk.DoubleVar(root, value=1.3)
parametro_de_escala = tk.DoubleVar(root, value=60)
tiempo_r_no_critico = tk.DoubleVar(root, value=21)
tamano_de_poblacion_1 = tk.DoubleVar(root, value=49721)
tamano_de_poblacion_2 = tk.DoubleVar(root, value=51195)
ruta1 = tk.DoubleVar(root, value=152.2)
ruta2 = tk.DoubleVar(root, value=348)
ruta3 = tk.DoubleVar(root, value=349)
ventilador = tk.DoubleVar(root, value=28)

# Valores

def dia_evaluacion():
    t_ = dia_de_evaluacion.get()
    return t_

def tp():
    tp_ = ventilador.get()
    return tp_

def poblacion1():
    n1_ = tamano_de_poblacion_1.get()
    return n1_

def poblacion2():
    n2_ = tamano_de_poblacion_2.get()
    return n2_

def valor_alpha():
    alpha_ = parametro_de_forma.get()
    return alpha_

def valor_beta():
    beta_ = parametro_de_escala.get()
    return beta_

def poblc_critica():
    pob_critica_ = poblacion_critica.get()
    return pob_critica_

def tiempo_de_recuperacion_no_c():
    t_no_c = tiempo_r_no_critico.get()
    return t_no_c

def recorrido_ruta1():
    ruta1_ = ruta1.get()
    return ruta1_

def recorrido_ruta2():
    ruta2_ = ruta2.get()
    return ruta2_

def recorrido_ruta3():
    ruta3_ = ruta3.get()
    return ruta3_

def pob_total():
    tamano_pop_tot = tamano_de_poblacion_1.get() + tamano_de_poblacion_2.get()
    return tamano_pop_tot

# --------------End Code Here-----------------------------------------------

x0y4 = ttk.Label(root, text="      ", style="BW.TLabel")
x0y4.grid(sticky="W", row=0, column=3)

# ----------------------------- Block's -------------------------------------------------------------

# --------------Start Code Here  'Column 0'-------------------------------------
x0y0 = ttk.Label(root, text="   ----------------------------------", style="BW.TLabel")
x0y0.grid(sticky="W", column=0, row=0)
x0y1 = ttk.Label(root, text="Horizonte de evaluacion:", style="BW.TLabel")
x0y1.grid(sticky="W", column=0, row=1)
x0y2 = ttk.Label(root, text="Poblacion critica:", style="BW.TLabel")
x0y2.grid(sticky="W", column=0, row=2)
x0y3 = ttk.Label(root, text="Parametro de forma (alfa):", style="BW.TLabel")
x0y3.grid(sticky="W", column=0, row=3)
x0y4 = ttk.Label(root, text="Parametro de escala(beta):", style="BW.TLabel")
x0y4.grid(sticky="W", column=0, row=4)
x0y5 = ttk.Label(root, text="Tiempo de recuperacion no critico:", style="BW.TLabel")
x0y5.grid(sticky="W", column=0, row=5)
x0y6 = ttk.Label(root, text="   ---------------------------------", style="BW.TLabel")
x0y6.grid(sticky="W", column=0, row=6)
x0y7 = ttk.Label(root, text="Tamaño de la poblacion 1:", style="BW.TLabel")
x0y7.grid(sticky="W", column=0, row=7)
x0y8 = ttk.Label(root, text="Tamaño de la poblacion 2:", style="BW.TLabel")
x0y8.grid(sticky="W", column=0, row=8)

x0y14 = ttk.Label(root, text='Graficos')
x0y14.grid(column=2, row=0)

x0y15 = ttk.Button(root, text='Grafica de recuperados', state=tk.NORMAL,
                   command=lambda: graf_recuperados(dia_evaluacion(), pob_total(),
                                                    valor_alpha(), valor_beta(),
                                                    poblc_critica(), tiempo_de_recuperacion_no_c(), tp()))
x0y15.grid(sticky="W", column=2, row=1)

x0y16 = ttk.Button(root, text='Grafica de recuperados criticos', state=tk.NORMAL,
                   command=lambda: graf_recuperados_crit(dia_evaluacion(), pob_total(),
                                                         valor_alpha(), valor_beta(),
                                                         poblc_critica(), tp()))
x0y16.grid(sticky="W", column=2, row=2)

x0y17 = ttk.Button(root, text='Grafica de infectados', state=tk.NORMAL,
                   command=lambda: graf_infectados(dia_evaluacion(), pob_total(),
                                                   valor_alpha(), valor_beta(),
                                                   poblc_critica()))
x0y17.grid(sticky="W", column=2, row=3)

x0y18 = ttk.Button(root, text='Grafica de infectados criticos', state=tk.NORMAL,
                   command=lambda: graf_infectados_crit(dia_evaluacion(), pob_total(),
                                                        valor_alpha(), valor_beta(),
                                                        poblc_critica()))
x0y18.grid(sticky="W", column=2, row=4)
x0y19 = ttk.Button(root, text='Casos totales', state=tk.NORMAL,
                   command=lambda: grafica_casos_totales(dia_evaluacion(), pob_total(),
                                                         valor_alpha(), valor_beta(),
                                                         poblc_critica()))
x0y19.grid(sticky="W", column=2, row=5)
x0y20 = ttk.Button(root, text='Casos activos', state=tk.NORMAL,
                   command=lambda: grafica_activos_por_dia(dia_evaluacion(), pob_total(),
                                                           valor_alpha(), valor_beta(),
                                                           poblc_critica(), tiempo_de_recuperacion_no_c(), tp()))
x0y20.grid(sticky="W", column=2, row=6)

# --------------End Code Here-----------------------------------------------

# --------------Start Code Here  'Column 1'--------------------------------

x1y0 = ttk.Label(text="----------------------------", style="BW.TLabel")
x1y0.grid(sticky="W",  column=1, row=0)
x1y1 = ttk.Entry(root, textvariable=dia_de_evaluacion)
x1y1.grid(column=1, row=1)
x1y2 = ttk.Entry(root, textvariable=poblacion_critica)
x1y2.grid(column=1, row=2)
x1y3 = ttk.Entry(root, textvariable=parametro_de_forma)
x1y3.grid(column=1, row=3)
x1y4 = ttk.Entry(root, textvariable=parametro_de_escala)
x1y4.grid(column=1, row=4)
x1y5 = ttk.Entry(root, textvariable=tiempo_r_no_critico)
x1y5.grid(column=1, row=5)
x1y6 = ttk.Label(root, text="-----------------------------", style="BW.TLabel")
x1y6.grid(sticky="W", column=1, row=6)
x1y7 = ttk.Entry(root, textvariable=tamano_de_poblacion_1)
x1y7.grid(column=1, row=7)
x1y8 = ttk.Entry(root, textvariable=tamano_de_poblacion_2)
x1y8.grid(column=1, row=8)

x1y14 = ttk.Label(root, text='Ventiladores')
x1y14.grid(column=3, row=0)
x1y15 = ttk.Radiobutton(root, text="INFINITY W4R", variable=ventilador, value=28)
x1y15.grid(sticky="W", column=3, row=1)
x1y16 = ttk.Radiobutton(root, text="Hamiltone", variable=ventilador, value=42)
x1y16.grid(sticky="W", column=3, row=2)
x1y17 = ttk.Radiobutton(root, text="GTX1060", variable=ventilador, value=56)
x1y17.grid(sticky="W", column=3, row=3)

# --------------End Code Here-----------------------------------------------

x3y19 = ttk.Label(root, text='By Volk', style="BW.TLabel")
x3y19.grid(sticky="E", column=4, row=18)

# --------------End Code Here-----------------------------------------------

root.mainloop()

# End File


import sqlite3
from django.urls import reverse
from django.shortcuts import render, redirect
from django.contrib.auth.decorators import login_required
from exercisesapp.models import Cohort, Student, Exercise
from ..connection import Connection

def create_student(cursor, row):
    _row = sqlite3.Row(cursor, row)

    student = Student()
    student.id = _row["student_id"]
    student.first_name = _row["first_name"]
    student.last_name = _row["last_name"]
    student.slack_handle = _row["slack_handle"]

    cohort = Cohort()
    cohort.id = _row["cohort_id"]
    cohort.name = _row["cohort_name"]

    student.cohort = cohort

    student.exercises = []

    exercise = None

    if _row["exercise_id"] is not None:
        exercise = Exercise()
        exercise.id = _row["exercise_id"]
        exercise.name = _row["exercise_name"]
        exercise.language = _row["language"]

    return  (student, exercise)

def get_student(student_id):
    with sqlite3.connect(Connection.db_path) as conn:
        conn.row_factory = create_student
        db_cursor = conn.cursor()

        db_cursor.execute("""
        SELECT
            s.id student_id,
            s.first_name,
            s.last_name,
            s.slack_handle,
            s.cohort_id,
            c.name cohort_name,
            e.id exercise_id,
            e.name exercise_name,
            e.language
        FROM exercisesapp_student s
        LEFT JOIN exercisesapp_cohort c ON c.id = s.cohort_id
        LEFT JOIN exercisesapp_assignment a ON a.student_id = s.id
        LEFT JOIN exercisesapp_exercise e ON e.id = a.exercise_id
        WHERE s.id = ?
        """, (student_id,))

        student_assignments = db_cursor.fetchall()

        this_student = None

        for (student, exercise) in student_assignments:
            if this_student is None:
                if exercise is not None:
                    student.exercises.append(exercise)
                this_student = student
            else:
                this_student.exercises.append(exercise)

        return this_student

@login_required
def student_details(request, student_id):
    if request.method == 'GET':
        student = get_student(student_id)

        template = 'students/details.html'

        context = {
            'student': student
        }

        return render(request, template, context)
    elif request.method == 'POST':
        form_data = request.POST
        if (
            "actual_method" in form_data
            and form_data["actual_method"] == "PUT"
        ):
            with sqlite3.connect(Connection.db_path) as conn:
                db_cursor = conn.cursor()

                db_cursor.execute("""
                UPDATE exercisesapp_student
                SET first_name = ?,
                last_name = ?,
                slack_handle = ?,
                cohort_id = ?
                WHERE id = ?
                """,
                (form_data['first_name'], form_data['last_name'], form_data['slack_handle'], form_data['cohort'], student_id))

            return redirect('exercisesapp:student', student_id)

        if (
            "actual_method" in form_data
            and form_data["actual_method"] == "DELETE"
        ):
            with sqlite3.connect(Connection.db_path) as conn:
                db_cursor = conn.cursor()

                db_cursor.execute("""
                    DELETE FROM exercisesapp_student
                    WHERE id = ?
                """, (student_id,))

            return redirect(reverse('exercisesapp:students'))


import logging
from fastapi import FastAPI, Response, HTTPException
from json import loads

from models import AdmissionReview, Patch, Response as ARResponse
from utils import verify_chain

app = FastAPI()
app.host = "0.0.0.0"

@app.get("/")
async def root():
    return {"message": "Nothing to see"}

@app.get("/health", status_code=204, response_class=Response)
async def health() -> None:
    if verify_chain():
        return
    raise HTTPException(status_code=400, detail="Certificate chain not valid")

@app.post("/mutate")
async def mutate(body: dict) -> None:
    ar = AdmissionReview(**body)
    obj = ar.request.object

    spec = obj.metadata.annotations.get("topologySpreadConstraints/spec", None)
    op = obj.metadata.annotations.get("topologySpreadConstraints/op", "add")
    path = obj.metadata.annotations.get("topologySpreadConstraints/path", "/spec/topologySpreadConstraints")

    if spec is None :
        return AdmissionReview(response={"uid": ar.request.uid, "patchType": None}).json()

    patch = Patch(op=op, path=path, value=loads(spec))
    response = ARResponse(uid=ar.request.uid, patch=patch.dump())

    logging.info(msg=f"Applying patch: {patch}")
    return AdmissionReview(response=response).json()


from __future__ import absolute_import
from __future__ import print_function
from __future__ import division
from __future__ import unicode_literals

from gslib.utils import boto_util
from gslib.utils import constants
from gslib.utils import system_util
from gslib.utils import ls_helper
from gslib.utils import retry_util
from gslib.utils import text_util
from gslib.utils import unit_util
import gslib.tests.testcase as testcase
from gslib.tests.util import SetEnvironmentForTest
from gslib.tests.util import TestParams
from gslib.utils.text_util import CompareVersions
from gslib.utils.unit_util import DecimalShort
from gslib.utils.unit_util import HumanReadableWithDecimalPlaces
from gslib.utils.unit_util import PrettyTime
import httplib2

import os
import six
from six import add_move, MovedModule

add_move(MovedModule('mock', 'mock', 'unittest.mock'))
from six.moves import mock

# TODO: Split tests for <foo>_util methods out into their own test classes.
class TestUtil(testcase.GsUtilUnitTestCase):
  """Tests for utility functions."""

  def testMakeHumanReadable(self):
    """Tests converting byte counts to human-readable strings."""
    self.assertEqual(unit_util.MakeHumanReadable(0), '0 B')
    self.assertEqual(unit_util.MakeHumanReadable(1023), '1023 B')
    self.assertEqual(unit_util.MakeHumanReadable(1024), '1 KiB')
    self.assertEqual(unit_util.MakeHumanReadable(1024**2), '1 MiB')
    self.assertEqual(unit_util.MakeHumanReadable(1024**3), '1 GiB')
    self.assertEqual(unit_util.MakeHumanReadable(1024**3 * 5.3), '5.3 GiB')
    self.assertEqual(unit_util.MakeHumanReadable(1024**4 * 2.7), '2.7 TiB')
    self.assertEqual(unit_util.MakeHumanReadable(1024**5), '1 PiB')
    self.assertEqual(unit_util.MakeHumanReadable(1024**6), '1 EiB')

  def testMakeBitsHumanReadable(self):
    """Tests converting bit counts to human-readable strings."""
    self.assertEqual(unit_util.MakeBitsHumanReadable(0), '0 bit')
    self.assertEqual(unit_util.MakeBitsHumanReadable(1023), '1023 bit')
    self.assertEqual(unit_util.MakeBitsHumanReadable(1024), '1 Kibit')
    self.assertEqual(unit_util.MakeBitsHumanReadable(1024**2), '1 Mibit')
    self.assertEqual(unit_util.MakeBitsHumanReadable(1024**3), '1 Gibit')
    self.assertEqual(unit_util.MakeBitsHumanReadable(1024**3 * 5.3),
                     '5.3 Gibit')
    self.assertEqual(unit_util.MakeBitsHumanReadable(1024**4 * 2.7),
                     '2.7 Tibit')
    self.assertEqual(unit_util.MakeBitsHumanReadable(1024**5), '1 Pibit')
    self.assertEqual(unit_util.MakeBitsHumanReadable(1024**6), '1 Eibit')

  def testHumanReadableToBytes(self):
    """Tests converting human-readable strings to byte counts."""
    self.assertEqual(unit_util.HumanReadableToBytes('1'), 1)
    self.assertEqual(unit_util.HumanReadableToBytes('15'), 15)
    self.assertEqual(unit_util.HumanReadableToBytes('15.3'), 15)
    self.assertEqual(unit_util.HumanReadableToBytes('15.7'), 16)
    self.assertEqual(unit_util.HumanReadableToBytes('1023'), 1023)
    self.assertEqual(unit_util.HumanReadableToBytes('1k'), 1024)
    self.assertEqual(unit_util.HumanReadableToBytes('2048'), 2048)
    self.assertEqual(unit_util.HumanReadableToBytes('1 k'), 1024)
    self.assertEqual(unit_util.HumanReadableToBytes('1 K'), 1024)
    self.assertEqual(unit_util.HumanReadableToBytes('1 KB'), 1024)
    self.assertEqual(unit_util.HumanReadableToBytes('1 KiB'), 1024)
    self.assertEqual(unit_util.HumanReadableToBytes('1 m'), 1024**2)
    self.assertEqual(unit_util.HumanReadableToBytes('1 M'), 1024**2)
    self.assertEqual(unit_util.HumanReadableToBytes('1 MB'), 1024**2)
    self.assertEqual(unit_util.HumanReadableToBytes('1 MiB'), 1024**2)
    self.assertEqual(unit_util.HumanReadableToBytes('1 g'), 1024**3)
    self.assertEqual(unit_util.HumanReadableToBytes('1 G'), 1024**3)
    self.assertEqual(unit_util.HumanReadableToBytes('1 GB'), 1024**3)
    self.assertEqual(unit_util.HumanReadableToBytes('1 GiB'), 1024**3)
    self.assertEqual(unit_util.HumanReadableToBytes('1t'), 1024**4)
    self.assertEqual(unit_util.HumanReadableToBytes('1T'), 1024**4)
    self.assertEqual(unit_util.HumanReadableToBytes('1TB'), 1024**4)
    self.assertEqual(unit_util.HumanReadableToBytes('1TiB'), 1024**4)
    self.assertEqual(unit_util.HumanReadableToBytes('1\t   p'), 1024**5)
    self.assertEqual(unit_util.HumanReadableToBytes('1\t   P'), 1024**5)
    self.assertEqual(unit_util.HumanReadableToBytes('1\t   PB'), 1024**5)
    self.assertEqual(unit_util.HumanReadableToBytes('1\t   PiB'), 1024**5)
    self.assertEqual(unit_util.HumanReadableToBytes('1e'), 1024**6)
    self.assertEqual(unit_util.HumanReadableToBytes('1E'), 1024**6)
    self.assertEqual(unit_util.HumanReadableToBytes('1EB'), 1024**6)
    self.assertEqual(unit_util.HumanReadableToBytes('1EiB'), 1024**6)

  def testCompareVersions(self):
    """Tests CompareVersions for various use cases."""
    # CompareVersions(first, second) returns (g, m), where
    #   g is True if first known to be greater than second, else False.
    #   m is True if first known to be greater by at least 1 major version,
    (g, m) = CompareVersions('3.37', '3.2')
    self.assertTrue(g)
    self.assertFalse(m)
    (g, m) = CompareVersions('7', '2')
    self.assertTrue(g)
    self.assertTrue(m)
    (g, m) = CompareVersions('3.32', '3.32pre')
    self.assertTrue(g)
    self.assertFalse(m)
    (g, m) = CompareVersions('3.32pre', '3.31')
    self.assertTrue(g)
    self.assertFalse(m)
    (g, m) = CompareVersions('3.4pre', '3.3pree')
    self.assertTrue(g)
    self.assertFalse(m)

    (g, m) = CompareVersions('3.2', '3.37')
    self.assertFalse(g)
    self.assertFalse(m)
    (g, m) = CompareVersions('2', '7')
    self.assertFalse(g)
    self.assertFalse(m)
    (g, m) = CompareVersions('3.32pre', '3.32')
    self.assertFalse(g)
    self.assertFalse(m)
    (g, m) = CompareVersions('3.31', '3.32pre')
    self.assertFalse(g)
    self.assertFalse(m)
    (g, m) = CompareVersions('3.3pre', '3.3pre')
    self.assertFalse(g)
    self.assertFalse(m)

    (g, m) = CompareVersions('foobar', 'baz')
    self.assertFalse(g)
    self.assertFalse(m)
    (g, m) = CompareVersions('3.32', 'baz')
    self.assertFalse(g)
    self.assertFalse(m)

    (g, m) = CompareVersions('3.4', '3.3')
    self.assertTrue(g)
    self.assertFalse(m)
    (g, m) = CompareVersions('3.3', '3.4')
    self.assertFalse(g)
    self.assertFalse(m)
    (g, m) = CompareVersions('4.1', '3.33')
    self.assertTrue(g)
    self.assertTrue(m)
    (g, m) = CompareVersions('3.10', '3.1')
    self.assertTrue(g)
    self.assertFalse(m)

  def _AssertProxyInfosEqual(self, pi1, pi2):
    self.assertEqual(pi1.proxy_type, pi2.proxy_type)
    self.assertEqual(pi1.proxy_host, pi2.proxy_host)
    self.assertEqual(pi1.proxy_port, pi2.proxy_port)
    self.assertEqual(pi1.proxy_rdns, pi2.proxy_rdns)
    self.assertEqual(pi1.proxy_user, pi2.proxy_user)
    self.assertEqual(pi1.proxy_pass, pi2.proxy_pass)

  def testMakeMetadataLine(self):
    test_params = (TestParams(args=('AFairlyShortKey', 'Value'),
                              expected='    AFairlyShortKey:        Value'),
                   TestParams(args=('', 'Value'),
                              expected='    :                       Value'),
                   TestParams(args=('AnotherKey', 'Value'),
                              kwargs={'indent': 2},
                              expected='        AnotherKey:         Value'),
                   TestParams(args=('AKeyMuchLongerThanTheLast', 'Value'),
                              expected=('    AKeyMuchLongerThanTheLast:Value')))
    for params in test_params:
      line = ls_helper.MakeMetadataLine(*(params.args), **(params.kwargs))
      self.assertEqual(line, params.expected)

  def testSetProxyInfo(self):
    """Tests SetProxyInfo for various proxy use cases in boto file."""
    valid_proxy_types = ['socks4', 'socks5', 'http']
    valid_proxy_host = ['hostname', '1.2.3.4', None]
    valid_proxy_port = [8888, 0]
    valid_proxy_user = ['foo', None]
    valid_proxy_pass = ['Bar', None]
    valid_proxy_rdns = [True, False, None]

    proxy_type_spec = {
        'socks4': httplib2.socks.PROXY_TYPE_SOCKS4,
        'socks5': httplib2.socks.PROXY_TYPE_SOCKS5,
        'http': httplib2.socks.PROXY_TYPE_HTTP,
        'https': httplib2.socks.PROXY_TYPE_HTTP
    }

    #Generate all input combination values
    boto_proxy_config_test_values = [{
        'proxy_host': p_h,
        'proxy_type': p_t,
        'proxy_port': p_p,
        'proxy_user': p_u,
        'proxy_pass': p_s,
        'proxy_rdns': p_d
    } for p_h in valid_proxy_host for p_s in valid_proxy_pass
                                     for p_p in valid_proxy_port
                                     for p_u in valid_proxy_user
                                     for p_t in valid_proxy_types
                                     for p_d in valid_proxy_rdns]

    #Test all input combination values
    with SetEnvironmentForTest({'http_proxy': 'http://host:50'}):
      for test_values in boto_proxy_config_test_values:
        proxy_type = proxy_type_spec.get(test_values.get('proxy_type'))
        proxy_host = test_values.get('proxy_host')
        proxy_port = test_values.get('proxy_port')
        proxy_user = test_values.get('proxy_user')
        proxy_pass = test_values.get('proxy_pass')
        proxy_rdns = bool(test_values.get('proxy_rdns'))

        # Added to force socks proxies not to use rdns as in SetProxyInfo()
        if not (proxy_type == proxy_type_spec['http']):
          proxy_rdns = False

        expected = httplib2.ProxyInfo(proxy_host=proxy_host,
                                      proxy_type=proxy_type,
                                      proxy_port=proxy_port,
                                      proxy_user=proxy_user,
                                      proxy_pass=proxy_pass,
                                      proxy_rdns=proxy_rdns)

        # Checks to make sure environment variable fallbacks are working
        if not (expected.proxy_host and expected.proxy_port):
          expected = httplib2.ProxyInfo(proxy_type_spec['http'], 'host', 50)
          # Assume proxy_rnds is True if a proxy environment variable exists.
          if test_values.get('proxy_rdns') == None:
            expected.proxy_rdns = True

        self._AssertProxyInfosEqual(boto_util.SetProxyInfo(test_values),
                                    expected)

  def testProxyInfoFromEnvironmentVar(self):
    """Tests ProxyInfoFromEnvironmentVar for various cases."""
    valid_variables = ['http_proxy', 'https_proxy']
    if not system_util.IS_WINDOWS:
      # Dynamically set Windows environment variables are case-insensitive.
      valid_variables.append('HTTPS_PROXY')
    # Clear any existing environment variables for the duration of the test.
    clear_dict = {}
    for key in valid_variables:
      clear_dict[key] = None
    with SetEnvironmentForTest(clear_dict):
      for env_var in valid_variables:
        for url_string in ['hostname', 'http://hostname', 'https://hostname']:
          with SetEnvironmentForTest({env_var: url_string}):
            self._AssertProxyInfosEqual(
                boto_util.ProxyInfoFromEnvironmentVar(env_var),
                httplib2.ProxyInfo(
                    httplib2.socks.PROXY_TYPE_HTTP, 'hostname',
                    443 if env_var.lower().startswith('https') else 80))
            # Shouldn't populate info for other variables
            for other_env_var in valid_variables:
              if other_env_var == env_var:
                continue
              self._AssertProxyInfosEqual(
                  boto_util.ProxyInfoFromEnvironmentVar(other_env_var),
                  httplib2.ProxyInfo(httplib2.socks.PROXY_TYPE_HTTP, None, 0))
        for url_string in [
            '1.2.3.4:50', 'http://1.2.3.4:50', 'https://1.2.3.4:50'
        ]:
          with SetEnvironmentForTest({env_var: url_string}):
            self._AssertProxyInfosEqual(
                boto_util.ProxyInfoFromEnvironmentVar(env_var),
                httplib2.ProxyInfo(httplib2.socks.PROXY_TYPE_HTTP, '1.2.3.4',
                                   50))
        for url_string in [
            'foo:bar@1.2.3.4:50', 'http://foo:bar@1.2.3.4:50',
            'https://foo:bar@1.2.3.4:50'
        ]:
          with SetEnvironmentForTest({env_var: url_string}):
            self._AssertProxyInfosEqual(
                boto_util.ProxyInfoFromEnvironmentVar(env_var),
                httplib2.ProxyInfo(httplib2.socks.PROXY_TYPE_HTTP,
                                   '1.2.3.4',
                                   50,
                                   proxy_user='foo',
                                   proxy_pass='bar'))
        for url_string in [
            'bar@1.2.3.4:50', 'http://bar@1.2.3.4:50', 'https://bar@1.2.3.4:50'
        ]:
          with SetEnvironmentForTest({env_var: url_string}):
            self._AssertProxyInfosEqual(
                boto_util.ProxyInfoFromEnvironmentVar(env_var),
                httplib2.ProxyInfo(httplib2.socks.PROXY_TYPE_HTTP,
                                   '1.2.3.4',
                                   50,
                                   proxy_user='bar'))
      for env_var in ['proxy', 'noproxy', 'garbage']:
        for url_string in ['1.2.3.4:50', 'http://1.2.3.4:50']:
          with SetEnvironmentForTest({env_var: url_string}):
            self._AssertProxyInfosEqual(
                boto_util.ProxyInfoFromEnvironmentVar(env_var),
                httplib2.ProxyInfo(httplib2.socks.PROXY_TYPE_HTTP, None, 0))

  # We want to make sure the wrapped function is called without executing it.
  @mock.patch.object(retry_util.http_wrapper,
                     'HandleExceptionsAndRebuildHttpConnections')
  @mock.patch.object(retry_util.logging, 'info')
  def testWarnAfterManyRetriesHandler(self, mock_log_info_fn, mock_wrapped_fn):
    # The only ExceptionRetryArgs attributes that the function cares about are
    # num_retries and total_wait_sec; we can pass None for the other values.
    retry_args_over_threshold = retry_util.http_wrapper.ExceptionRetryArgs(
        None, None, None, 3, None, constants.LONG_RETRY_WARN_SEC + 1)
    retry_args_under_threshold = retry_util.http_wrapper.ExceptionRetryArgs(
        None, None, None, 2, None, constants.LONG_RETRY_WARN_SEC - 1)

    retry_util.LogAndHandleRetries()(retry_args_under_threshold)
    self.assertTrue(mock_wrapped_fn.called)
    # Check that we didn't emit a message.
    self.assertFalse(mock_log_info_fn.called)

    retry_util.LogAndHandleRetries()(retry_args_over_threshold)
    self.assertEqual(mock_wrapped_fn.call_count, 2)
    # Check that we did emit a message.
    self.assertTrue(mock_log_info_fn.called)

  def testUIDecimalShort(self):
    """Tests DecimalShort for UI."""
    self.assertEqual('12.3b', DecimalShort(12345678910))
    self.assertEqual('123.5m', DecimalShort(123456789))
    self.assertEqual('1.2k', DecimalShort(1234))
    self.assertEqual('1.0k', DecimalShort(1000))
    self.assertEqual('432', DecimalShort(432))
    self.assertEqual('43.2t', DecimalShort(43.25 * 10**12))
    self.assertEqual('43.2q', DecimalShort(43.25 * 10**15))
    self.assertEqual('43250.0q', DecimalShort(43.25 * 10**18))

  def testUIPrettyTime(self):
    """Tests PrettyTime for UI."""
    self.assertEqual('25:02:10', PrettyTime(90130))
    self.assertEqual('01:00:00', PrettyTime(3600))
    self.assertEqual('00:59:59', PrettyTime(3599))
    self.assertEqual('100+ hrs', PrettyTime(3600 * 100))
    self.assertEqual('999+ hrs', PrettyTime(3600 * 10000))

  def testUIHumanReadableWithDecimalPlaces(self):
    """Tests HumanReadableWithDecimalPlaces for UI."""
    self.assertEqual('1.0 GiB',
                     HumanReadableWithDecimalPlaces(1024**3 + 1024**2 * 10, 1))
    self.assertEqual('1.0 GiB', HumanReadableWithDecimalPlaces(1024**3), 1)
    self.assertEqual('1.01 GiB',
                     HumanReadableWithDecimalPlaces(1024**3 + 1024**2 * 10, 2))
    self.assertEqual('1.000 GiB',
                     HumanReadableWithDecimalPlaces(1024**3 + 1024**2 * 5, 3))
    self.assertEqual('1.10 GiB',
                     HumanReadableWithDecimalPlaces(1024**3 + 1024**2 * 100, 2))
    self.assertEqual('1.100 GiB',
                     HumanReadableWithDecimalPlaces(1024**3 + 1024**2 * 100, 3))
    self.assertEqual('10.00 MiB',
                     HumanReadableWithDecimalPlaces(1024**2 * 10, 2))
    # The test below is good for rounding.
    self.assertEqual('2.01 GiB', HumanReadableWithDecimalPlaces(2157969408, 2))
    self.assertEqual('2.0 GiB', HumanReadableWithDecimalPlaces(2157969408, 1))
    self.assertEqual('0 B', HumanReadableWithDecimalPlaces(0, 0))
    self.assertEqual('0.00 B', HumanReadableWithDecimalPlaces(0, 2))
    self.assertEqual('0.00000 B', HumanReadableWithDecimalPlaces(0, 5))

  def testAmzGenerationTypeConversions(self):
    amz_gen_as_str = six.ensure_str('9PpsRjBGjBh90IvIS96dgRc_UL6NyGqD')
    amz_gen_as_long = 25923956239092482442895228561437790190304192615858167521375267910356975448388
    self.assertEqual(text_util.DecodeLongAsString(amz_gen_as_long),
                     amz_gen_as_str)
    self.assertEqual(text_util.EncodeStringAsLong(amz_gen_as_str),
                     amz_gen_as_long)

  def DoTestAddQueryParamToUrl(self, url, param_name, param_val, expected_url):
    new_url = text_util.AddQueryParamToUrl(url, param_name, param_val)
    self.assertEqual(new_url, expected_url)

  def testAddQueryParamToUrlWorksForASCIIValues(self):
    # Note that the params here contain empty values and duplicates.
    old_url = 'http://foo.bar/path/endpoint?a=1&a=2&b=3&c='
    param_name = 'newparam'
    param_val = 'nevalue'
    expected_url = '{}&{}={}'.format(old_url, param_name, param_val)

    self.DoTestAddQueryParamToUrl(old_url, param_name, param_val, expected_url)

  def testAddQueryParamToUrlWorksForUTF8Values(self):
    old_url = 'http://foo.bar/path/êndpoint?Â=1&a=2&ß=3&c='
    param_name = 'nêwparam'
    param_val = 'nêwvalue'
    # Expected return value is a UTF-8 encoded `str`.
    expected_url = '{}&{}={}'.format(old_url, param_name, param_val)

    self.DoTestAddQueryParamToUrl(old_url, param_name, param_val, expected_url)

  def testAddQueryParamToUrlWorksForRawUnicodeValues(self):
    old_url = 'http://foo.bar/path/êndpoint?Â=1&a=2&ß=3&c='
    param_name = 'nêwparam'
    param_val = 'nêwvalue'
    # Since the original URL was a `unicode`, the returned URL should also be.
    expected_url = '{}&{}={}'.format(old_url, param_name, param_val)

    self.DoTestAddQueryParamToUrl(old_url, param_name, param_val, expected_url)

  @mock.patch.object(boto_util, 'GetMaxUploadCompressionBufferSize')
  def testGetMaxConcurrentCompressedUploadsMinimum(self, mock_config):
    """Test GetMaxConcurrentCompressedUploads returns at least 1."""
    mock_config.return_value = 0
    self.assertEqual(boto_util.GetMaxConcurrentCompressedUploads(), 1)
    mock_config.return_value = -1
    self.assertEqual(boto_util.GetMaxConcurrentCompressedUploads(), 1)


from keras.models import Sequential
from keras.layers import LSTM, Dense
from keras.preprocessing.sequence import pad_sequences
import numpy as np

data_dim = 2
timesteps = 2
num_classes = 2
train_samples = 1000
test_samples = 100
# set the sample_weights for each training sample
sample_weights = np.array([-1 for _ in range(train_samples)])

# each training sample is a 2-timestamp sequence
x_train = [[[1,1], [1,2]] for _ in range(train_samples)]
# label is the label from the input sequence
# in this setting, we don't need to output the sequence, because we are not going to re-use the sequence for another prediction
y_train = [[0,1] for _ in range(train_samples)]
# pad them
x_train = pad_sequences(x_train, maxlen=timesteps, padding='pre')
y_train = pad_sequences(y_train)

x_val = [[[1,1], [1,2]] for _ in range(test_samples)]
y_val = [[0,1] for _ in range(test_samples)]

# sample_weights = [[-1, 1]]

# expected input data shape: (batch_size, timesteps, data_dim)
model = Sequential()
model.add(LSTM(32, return_sequences=True,
               input_shape=(timesteps, data_dim)))  # returns a sequence of vectors of dimension 32
model.add(LSTM(32, return_sequences=True))  # returns a sequence of vectors of dimension 32
model.add(LSTM(32, return_sequences=False))  # return a single vector of dimension 32
# models.add(LSTM(num_classes, return_sequences=True, activation='softmax'))  # return a single vector of dimension 32
model.add(Dense(num_classes, activation='softmax'))

model.compile(loss='categorical_crossentropy',
              optimizer='rmsprop',
              metrics=['accuracy'],
              # sample_weight_mode='temporal'
              )

model.fit(x_train, y_train,
          batch_size=64, epochs=5,
          validation_data=(x_val, y_val),
          sample_weight=sample_weights
          )

question = np.array([[[1,1], [1,2]]])
question = pad_sequences(question, maxlen=timesteps, padding='pre')
print(question)
ret = model.predict(question, )
print(ret)


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

"""
KT6
Kysy käyttäjältä mitä hän haluaa seuraavista vaihtoehdoista (eli käyttäjä syöttää joko numeron 0, 1, 2 tai 3) :

   0 = Lopetus
   1 = Anna säde
   2 = Laske ympyrän piiri
   3 = Laske ympyrän pinta-ala

   Anna valintasi:

Tulosta kysymys edellä kuvatulla tavalla.

Muu kuin 0,1,2,3 vastaa nollaa eli päättää ohjelman toiminnan.

Vaihtoehto 0 päättää ohjelman

Vaihtoehto 1 kysyy ympyrän säteen.  Säteen oletusarvo on nolla (0.0)

Vaihtoehto 2 tulostaa ympyrän piirin (laskukaava on piiri = 2 * pii * säde)

Vaihtoehto 3 tulostaa ympyrän alan (laskukaava on  ala = pii * sade * sade) pinta-ala ja tulosta se.

Jos vaihtoehto on ollut 1,2,3, niin toimenpiteiden (syöttö/tulostus) jälkeen tulostetaan edellä kuvattu  vaihtoehtokysymys uudelleen

Hae piin arvo math moduulista (koodin alkuun import math ja sen jälkeen pii saadaan  math.pi muuttujasta)

Tulosta kaikki desimaaliluvut kahden desimalin tarkkuudella.

Esimerkkiajo ohessa

0 = Lopetus
1 = Anna säde
2 = Laske ympyrän piiri
3 = Laske ympyrän pinta-ala
Anna valintasi: 1
Anna säde: 12

0 = Lopetus
1 = Anna säde
2 = Laske ympyrän piiri
3 = Laske ympyrän pinta-ala
Anna valintasi: 2
Piiri on 75.40

0 = Lopetus
1 = Anna säde
2 = Laske ympyrän piiri
3 = Laske ympyrän pinta-ala
Anna valintasi: 3
Ala on 452.39

0 = Lopetus
1 = Anna säde
2 = Laske ympyrän piiri
3 = Laske ympyrän pinta-ala
Anna valintasi: 0

"""
syotto = 4
valinta = 4
sade = 0.0
piiri = 0.0
pinta_ala = 0.0
pii = 3.14159265359

while valinta != 0:
   print('\n 0 = Lopetus \n 1 = Anna säde \n 2 = Laske ympyrän piiri \n 3 = Laske ympyrän pinta-ala')

   syotto = input("\n Anna valintasi: ")

   try:
      valinta = int(syotto)

   except:
      valinta = 0

   if valinta == 1:
      sade = float(input("\n säde: "))
   elif valinta == 2:
        piiri = 2 * pii * sade
        print(f'\n Piiri on {piiri:.2f}')
   elif valinta == 3:
      pinta_ala = pii * (sade ** 2)
      print(f'\n Ala on {round(pinta_ala, 2)}')
   else:
      valinta = 0


import sys
from os.path import exists
import argparse
import pandas as pd

def get_filenames():
    """
    Collect filenames as input

    Return:
      plans, zips, slcsp
    """
    parser = argparse.ArgumentParser(description='Accept file names.')
    parser.add_argument('-p', '--plans',
                        help='csv file with all the health plans in the U.S. on the marketplace',
                        required=True)
    parser.add_argument('-z', '--zips',
                        help='''
                        csv file with a mapping of ZIP Code to county/counties & rate area(s)
                        ''',
                        required=True)
    parser.add_argument('-s', '--slcsp',
                        help='csv file wit the ZIP codes that need to be processed',
                        required=True)
    args = parser.parse_args()
    for path in (args.plans, args.zips, args.slcsp):
        if not exists(path):
            print(f'Error: {path} is not a valid file name')
            parser.print_help()
            sys.exit(9)
    return (args.plans, args.zips, args.slcsp)

def csv_to_df(filename: str):
    """
    Read a csv file and convert to a pandas dataframe
    path (str): The path to a csv file

    Returns:
      pandas Dataframe
    """
    return pd.read_csv(filename)

def get_ref_plans(plans: pd.DataFrame):
    """
    Compute the refeence plans to be used for SLCSP

    Select only the silver plans.
    Rank them in ascending rate for each state and area
    Pick the second lowest from the ranked plans
    Pick the only (lowest) plan if there is no second-ranked plan
    Merge the picked plans

    Params:
      plans Pandas dataframe that needs to includ state, rate_area and rate

    Returns:
      ref_plans: Pandas dataframe that has exactly one rate per state and rate area
    """
    COLS_TO_RETURN = ['state', 'rate_area', 'rate']
    silver_filter = plans['metal_level'] == 'Silver'
    silver_plans = plans[silver_filter]
    silver_plans = silver_plans[COLS_TO_RETURN]
    ranked_selver_plans = silver_plans.assign(
        rn=silver_plans.sort_values(["rate"])
        .groupby(['state', 'rate_area'])
        .cumcount() + 1
    ).sort_values(['state', 'rate_area', "rn"])
    second_lowest = ranked_selver_plans[
        ranked_selver_plans['rn'] == 2]

    # lowest = ranked_silver minus plans with many rates
    tmp = pd.merge(ranked_selver_plans, second_lowest, indicator=True,
                   on=['state', 'rate_area'], how='outer',
                   suffixes=[None, '_y'])
    lowest = tmp[tmp['_merge'] == 'left_only']
    return pd.concat([lowest, second_lowest],
                     ignore_index=True)[COLS_TO_RETURN]

def get_zip_plans(zips: pd.DataFrame, ref_plans: pd.DataFrame):
    """
    Compute a ref plan for each zipcode

    Drop zipcode if it maps to more than one state and rate_area
    Params:
    zips dataframe mapping zipcode to state and rate_area
    refs_plan dataframe mapping state and rate_area to rate

    Returns:
    zip_plans dataframe mapping zipcode to rate
    """
    zips_df = zips[['zipcode', 'state', 'rate_area']] \
        .drop_duplicates(keep=False)
    zip_plans = pd.merge(zips_df, ref_plans)
    return zip_plans[['zipcode', 'rate']]

def get_plans_for_inout(slcsp, zip_plans):
    return slcsp.merge(zip_plans, on='zipcode', how='left').rename(
        columns={'rate_y': 'rate'})[['zipcode', 'rate']]

if __name__ == "__main__":
    fnames = get_filenames()
    plans, zips, slcsp = (csv_to_df(fname) for fname in fnames)

    try:
        ref_plans = get_ref_plans(plans)
        zip_plans = get_zip_plans(zips, ref_plans)
        slcsp_out = get_plans_for_inout(slcsp, zip_plans)
    except KeyError as err:
        print(err, file=sys.stderr)
        print('Invalid file. Must be a csv file with the relevant columns')
        sys.exit(1)
    slcsp_out.to_csv(sys.stdout, index=False)


import logging
import os
import shutil
import unittest

from RandomForest.RandomForestTrainer import RandomForestTrainer
from sklearn.ensemble import RandomForestClassifier
from FileProcessingService import FileProcessingService
from SupportedFileTypes import SupportedFileTypes
from SupportedThirdPartyResponses import SupportedThirdPartyResponses
from ThirdPartyProgramCaller import ThirdPartyProgramCaller

class RandomForestTrainerIT(unittest.TestCase):

    log = logging.getLogger(__name__)
    log.setLevel(logging.INFO)

    def setUp(self):
        self.current_working_dir = os.getcwd()  # Should be this package.
        self.number_of_genomes = 20

    def tearDown(self):
        if self.generated_folder != "/" and os.path.isdir(self.generated_folder):
            shutil.rmtree(self.generated_folder)

    def initializeServicesAndCreateGenomes(self, file_name, file_type, response_type):
        data_file = self.setTargetFile('SampleDataFiles', file_name)
        file_processing_service = FileProcessingService(data_file, file_type,
                                                        self.number_of_genomes, self.current_working_dir)
        self.generated_folder = self.current_working_dir + file_processing_service.GENERATED_FOLDER_NAME
        genomes_created = file_processing_service.createGenomes()
        file_processing_service.data_file.close()
        self.thirdPartyProgramCaller = ThirdPartyProgramCaller(self.current_working_dir, file_type, genomes_created[0],
                                                               response_type, self.number_of_genomes, 0)
        return genomes_created

    def setTargetFile(self, path_name, file_name):
        resource_path = '/'.join((path_name, file_name))
        return open(resource_path)

    def getThirdPartyResult(self):
        return self.thirdPartyProgramCaller.callThirdPartyProgram(True)

    @staticmethod
    def assertModelTrainedSuccessfully(genomes, model, expected_classes):
        assert model is not None
        assert model.feature_importances_.size == len(genomes[1][0])  # num 'importances' == num features
        if model is RandomForestClassifier:
            assert len(model.classes_) == expected_classes

    def testIntegerClassifierModelCreatedSuccessfully(self):
        genomes = self.initializeServicesAndCreateGenomes('WNT_ERK_crosstalk.octave', SupportedFileTypes.OCTAVE,
                                                          SupportedThirdPartyResponses.INTEGER)
        third_party_result = self.getThirdPartyResult()

        random_forest_trainer = RandomForestTrainer(genomes[1], third_party_result)
        random_forest_result = random_forest_trainer.trainRandomForestClassifier(0.7)

        self.assertModelTrainedSuccessfully(genomes, random_forest_result[0], 2)

    def testRegressorModelCreatedSuccessfully(self):
        genomes = self.initializeServicesAndCreateGenomes('WNT_ERK_crosstalk_float_output.octave',
                                                          SupportedFileTypes.OCTAVE,
                                                          SupportedThirdPartyResponses.FLOAT)
        third_party_result = self.getThirdPartyResult()

        random_forest_trainer = RandomForestTrainer(genomes[1], third_party_result)
        random_forest_result = random_forest_trainer.trainRandomForestRegressor(0.7)

        self.assertModelTrainedSuccessfully(genomes, random_forest_result[0], 2)

    def testMultiClassifierModelCreatedSuccessfullyWithLinearProgramming(self):
        response_type = SupportedThirdPartyResponses.INTEGER
        attempts_at_multi_classification = 0
        hit_more_than_two_outcomes = False
        third_party_result = {}
        genomes = []

        while attempts_at_multi_classification < 10 and not hit_more_than_two_outcomes:
            attempts_at_multi_classification += 1
            self.log.info("Attempt number %s at getting multi-classifier results.", attempts_at_multi_classification)
            genomes = self.initializeServicesAndCreateGenomes('linearProgrammingModel.octave',
                                                              SupportedFileTypes.OCTAVE, response_type)
            third_party_result = self.getThirdPartyResult()
            classes = list(set(third_party_result.values()))
            if len(classes) > 2:
                hit_more_than_two_outcomes = True

        if len(genomes) == 0 or third_party_result == {}:
            self.log.error("Unable to return more than 2 classes from third party response.")
            assert False

        random_forest_trainer = RandomForestTrainer(genomes[1], third_party_result)
        random_forest_result = random_forest_trainer.trainRandomForestClassifier(0.7)

        self.assertModelTrainedSuccessfully(genomes, random_forest_result[0], 3)


import os
import random

import pygame

from button.button import Button
from utils.constants import *
from pygame.locals import *

from letter.letter import Letter
from plane.plane import Plane
from utils.helpers import scale_image

global SCORE, NEXT_LETTER, LIVES

# Link para generar audio en mp3 (parametro q="texto"):
# https://translate.google.com/translate_tts?ie=UTF-8&client=tw-ob&tl=es&q=
# Link para trabajar con audios:
# https://pythonprogramming.net/adding-sounds-music-pygame/

class Game:
    def __init__(self):
        global SCORE, NEXT_LETTER, LIVES

        pygame.mixer.pre_init(44100, -16, 2, 2048)
        pygame.mixer.init()
        pygame.mixer.music.load(os.path.join("assets/sounds", "8bit-game-music-sound.ogg"))
        pygame.mixer.music.play(loops=-1)
        pygame.mixer.music.set_volume(0.0)
        self.plane_sound = pygame.mixer.Sound(os.path.join("assets/sounds", "plane-sound.ogg"))
        self.search_letter_a_sound = pygame.mixer.Sound(os.path.join("assets/audio", "audio-buscar-la-letra-a.mp3"))
        self.search_letter_e_sound = pygame.mixer.Sound(os.path.join("assets/audio", "audio-buscar-la-letra-e.mp3"))
        self.search_letter_i_sound = pygame.mixer.Sound(os.path.join("assets/audio", "audio-buscar-la-letra-i.mp3"))
        self.search_letter_o_sound = pygame.mixer.Sound(os.path.join("assets/audio", "audio-buscar-la-letra-o.mp3"))
        self.search_letter_u_sound = pygame.mixer.Sound(os.path.join("assets/audio", "audio-buscar-la-letra-u.mp3"))
        self.success_sound = pygame.mixer.Sound(os.path.join("assets/sounds", "success-sound.mp3"))
        self.error_sound = pygame.mixer.Sound(os.path.join("assets/sounds", "error-sound.mp3"))
        self.game_start_sound = pygame.mixer.Sound(os.path.join("assets/sounds", "game-start-sound.mp3"))

        pygame.init()
        pygame.display.set_caption(TITLE)

        self.replay = True
        self.intro = True
        self.play = True
        self.gameover = True

        self.font = pygame.font.SysFont("Gaegu", 80)
        self.font2 = pygame.font.SysFont("Gaegu", 50)

        self.clock = pygame.time.Clock()
        self.screen = pygame.display.set_mode((WIDTH, HEIGHT))
        self.bg_scroll = 0
        self.bg = pygame.image.load('assets/images/bg.png').convert_alpha()

        self.numbers_images = []
        for i in range(10):
            number_image = pygame.image.load(f'assets/images/numeros/number{i}.png').convert_alpha()
            self.numbers_images.append(number_image)

        self.heart_images = []
        self.heart_image_index = 0
        for i in range(8):
            heart_image = pygame.image.load(f'assets/images/hearts/heart{i}.png').convert_alpha()
            heart_image = scale_image(heart_image, 30)
            self.heart_images.append(heart_image)

        self.gameover_image = pygame.image.load('assets/images/textGameOver.png').convert_alpha()

        self.ADDLETTER = pygame.USEREVENT + 1
        pygame.time.set_timer(self.ADDLETTER, 2000)

        SCORE = SCORE_INITIAL
        LIVES = LIVES_INITIAL
        NEXT_LETTER = random.choice(list(LETTERS_UPPER))

        while self.replay:
            self.replay = False
            self.menu()
            self.game_play()
            self.game_over()
            if not self.replay:
                break
            else:
                SCORE = SCORE_INITIAL
                LIVES = LIVES_INITIAL
                NEXT_LETTER = random.choice(list(LETTERS_UPPER))
                self.intro = True
                self.play = True
                self.gameover = True

        pygame.quit()

    def play_audio_letter(self, letter):
        if letter == "A":
            self.search_letter_a_sound.play()
        elif letter == "E":
            self.search_letter_e_sound.play()
        elif letter == "I":
            self.search_letter_i_sound.play()
        elif letter == "O":
            self.search_letter_o_sound.play()
        elif letter == "U":
            self.search_letter_u_sound.play()

    def draw_bg_image(self):
        self.screen.blit(self.bg, (0 - self.bg_scroll, 0))
        self.screen.blit(self.bg, (WIDTH - self.bg_scroll, 0))
        self.bg_scroll += 1
        if self.bg_scroll == WIDTH:
            self.bg_scroll = 0

    def show_score(self, score):
        num_digits = len(str(score))
        score_x = int(WIDTH / 2 - self.numbers_images[0].get_width() * num_digits / 2)
        for digit in str(score):
            number_image = self.numbers_images[int(digit)]
            self.screen.blit(number_image, (score_x, 30))
            score_x += number_image.get_width()

    def show_letter_to_capture(self):
        letter_image = pygame.image.load(LETTERS_UPPER[NEXT_LETTER]).convert_alpha()
        letter_image = scale_image(letter_image, 50)
        self.screen.blit(letter_image, (WIDTH - letter_image.get_width() - 20, 20))

    def show_lives_remaining(self, lives):
        for i in range(lives):
            heart_image = self.heart_images[int(self.heart_image_index)]
            heart_x = 30 + i * (heart_image.get_width() + 10)
            heart_y = 30
            self.screen.blit(heart_image, (heart_x, heart_y))
        self.heart_image_index += 0.1
        if self.heart_image_index >= len(self.heart_images):
            self.heart_image_index = 0

    def menu(self):
        self.draw_bg_image()

        prefijo = self.font2.render("Vamos a jugar", True, WHITE)
        prefijo_position = (
            WIDTH / 2 - prefijo.get_width() // 2,
            HEIGHT / 2 - prefijo.get_height() - 350 // 2
        )

        title = self.font.render("-= AviOn AtrApA VoCaLes =-", True, WHITE)
        title_position = (
            WIDTH / 2 - title.get_width() // 2,
            HEIGHT / 2 - title.get_height() - 120 // 2
        )

        buttons = pygame.sprite.Group()
        play_button = Button(500, 400, 'assets/images/play-button.png', self.play_button_click)
        buttons.add(play_button)

        while self.intro:
            for event in pygame.event.get():
                if event.type == QUIT:
                    self.intro = False
                    exit()
                elif event.type == MOUSEBUTTONDOWN:
                    for entity in buttons:
                        entity.on_click(event)

            buttons.update()
            self.screen.fill(BLUE)

            self.screen.blit(title, title_position)
            self.screen.blit(prefijo, prefijo_position)

            for entity in buttons:
                self.screen.blit(entity.surface, entity.rect)

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

    def play_button_click(self):
        self.intro = False
        self.game_start_sound.play()

    def game_play(self):
        global SCORE, NEXT_LETTER, LIVES
        self.play_audio_letter(NEXT_LETTER)

        plane = Plane()
        self.plane_sound.play(loops=-1)
        self.plane_sound.set_volume(0.2)

        letters = pygame.sprite.Group()
        all_sprites = pygame.sprite.Group()
        all_sprites.add(plane)

        while self.play:
            for event in pygame.event.get():
                if event.type == QUIT:
                    self.play = False
                    exit()
                elif event.type == self.ADDLETTER:
                    new_letter = Letter()
                    letters.add(new_letter)
                    all_sprites.add(new_letter)

            if pygame.mouse.get_pressed()[0]:
                plane.fly_up()

            plane.update()
            letters.update()

            self.draw_bg_image()

            for entity in all_sprites:
                self.screen.blit(entity.image, entity.rect)

            for le in letters:
                if pygame.sprite.spritecollide(plane, letters, False, pygame.sprite.collide_mask):
                    if le.key == NEXT_LETTER:
                        self.success_sound.play()
                        SCORE += 1
                        NEXT_LETTER = random.choice(list(LETTERS_UPPER))
                        self.play_audio_letter(NEXT_LETTER)
                    else:
                        self.error_sound.play()
                        LIVES -= 1
                        if LIVES == 0:
                            self.play = False
                    le.kill()

            self.show_letter_to_capture()
            self.show_score(SCORE)
            self.show_lives_remaining(LIVES)

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

    def game_over(self):
        buttons = pygame.sprite.Group()
        restart_button = Button(500, 300, 'assets/images/restart-button.png', self.restart_button_click)
        buttons.add(restart_button)
        self.plane_sound.stop()

        while self.gameover:
            for event in pygame.event.get():
                if event.type == QUIT:
                    self.gameover = False
                    exit()
                elif event.type == MOUSEBUTTONDOWN:
                    for entity in buttons:
                        entity.on_click(event)

            gameover_x = WIDTH / 2 - self.gameover_image.get_width() / 2
            gameover_y = HEIGHT / 2 - self.gameover_image.get_height() / 2 - 150
            self.screen.blit(self.gameover_image, (gameover_x, gameover_y))

            buttons.update()
            for entity in buttons:
                self.screen.blit(entity.surface, entity.rect)

            pygame.display.flip()

    def restart_button_click(self):
        self.gameover = False
        self.replay = True
        pygame.display.flip()

if __name__ == "__main__":
    g = Game()


from __future__ import print_function
import httplib2
from pprint import pprint
from googleapiclient import discovery

from modules import google_auth

discoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'
               'version=v4')

http = google_auth.get_credentials().authorize(httplib2.Http())
service = discovery.build('sheets', 'v4', credentials=google_auth.get_credentials())

#Add our data (value) to Google Sheet (spreadsheet_id)
def GS_Append(value, spreadsheet_id, range_name):

    #How the data should be interpreted
    value_input_option = 'USER_ENTERED'

    values = value

    body = {'values': values}

    request_other = service.spreadsheets().values().append(spreadsheetId=spreadsheet_id, range=range_name,
                                                     valueInputOption= value_input_option,
                                                     body = body)

    response = request_other.execute()

    pprint(response)


from flask import Flask, render_template, request, redirect, abort
from bokeh.embed import components
import csv

app = Flask(__name__)

app.vars={}

# Load in stock data, writing as sg to be able to call to the functions later on
import StockGraphs as sg

@app.route('/',methods=['POST'])
def index_savel ():

    # Creating list of stocksymbols users can enter, and giving in error message if they enter letters that aren't stock
    myfile = open("stocktickers.csv", "r")
    stocksymbols = csv.reader(myfile)
    stocksymbolslist = []
    for row in stocksymbols:
        stocksymbolslist.append(row[0])

    # request was a POST
    app.vars['ticker_symbol'] = request.form['stockform']
    if app.vars['ticker_symbol'] in stocksymbolslist:
        return index(app.vars['ticker_symbol'])
    else:
        abort(406)

# Index page
@app.route('/',methods=['GET'])
# putting the equal sign after sets a default value
def index(co='AAPL'):
    # which metric was selected by user
    metric = request.form.get("feature_name")
    # setting a default metric
    if metric == None:
        metric = "close"

    options = ['open', 'close', 'high', 'low', 'volume']

    # Make the Plot

    plot = sg.getstockplot(co,metric)

    # Embed plot into HTML via Flask Render
    script, div = components(plot)

    return render_template("template.html", script=script, div=div,
        feature_names=options,  current_feature_name=metric)

if __name__ == '__main__':
  app.run(port=33507)


from django.shortcuts import render,redirect
from django.views.generic import CreateView, ListView, DetailView, UpdateView, DeleteView
from .models import Reader, Reading
from django.contrib.auth.mixins import LoginRequiredMixin
from datetime import date, datetime, timedelta
from .forms import UserRegisterForm, ReadingSchedule
from django.contrib import messages
from django.core.mail import send_mail

month = date.today().month
year = date.today().year
day = date.today().day
today = date(year, month, day)

try:
    read = Reading.objects.get(date_reading=today)
    if read:
        send_mail(
            'Reading', 'you are reaing today',
             'kuhneykwame@gmail.com', ['woden42076@mailernam.com'],
             fail_silently=False
            )
except Reading.DoesNotExist:
    pass

# Create your views here.
def home(request):
    month = date.today().month
    year = date.today().year
    day = date.today().day
    today = date(year, month, day)
    return render(request,'readers/home.html',{'lists':Reading.objects.all().order_by('date_reading'),'today':today,'month':month})

def register(request):
    if request.method == 'POST':
        form = UserRegisterForm(request.POST)
        if form.is_valid():
            form.save()
            username = form.cleaned_data.get('username')
            messages.success(request, f'Your account has been created. You can now login')
            return redirect('login')
    else:
        form = UserRegisterForm()
    return render(request, 'readers/register.html',{'form':form})

class ReaderDetailView(DetailView):
    model = Reader
    template_name = 'readers/readers-detail.html'

class ReadingDetailView(DetailView):
    model = Reading
    template_name = 'readers/reading-detail.html'

class ReadingCreateView(CreateView,LoginRequiredMixin):
    model = Reading
    template_name = 'readers/reading_create.html'
    fields = ['reader','date_reading']

class ReaderCreateView(CreateView, LoginRequiredMixin):
    model = Reader
    template_name = 'readers/reader_create.html'
    fields = ['name','profile_image','date_joined']

#class AdminCreateView(CreateView):
 #   model = Admin
  #  template_name = 'readers/admin-create.html'
   # fields = ['name','profile_image']

def reading(request):
    if request.method == 'POST':
        form = ReadingSchedule(request.POST)
        if form.is_valid():
            username = form.cleaned_data.get('reader')
            date = form.cleaned_data.get('date_reading')
            publication = form.cleaned_data.get('publication')
            title = form.cleaned_data.get('title')
            try:
                obj = Reading.objects.get(date_reading=date)
                messages.success(request, f'This schedule has already been created')
                '''send_mail(
                     'Subject here', 'Here is the message.',
                     'kuhneykwame@gmail.com', ['vonaf26544@upcmaill.com'],
                     fail_silently=False
                )'''
            except Reading.DoesNotExist:
                obj = Reading(reader=username, date_reading=date, publication=publication, title=title)
                obj.save()
                return redirect('home')
    else:
        form = ReadingSchedule()
    return render(request,'readers/reading_create.html',{'form':form})

class ReaderListView(ListView):
    model = Reader
    template_name = 'readers/readers-list.html'
    context_object_name = 'readers'
    ordering = ['date_joined']

class ReadingUpdateView(UpdateView, LoginRequiredMixin):
    model = Reading
    template_name = 'readers/reading-update.html'
    fields = ['reader','date_reading','publication','title']

class ReadingDeleteView(DeleteView):
    model = Reading
    template_name = 'readers/reading_delete.html'
    success_url = '/'

def listview(request):
    month = date.today().month
    year = date.today().year
    day = date.today().day
    today = date(year, month, day)
    return render(request,'readers/table-list.html',{'lists':Reading.objects.all().order_by('date_reading'),'today':today})


import pandas as pd

from itables import javascript

def test_datatables_repr_max_columns_none():
    test_df = pd.DataFrame([1, 2])
    with pd.option_context("display.max_columns", None):
        html = javascript._datatables_repr_(test_df)
        assert html


#!/usr/bin/env python
# -*- coding:utf-8 -*-
#
#   Author  :   cold
#   E-mail  :   wh_linux@126.com
#   Date    :   13/03/08 11:28:36
#   Desc    :   获取消息
#
import json
import socket
import httplib
from .base import WebQQHandler
from ..webqqevents import RetryEvent, WebQQPollEvent, WebQQMessageEvent
from ..webqqevents import ReconnectEvent

class PollHandler(WebQQHandler ):
    """ 获取消息 """
    def setup(self):
        self.method = "POST"
        if not self.req:
            url = "http://d.web2.qq.com/channel/poll2"
            params = [("r", '{"clientid":"%s", "psessionid":"%s",'
                    '"key":0, "ids":[]}' % (self.webqq.clientid,
                                            self.webqq.psessionid)),
                    ("clientid", self.webqq.clientid),
                    ("psessionid", self.webqq.psessionid)]
            self.req = self.http_sock.make_request(url, params, self.method)
            self.req.add_header("Referer", "http://d.web2.qq.com/proxy.html?v="
                                "20110331002&callback=1&id=2")
        try:
            self.sock, self.data = self.http_sock.make_http_sock_data(self.req)
        except socket.error:
            self.webqq.event(RetryEvent(PollHandler, self.req, self))
            self._writable = False
            self.sock = None
            self.data = None

    def handle_write(self):
        self._writable = False
        try:
            self.sock.sendall(self.data)
        except socket.error:
            self.webqq.event(RetryEvent(PollHandler, self.req, self))
        else:
            self._readable = True

    def handle_read(self):
        try:
            resp = self.http_sock.make_response(self.sock, self.req, self.method)
            tmp = resp.read()
            data = json.loads(tmp)
            if data:
                self._readable = False
                #if data.get("retcode") == 121:
                #    self.webqq.event(ReconnectEvent(self))
                self.webqq.event(WebQQPollEvent(self))
                self.webqq.event(WebQQMessageEvent(data, self))
        except ValueError:
            pass
        except socket.error:
            self.webqq.event(WebQQPollEvent(self))
        except httplib.BadStatusLine:
            pass

    def is_writable(self):
        with self.lock:
            return self.sock and self.data and self._writable


# -*- coding: utf-8 -*-
import math
import matplotlib.pyplot as plt

a=10
b=8./3.

class Position():
    def __init__(self,_r,_x0=1,_y0=0,_z0=0,_t0=0,_time=60,_dt=0.0001):
        self.x=[_x0]
        self.y=[_y0]
        self.z=[_z0]
        self.t=[_t0]
        self.r=_r
        self.time=_time
        self.dt=_dt
        self.n=int(self.time/self.dt)
    def calculate(self):
        for i in range(self.n):
            self.x.append(self.x[-1]+a*(self.y[-1]-self.x[-1])*self.dt)
            self.y.append(self.y[-1]+(-self.x[-2]*self.z[-1]+self.r*self.x[-2]-self.y[-1])*self.dt)
            self.z.append(self.z[-1]+(self.x[-2]*self.y[-2]-b*self.z[-1])*self.dt)
            self.t.append(self.t[-1]+self.dt)
    def plot_zx(self,color):
        plt.plot(self.x,self.z,color)
    def plot_zy(self,color):
        plt.plot(self.y,self.z,color)
fig=plt.figure(figsize=(8,12))
ax1=plt.subplot(211)
A=Position(25)
A.calculate()
A.plot_zx('k-')
plt.title('Phase space plot:z vetsus x')
plt.xlabel('x')
plt.ylabel('z')
plt.legend()

ax2=plt.subplot(212)
B=Position(25)
B.calculate()
B.plot_zy('k-')
plt.title('Phase space plot:z vetsus y')
plt.xlabel('y')
plt.ylabel('z')
plt.legend()

plt.show()


'''
Author: Tolga MIRMIRIK (@mirmirik)

Twitter API'sine bağlanıp, dış parametrelere göre tweeter içinde arama yapmak için yazılmış deneme / sandbox kodu.
myTwitter.cfg dosyası içine ilgili değerleri ekleyip, komut satırından "python twSearch.py -s <kelime>" yazarak çalıştırılabilir.

Parametreler:
    -s, --search    : Arama yapılacak text
    -r, --replyTo   : <kaldırılacak>, bir tweet'e cevap verilecekse, o tweet'in ID'si
    -t, --text      : <kaldırılacak>, Tweet reply olacaksa, verilecn cevap text'i.

Konfigürasyon dosyası değerleri:
    [auth]
    ACCOUNT = <bilgilerine erişilecek size ait hesap adı>
    CONSUMER_KEY = <Twitter Development / APPS kısmından alınacak olacan CONSUMER KEY>
    CONSUMER_SECRET = <Twitter Development / APPS kısmından alınacak olacan CONSUMER SECRET>

Twitter API'ye erişim sağlayan wrapper library:
    https://github.com/sixohsix/twitter

Twitter Search detayları:
    https://developer.twitter.com/en/docs/tweets/search/overview
'''

import argparse
import sys
from twitter import Twitter, OAuth, oauth_dance, read_token_file
import os
import json
from datetime import datetime
import urllib.parse
import configparser

IN_DEBUG_MODE: bool = True
GET_FOLLOWERS: bool = True

cfg = configparser.ConfigParser()
cfg.read("myTwitter.cfg")

TW_ACCOUNT = cfg.get('auth', 'ACCOUNT')
CONSUMER_KEY = cfg.get('auth', 'CONSUMER_KEY')
CONSUMER_SECRET = cfg.get('auth', 'CONSUMER_SECRET')

SEARCH_RESULTS_FILE = "data/search_" + datetime.today().strftime('%Y%m%d') + ".txt"

MY_TWITTER_CREDS = os.path.expanduser('.tw_credentials_' + TW_ACCOUNT)

if not os.path.exists("data"):
    os.makedirs("data")

if not os.path.exists(MY_TWITTER_CREDS):
    oauth_dance("TW_App",
                CONSUMER_KEY,
                CONSUMER_SECRET,
                MY_TWITTER_CREDS)

oauth_token, oauth_secret = read_token_file(MY_TWITTER_CREDS)

# def replyto_tweet(replyto, tweettext):
#     """ID'si verilen tweet'e tweettext parametresi ile verilen yazıyı 'reply' olarak ekler.

#     Parametreler:
#         - replyto -- Cevap verilecek tweet'in ID'si
#         - tweettext -- Verilecek cevap yazısız
#     """
#     tw = Twitter(auth=OAuth(
#                 oauth_token,
#                 oauth_secret,
#                 CONSUMER_KEY,
#                 CONSUMER_SECRET))

#     tw.statuses.update(status=tweettext,
#                        in_reply_to_status_id=replyto)

def search_twitter(searchparameter):
    """ Twitter'daki son girilen tweetler içinde, verilen text'i arar. Bulunan son 100 tweet liste olarak ekrana ve dosyaya yazılır

    Parametreler:
        - searchparameter -- Aranılan keyword / text
    """
    activeCursor = -1
    searchThis = urllib.parse.quote(searchparameter.encode('utf-8'))
    searchThis = searchparameter

    tw = Twitter(auth=OAuth(
                oauth_token,
                oauth_secret,
                CONSUMER_KEY,
                CONSUMER_SECRET))

    if IN_DEBUG_MODE:
        fn = open(SEARCH_RESULTS_FILE, "w+")

    print("Search String: {0}".format(searchThis) + "\n")

    print("{:25s} {:25s} {:25s}".format(
        "TwId", "Tweet", "Created"))
    print("-" * 150)

    if IN_DEBUG_MODE:
        fn.write("{0}\t{1}\t{2}\t".format("TweetId",
                                          "Tweet text",
                                          "Created At") + "\n")

    while activeCursor != 0:
        f = tw.search.tweets(q=searchThis, count=100)

        _lastInteraction = ""

        for tw in f["statuses"]:
            try:
                if (tw["id"]):
                    # TW standart tarih formatı: Sat Aug 11 12:51:00 +0000 2018
                    _tempDate = tw["created_at"]
                    dtObj = datetime.strptime(_tempDate, '%a %b %d %H:%M:%S %z %Y')
                    _lastInteraction = "{0:2}.{1:2}.{2}".format(
                        str(dtObj.day), str(dtObj.month), str(dtObj.year))

            except KeyError:
                _lastInteraction = "Not found"

            print("{:25s} {:25s} {:25s}".format(
                tw["id_str"], tw["text"], _lastInteraction))
            if IN_DEBUG_MODE:
                fn.write("{0}\t{1}\t{2}".format(
                    tw["id"], tw["text"], _lastInteraction) + "\n")

        activeCursor = 0

    if IN_DEBUG_MODE:
        fn.close()

def main():
    parser = argparse.ArgumentParser(description="Search twitter for specific text")
    parser.add_argument("-s", "--search",
                        dest="SEARCH_STRING",
                        help="Search string to be used in application",
                        metavar="search text")

    # parser.add_argument("-r", "--replyto",
    #                     dest="REPLY_TO",
    #                     help="Tweet id of the tweet that will be replied",
    #                     metavar="replyto Id")

    # parser.add_argument("-t", "--text",
    #                     dest="REPLY_TEXT",
    #                     help="Tweet that will be sent",
    #                     metavar="tweet text")

    args = parser.parse_args()
    if args.SEARCH_STRING:
        search_twitter(args.SEARCH_STRING)
    # elif args.REPLY_TO:
    #     replyto_tweet(args.REPLY_TO, args.REPLY_TEXT)

if __name__ == "__main__":
    main()


import os
import re
import sys
import json
import codecs
import operator
import numpy as np
from tqdm import tqdm
'''
这是一个专门预处理数据的文件
'''
np.random.seed(1234)
special_chars = re.compile(r'[^A-Za-z_\d,.?!;:$\- \'\"]', re.IGNORECASE)

source_dir = os.path.join('.', 'raw')
emb_dir = os.path.join('.', 'embedding')
target_dir = os.path.join('.', 'data')

# special tokens
PAD = '__PAD__'
UNK = '__UNK__'

def clean_text(text):
    '''
    英文版的
    清洗数据 去掉特殊的字符
    :param text: 需要清洗的文本
    :return: 返回清洗好的文本

    '''
    text = text.replace("``", '"').replace("''", '"').replace("`", "'")  # convert quote symbols
    text = text.replace("n 't", "n't").replace("can not", "cannot")
    text = special_chars.sub(' ', text)
    text = re.sub(' +', ' ', text)
    return text

def load_data(filename, clean=True, encoding='utf-8'):
    '''

    :param filename: 文件的路径名
    :param clean:
    :param encoding: 编码
    :return: 数据集合 [tuple(data,label)]  类别的个数
    '''
    dataset = []
    labels = set()
    with codecs.open(filename, 'r', encoding=encoding) as f:
        for line in f:
            if encoding is not 'utf-8':
                line = line.encode('utf-8').decode(encoding)  # convert string to utf-8 version
            line = line.strip().split(' ')  # all the tokens and labels are split by __BLANKSPACE__
            if clean:
                sentence = clean_text(' '.join(line[1:])).split(' ')  # clean text and convert to tokens again
            else:
                sentence = line[1:]
            label = int(line[0])
            labels.add(label)
            dataset.append((sentence, label))
    return dataset, len(labels)

def load_glove_vocab(filename):
    '''
    :param filename: 文件路径
    :return: 返回所有的单词 不包含其对应的向量 是一个集合!!!!
    '''
    with open(filename, 'r', encoding='utf-8') as f:
        vocab = {line.strip().split()[0] for line in tqdm(f, desc='Loading GloVe vocabularies')}
    print('\t -- totally {} tokens in GloVe embeddings.\n'.format(len(vocab)))
    return vocab

def save_filtered_vectors(vocab, glove_path, save_path, word_dim):
    '''

    :param vocab: 是一个映射词典 word_idx
    :param glove_path:
    :param save_path:
    :param word_dim:
    :return:
    '''
    """Prepare pre-trained word embeddings for dataset"""
    embeddings = np.zeros([len(vocab), word_dim])  # embeddings[0] for PAD  声明一个所谓的多维度的数组
    scale = np.sqrt(3.0 / word_dim)
    embeddings[1] = np.random.uniform(-scale, scale, [1, word_dim])  # for UNK    这是一句好代码
    with open(glove_path, 'r', encoding='utf-8') as f:
        for line in tqdm(f, desc='Filtering GloVe embeddings'):
            line = line.strip().split(' ')
            word = line[0]
            embedding = [float(x) for x in line[1:]]
            if word in vocab:
                idx = vocab[word]
                embeddings[idx] = np.asarray(embedding)
    sys.stdout.write('Saving filtered embeddings...')
    np.savez_compressed(save_path, embeddings=embeddings)  #保存时候压缩一下
    sys.stdout.write(' done.\n')

def write_vocab(vocab, filename):
    '''
    :param vocab: 最后的词典
    :param filename: 保存最后的词典
    :return:
    '''
    sys.stdout.write('Writing vocab to {}...'.format(filename))
    with open(filename, 'w',encoding="utf-8") as f:
        for i, word in enumerate(vocab):
            f.write('{}\n'.format(word)) if i < len(vocab) - 1 else f.write(word)   # 这是一句好代码
    sys.stdout.write(' done. Totally {} tokens.\n'.format(len(vocab)))

def load_vocab(filename):
    '''
    :param filename:
    :return: 返回的是词典  id到单词的映射 word_idx, idx_word
    '''
    """read vocabulary from file into dict"""
    word_idx = dict()
    idx_word = dict()
    with open(filename, 'r', encoding='utf-8') as f:
        for idx, word in enumerate(f):
            word = word.strip()
            word_idx[word] = idx
            idx_word[idx] = word
    return word_idx, idx_word

def build_vocab(datasets, threshold=0):
    '''

    :param datasets:  数据
    :param threshold: 统计单词的最低词频
    :return: 返回最后的单词表和字符表
    '''

    word_count = dict()  # 字典
    char_vocab = set()   # 集合
    for dataset in datasets:
        for words, _ in dataset:
            for word in words:
                char_vocab.update(word)  # update char vocabulary  这是统计所有的字符的
                word_count[word] = word_count.get(word, 0) + 1  # update word count in word dict
    word_count = reversed(sorted(word_count.items(), key=operator.itemgetter(1)))
    word_vocab = set([w[0] for w in word_count if w[1] >= threshold])
    char_vocab = char_vocab
    return word_vocab, char_vocab

def dump_to_json(dataset, filename):
    '''
     没啥说的 保存到json文件自己中
    :param dataset:
    :param filename:
    :return:
    '''
    """Save built dataset into json"""
    if dataset is not None:
        with open(filename, 'w') as f:
            json.dump(dataset, f)
        sys.stdout.write('dump dataset to {}.\n'.format(filename))

def split_train_dev_test(dataset, dev_ratio=0.1, test_ratio=0.1, build_test=True, shuffle=True):
    '''

    :param dataset: 原始的数据列表  tuple()列表
    :param dev_ratio:   验证集合的比例
    :param test_ratio:  测试集合的比例
    :param build_test:
    :param shuffle:
    :return:
    '''
    """Split dataset into train, dev as well as test sets"""
    if shuffle:
        np.random.shuffle(dataset)
    data_size = len(dataset)
    if build_test:
        train_position = int(data_size * (1 - dev_ratio - test_ratio))
        dev_position = int(data_size * (1 - test_ratio))
        train_set = dataset[:train_position]
        dev_set = dataset[train_position:dev_position]
        test_set = dataset[dev_position:]
        return train_set, dev_set, test_set
    else:
        # dev_ratio = dev_ratio + test_ratio
        train_position = int(data_size * (1 - dev_ratio))
        train_set = dataset[:train_position]
        dev_set = dataset[train_position:]
        return train_set, dev_set, None

def fit_word_to_id(word, word_vocab, char_vocab):
    '''
    Convert word str to word index and char indices
    :param word:           一个单词
    :param word_vocab:     word_id 映射词典
    :param char_vocab:     char_id 映射词典
    :return: 返回有两个 1.返回的是一个标量单词的id  2 返回的是一个这个单词所包含的字符的ids,是一个列表
    '''

    char_ids = []
    for char in word:
        char_ids += [char_vocab[char]] if char in char_vocab else [char_vocab[UNK]]
    word = word_vocab[word] if word in word_vocab else word_vocab[UNK]
    return word, char_ids

def build_dataset(raw_dataset, filename, word_vocab, char_vocab, num_labels, one_hot=True):
    '''

    :param raw_dataset: 原始单词合数据集合 [tuple(dataset,label)]
    :param filename:    保存的文件路径名字
    :param word_vocab:  word_id映射词典
    :param char_vocab:  char_id映射字符
    :param num_labels:  类别的数目
    :param one_hot:
    :return:
    '''
    """Convert dataset into word/char index, make labels to be one hot vectors and dump to json file"""
    dataset = []   #是一个字典列表
    for sentence, label in raw_dataset:
        words = []                         #列表相加  第一个元素是单词的id 剩下的字符的ids!!!!!!!!!!!!!!!!!!!!!!!!!!1
        for word in sentence:
            words += [fit_word_to_id(word, word_vocab, char_vocab)]
        if one_hot:
            label = [1 if i == label else 0 for i in range(num_labels)]    #这一句代码写的还可以
        dataset.append({'sentence': words, 'label': label})
    dump_to_json(dataset, filename=filename)

def prepro_general(train_set, dev_set, test_set, num_labels, data_folder, glove_vocab, glove_path):
    """Performs to build vocabularies and processed dataset"""
    # build vocabularies
    word_vocab, char_vocab = build_vocab([train_set, dev_set])  # only process train and dev sets
    if glove_vocab is None:
        glove_vocab = load_glove_vocab(glove_path)
    word_vocab = [PAD, UNK] + list(word_vocab & glove_vocab)  # 集合求并 保证最后的词典都有单词向量   然后转换成列表类型
    write_vocab(word_vocab, filename=os.path.join(data_folder, 'words.vocab'))
    char_vocab = [PAD, UNK] + list(char_vocab)  # add PAD and UNK tokens
    write_vocab(char_vocab, filename=os.path.join(data_folder, 'chars.vocab'))
    # build embeddings
    word_vocab, _ = load_vocab(os.path.join(data_folder, 'words.vocab'))
    save_filtered_vectors(word_vocab, glove_path, os.path.join(data_folder, 'glove.filtered.npz'), word_dim=300)
    # build dataset
    char_vocab, _ = load_vocab(os.path.join(data_folder, 'chars.vocab'))  #char_vocab 是一个映射词典
    build_dataset(train_set, os.path.join(data_folder, 'train.json'), word_vocab, char_vocab, num_labels=num_labels,
                  one_hot=True)
    build_dataset(dev_set, os.path.join(data_folder, 'dev.json'), word_vocab, char_vocab, num_labels=num_labels,
                  one_hot=True)
    build_dataset(test_set, os.path.join(data_folder, 'test.json'), word_vocab, char_vocab, num_labels=num_labels,
                  one_hot=True)
    # save number of labels information into json
    with open(os.path.join(data_folder, 'label.json'), 'w') as f:
        json.dump({"label_size": num_labels}, f)

def prepro_sst(glove_path, glove_vocab=None, mode=1):
    '''

    :param glove_path:
    :param glove_vocab:
    :param mode:
    :return:
    '''
    print('Process sst{} dataset...'.format(mode))
    data_folder = os.path.join(target_dir, 'sst{}'.format(mode))
    if not os.path.exists(data_folder):
        os.makedirs(data_folder)
    # load dataset
    name = 'fine' if mode == 1 else 'binary'
    train_set, num_labels = load_data(os.path.join(source_dir, 'sst{}'.format(mode), 'stsa.{}.train'.format(name)))
    dev_set, _ = load_data(os.path.join(source_dir, 'sst{}'.format(mode), 'stsa.{}.dev'.format(name)))
    test_set, _ = load_data(os.path.join(source_dir, 'sst{}'.format(mode), 'stsa.{}.test'.format(name)))
    # build general
    prepro_general(train_set, dev_set, test_set, num_labels, data_folder, glove_vocab, glove_path)
    print()

def prepro_trec(glove_path, glove_vocab=None):
    print('Process trec dataset...')
    data_folder = os.path.join(target_dir, 'trec')
    if not os.path.exists(data_folder):
        os.makedirs(data_folder)
    # load dataset
    train_set, num_labels = load_data(os.path.join(source_dir, 'trec', 'TREC.train.all'), encoding='windows-1252')
    test_set, _ = load_data(os.path.join(source_dir, 'trec', 'TREC.test.all'))
    train_set, dev_set, _ = split_train_dev_test(train_set, build_test=False)
    # build general
    prepro_general(train_set, dev_set, test_set, num_labels, data_folder, glove_vocab, glove_path)
    print()

def prepro_other(name, filename, glove_path, glove_vocab=None, encoding='utf-8'):
    print('Process {} dataset...'.format(name))
    data_folder = os.path.join(target_dir, name)
    if not os.path.exists(data_folder):
        os.makedirs(data_folder)
    # load dataset
    train_set, num_labels = load_data(os.path.join(source_dir, name, filename), encoding=encoding)
    train_set, dev_set, test_set = split_train_dev_test(train_set)
    # build general
    prepro_general(train_set, dev_set, test_set, num_labels, data_folder, glove_vocab, glove_path)
    print()

def main():
    glove_path = os.path.join(emb_dir, 'glove.42B.300d.txt')
    glove_vocab = load_glove_vocab(glove_path)
    # process sst1 dataset
    prepro_sst(glove_path, glove_vocab, mode=1)
    # process sst2 dataset
    prepro_sst(glove_path, glove_vocab, mode=2)
    # process trec dataset
    prepro_trec(glove_path, glove_vocab)
    # process subj dataset
    prepro_other('subj', 'subj.all', glove_path, glove_vocab, encoding='windows-1252')
    # process mr dataset
    prepro_other('mr', 'rt-polarity.all', glove_path, glove_vocab, encoding='windows-1252')
    # process mpqa dataset
    prepro_other('mpqa', 'mpqa.all', glove_path, glove_vocab)
    # process cr dataset
    prepro_other('cr', 'custrev.all', glove_path, glove_vocab)
    print('Pre-processing all the datasets finished... data is located at {}'.format(target_dir))

if __name__ == '__main__':
    main()


import datetime
import random
import uuid

APPLICATION_ID_PREFIX = 'amzn1.ask.skill'
CONFIRMATION_STATUSES = (
    'CONFIRMED',
    'DENIED',
    'NONE',
)
DEVICE_ID_CHARACTER_SET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
DEVICE_ID_LENGTH = 156
DEVICE_ID_PREFIX = 'amzn1.ask.device'
DIALOG_STATES = (
    'COMPLETED',
    'IN_PROGRESS',
    'STARTED',
)
REQUEST_ID_PREFIX = 'amzn1.echo-api.request'
SESSION_ENDED_ERROR_TYPES = (
    'DEVICE_COMMUNICATION_ERROR',
    'INTERNAL_ERROR',
    'INVALID_RESPONSE',
)
SESSION_ID_PREFIX = 'amzn1.echo-api.session'
TIMESTAMP_FORMAT = '%Y-%m-%dT%H:%M:%SZ'
USER_ID_CHARACTER_SET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
USER_ID_LENGTH = 207
USER_ID_PREFIX = 'amzn1.ask.account'

def generate_access_token() -> str:
    """Generates a user access token similar to what might be in an Alexa
    request.

    :return: Generated access token
    """

    return 'laksfdqiohjweipobqvcljakhnfioquwefoiu'

def generate_application_id(prefix: str=APPLICATION_ID_PREFIX) -> str:
    """Generates an Alexa skill application ID, which is composed of a static
    prefix followed by a UUID.

    :param prefix: Optionally-specified prefix to use

    :return: Generated Alexa skill application ID
    """

    return '.'.join([prefix, str(uuid.uuid4())])

def generate_consent_token() -> str:
    """Generates a consent token similar to what might be in an Alexa request.
    Consent tokens indicate which permissions a user has granted a skill and
    are used to request user-specific information from AWS API's.

    :return: Generated Alexa skill consent token
    """

    return 'Atza|MQEWY...6fnLok'

def generate_confirmation_status() -> str:
    """Return a valid value for the 'confirmationStatus' value of an Alexa intent.

    :return: A randomly-chosen confirmation status.
    """

    return random.choice(CONFIRMATION_STATUSES)

def generate_dialog_state() -> str:
    """Return a valid value for the 'dialogState' value of an Alexa request.

    :return: A randomly-chosen dialog state.
    """

    return random.choice(DIALOG_STATES)

def generate_device_id(
        prefix: str=DEVICE_ID_PREFIX,
        character_set: str=DEVICE_ID_CHARACTER_SET,
        length: int=DEVICE_ID_LENGTH) -> str:
    """Generates a device ID similar to those for an Amazon Echo as seen in an
    Alexa request.

    :param prefix: Optional ID prefix
    :param character_set: Optional character set to use in ID generation
    :param length: Optional length of the generated ID

    :return: Generated Amazon Echo device ID
    """

    device_id = ''
    for count in range(length):
        device_id += random.choice(character_set)

    return '.'.join([prefix, device_id])

def generate_request_id(prefix: str=REQUEST_ID_PREFIX) -> str:
    """Generates an Alexa skill request ID, composed of a static prefix joined
    with a UUID.

    :param prefix: Optional ID prefix

    :return: Generated Alexa skill session ID
    """

    return '.'.join([prefix, str(uuid.uuid4())])

def generate_session_ended_error_type() -> str:
    """ Generate a valid error type for a SessionEndedRequest.

    :return: A randomly-selected error type.
    """

    return random.choice(SESSION_ENDED_ERROR_TYPES)

def generate_session_id(prefix: str=SESSION_ID_PREFIX) -> str:
    """Generates an Alexa skill session ID, composed of a static prefix joined
    with a UUID.

    :param prefix: Optional ID prefix

    :return: Generated Alexa skill session ID
    """

    return '.'.join([prefix, str(uuid.uuid4())])

def generate_timestamp(timestamp: datetime.datetime=None) -> str:
    """Generates a random timestamp in the format used by Alexa requests. If a
    specific time is passed, it will be formatted and returned instead.

    :param timestamp: Optional datetime to format and return

    :return: Formatted timestamp as a string
    """

    if timestamp is None:
        timestamp = datetime.datetime.now(datetime.timezone.utc)

    return timestamp.strftime(TIMESTAMP_FORMAT)

def generate_user_id(
        prefix: str=USER_ID_PREFIX, character_set: str=USER_ID_CHARACTER_SET,
        length: int=USER_ID_LENGTH) -> str:
    """Generates an Alexa skill user ID, composed of a static prefix joined
    with a random string. Alexa skill docs indicate that this ID changes if a
    user disables and subsequently re-enables a skill.

    :param prefix: Optional ID prefix
    :param character_set: Optional character set to use in ID generation
    :param length: Optional length of the generated ID

    :return: Generated Alexa skill user ID
    """

    user_id = ''
    for count in range(length):
        user_id += random.choice(character_set)

    return '.'.join([prefix, user_id])


import pandas as pd
import os

file_dir = os.getcwd()
stop_gap_file_name = file_dir + '/common_words.csv'

f = open(stop_gap_file_name, 'r')
data = f.read().split('\n')
stop = []
for d in data:
    stop.append(d)

file_name = file_dir + '/topics_data.csv'

data = pd.read_csv(file_name)

words = []
for ind, row in data.T.iteritems():
    details = row['comment_body'].lower().split(' ')
    for d in details:
        if d not in stop:
            words.append(d)

word_series = pd.Series(words)

word_counts = word_series.value_counts()
word_counts = word_counts[0:100]
word_counts_df = pd.DataFrame({'word': word_counts.index, 'count': word_counts})
file_name = file_dir + '/word_counts.csv'
word_counts_df.to_csv(file_name, index=False)

comment_author_counts = data['comment_author'].value_counts()
comment_author_counts_df = pd.DataFrame({'author': comment_author_counts.index, 'count': comment_author_counts})
file_name = file_dir + '/comment_author_counts.csv'
comment_author_counts_df.to_csv(file_name, index=False)

data['created'] = pd.to_datetime(data['created'])
data['comment_created'] = pd.to_datetime(data['comment_created'])

unique_submission_ids = data['id'].unique()

comment_duration_dict = {'id':[], 'duration': []}

for usi in unique_submission_ids:
    submission_data = data[data['id'] == usi]
    created = submission_data['created'].unique()
    if len(created) > 1:
        print("More than one created value")
        continue
    created = created[0]
    min_comment = submission_data['comment_created'].min()
    max_comment = submission_data['comment_created'].max()
    comment_duration = max_comment - min_comment
    comment_duration_dict['id'].append(usi)
    comment_duration_dict['duration'].append(comment_duration.seconds/60.0/60.0)

duration_data_df = pd.DataFrame(comment_duration_dict)
file_name = file_dir + '/duration_data.csv'
duration_data_df.to_csv(file_name, index=False)

Resources/T16 - Data Analysis Challenge Part 2/challenge_part_2_SOLUTION.py