class Pelicula:
    def __init__(self,categoria, titulo, director, anio, fecha, hora):
        self.categoria = categoria
        self.titulo = titulo
        self.director = director
        self.anio = anio
        self.fecha = fecha
        self.hora = hora
        self.next = None
        self.previous = None

    def mostrar(self):
        print(f'Categoria: {self.categoria}\nTitulo: {self.titulo}\nDirector: {self.director}\nAnio: {self.anio}\nFecha: {self.fecha}\nHora: {self.hora}\n')

class Peliculas:
    def __init__(self):
        self.cabeza = None

    def vacia(self):
        return self.cabeza is None

    def add_pelicula(self, categoria, titulo, director, anio, fecha, hora):
        nueva_pelicula = Pelicula(categoria, titulo, director, anio, fecha, hora)
        if self.vacia():
            self.cabeza = nueva_pelicula
        else:
            pelicula_actual = self.cabeza
            while pelicula_actual.next is not None:
                pelicula_actual = pelicula_actual.next
            pelicula_actual.next = nueva_pelicula
            nueva_pelicula.previous = pelicula_actual

    def buscar_pelicula(self, titulo, hora, fecha):
        actual = self.cabeza
        while actual is not None:
            if actual.titulo == titulo:
                if actual.hora == hora:
                    if actual.fecha == fecha:
                        actual.mostrar()
                        return True
            actual = actual.next
        return False

    def datos_pelicula(self, titulo, hora, fecha):
        actual = self.cabeza
        while actual is not None:
            if actual.titulo == titulo:
                if actual.hora == hora:
                    if actual.fecha == fecha:
                        return Pelicula(actual.categoria, actual.titulo, actual.director, actual.anio, actual.fecha, actual.hora)
            actual = actual.next
        return False

    def actualizar_pelicula(self, titulo, hora, fecha):
        actual = self.cabeza
        while actual is not None:
            if actual.titulo == titulo:
                if actual.hora == hora:
                    if actual.fecha == fecha:
                        actual.mostrar()
                        print('----------INGRESE LOS DATOS NUEVOS------')
                        categoria = input('Categoria: ')
                        actual.categoria = categoria
                        titulo = input('Titulo: ')
                        actual.titulo = titulo
                        director = input('Director: ')
                        actual.director = director
                        anio = input('Anio: ')
                        actual.anio = anio
                        fecha = input('fecha: ')
                        actual.fecha = fecha
                        hora = input('Hora: ')
                        actual.hora = hora
                        return True
            actual = actual.next
        return False

    def eliminar_pelicula(self, titulo, hora, fecha):
        actual = self.cabeza
        while actual is not None:
            if actual.titulo == titulo:
                if actual.hora == hora:
                    if actual.fecha == fecha:
                        if self.cabeza is None:
                            return False
                        if self.cabeza.titulo == titulo:
                            self.cabeza = self.cabeza.next
                            return True
                        while actual.next is not None:
                            if actual.next.titulo == titulo:
                                actual.next = actual.next.next
                                return True
                        return True
            actual = actual.next
        return False

    def imprimir_pelicula(self):
        pelicula_actual = self.cabeza
        while pelicula_actual is not None:
            pelicula_actual.mostrar()
            pelicula_actual = pelicula_actual.next


# Python bytecode 2.7 (decompiled from Python 2.7)
# Embedded file name: scripts/common/site-packages/future-0.18.2/libfuturize/main.py
from __future__ import absolute_import, print_function, unicode_literals
import future.utils
from future import __version__
import sys
import logging
import optparse
import os
from lib2to3.main import warn, StdoutRefactoringTool
from lib2to3 import refactor
from libfuturize.fixes import lib2to3_fix_names_stage1, lib2to3_fix_names_stage2, libfuturize_fix_names_stage1, libfuturize_fix_names_stage2
fixer_pkg = u'libfuturize.fixes'

def main(args=None):
    parser = optparse.OptionParser(usage=u'futurize [options] file|dir ...')
    parser.add_option(u'-V', u'--version', action=u'store_true', help=u'Report the version number of futurize')
    parser.add_option(u'-a', u'--all-imports', action=u'store_true', help=u'Add all __future__ and future imports to each module')
    parser.add_option(u'-1', u'--stage1', action=u'store_true', help=u'Modernize Python 2 code only; no compatibility with Python 3 (or dependency on ``future``)')
    parser.add_option(u'-2', u'--stage2', action=u'store_true', help=u'Take modernized (stage1) code and add a dependency on ``future`` to provide Py3 compatibility.')
    parser.add_option(u'-0', u'--both-stages', action=u'store_true', help=u'Apply both stages 1 and 2')
    parser.add_option(u'-u', u'--unicode-literals', action=u'store_true', help=u"Add ``from __future__ import unicode_literals`` to implicitly convert all unadorned string literals '' into unicode strings")
    parser.add_option(u'-f', u'--fix', action=u'append', default=[], help=u"Each FIX specifies a transformation; default: all.\nEither use '-f division -f metaclass' etc. or use the fully-qualified module name: '-f lib2to3.fixes.fix_types -f libfuturize.fixes.fix_unicode_keep_u'")
    parser.add_option(u'-j', u'--processes', action=u'store', default=1, type=u'int', help=u'Run 2to3 concurrently')
    parser.add_option(u'-x', u'--nofix', action=u'append', default=[], help=u'Prevent a fixer from being run.')
    parser.add_option(u'-l', u'--list-fixes', action=u'store_true', help=u'List available transformations')
    parser.add_option(u'-p', u'--print-function', action=u'store_true', help=u'Modify the grammar so that print() is a function')
    parser.add_option(u'-v', u'--verbose', action=u'store_true', help=u'More verbose logging')
    parser.add_option(u'--no-diffs', action=u'store_true', help=u"Don't show diffs of the refactoring")
    parser.add_option(u'-w', u'--write', action=u'store_true', help=u'Write back modified files')
    parser.add_option(u'-n', u'--nobackups', action=u'store_true', default=False, help=u"Don't write backups for modified files.")
    parser.add_option(u'-o', u'--output-dir', action=u'store', type=u'str', default=u'', help=u'Put output files in this directory instead of overwriting the input files.  Requires -n. For Python >= 2.7 only.')
    parser.add_option(u'-W', u'--write-unchanged-files', action=u'store_true', help=u'Also write files even if no changes were required (useful with --output-dir); implies -w.')
    parser.add_option(u'--add-suffix', action=u'store', type=u'str', default=u'', help=u"Append this string to all output filenames. Requires -n if non-empty. For Python >= 2.7 only.ex: --add-suffix='3' will generate .py3 files.")
    flags = {}
    refactor_stdin = False
    options, args = parser.parse_args(args)
    if options.write_unchanged_files:
        flags[u'write_unchanged_files'] = True
        if not options.write:
            warn(u'--write-unchanged-files/-W implies -w.')
        options.write = True
    if options.output_dir and not options.nobackups:
        parser.error(u"Can't use --output-dir/-o without -n.")
    if options.add_suffix and not options.nobackups:
        parser.error(u"Can't use --add-suffix without -n.")
    if not options.write and options.no_diffs:
        warn(u"not writing files and not printing diffs; that's not very useful")
    if not options.write and options.nobackups:
        parser.error(u"Can't use -n without -w")
    if u'-' in args:
        refactor_stdin = True
        if options.write:
            print(u"Can't write to stdin.", file=sys.stderr)
            return 2
    if options.print_function:
        flags[u'print_function'] = True
    level = logging.DEBUG if options.verbose else logging.INFO
    logging.basicConfig(format=u'%(name)s: %(message)s', level=level)
    logger = logging.getLogger(u'libfuturize.main')
    if options.stage1 or options.stage2:
        options.both_stages = False
    else:
        options.both_stages = True
    avail_fixes = set()
    if options.stage1 or options.both_stages:
        avail_fixes.update(lib2to3_fix_names_stage1)
        avail_fixes.update(libfuturize_fix_names_stage1)
    if options.stage2 or options.both_stages:
        avail_fixes.update(lib2to3_fix_names_stage2)
        avail_fixes.update(libfuturize_fix_names_stage2)
    if options.unicode_literals:
        avail_fixes.add(u'libfuturize.fixes.fix_unicode_literals_import')
    if options.version:
        print(__version__)
        return 0
    else:
        if options.list_fixes:
            print(u'Available transformations for the -f/--fix option:')
            for fixname in sorted(avail_fixes):
                print(fixname)

            if not args:
                return 0
        if not args:
            print(u'At least one file or directory argument required.', file=sys.stderr)
            print(u'Use --help to show usage.', file=sys.stderr)
            return 2
        unwanted_fixes = set()
        for fix in options.nofix:
            if u'.fix_' in fix:
                unwanted_fixes.add(fix)
            found = [ f for f in avail_fixes if f.endswith(u'fix_{0}'.format(fix)) ]
            if len(found) > 1:
                print(u'Ambiguous fixer name. Choose a fully qualified module name instead from these:\n' + u'\n'.join((u'  ' + myf for myf in found)), file=sys.stderr)
                return 2
            if len(found) == 0:
                print(u'Unknown fixer. Use --list-fixes or -l for a list.', file=sys.stderr)
                return 2
            unwanted_fixes.add(found[0])

        extra_fixes = set()
        if options.all_imports:
            if options.stage1:
                prefix = u'libfuturize.fixes.'
                extra_fixes.add(prefix + u'fix_add__future__imports_except_unicode_literals')
            else:
                prefix = u'libpasteurize.fixes.'
                extra_fixes.add(prefix + u'fix_add_all__future__imports')
                extra_fixes.add(prefix + u'fix_add_future_standard_library_import')
                extra_fixes.add(prefix + u'fix_add_all_future_builtins')
        explicit = set()
        if options.fix:
            all_present = False
            for fix in options.fix:
                if fix == u'all':
                    all_present = True
                if u'.fix_' in fix:
                    explicit.add(fix)
                found = [ f for f in avail_fixes if f.endswith(u'fix_{0}'.format(fix)) ]
                if len(found) > 1:
                    print(u'Ambiguous fixer name. Choose a fully qualified module name instead from these:\n' + u'\n'.join((u'  ' + myf for myf in found)), file=sys.stderr)
                    return 2
                if len(found) == 0:
                    print(u'Unknown fixer. Use --list-fixes or -l for a list.', file=sys.stderr)
                    return 2
                explicit.add(found[0])

            if len(explicit & unwanted_fixes) > 0:
                print(u'Conflicting usage: the following fixers have been simultaneously requested and disallowed:\n' + u'\n'.join((u'  ' + myf for myf in explicit & unwanted_fixes)), file=sys.stderr)
                return 2
            requested = avail_fixes.union(explicit) if all_present else explicit
        else:
            requested = avail_fixes.union(explicit)
        fixer_names = (requested | extra_fixes) - unwanted_fixes
        input_base_dir = os.path.commonprefix(args)
        if input_base_dir and not input_base_dir.endswith(os.sep) and not os.path.isdir(input_base_dir):
            input_base_dir = os.path.dirname(input_base_dir)
        if options.output_dir:
            input_base_dir = input_base_dir.rstrip(os.sep)
            logger.info(u'Output in %r will mirror the input directory %r layout.', options.output_dir, input_base_dir)
        if future.utils.PY26:
            extra_kwargs = {}
        else:
            extra_kwargs = {u'append_suffix': options.add_suffix,
             u'output_dir': options.output_dir,
             u'input_base_dir': input_base_dir}
        rt = StdoutRefactoringTool(sorted(fixer_names), flags, sorted(explicit), options.nobackups, (not options.no_diffs), **extra_kwargs)
        if not rt.errors:
            if refactor_stdin:
                rt.refactor_stdin()
            else:
                try:
                    rt.refactor(args, options.write, None, options.processes)
                except refactor.MultiprocessingUnsupported:
                    print(u"Sorry, -j isn't supported on this platform.", file=sys.stderr)
                    return 1

            rt.summarize()
        return int(bool(rt.errors))


#!/usr/bin/env python

from pyspark import SparkContext
from nltk.tokenize import word_tokenize
from argparse import ArgumentParser

args = ArgumentParser()
args.add_argument("-u", "--url", help="spark cluster URL")
args.add_argument("-o", "--output", default="tokens.out", help="output file")
opts = args.parse_args()

print(opts.url)
sc = SparkContext(opts.url, "Tokenizer")
text = sc.textFile("/gscratch/stf/kearnsw/freebase-rdf-latest")
tokens = text.flatMap(lambda line: word_tokenize(line))
tokens.saveAsTextFile("/gscratch/stf/kearnsw/{0}".format(opts.output))


import sys

from essentia import INFO
import essentia
from essentia.progress import Progress
from essentia.standard import *
import numpy as np
import conf

opts={'name' : 'essOnsetFunc',
      'lala':2}

def compute(audio):
    audio = essentia.array(audio)
    sampleRate  = int(conf.opts['sampleRate'])
    frameSize   = int(conf.opts['frameSize'])
    hopSize     = int(conf.opts['hopSize'])
    zeroPadding = int(conf.opts['zeroPadding'])
    windowType  = conf.opts['windowType']

    frameRate = float(sampleRate)/float(hopSize)

    INFO('Computing Ess Detection...')

    frames  = FrameGenerator(audio = audio, frameSize = frameSize, hopSize = hopSize)
    window  = Windowing(size = frameSize, zeroPadding = zeroPadding, type = windowType)
    fft = FFT()
    cartesian2polar = CartesianToPolar()
    onsetdetectionHFC = OnsetDetection(method = "hfc", sampleRate = sampleRate)
    onsetdetectionComplex = OnsetDetection(method = "complex", sampleRate = sampleRate)

    total_frames = frames.num_frames()
    n_frames = 0
    start_of_frame = -frameSize*0.5

    hfc = []
    complex = []

    progress = Progress(total = total_frames)
    maxhfc=0

    for frame in frames:

        windowed_frame = window(frame)
        complex_fft = fft(windowed_frame)
        (spectrum,phase) = cartesian2polar(complex_fft)
        hfc.append(onsetdetectionHFC(spectrum,phase))
        maxhfc = max(hfc[-1],maxhfc)
        complex.append(onsetdetectionComplex(spectrum,phase))

        # display of progress report
        progress.update(n_frames)

        n_frames += 1
        start_of_frame += hopSize

    # The onset rate is defined as the number of onsets per seconds
    res = [[x/maxhfc for x in hfc]]
    res +=[complex]

    return np.array(res)


import tkinter
import tkinter.messagebox

class MyGUI:
	def __init__(self) -> None:
		# Create the main window
		self.window = tkinter.Tk()

		self.button = tkinter.Button(self.window, text="Click Me", command=self.do_something)
		self.quit_button = tkinter.Button(self.window, text="Quit", command=self.window.destroy)

		self.button.pack()
		self.quit_button.pack()

		tkinter.mainloop()

	def do_something(self):
		tkinter.messagebox.showinfo("Response", "Thanks for the click.")

gui = MyGUI()

Chapter 13 - GUI Programming/Book Exercises/quit_button.py


def count_words(filepath):
    text = open(filepath)

    word_count = {}

    for line in text:
        line = line.rstrip()
        words = line.split(" ")

        for word in words:
            word_count[word] = word_count.get(word, 0) + 1

    for key, value in word_count.items():
        print(f"{key} {value}")

count_words("test.txt")


"""
括号匹配, 栈的经典应用场景
思路:
    1. 循环遍历文本, 遇到开括号就入栈
    2. 遇到闭括号, 弹出栈顶元素并进行匹配
    3. 匹配, 就继续操作, 不匹配, 操作结束, 返回失败信息
"""
from  stack import *

def bracket_match(text):
    # text是被检查的文本
    parens = "()[]{}"
    open_parens = "([{"
    # 表示匹配关系的字典
    matchDict = {
        "}" : "{",
        "]" : "[",
        ")" : "("
    }

    # 内部函数, 括号生成器, 每次返回text 里下一个符号和对应的下标
    def bracket_gen(text):
        i, text_len = 0, len(text)
        while True:
            while i < text_len and text[i] not in parens:
                i += 1
            if i >= text_len:
                return
            yield text[i], i
            i += 1

    obj = Stack_lineTable()

    for pr , i in bracket_gen(text):
        if pr in open_parens:
            obj.push(pr)
            print(pr)
        elif obj.pop() != matchDict[pr]:
            print("匹配" + pr + "出现失败. 位置是: " , i)
            return False
    print("匹配成功")
    return True

text = "{{})}"
print(bracket_match(text))


from collections import Counter
import sys

n = int(sys.stdin.readline())
arr=[]
for _ in range(n):
    arr.append(int(sys.stdin.readline()))

arr.sort()

print(round(sum(arr)/n))
print(arr[n//2])

most_arr = Counter(arr).most_common(2)

if len(most_arr)>1:
    if most_arr[0][1]==most_arr[1][1]:
        print(most_arr[1][0])
    else:
        print(most_arr[0][0])
else:
    print(most_arr[0][0])

print(arr[n-1] - arr[0])


#/user/bin/python3

import math

#Hernandez Inzunza Marco Cesar 4-1

print("#############################")
print("### Ejercicio numero uno ###")
print("##############################")

def numero_de_permutaciones(num):

    fac = 1
    for i in range(1, num+1):
        fac = fac * i
    return fac

def permutaciones(n, m):
    perm = numero_de_permutaciones(n)/numero_de_permutaciones(n-m)
    return perm

def combinaciones(n,m):
    comb = numero_de_permutaciones(n)/numero_de_permutaciones(n-m) * numero_de_permutaciones(m)
    return comb

def vec_para():

    vector = []
    elementos = int(input("cuantos elementos a capturar > "))
    for i in range(elementos):
        numeros = float(input("insertar elemento por favor > "))
        vector.append(numeros)
    return vector

def fmedia(vector):

    media = sum(vector)/ len(vector)
    print("La media es > ", media)
    return media

def dev_Stand(media, vector):

    vec3 = []
    for elemento in range(len(vector)):
        elemento = vector[elemento]
        resultado = (elemento - media) ** 2
        vec3.append(resultado)
        zigma = sum(vec3)
    sqrt_ = math.sqrt(zigma/ len(vector))
    print("La desviacion estandar es > ", sqrt_)
    return sqrt_

def media_sqrt(vector):

    cuad = []
    for elemento in range(len(vector)):
        elemento = vector[elemento] ** 2
        cuad.append(elemento)
    vec_sum = sum(cuad)
    media_cuad = math.sqrt(vec_sum/len(vector))
    print("La media cuadratica es >", media_cuad)

    return media_cuad

def num_finder():

    print("\n")
    print("#############################")
    print("### Ejercicio numero Tres ###")
    print("##############################")
    print("Presione Q para dejar de capturar y proceder a buscar el numero")

    vector = []
    loop_controler = False
    while loop_controler != True:
        try:
            args = float(input("numero > "))
            vector.append(args)
            if(vector[-1] == 'Q'):
                loop_controler = True
        except ValueError as Error:
            loop_controler = True
    if loop_controler != True:
        return "ese no esta permitido"
    else:
        to_find = float(input("Que numero desea buscar? > "))
        appeard = vector.count(to_find)

        return print("Cantidad de veces que aparecio > ", appeard)

def fwrapper():

    print("\n")
    print("#############################")
    print("### Ejercicio numero dos ###")
    print("##############################")

    try:
        vector = vec_para()
        media_ = fmedia(vector)
        dev_stand = dev_Stand(media_, vector)
        media_sqrt_ = media_sqrt(vector)

    except ValueError:
        print("Solo valores numericos")

if __name__ == "__main__":
    print("numero de combinaciones", combinaciones(5,2))
    print("numero de permutaciones", permutaciones(5,2))
    fwrapper()
    num_finder()


num_students = int(input("How many students are in the class? "))

midterm_scores = []
final_scores = []

# Loop through each student and prompt for their exam scores
for i in range(num_students):
    midterm_score = float(input("Enter the midterm score for student " + str(i+1) + ": "))
    final_score = float(input("Enter the final score for student " + str(i+1) + ": "))
    midterm_scores.append(midterm_score)
    final_scores.append(final_score)

# Calculate the average midterm and final exam scores
avg_midterm = sum(midterm_scores) / num_students
avg_final = sum(final_scores) / num_students

# Calculate the average grade for the class
avg_grade = 0.4 * avg_midterm + 0.6 * avg_final

# Determine the letter grade based on the average grade
if avg_grade >= 90:
    letter_grade = "A"
elif avg_grade >= 80:
    letter_grade = "B"
elif avg_grade >= 70:
    letter_grade = "C"
elif avg_grade >= 60:
    letter_grade = "D"
else:
    letter_grade = "F"

# Display the average grade and letter grade for the class
print("The average grade for the class is:", round(avg_grade, 2))
print("The letter grade for the class is:", letter_grade)


import os, sys

# Print logo
Logo = '''
    My auto config setup script

                  __..--''``---....___   _..._    __
        /// //_.-'    .-/";  `        ``<._  ``.''_ `. / // /
       ///_.-' _..--.'_    \                    `( ) ) // //
       / (_..-' // (< _     ;_..__               ; `' / ///
        / // // //  `-._,_)' // / ``--...____..-' /// / //
                                                            By Aroy
    '''
print(Logo)

home_folder = os.getenv('HOME')

def query_yes_no(question, default):
#    Ask a yes/no question via input() and return their answer.
#
#    "question" is a string that is presented to the user.
#    "default" is the presumed answer if the user just hits <Enter>.
#            It must be "yes" (the default), "no" or None (meaning
#            an answer is required of the user).
#
#    The "answer" return value is True for "yes" or False for "no".

    valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
    if default is None:
        prompt = " [y/n] "
    elif default == "yes":
        prompt = " [Y/n] "
    elif default == "no":
        prompt = " [y/N] "
    else:
        raise ValueError("invalid default answer: '%s'" % default)

    while True:
        sys.stdout.write(question + prompt)
        choice = input().lower()
        if default is not None and choice == "":
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' " "(or 'y' or 'n').\n")

def install_missing_packages():

    awnser = query_yes_no("Install missing packages:", "yes")

    if awnser == True:

        if os.path.exists("/usr/bin/yay"):
            print("Found Yay")
            os.system("yay -Sy --needed \
                zsh \
                zsh-autosuggestions \
                zsh-completions \
                zsh-history-substring-search \
                zsh-theme-powerlevel10k-git\
                ttf-meslo-nerd-font-powerlevel10k \
                lscolors-git \
                nano-syntax-highlighting")

        else:
            print("Did not find Yay installing yay")
            os.system("sudo pacman -Sy --needed \
                zsh \
                zsh-autosuggestions \
                zsh-completions \
                zsh-history-substring-search \
                ttf-meslo-nerd-font-powerlevel10k \
                nano-syntax-highlighting \
                yay")

            os.system("yay -Sy --needed \
                zsh-theme-powerlevel10k-git \
                lscolors-git ")

def backup_old_user_configs():

    awnser = query_yes_no("\nBackup old user config files(Recommended):", "yes")

    user_backup_files = [
        '.zshrc',
        '.zhistory',
        '.zprofile',
        '.zcompdump',
        '.zshrc'
    ]

    if awnser == True:

        if not os.path.exists(home_folder + "/Config-Backup"):
            os.mkdir(home_folder + "/Config-Backup")
        elif os.path.exists(home_folder + "/Config-Backup"):
            print("Found old config backup folder")
            os.system("mv -v -i" + home_folder + "/Config-Backup " + home_folder + "/Config-Backup~")
            os.mkdir(home_folder + "/Config-Backup")

        for f in user_backup_files:
            if os.path.exists(home_folder + "/" + f):
                print("Exists (Backing up)   :", home_folder + "/" + f)
                os.system("mv -v -i " + home_folder + "/" + f + " " + home_folder + "/Backup/")
            else:
                print("Doesn't exists skiping:", home_folder + "/" + f)

def copy_new_user_configs():

    if query_yes_no("\nCopy new user config files:", "yes") == True:

        cwd = os.getcwd()

        user_new_configs = [
                '/zsh/.p10k.zsh',
                '/zsh/.zprofile',
                '/zsh/.zshrc',

                '/git/.gitconfig',

                '/nano/.nanorc'
            ]

        for f in user_new_configs:
            os.system("cp -v -i " + cwd + f + " " + home_folder)

def set_default_shell():

    if query_yes_no("\nSet ZSH to default shell?:", "yes"):

        os.system("chsh -s $(which zsh)")

if __name__ =='__main__':
    install_missing_packages()

    backup_old_user_configs()

    copy_new_user_configs()

    set_default_shell()


import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_csv(".categoria/DENUE/test.csv")

print(df.head())

BBox = ((df.Longitud.min(),   df.Longitud.max(),
        df.Latitud.min(), df.Latitud.max()) )

print( BBox )

mymap = plt.imread("./map.png")
fig, ax = plt.subplots(figsize = (8,7))
ax.scatter(df.Longitud, df.Latitud, zorder=1, alpha= 0.2, c='b', s=10)
ax.set_title('Plotting Spatial Data on Map')
ax.set_xlim(BBox[0],BBox[1])
ax.set_ylim(BBox[2],BBox[3])
ax.imshow(mymap, zorder=0, extent = BBox, aspect= 'equal')
plt.show()


from hangman_codes import *

previous_moves = []
bool_user_won = None

print(f"5 lives left. \n{hangmanizer(initial_word)}")
while lives > 0:
    alphabet = input('Enter your keyword..\n> ').lower()
    previous_moves.append(alphabet)
    if (alphabet in punctuation or alphabet in digits or len(alphabet) == 0) or not find_index(initial_word, alphabet):
        lives -= 1
        print("Ouch. Wrong move.")
    current_state = hangmanizer(initial_word, indices)
    print(f"{lives} lives left. Previous moves: {' '.join(previous_moves)}\n{current_state}")
    if initial_word == current_state:
        bool_user_won = True
        break
print(user_won(bool_user_won))


from keras.datasets import boston_housing
from keras import models
from keras import layers
import numpy as np
from keras import backend as K
import matplotlib.pyplot as plt

(train_data, train_target), (test_data, test_target) = boston_housing.load_data()

print(train_data.shape)
print(test_data.shape)
print(train_target)

mean = train_data.mean(axis=0)

train_data -= mean

std = train_data.std(axis=0)
train_data /= std

test_data -= mean
test_data /= std

def build_model():
    model = models.Sequential()
    model.add(layers.Dense(64, activation='relu', input_shape=(train_data.shape[1],)))
    model.add(layers.Dense(64, activation='relu'))
    model.add(layers.Dense(1))
    model.compile(optimizer='rmsprop', loss='mse', metrics=['mae'])
    return model

k = 4
num_val_sample = len(train_data) // k
num_epochs = 100
all_scores = []

for i in range(k):
    print('process fold #', i)
    val_data = train_data[i * num_val_sample: (i + 1) * num_val_sample]
    val_target = train_target[i * num_val_sample:(i + 1) * num_val_sample]
    partial_train_data = np.concatenate(
        [train_data[:i * num_val_sample],
         train_data[(i + 1) * num_val_sample:]],
        axis=0)
    partial_train_target = np.concatenate(
        [train_target[:i * num_val_sample],
         train_target[(i + 1) * num_val_sample:]],
        axis=0)
    model = build_model()
    model.fit(partial_train_data, partial_train_target, epochs=num_epochs, batch_size=1, verbose=0)
    val_mse, val_mae = model.evaluate(val_data, val_target, verbose=0)
    all_scores.append(val_mae)
    print(all_scores)

K.clear_session()

num_epochs = 500
all_mae_histories = []

for i in range(k):
    print('processing fold ##', i)
    val_data = train_data[i * num_val_sample:(i + 1) * num_val_sample]
    val_target = train_target[i * num_val_sample:(i + 1) * num_val_sample]

    partial_train_data = np.concatenate([train_data[:i * num_val_sample], train_data[(i + 1) * num_val_sample:]],
                                        axis=0)

    partial_train_target = np.concatenate(
        [train_target[:i * num_val_sample], train_target[(i + 1) * num_val_sample:]],
        axis=0)
    model = build_model()
    history = model.fit(partial_train_data, partial_train_target, validation_data=(val_data, val_target),
                        epochs=num_epochs, batch_size=1, verbose=0)
    mae_history = history.history['val_mean_absolute_error']
    all_mae_histories.append(mae_history)

    print(all_mae_histories)

average_mae_history = [np.mean([x[i] for x in all_mae_histories]) for i in range(num_epochs)]

plt.plot(range(1, len(average_mae_history) + 1), average_mae_history)
plt.xlabel('Epochs')
plt.ylabel('Validation Mae')
plt.show()


# DEPENDENCIES
from bs4 import BeautifulSoup
from splinter import Browser
import requests
import pandas as pd

def init_browser():
	executable_path = {"executable_path": "chromedriver"}
	return Browser("chrome", **executable_path, headless=False)

def scrape():
	browser = init_browser()

	mars_update = {}

	# NASA MARS NEWS
	url = 'https://mars.nasa.gov/news/'
	browser.visit(url)

	html = browser.html
	soup = BeautifulSoup(html, 'html.parser')

	recent = soup.find('div', class_='list_text')
	news_title = recent.find('div', class_='content_title').text
	news_p = recent.find('div', class_='article_teaser_body').text

	mars_update['news_title'] = news_title
	mars_update['news_p'] = news_p

	# JPL MARS IMAGE
	url_jpl = 'https://www.jpl.nasa.gov/spaceimages/?search=&category=Mars'
	browser.visit(url_jpl)

	html = browser.html
	soup = BeautifulSoup(html, 'html.parser')

	img_find = soup.find('footer')
	img = img_find.find('a', class_='button fancybox')['data-fancybox-href']
	img_url = "https://jpl.nasa.gov" + img
	featured_image_url = img_url

	mars_update['featured_image_url'] = featured_image_url

	# MARS WEATHER
	url_tweet = 'https://twitter.com/marswxreport?lang=en'
	browser.visit(url_tweet)

	html = browser.html
	soup = BeautifulSoup(html, 'html.parser')

	tweet_box = soup.find('div', class_='js-tweet-text-container')
	tweet = tweet_box.find('p', class_='TweetTextSize TweetTextSize--normal js-tweet-text tweet-text').text
	mars_weather = tweet

	mars_update['mars_weather'] = mars_weather

	# MARS FACTS
	url_facts = 'https://space-facts.com/mars/'
	browser.visit(url_facts)

	mars_table = pd.read_html(url_facts)
	mars_df = mars_table[0]
	mars_df.columns = ['Mars', 'Data']
	mars_df = mars_df.set_index('Mars')
	mars_table_html = mars_df.to_html()
	mars_table_html = mars_table_html.replace('\n', '')

	mars_update['mars_table'] = mars_table_html

	# MARS HEMISPHERES
	url_hemi = 'https://astrogeology.usgs.gov/search/results?q=hemisphere+enhanced&k1=target&v1=Mars'
	browser.visit(url_hemi)

	html = browser.html
	soup = BeautifulSoup(html, 'html.parser')

	hemisphere_image_urls = []

	for h in range(4):
	    browser.find_by_tag('h3')[h].click()
	    html = browser.html
	    soup = BeautifulSoup(html, 'html.parser')
	    title = soup.find('h2', class_='title').text
	    img_url_partial = soup.find('img', class_='wide-image')['src']
	    img_url = 'https://astrogeology.usgs.gov' + img_url_partial
	    dict = {'title':title, 'img_url':img_url}
	    hemisphere_image_urls.append(dict)
	    browser.back()

	mars_update['mars_hemispheres'] = hemisphere_image_urls
	browser.quit()

	return mars_update


notes = ('s','r','g','m','p','d','n','*')

a = []

file1 = open('notes.csv','w')
for note1 in notes:
    for note2 in notes:
        for note3 in notes:
            a.append(note1+note2+note3)
groups = []
for note in a:
    if note.count(note[0])>=3:groups.append(note)
file1.write(','.join(groups)+'\n')

groups = []
main = []
for note in a:
    if note[0]==note[1] and not(note.count(note[0])>=3):groups.append(note)
main.append(groups[0])
for group in groups:
    if not group in main:
        if group[0] == main[-1][-1]:
            try:
                if group[-1] == notes[notes.index(group[0])+1]:
                    main.append(group)
            except:
                print('out')

file1.write(','.join(main)+'\n')

file1.close()


from collections import Counter

def apply_look_and_say(line: str, times: int=40):
    for _ in range(times):
        old_line = line
        line = look_and_say(line)
        test_look_and_say_result(old_line, new_line=line)
    return len(line)

def look_and_say(line):
    c = 0
    output = ''

    while c < len(line):
        num = line[c]
        count = 0
        while c < len(line) and line[c] == num:
            count += 1
            c+=1
        output += (str(count) + num)
    return output

def test_look_and_say_result(old_line, new_line):
    old_count = Counter(old_line)
    new_count = dict()
    for c in range(0, len(new_line), 2):
        count = int(new_line[c])
        num = new_line[c+1]

        new_count[num] = new_count.get(num, 0) + count

    assert old_count == new_count, f'oldline: {old_line}, newline: {new_line}'

def test_look_and_say():
    in_outs = [('1', '11'), ('11', '21'), ('21', '1211'),
               ('1211', '111221'), ('111221', '312211'),
               ('1113222113', '3113322113')]
    for inp, outp in in_outs:
        assert look_and_say(inp) == outp

if __name__ == '__main__':
    # test_look_and_say()
    from utils import AdventSession, extract_year_day_from_path
    session = AdventSession(**extract_year_day_from_path(__file__))

    line = session.read_input().strip()

    part1_answer = apply_look_and_say(line, times=40)
    print(part1_answer)
    session.post_answer(part1_answer, level=1)

    part2_answer = apply_look_and_say(line, times=50)
    print(part2_answer)
    session.post_answer(part2_answer, level=2)


from model.formfiller import Contact
from random import randrange

def test_modify_first_contact(app):

    if app.contact.count() == 0:
        app.contact.add_new_contact(Contact(firstname="tester", lastname="tester"))
    old_contacts = app.contact.get_contact_list()
    index = randrange(len(old_contacts))
    contact = Contact(firstname="roman", lastname="erotoman")
    contact.id = old_contacts[index].id
    app.contact.modify_contact_by_index(index, contact)
    assert len(old_contacts) == app.contact.count()
    new_contacts = app.contact.get_contact_list()
    old_contacts[index] = contact
    assert sorted(old_contacts, key=Contact.id_or_max) == sorted(new_contacts, key=Contact.id_or_max)


import numpy as np
import torch
import torchvision.transforms as transforms
import os
import csv
import cv2
from torch.utils.data import Dataset, DataLoader, Subset
import matplotlib.pyplot as plt
from PIL import Image

dataroot = r"./data/CelebA-20220516T115258Z-001/CelebA/Img/img_align_celeba/img_align_celeba"
labels_path = r"./data/CelebA-20220516T115258Z-001/CelebA/Anno/identity_CelebA.txt"
device = torch.device('cpu')
if torch.cuda.is_available():
    device = torch.device('cuda')

class ListDict(dict):
    """ Dictionary whose values are lists. """

    def __missing__(self, key):
        value = self[key] = []
        return value

class CustomDataset(Dataset):

    def create_class_map(self, size):
        lstdct = ListDict()
        with open(self.label_path, 'r') as csvfile:
            for row in csv.reader(csvfile, delimiter=' '):
                value, key = row[:2]
                if not lstdct[key] or len(lstdct[key]) < size:
                    lstdct[key].append(value)
        return lstdct

    def get_key(self, class_name):
        for key, class_id in self.class_map.items():
            if class_name in class_id:
                return key

    def task_class_remap(self):
        # you can use this code to remap the classes and assign to tasks
        existing_mapping = self.class_map
        tasks = np.arange(0, self.tasks)
        task_map = {}
        # self.data = []
        for i, task in enumerate(tasks):  # for each task
            classes = np.arange(0, self.classes_per_task)
            class_map = {}
            keys_to_be_deleted = []
            for y, (class_remapped, (key, val)) in enumerate(zip(classes, existing_mapping.items())):
                class_map[y + i * self.classes_per_task] = val
                for each in val:
                    self.data.append([dataroot + os.path.sep + each, y + i * self.classes_per_task])
                keys_to_be_deleted.append(key)
            for key_ in keys_to_be_deleted:
                del (existing_mapping[key_])
            task_map[task] = class_map
        return task_map

    def __init__(self, tasks=3, classes=15, shots=10, img_path=dataroot, label_path=labels_path,
                 transform=None, image_size=32):
        self.img_dim = (image_size, image_size)
        self.transform = transform
        self.tasks = tasks  # 3
        self.classes = classes  # 15
        self.classes_per_task = int(classes / tasks)  # 5
        self.samples_per_class = shots  # 10
        self.samples_per_task = self.classes_per_task * self.samples_per_class  # 50

        self.img_path = img_path
        self.label_path = label_path
        # this creates a dict of lists, each key is the class, each value is list of files corresponding to that class
        self.class_map = self.create_class_map(self.samples_per_class)
        # trims the lists down
        self.class_map = {key: val for key, val in self.class_map.items() if len(val) >= self.samples_per_class}
        count_above_5 = len({key: val for key, val in self.class_map.items() if len(val) == self.samples_per_class})
        self.data = []
        self.task_map = self.task_class_remap()

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

    def __getitem__(self, idx):
        img_path, class_id = self.data[idx]
        img_tensor = cv2.resize(cv2.imread(img_path), self.img_dim)
        class_id = torch.tensor([int(class_id)])
        if self.transform:
            img_tensor = self.transform(img_tensor)
        return img_tensor, class_id

# class CustomLoader:
#     def segment_dataset(self):
#         for task in range(self.dataset.tasks):
#             indexes = np.arange(task * self.number_of_samples, (task + 1) * self.number_of_samples)
#             self.train_indexes.append(np.random.choice(indexes, self.train_size, replace=False))
#             indexes = np.delete(indexes, np.where(np.isin(indexes, self.train_indexes)))
#             self.val_indexes.append(np.random.choice(indexes, self.val_size, replace=False))
#             indexes = np.delete(indexes, np.where(np.isin(indexes, self.val_indexes)))
#             self.test_indexes.append(np.random.choice(indexes, self.test_size, replace=False))
#             # indexes = np.delete(indexes, np.where(np.isin(indexes, self.test_indexes)))
#
#     def __init__(self, celeb_dataset):
#         self.dataset = celeb_dataset
#         self.number_of_samples = self.dataset.classes * self.dataset.samples_per_class
#         self.test_size = int(np.floor(self.number_of_samples / self.dataset.class_size))
#         self.train_size = int((self.number_of_samples - self.test_size) * .8)
#         self.val_size = self.number_of_samples - self.test_size - self.train_size
#         self.train_indexes = []
#         self.val_indexes = []
#         self.test_indexes = []
#         self.segment_dataset()
#         self.task_train = 0
#         self.task_val = 0
#         self.task_test = 0
#
#     def train_loader(self, current_task, batch_size=4):
#         train_subset = Subset(self.dataset, self.train_indexes[current_task])
#         train_loader = DataLoader(train_subset, shuffle=True, batch_size=batch_size)
#         return train_loader
#
#     def val_loader(self, current_task, batch_size=4):
#         val_subset = Subset(self.dataset, self.val_indexes[current_task])
#         val_loader = DataLoader(val_subset, shuffle=True, batch_size=batch_size)
#         return val_loader
#
#     def test_loader(self, current_task, batch_size=4):
#         test_subset = Subset(self.dataset, self.test_indexes[current_task])
#         test_loader = DataLoader(test_subset, shuffle=False, batch_size=batch_size)
#         return test_loader
#
#     def train_sampler(self, batch_size=4):
#         if self.dataset.tasks >= self.task_train:
#             train_subset = Subset(self.dataset, self.train_indexes[self.task_train])
#             train_loader = DataLoader(train_subset, shuffle=True, batch_size=batch_size)
#             next_sample = next(iter(train_loader))
#             if train_loader.__len__() == 0:
#                 self.task_train += 1
#             return next_sample
#
# def val_sampler(self, batch_size=4):
#     if self.dataset.tasks >= self.task_val:
#         val_subset = Subset(self.dataset, self.val_indexes[self.task_val])
#         val_loader = DataLoader(val_subset, shuffle=True, batch_size=batch_size)
#         next_sample = next(iter(val_loader))
#         if val_loader.__len__() == 0:
#             self.task_val += 1
#         return next_sample
#
# def test_sampler(self, batch_size=4):
#     if self.dataset.tasks >= self.task_test:
#         test_subset = Subset(self.dataset, self.test_indexes[self.task_test])
#         test_loader = DataLoader(test_subset, shuffle=True, batch_size=batch_size)
#         next_sample = next(iter(test_loader))
#         if test_loader.__len__() == 0:
#             self.task_test += 1
#         return next_sample

def extract(nested_list, index):
    temp = []
    for class_ in nested_list:
        for i in index:
            temp.append(class_[i])
    return temp

def sample_dataset_train(train_size, indexes, samples_per_class):
    train_indexes = sorted(
        [y for sub in [indexes[x::samples_per_class] for x in range(0, train_size)]
         for y in sub])
    train = [train_indexes[i:i + train_size] for i in range(0, len(train_indexes),
                                                            train_size)]
    random_train = np.random.choice(np.arange(train_size), (2,), replace=False)
    return extract(train, random_train)

def sample_dataset_val(train_size, test_size, indexes, samples_per_class):
    cutoff = train_size + test_size  # 80%

    val_indexes = sorted(
        [y for sub in [indexes[x::samples_per_class] for x in range(train_size, cutoff)]
         for y in sub])
    val = [val_indexes[i:i + test_size] for i in range(0, len(val_indexes), test_size)]
    random_test = np.random.choice(np.arange(test_size), (2,), replace=True)
    return extract(val, random_test)

def sample_dataset_test(train_size, test_size, indexes, samples_per_class):
    cutoff = train_size + test_size  # 80%

    test_indexes = sorted(
        [y for sub in [indexes[x::samples_per_class] for x in range(cutoff,
                                                                    samples_per_class)]
         for y in sub])
    test = [test_indexes[i:i + test_size] for i in range(0, len(test_indexes), test_size)]
    random_test = np.random.choice(np.arange(test_size), (2,), replace=True)
    return extract(test, random_test)

class CustomSampler:
    def __init__(self, celeb_dataset, global_labels=False):
        self.dataset = celeb_dataset
        self.samples_per_class = celeb_dataset.samples_per_class
        self.num_tasks = self.dataset.tasks  # 3
        self.number_of_samples = len(self.dataset)
        self.sample_size = 10  # essentially the batch size
        self.train_size = int(np.floor(self.dataset.samples_per_class * .6))
        self.test_val_size = int(np.floor(self.dataset.samples_per_class * .2))
        self.train_indexes, self.val_indexes, self.test_indexes = [], [], []
        if global_labels:
            self.indexes = np.arange(self.dataset.tasks * self.dataset.samples_per_task)
        else:
            task = np.random.randint(self.dataset.tasks)
            self.indexes = np.arange(task * self.dataset.samples_per_task,
                                     (task + 1) * self.dataset.samples_per_task)

    def train_sampler(self):
        self.train_indexes = sample_dataset_train(self.train_size, self.indexes,
                                                  self.samples_per_class)
        train_subset = Subset(self.dataset, self.train_indexes)
        train_loader = DataLoader(train_subset, shuffle=True, batch_size=self.sample_size)
        next_sample = next(iter(train_loader))
        return next_sample

    def val_sampler(self):
        self.val_indexes = sample_dataset_val(self.train_size, self.test_val_size,
                                              self.indexes, self.samples_per_class)
        val_subset = Subset(self.dataset, self.val_indexes)
        val_loader = DataLoader(val_subset, shuffle=True, batch_size=self.sample_size)
        next_sample = next(iter(val_loader))
        return next_sample

    def test_sampler(self):
        self.test_indexes = sample_dataset_test(self.train_size, self.test_val_size,
                                                self.indexes, self.samples_per_class)
        test_subset = Subset(self.dataset, self.test_indexes)
        test_loader = DataLoader(test_subset, shuffle=True, batch_size=self.sample_size)
        next_sample = next(iter(test_loader))
        return next_sample

# class CustomBenchmarkSampler:
#     def sample_dataset_train(self, train_size, indexes, samples_per_class):
#         train_indexes = sorted(
#             [y for sub in [indexes[x::samples_per_class] for x in range(0, train_size)] for y in sub])
#         train = [train_indexes[i:i + train_size] for i in range(0, len(train_indexes), train_size)]
#         random_train = np.random.choice(np.arange(train_size), (2,), replace=False)
#         self.train_indexes = extract(train, random_train)
#
#     def sample_dataset_val(self, train_size, test_size, indexes, samples_per_class):
#         cutoff = train_size + test_size  # 80%
#
#         val_indexes = sorted(
#             [y for sub in [indexes[x::samples_per_class] for x in range(train_size, cutoff)] for y in sub])
#         val = [val_indexes[i:i + test_size] for i in range(0, len(val_indexes), test_size)]
#         random_test = np.random.choice(np.arange(test_size), (2,), replace=False)
#         self.val_indexes = extract(val, random_test)
#
#     def sample_dataset_test(self, train_size, test_size, indexes, samples_per_class):
#         cutoff = train_size + test_size  # 8
#
#         test_indexes = sorted(
#             [y for sub in [indexes[x::samples_per_class] for x in range(cutoff, samples_per_class)] for y in sub])
#         test = [test_indexes[i:i + test_size] for i in range(0, len(test_indexes), test_size)]
#         random_test = np.random.choice(np.arange(test_size), (2,), replace=False)
#         self.test_indexes = extract(test, random_test)
#
#     def __init__(self, celeb_dataset):
#         self.dataset = celeb_dataset
#         self.samples_per_class = celeb_dataset.samples_per_class
#         self.num_tasks = self.dataset.tasks  # 3
#         self.number_of_samples = len(self.dataset)
#         self.sample_size = 10  # essentially the batch size
#         self.train_size = int(np.floor(self.samples_per_class * .6))
#         self.test_val_size = int(np.floor(self.samples_per_class * .2))
#         self.indexes = np.arange(self.dataset.tasks * self.dataset.samples_per_task)
#         self.train_indexes, self.val_indexes, self.test_indexes = [], [], []
#
#     def train_sampler(self):
#         self.sample_dataset_train(self.train_size, self.indexes, self.samples_per_class)
#         train_subset = Subset(self.dataset, self.train_indexes)
#         train_loader = DataLoader(train_subset, shuffle=True, batch_size=self.sample_size)
#         next_sample = next(iter(train_loader))
#         return next_sample
#
#     def val_sampler(self):
#         self.sample_dataset_val(self.train_size, self.test_val_size, self.indexes, self.samples_per_class)
#         val_subset = Subset(self.dataset, self.val_indexes)
#         val_loader = DataLoader(val_subset, shuffle=False, batch_size=self.sample_size)
#         next_sample = next(iter(val_loader))
#         return next_sample
#
#     def test_sampler(self):
#         self.sample_dataset_test(self.train_size, self.test_val_size, self.indexes, self.samples_per_class)
#         test_subset = Subset(self.dataset, self.test_indexes)
#         test_loader = DataLoader(test_subset, shuffle=False, batch_size=self.sample_size)
#         next_sample = next(iter(test_loader))
#         return next_sample

def task_sampler_viewer(num_tasks, ways, shots, transformation, dataroot, labels_path, image_size):
    dataset = CustomDataset(tasks=num_tasks, classes=ways, shots=shots, img_path=dataroot, label_path=labels_path,
                            transform=transformation,
                            image_size=image_size)
    for i in range(10):
        train_sampler2 = CustomSampler(dataset, global_labels=False)
        data1, labels = train_sampler2.train_sampler()
        im_array = torch.empty((image_size, 10 * image_size, 3))
        im_array = im_array[image_size:, :, :]
        im_array = torch.cat([im_array, torch.cat(data1.split(1, 0), 3).squeeze().permute(1, 2, 0)])
        rgb = cv2.cvtColor(im_array.numpy(), cv2.COLOR_BGR2RGB)
        plt.figure(figsize=(5, 1))
        plt.imshow(rgb, cmap=plt.cm.Spectral, interpolation='nearest')
        title_string = ""
        for x, label in enumerate(labels.numpy()):
            title_string += str(label[0])
            if x != len(labels.numpy()) - 1:
                title_string += ", "
        plt.title("sample containing classes: " + title_string, fontsize=9)
        plt.tight_layout()
        plt.savefig(f"{RESULTS_DIR}/sample_{i + 1}")
        print(f"saved to {RESULTS_DIR}/sample_{i + 1}")
        # plt.show()
        # plt.clf()

if __name__ == '__main__':
    RESULTS_DIR = './sample_images'
    if not os.path.exists(RESULTS_DIR):
        os.makedirs(RESULTS_DIR)
    # # tasks = [3, 5]
    # # classes = [5, 10]
    # # batch_size = [10, 15]
    # # for task in tasks:
    # #     for class_ in classes:
    # #         for batch in batch_size:
    # #             dataset = CustomDataset(tasks=task, classes=class_, batch_size=batch)
    # #             dataset_task_splitter(dataset)
    # image_size = 128
    # transformation = transforms.Compose([
    #     transforms.ToTensor(),
    #     transforms.ConvertImageDtype(torch.float),
    #     transforms.Resize(image_size),
    #     transforms.CenterCrop(image_size)
    #     # transforms.Normalize((0.485, 0.456, 0.406), (0.229, 0.224, 0.225))
    # ])
    #
    # dataset = CustomDataset(tasks=1000, classes=5000, transform=transformation, image_size=image_size)
    # train_sampler = CustomSampler(dataset)
    # print(train_sampler.train_sampler()[1].T)
    #
    # dataset = CustomDataset(tasks=3, classes=15, transform=transformation, image_size=image_size)
    # train_sampler = CustomSampler(dataset)
    # print(train_sampler.train_sampler()[1].T)
    # # train_sampler = CustomBenchmarkSampler(dataset, train_ways=5, train_samples=2, test_ways=5, test_samples=2)
    # # print(train_sampler.train_sampler()[1].T)
    # # print(train_sampler.val_sampler()[1].T)
    # # print(train_sampler.test_sampler()[1].T)
    # # print(train_loaderA)
    # # for task in range(0, dataset.tasks):
    # #     print(len(next(iter(train_loaderA.test_loader(task)))[0]))
    # # print((next(iter(train_loaderA.test_loader(task)))[0]))
    # # dataset_task_splitter(dataset)
    # # print(dataset)
    # # class_number = dataset.__len__()
    # # train_size = int(0.8 * len(dataset))
    # # test_size = len(dataset) - train_size
    # # train_dataset, test_dataset = torch.utils.data.random_split(dataset, [train_size, test_size])
    # #
    # # train_loader = DataLoader(train_dataset, batch_size=12, shuffle=False)
    # # test_loader = DataLoader(test_dataset, batch_size=12, shuffle=False)
    # # x = next(iter(train_loader))
    # # y = next(iter(test_loader))
    #
    # # dataloader = DataLoader(dataset, batch_size=10, shuffle=False)
    # # x = next(iter(dataloader))
    # # print(next(iter(dataloader)))
    #
    # # for imgs, labels in dataloader:
    # #     print("Batch of images has shape: ", imgs.shape)
    # #     print("Batch of labels has shape: ", labels.shape)
    # # dataset, label = create_dataset(shots, ways, meta_batch_size, dataroot, labels_path, image_size=32
    # # batch, dataset, label = batch_loader(5, dataset, class_number)
    # image_size = 112
    # transformation = transforms.Compose([
    #     transforms.ToTensor(),
    #     transforms.ConvertImageDtype(torch.float),
    #     transforms.Resize(image_size),
    #     transforms.CenterCrop(image_size)
    # ])
    # test_accuracy_celeb = 0
    # num_tasks = 10
    # ways = 50
    # shots = 5
    # iterations = 1
    # batch_size = 32
    #
    # dataset = CustomDataset(tasks=num_tasks, classes=ways, shots=shots, img_path=dataroot, label_path=labels_path,
    #                         transform=transformation, image_size=image_size)

    # dataset = CustomDataset(tasks=1000, classes=5000, transform=transformation, image_size=image_size)
    # train_sampler = CustomSampler(dataset, global_labels=True)
    # print(train_sampler.test_sampler()[1].T)
    # train_sampler = CustomSampler(dataset, global_labels=True)
    # print(train_sampler.test_sampler()[1].T)
    # train_sampler = CustomSampler(dataset, global_labels=True)
    # print(train_sampler.test_sampler()[1].T)

    # train_sampler2 = CustomSampler(dataset, global_labels=False)
    # print(train_sampler2.train_sampler()[1].T)
    # train_sampler2 = CustomSampler(dataset, global_labels=False)
    # print(train_sampler2.train_sampler()[1].T)
    # train_sampler2 = CustomSampler(dataset, global_labels=False)
    # print(train_sampler2.train_sampler()[1].T)

    tasks = 10
    ways = 50
    shots = 5
    img_size = 112
    transform = transforms.Compose([
        transforms.ToTensor(),
        transforms.ConvertImageDtype(torch.float),
        transforms.Resize(img_size),
        transforms.CenterCrop(img_size)
    ])
    data = dataroot
    labels = labels_path
    task_sampler_viewer(tasks, ways, shots, transform, data, labels, img_size)


# test script to pull data from website
import src.scrape_data as src_sd
import src.transform_data as src_tr

# pro-football reference site
NFL_URL = 'https://www.pro-football-reference.com/years/2018/games.htm'

# generate data frame
data_table = src_sd.get_first_table(NFL_URL) # this will select the table on the site
column_names = src_sd.list_of_headers(data_table)
final_data_frame = src_sd.create_df(soup_table=data_table, list_of_column_names=column_names)

# output website dataframe
final_data_frame.to_csv('data/raw/test_data_pull.csv', sep='|', index=False)

# Transform data
cols = ['Winner/tie', 'Home/Away', 'Loser/tie'
        , 'PtsW', 'PtsL', 'YdsW', 'TOW', 'YdsL', 'TOL']
updated_df = src_tr.filter_df(final_data_frame, cols)

new_col_names = ['team_f', 'home/away', 'team_a', 'pts_f'
                 , 'pts_a', 'yds_f', 'to_f', 'yds_a', 'to_a']
updated_df = src_tr.update_cols(updated_df, new_col_names)

updated_df = src_tr.assign_home(updated_df
                                , 'home/away'
                                , 'home_f'
                                , {'x': ['', 1, 0]})

# transform scraped data into ML available data
ml_df = src_tr.create_dummies(updated_df, ['team_f', 'team_a'])

ml_df.drop(['team_f', 'team_a', '_f', '_a', 'home/away'], axis=1, inplace=True)
ml_df.to_csv('data/processed/ml_data_prep.csv', sep='|', index=False)


import pandas as pd
from sklearn.model_selection import train_test_split as tts
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.svm import SVC
import sklearn
from sklearn import metrics

#reading the csv files of the bots and non-bots
bot =  pd.read_csv('C:\\Users\\Simran Singh\\Desktop\\bots_data.csv', encoding='latin1');
nonbot = pd.read_csv('C:\\Users\\Simran Singh\\Desktop\\nonbots_data.csv', encoding='latin1');

#combining bots and non-bots into a single dataframe
all_users = pd.concat([bot, nonbot])
all_users.fillna('', inplace = True);

#splitting the dataframe into training data and testing data
y = all_users.bot;
x = all_users.drop('bot', axis = 1)
X_train, X_test, y_train, y_test = tts(x, y,test_size=0.25);

#TF-IDF of the 'description' parameter of the training dataset
#description      	String	       The user-defined UTF-8 string describing their account.
vectorizer = CountVectorizer()  #Converts a collection of text documents to a matrix of token counts
words_count = vectorizer.fit_transform(X_train['description'])  #Learns the vocabulary dictionary and returns term-document matrix.
tf_transformer = sklearn.feature_extraction.text.TfidfTransformer(use_idf=True).fit(words_count)
X_train = tf_transformer.transform(words_count)

clf = sklearn.svm.LinearSVC()
clf.fit(X_train, y_train)

#TF-IDF of the 'description' parameter of the test dataset
test_word_count = vectorizer.transform(X_test['description'])
X_test = tf_transformer.transform(test_word_count)

#Predicting the labels
y_predicted = clf.predict(X_test)

#Printing the accuracy of the SVM classifier
print("Accuracy of SVM  {}".format(metrics.accuracy_score(y_test, y_predicted)))


from django.shortcuts import render, redirect
from .forms import ContactForm
from django.contrib import messages
from .models import Contact

MANTENIMIENTO = False #maintenence mode
def index(request):

    if MANTENIMIENTO == True:
        return render(request, 'main/maintenence.html')

    else:
        if request.POST:
            f = ContactForm(request.POST)
            if f.is_valid():
                messages.success(request, "Message sent successfuly!")
                name = f.cleaned_data["name"]
                email = f.cleaned_data["email"]
                message = f.cleaned_data["message"]
                contact = Contact(name=name,email=email,message=message)
                contact.save()
                return redirect('/#contact')

        else:
            f = ContactForm()

        return render(request, 'main/index.html', { 'form': f })


def div(a,b):
    try:
        print(a/b)
    except ZeroDivisionError:
        print("Division by zero not possible")

number1 = float(input('Enter number 1:'))
number2 = float(input('Enter number 2:'))
div(number1,number2)

def open_file(file):
    try :
        fhand = open(file)
        for line in fhand:
            print(line,end="")
    except FileNotFoundError:
        print("File not found")

file = input("Enter file name:")
open_file(file)


import pandas
import cv2

def CPORB(file1, file2):
    img1 = cv2.imread(file1, 0)
    img2 = cv2.imread(file2, 0)

    orb = cv2.ORB_create()

    kp1, des1 = orb.detectAndCompute(img1, None)
    kp2, des2 = orb.detectAndCompute(img2, None)

    bf = cv2.BFMatcher(cv2.NORM_HAMMING, crossCheck=True)

    matches = bf.match(des1,des2)

    matches = sorted(matches, key = lambda x:x.distance)

    img3 = cv2.drawMatches(img1,kp1,img2,kp2,matches[:20],None,flags=2)

    #plt.imshow(img3),plt.show()

    data = [[len(kp1),len(kp2),len(matches)]]
    result_data=pandas.DataFrame(data, columns=['Image1_feature','Image2_feature','match_feature'])

    return result_data


#덧셈을 배운지 얼마 안 된 준환이는 덧셈에 아직도 어려움을 느낀다.
#그래서 준환이는 N자리인 두 양수를 더하는 연습을 하기로 했다.
#당신은 준환이를 위해 답안지를 만들어주기로했다.
#두 양수가 주어질 때 두 수를 더한 결과를 구하는 프로그램을 작성하라.
#입력: T/ 두 양의 정수 A,B(1<=A,B<10^100)
#출력: A+B
#[참고]
# 뒷자리부터 계산하고, 출력은 앞자리부터.
T=int(input())
for tc in range(1,T+1):
    A,B = input().split()
    lenA = len(A)
    lenB = len(B)
    stack = []
    i = lenA - 1
    j = lenB - 1
    carry = 0   #자리 올림 처음에는 0
    while i >= 0 and j >= 0:
        s = int(A[i]) + int(B[i]) + carry
        carry = s//10
        stack.append(s%10)
        i -= 1
        j -= 1
    while i>=0:
        s=int(A[i]) + carry
        carry = s//10
        stack.append(s%10)
        j -= 1
    if carry != 0:
        stack.append(carry) #9999 + 1인 경우
    print('#{}'.format(tc),end='')
    while stack:
        print(stack.pop(),end='') #stack이 빌 때까지 출력하는 것
    print()


from __future__ import print_function
from string import ascii_lowercase
from random import choice, randint

def get_sentence():
    sentence = input("Input the sentence:")
    sentence = sentence.lower()
    sentence = [x for x in sentence if x in ascii_lowercase + " "]
    sentence = "".join(sentence)
    # print("What have we received after filtering:", sentence)
    return sentence

def random_str(str_len):
    out_str = []
    for i in range(0, str_len):
        out_str.append(choice(ascii_lowercase + " "))
    out_str = "".join(out_str)
    return out_str

def create_population(max_population,sentence,generation):
    for i in range(max_population):
        random = random_str(len(sentence))
        # print(random)
        generation.append(random)
    return generation

def print_list(list_to_print):
    for x in list_to_print: print(x)

def isPresent(sentence, generation):
  selection_word = sentence
  if selection_word in generation:
    return True
  else:
    return False

def crossingover( max_population, generation):

   my_length = len(my_sentence)
   if my_length >3:
       for k in range(0, len(generation)-2, 3):
            parent1 = generation[k]
            parent2 = generation[k + 1]

            #print('my_length ', my_length)
            break_index1 = choice(range(1, my_length - 2))
            break_index2 = choice(range(break_index1+1, my_length - 1))

            '''print('break1: %s break2: %s', break_index1, break_index2)
            print('1:%s 2:%s', parent1[:break_index1+1], parent2[break_index1:break_index2])
            print(' 2:%s',parent2[break_index1:break_index2])'''

            child1 = parent1[:break_index1+1] + parent2[break_index1+1:break_index2+1] + parent1[break_index2+1:]
            child2 = parent2[:break_index1+1] + parent1[break_index1+1:break_index2+1] + parent2[break_index2+1:]
            #print(child1)
            generation.append(child1)
            #print(child2)
            generation.append(child2)
       else:
           for i in range(0, max_population, 2):
                mother = generation[i]
                father = generation[i + 1]
                break_index = choice(range(1, len(my_sentence) - 1))
                child1 = mother[:break_index]
                child2 = father[:break_index]
                child1 = child1 + father[break_index:]
                child2 = child2 + mother[break_index:]
                generation.append(child1)
                generation.append(child2)

def mutation(generation, probability, my_sentence):
    mutated_count = 0
    for entity in generation:
        if (randint(0, 100) < probability):
            #print("before mutation ", entity)
            mutated_index = choice(range(0, len(my_sentence)))
            mutation_char = str(choice(ascii_lowercase + " "))
            output_str = entity[:mutated_index]
            output_str = output_str + mutation_char + entity[mutated_index+1:]
            #entity = output_str
            generation.remove(entity)
            generation.append(output_str)
            #print("after : ",output_str )
            mutated_count+=1
    return mutated_count

def mutate(gene):
     mutated_index = choice(range(0, len(my_sentence)))
     mutation_char = str(choice(ascii_lowercase + " "))
     output_str = gene[:mutated_index]
     output_str = output_str + mutation_char + gene[mutated_index+1:]
     return output_str

def mismatch(str1):
    mismatch = 0
    for c1,c2 in zip(str1,my_sentence):
        if c1 != c2:
            #print("mismatch" , c1 )
             mismatch += 1
    '''if mismatch == 1:               #direct mutation
        for c1,c2 in zip(str1,sentence):
            if c1 != c2:
                #print("mismatch" , c1 )
                c1 = choice(ascii_lowercase + " ")'''
    return mismatch

def selection():
  filtering()
  print("After filtering: ", generation)
  generation.sort(key = mismatch)
  print("After sorting: ", generation)
  del generation[max_population::]

def filtering():
    a=generation
    for i in range( len( a ) ):
        c=a[i]
        for j in range( len( a ) ):
            if a[j]==c and i<j:  a[j]= mutate(a[j])
            else: pass

my_sentence = get_sentence()
max_population = 50 # max members in first population
generation = []
generation_count = 0
max_num_generations = 6000
probability = 20
create_population(max_population, my_sentence, generation )
for i in range(max_num_generations):
    if (isPresent(my_sentence, generation)):
        print("found")
        # print(generation)
        break
    else:
        generation_count =i+1
        print("Generation  ", generation_count)
        print("Created ", generation)
        crossingover( max_population, generation)

        print("Crossing ", generation)

        mutated_count = mutation(generation, probability, my_sentence)    #amount of mutations
        print("Mutate ", generation)
        selection()
        print("Select ", generation)
        if generation_count > max_num_generations:
            raise Exception("Not reached in the maximal number of generations")
print(generation_count, generation[0])


r, c = map(int, input().split())

s = list(input() for _ in range(r))
res = []
order = []

for i in range(r):
    cnt = 0
    for j in s[i]:
        if j == 'S' or j == '.' or j == 'F':
            cnt += 1
        else:
            order.append(j)
            break

    if cnt <= c - 4:
        res.append(cnt)

ans = [0]*9
for rank in range(1, 10):
    max_num = -1
    for p in range(len(res)):
        if res[p] > max_num:
            max_num = res[p]

    if max_num >= 0:
        for k in range(9):
            if res[k] == max_num:
                res[k] = -1
                ans[k] = rank

for i in range(1, 10):
    print(ans[order.index(str(i))])


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

import pandas as pd
import os

from pandas.core.frame import DataFrame

df = pd.read_csv('~/Downloads/random.csv')

#dataFrame = df[['src_name','src_group','src_addr','src_port','dest_name','dest_group','dest_addr','dest_port','protocol_name']]

dataFrame = df[['src_name','src_group','src_addr','dest_name','dest_group','dest_addr']]

selectFrame = dataFrame.loc[dataFrame['src_addr'] != dataFrame['dest_addr']]   # no self dependency
selectFrame1 = selectFrame.loc[selectFrame['src_name'] != selectFrame['dest_name']] # no self dependency
selectFrame2 = selectFrame1.loc[selectFrame1['src_group'] != selectFrame1['dest_group']] # no self dependency

selectFrame3 = selectFrame2.loc[selectFrame2['src_group'] != 'none']
selectFrame4 = selectFrame3.loc[selectFrame3['dest_group'] != 'none']

'''
# no self dependency - output
-----------------------------
print(selectFrame4)
selectFrame4.to_csv("slc_dependencies.py")
'''

'''
# no duplicates & self dependency - output
------------------------------------------
nodupself = selectFrame4.drop_duplicates(subset=['src_name','src_group','src_addr','dest_name','dest_group','dest_addr'])
nodupself.to_csv("slc_dependencies1.csv")
'''

#selectFrame2.to_csv("dependencies_with_unknown.csv")


'''
Is Unique: Implement an algorithm to determine if a string has all unique characters.
What if you cannot use additional data structures?
'''

# ask if ascii or unicode string because ascii has only 128 strings so if length of given string is greater than 128, we can return false.

def isUnique(string): #without using additional data structure

    # Time Complexity: O(nlogn)
    # Space Complexity: O(1)

    string.sort()

    for i in range(1, len(string)):
        if string[i] == string[i-1]:
            return False
    return True

def isUnique(string): #using additional space

    # Time Complexity: O(n)
    # Space Complexity: O(n)

    numSet = set()

    for ch in string:
        if ch in numSet:
            return False
        numSet.add(ch)
    return True


from inc_noesis import *
import noesis
import rapi
from Sanae3D.Sanae import SanaeObject

def registerNoesisTypes():
    '''Register the plugin. Just change the Game name and extension.'''

    handle = noesis.register("Valkyie Sky", ".xml")
    noesis.setHandlerTypeCheck(handle, noepyCheckType)
    noesis.setHandlerLoadModel(handle, noepyLoadModel)
    return 1

def noepyCheckType(data):
    '''Verify that the format is supported by this plugin. Default yes'''

    return 1

def noepyLoadModel(data, mdlList):
    '''Build the model, set materials, bones, and animations. You do not
    need all of them as long as they are empty lists (they are by default)'''

    ctx = rapi.rpgCreateContext()
    parser = SanaeParser(data)
    parser.parse_file()
    mdl = rapi.rpgConstructModel()
    mdl.setModelMaterials(NoeModelMaterials(parser.texList, parser.matList))
    mdl.setBones(parser.boneList)
    mdl.setAnims(parser.animList)
    mdlList.append(mdl)
    return 1

class SanaeParser(SanaeObject):

    def __init__(self, data):
        '''Initialize some data. Refer to Sanae.py to see what is already
        initialized'''

        super(SanaeParser, self).__init__(data)

    def read_name(self):

        string = self.inFile.readString()
        padding = 80 - len(string) - 1
        self.inFile.seek(padding, 1)
        return string

    def parse_positions(self, numVerts):

        buff = self.inFile.readBytes(12*numVerts)
        rapi.rpgBindPositionBuffer(buff, noesis.RPGEODATA_FLOAT, 12)

    def parse_normals(self, numNorms):

        buff = self.inFile.readBytes(12*numNorms)
        rapi.rpgBindNormalBuffer(buff, noesis.RPGEODATA_FLOAT, 12)

    def parse_uv(self, numUV):

        buff = self.inFile.readBytes(8*numUV)
        rapi.rpgBindUV1Buffer(buff, noesis.RPGEODATA_FLOAT, 8)

    def parse_faces(self, numFaces):

        idxBuff = bytes()
        for i in range(numFaces):
            self.inFile.readUInt()
            idxBuff += self.inFile.readBytes(12)

        rapi.rpgCommitTriangles(idxBuff, noesis.RPGEODATA_UINT, numFaces * 3, noesis.RPGEO_TRIANGLE, 1)

    def parse_file(self):
        '''Main parser method'''

        idstring = self.read_name()
        self.inFile.read('4L')
        numSects = self.inFile.readUInt()
        self.inFile.read('4L')

        for i in range(numSects):
            self.read_name()
        self.inFile.readUInt()
        if numSects == 1:
            self.inFile.readUInt()
        self.inFile.read('9f')
        self.inFile.read('5L')

        self.inFile.seek(320, 1)
        self.inFile.read('9f')
        self.inFile.read('5L')

        texName = self.read_name()
        self.inFile.seek(320, 1)
        self.inFile.seek(220, 1)
        prop = self.read_name()
        if prop == "Particle_View":
            self.inFile.seek(220, 1)
            editable = self.read_name()

        meshType = self.inFile.readUInt()
        if meshType in [1,2]:
            self.inFile.seek(184, 1)
            numVerts, numNorms, numUV, numIdx, numFaces, matNum, \
                numUnk1, numUnk2 = self.inFile.read('8L')
            self.parse_positions(numVerts)
            self.parse_normals(numNorms)
            self.parse_uv(numUV)
            self.parse_faces(numFaces)
            #self.parse_indices(numIdx)
            self.plot_points(numVerts)


# ==============================================================================
# This code is derived from
# https://github.com/fchollet/keras/blob/master/examples/mnist_mlp.py
# and partially modified
# ==============================================================================
# The LISENCE of original code is on
# https://github.com/fchollet/keras/blob/master/LICENSE
# ==============================================================================

from __future__ import print_function

import keras
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers import Dense, Dropout
from keras.optimizers import RMSprop

batchsize = 100
num_classes = 10
epoch = 5

# the data, shuffled and split between train and test sets
print("data loading...")
(x_train, y_train), (x_test, y_test) = mnist.load_data()
print("DONE")

# 画像(28x28) -> 一次元ベクトル化
x_train = x_train.reshape(60000, 784)
x_test = x_test.reshape(10000, 784)

x_train = x_train.astype('float32')
x_test = x_test.astype('float32')
x_train /= 255
x_test /= 255

print(x_train.shape[0], 'train samples')
print(x_test.shape[0], 'test samples')

# convert class vectors to binary class matrices
y_train = keras.utils.to_categorical(y_train, num_classes)
y_test = keras.utils.to_categorical(y_test, num_classes)

# Network definition
model = Sequential()
## 1st layer
model.add(Dense(512, activation='relu', input_shape=(784,)))
model.add(Dropout(0.2))
## 2nd layer
model.add(Dense(512, activation='relu'))
model.add(Dropout(0.2))
## 3rd layer
model.add(Dense(10, activation='softmax'))

# display constructed model
model.summary()

# Run the training
model.compile(loss='categorical_crossentropy',
              optimizer=RMSprop(),
              metrics=['accuracy'])

history = model.fit(x_train, y_train,
                    batch_size=batchsize,
                    epochs=epoch,
                    verbose=1,
                    validation_data=(x_test, y_test))

# evaluate the model
score = model.evaluate(x_test, y_test, verbose=0)
print('Test loss:', score[0])
print('Test accuracy:', score[1])


from keras.layers import LSTM, TimeDistributed, Dense, Input, RepeatVector, Layer
from keras.models import Model
from keras import backend as K

def make_models(noise_dimension, max_chars, char_dimension):
    '''
    Args:
        noise_dimension (int)
        max_chars (int)
        char_dimension (int)

    Returns:
        generator (Model):     Takes noise vector and returns a max_chars long
                               sequence of char_dimensioned vectors
        discriminator (Model): Takes a sequence and classifies it as real or
                               artificially generated text
        GAN (Model):           Staked generator and discriminator
    '''
    gen_input = Input(shape=(noise_dimension,), name='noise')
    gen = RepeatVector(max_chars, name='lots_of_noise')(gen_input)
    gen = LSTM(64, return_sequences=True, name='gen_lstm_1')(gen)
    gen = LSTM(64, return_sequences=True, name='gen_lstm_2')(gen)
    gen = TimeDistributed(Dense(char_dimension, activation='softmax'),
                          name='gen_out')(gen)
    gen_output = TimeDistributed(OneHot(), name='one_hot')(gen)
    generator = Model(input=gen_input, output=gen_output, name='generator')
    generator.compile(loss='mae', optimizer='adam')
    print('\t\t Generator Summary:')
    generator.summary()

    seq_input = Input(shape=(max_chars, char_dimension), name='text')
    dis = LSTM(64, return_sequences=True, name='dis_lstm_1')(seq_input)
    dis = LSTM(64, name='dis_lstm_to_vec')(dis)
    dis_output = Dense(1, activation='sigmoid', name='dis_out')(dis)
    discriminator = Model(input=seq_input, output=dis_output, name='discriminator')
    discriminator.compile(loss='binary_crossentropy', optimizer='adam')
    print('\t\t Discriminator Summary:')
    discriminator.summary()

    gan_input = Input(shape=(noise_dimension,), name='gan_noise')
    gan_gen = generator(gan_input)
    gan_dis = discriminator(gan_gen)
    gan = Model(input=gan_input, output=gan_dis)
    gan.compile(loss='binary_crossentropy', optimizer='adam')
    print('\t\t GAN Summary:')
    gan.summary()

    return generator, discriminator, gan

def one_hot(x):
    '''
    Sparse-ifies 3-dimensional tensor by making the largest value 1 and the rest 0.
    Aka, make one hot.

    Args:
        x (3d theano tensor)

    Returns:
       3d theano tensor
    '''
    return K.cast(K.equal(K.max(x, axis=-1, keepdims=True), x), K.floatx())

class OneHot(Layer):
    def __init__(self, **kwargs):
        self.uses_learning_phase = True
        super(OneHot, self).__init__(**kwargs)

    def call(self, x, mask=None):
        x = K.in_test_phase(one_hot(x), x)
        #x = K.in_test_phase(one_hot(x), one_hot(x))
        return x

    def get_config(self):
        return super(OneHot, self).get_config()


import re
import util
from demjson import demjson

__author__ = 'Jose Riha/Lubomir Kucera'
__name__ = 'exashare'

def supports(url):
    return re.search(r'exashare\.com/embed\-[^\.]+\.html', url) is not None

def resolve(url):
    realurl = re.search(r'<iframe src="([^"]+)".*', util.request(url), re.I | re.S).group(1)
    data = re.search(r'<script[^\.]+?\.setup\((.+?)\);', util.request(realurl), re.I | re.S)
    if data:
        data = data.group(1).decode('string_escape')
        data = re.sub(r'\w+\(([^\)]+?)\)', r'\1', data) # Strip JS functions
        data = re.sub(r': *([^"][a-zA-Z]+)',r':"\1"', data) # Fix incorrect JSON
        data = demjson.decode(data)
        if 'sources' in data:
            result = []
            for source in data['sources']:
                if 'tracks' in data:
                    for track in data['tracks']:
                        result.append({
                                       'url': source['file'],
                                      'subs': track['file'],
                                      'lang': ' %s subtitles' % track['label']
                                       })
            return result
    return None


### code to rotate between IP addresses and user-agent for the headers of the requests, but cannot find good free ip-addresses.
### code here for reference only, not used
import requests
from lxml.html import fromstring
from itertools import cycle

def get_proxies():
    # scrapes the free ip website to return a set of free ips
    url = 'https://free-proxy-list.net/'
    response = requests.get(url)
    parser = fromstring(response.text)
    proxies = set()
    for i in parser.xpath('//tbody/tr')[:10]:
        if i.xpath('.//td[7][contains(text(),"yes")]'):
            # Grabbing IP and corresponding PORT
            proxy = ":".join([i.xpath('.//td[1]/text()')[0], i.xpath('.//td[2]/text()')[0]])
            proxies.add(proxy)
    return proxies

def generate_good_proxies():
    proxies = get_proxies()
    proxy_pool = cycle(proxies)
    good_proxy = []

    url = 'https://httpbin.org/ip'
    for i in range(1,11):
        #Get a proxy from the pool
        proxy = next(proxy_pool)
        print("Request #%d"%i)
        try:
            response = requests.get(url,proxies={"http": proxy, "https": proxy})
            print(response.json())
            good_proxy.append(proxy)
        except:
            #Most free proxies will often get connection errors. You will have retry the entire request using another proxy to work.
            #We will just skip retries as its beyond the scope of this tutorial and we are only downloading a single url
            print("Skipping. Connnection error")
    return good_proxy

ua_set = {
    'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:77.0) Gecko/20190101 Firefox/77.0',
    'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.77 Safari/537.36',
    'Mozilla/5.0 (Windows NT 6.1; WOW64; Trident/7.0; AS; rv:11.0) like Gecko'
}

if __name__ == '__main__':
    print(get_proxies())


import matplotlib.pyplot as plt
import numpy as np

xlabels=['R=50,C=1','R=75,C=1','R=100,C=1','R=150,C=1','R=50,C=0.1','R=75,C=0.1','R=100,C=0.1','R=150,C=0.1','R=50,C=10','R=75,C=10','R=100,C=10','R=150,C=10',]

filename=['LRF_L2_multi','LRF_L2_ovr','LRF_L1_multi','LRF_L1_ovr','LRF_elasticnet_multi','LRF_elasticnet_ovr']
C=[1,0.1,10]
R=[50,75,100,150]

data=[]
for fi in range(len(filename)):
    t=[]
    for i in range(len(C)):
        for j in range(len(R)):
            name=filename[fi]+'/prediction_'+str(C[i])+'_'+str(R[j])+'.dat'
            f=open(name)
            cont=f.readlines()
            l=cont[-1].split('=')
            t.append(float(l[1]))
    data.append(t)

L2multi=data[0]
L2ovr=data[1]
L1multi=data[2]
L1ovr=data[3]
elasticnetmulti=data[4]
elasticnetovr=data[5]

fig, ax = plt.subplots()

ax.plot(np.array(L2multi)/60,'rs-',label='L2 multi lbfgs')
ax.plot(np.array(L1multi)/60,'bs-',label='L1 multi saga')
ax.plot(np.array(elasticnetmulti)/60,'ks-',label='En multi saga')

ax.plot(np.array(L2ovr)/60,'ro:',label='L2 ovr lbfgs')
ax.plot(np.array(L1ovr)/60,'bo:',label='L1 ovr liblinear')
ax.plot(np.array(elasticnetovr)/60,'ko:',label='EN ovr saga')

ax.legend()
ax.set_ylabel('time in minutes')
positions = range(len(xlabels))
plt.xticks(positions, xlabels)
labels = [item.get_text() for item in ax.get_xticklabels()]
#print(labels)

for tick in ax.get_xticklabels():
    tick.set_rotation(90)

fig.tight_layout()

fig.savefig('time_taking.png',bbox_inches='tight')


# -*- coding: utf-8 -*-
"""
Created on Wed Mar 28 16:58:57 2018

@author: xingxf03
"""
import numpy as np
import matplotlib.pyplot as plt
# Fixing random state for reproducibility
np.random.seed(19680801)

plt.subplot(211)
plt.imshow(np.random.random((100, 100)), cmap=plt.cm.BuPu_r)
plt.subplot(212)
plt.imshow(np.random.random((100, 100)), cmap=plt.cm.BuPu_r)

plt.subplots_adjust(bottom=0.1, right=0.8, top=0.9)
cax = plt.axes([0.85, 0.1, 0.075, 0.8])
plt.colorbar(cax=cax)
plt.show()

#
def func3(x, y):
    return (1 - x / 2 + x**5 + y**3) * np.exp(-(x**2 + y**2))

# make these smaller to increase the resolution
dx, dy = 0.05, 0.05

x = np.arange(-3.0, 3.0, dx)
y = np.arange(-3.0, 3.0, dy)
X, Y = np.meshgrid(x, y)

# when layering multiple images, the images need to have the same
# extent.  This does not mean they need to have the same shape, but
# they both need to render to the same coordinate system determined by
# xmin, xmax, ymin, ymax.  Note if you use different interpolations
# for the images their apparent extent could be different due to
# interpolation edge effects

extent = np.min(x), np.max(x), np.min(y), np.max(y)
fig = plt.figure(frameon=False)

Z1 = np.add.outer(range(8), range(8)) % 2  # chessboard
im1 = plt.imshow(Z1, cmap=plt.cm.gray, interpolation='nearest',
                 extent=extent)

Z2 = func3(X, Y)

im2 = plt.imshow(Z2, cmap=plt.cm.viridis, alpha=.9, interpolation='bilinear',
                 extent=extent)

plt.show()


from pyamaze import maze, agent, COLOR, textLabel
from timeit import timeit

def RCW():
    global direction
    k = list(direction.keys())
    v = list(direction.values())
    v_rotated = [v[-1]] + v[:-1]
    direction = dict(zip(k, v_rotated))

def RCCW():
    global direction
    k = list(direction.keys())
    v = list(direction.values())
    v_rotated = v[1:] + [v[0]]
    direction = dict(zip(k, v_rotated))

def moveForward(cell):
    if direction['forward'] == 'E':
        return (cell[0], cell[1] + 1), 'E'
    if direction['forward'] == 'W':
        return (cell[0], cell[1] - 1), 'W'
    if direction['forward'] == 'N':
        return (cell[0] - 1, cell[1]), 'N'
    if direction['forward'] == 'S':
        return (cell[0] + 1, cell[1]), 'S'

def wallFollower(m):
    global direction
    direction = {'forward': 'N', 'left': 'W', 'back': 'S', 'right': 'E'}
    currCell = (m.rows, m.cols)
    path = ''
    while True:

        if currCell == (1, 1):
            break
        if m.maze_map[currCell][direction['left']] == 0:
            if m.maze_map[currCell][direction['forward']] == 0:
                RCW()
            else:
                currCell, d = moveForward(currCell)
                path += d
        else:
            RCCW()
            currCell, d = moveForward(currCell)
            path += d
    path2 = path
    while 'EW' in path2 or 'WE' in path2 or 'NS' in path2 or 'SN' in path2:
        path2 = path2.replace('EW', '')
        path2 = path2.replace('WE', '')
        path2 = path2.replace('NS', '')
        path2 = path2.replace('SN', '')
    return path, path2

if __name__ == '__main__':
    myMaze = maze(5, 5)
#    myMaze.CreateMaze()
    myMaze.CreateMaze(loadMaze='maze3.csv')

    path, path2 = wallFollower(myMaze)
    b = agent(myMaze, footprints=True, color=COLOR.red)
    myMaze.tracePath({b: path2}, delay=30)

    textLabel(myMaze, 'Wall fallower - długość ścieżki końcowej', len(path2) + 1)
    textLabel(myMaze, 'Wall fallower - liczba przeszukań', len(path) + 1)

    t1 = timeit(stmt='wallFollower(myMaze)', number=1000, globals=globals())
    textLabel(myMaze, 'Wall fallower - czas przejścia (s)', t1)
    myMaze.run()


# ------------------------------------------------------------------------------
# Question: 0238_product_of_array_except_self.py
# ------------------------------------------------------------------------------
# tags:[medium, array]
'''
Given an array nums of n integers where n > 1,  return an array
output such that output[i] is equal to the product of all the elements of nums
except nums[i].

Example:

Input:  [1,2,3,4]
Output: [24,12,8,6]
Constraint: It's guaranteed that the product of the elements of any prefix or
suffix of the array (including the whole array) fits in a 32 bit integer.

Note: Please solve it without division and in O(n).

Follow up:
Could you solve it with constant space complexity? (The output array does not
count as extra space for the purpose of space complexity analysis.)

'''

# ------------------------------------------------------------------------------
# Solutions
# ------------------------------------------------------------------------------

from typing import *
import functools
import unittest

class Solution:
    '''
    Time: O(n)
    Space: O(n)

    Input:  [4,5,1,8,2]
    Output: [80, 64, 320, 40, 160]

    n = [4  5  1   8  2]
    L = [1  4  20 20 160]
    R = [80  16 16  2 1]
    Result[i] = L[i] * R[i]
    '''
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        n = len(nums)
        L = [1] * n
        R = [1] * n
        for i in range(1, n):
            L[i] = nums[i-1] * L[i-1]
        for i in range(n - 2, -1, -1):
            R[i] = nums[i+1] * R[i+1]
        result = [L[i] * R[i] for i in range(n)]
        return (result)

class Solution2:
    '''
    Time: O(n)
    Space: O(1)
    '''
    def productExceptSelf(self, nums: List[int]) -> List[int]:
        n = len(nums)
        ans = [1]
        for i in range(1, n):
            ans = ans + [nums[i - 1] * ans[-1]]
        print(ans)
        R = 1
        for i in range(n - 2, -1, -1):
            R *= nums[i + 1]
            print(R)
            ans[i] *= R
        print(ans)
        return (ans)

# ------------------------------------------------------------------------------
# Tests
# ------------------------------------------------------------------------------

class TestSolution(unittest.TestCase):
    def test_simple(self):
        s = Solution()
        nums = [4, 5, 1, 8, 2, 10, 6]
        result = s.productExceptSelf(nums)
        self.assertEqual(result, [4800, 3840, 19200, 2400, 9600, 1920, 3200])

    def test_simple2(self):
        s = Solution()
        nums = [4, 5, 1, 8, 2]
        result = s.productExceptSelf(nums)
        self.assertEqual(result, [80, 64, 320, 40, 160])

class TestSolution2(unittest.TestCase):
    def test_simple2(self):
        s = Solution2()
        nums = [4, 5, 1, 8, 2]
        result = s.productExceptSelf(nums)
        self.assertEqual(result, [80, 64, 320, 40, 160])

unittest.main(verbosity=2)


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

"""This module provides extensions for sending SMTP mails."""

import os
import smtplib

from email.mime.image import MIMEImage
from email.mime.application import MIMEApplication
from email.mime.multipart import MIMEMultipart
from email.mime.text import MIMEText

class SMTP(smtplib.SMTP):
    """The SMTP extension class.

       Extends the SMTP class of the smtplib module.

       Example:
       from smtp_extensions import SMTP

       smtp = SMTP("localhost", 25)
       smtp.sendhtml(sender="from@address",
                     subject="subject",
                     message="hello",
                     recipients="to@address,to2@address",
                     attachments=["filepath1", "filepath2"])
    """

    def sendhtml(self, sender, subject, message, recipients, **kwargs):
        """Send a multipart html message.

           :param str sender: The sender's address (fromaddress).
           :param str subject: The email subject.
           :param str message: The message in HTML format.
           :param str recipients: The recipient addresses (comma-separated string).

           :param **kwargs: Arbitrary list of keyword arguments
                    ccs: The recipient cc addresses (comma-separated string).
                    bccs: The recipient bcc addresses (comma-separated string).
                    attachments: The list of attachments.
                    images: The list of images to be embedded into given html message, e.g.
                            " matches the first image in the list
        """
        ccs = kwargs.pop("ccs", "")
        bccs = kwargs.pop("bccs", "")
        attachments = kwargs.pop("attachments", None)
        images = kwargs.pop("images", None)
        assert not kwargs, 'Unknown arguments: %r' % kwargs

        # note:
        # content-type 'related' is important to display embedded images
        # properly in mail clients like thunderbird
        msg = MIMEMultipart("related")
        msg["Subject"] = subject
        msg["From"] = sender
        msg["To"] = recipients
        msg["CC"] = ccs
        # disable this, otherwise "to and cc" receivers will see the bcc receivers
        # msg["BCC"] = BCCs
        msg.attach(MIMEText(message, "html"))

        # embed images
        if images is None:
            images = []
        for image in images:
            with open(image, "rb") as file:
                msg_mimepart = MIMEImage(file.read())
                msg_mimepart.add_header("Content-ID", "<image{}>".format(images.index(image) + 1))
                msg.attach(msg_mimepart)

        # add attachments
        if attachments is None:
            attachments = []
        for attachment in attachments:
            with open(attachment, "rb") as file:
                msg_mimepart = MIMEApplication(file.read())
                msg_mimepart.add_header("Content-Disposition", "attachment", filename=os.path.basename(attachment))
                msg.attach(msg_mimepart)

        self.sendmail(sender, recipients.split(",") + ccs.split(",") + bccs.split(","), msg.as_string())


import re

with open('4.txt', 'r') as f:
    data = f.read().splitlines()

count = 0

for line in data:
    groups = list(map(int, re.split(',|-', line)))

    if (groups[0] >= groups[2]) & (groups[1] <= groups[3]):
        count += 1
    elif (groups[2] >= groups[0]) & (groups[3] <= groups[1]):
        count += 1

print(count) # part 1 solution

with open("4.txt", "r") as f:
    data = re.findall(r"(\d+)-(\d+),(\d+)-(\d+)", f.read())
    data = [[int(e) for e in row] for row in data]

overlap = [max(a, c) <= min(b, d) for a, b, c, d in data]

print(sum(overlap))  # part 2 solution


from connection_manager import DB
import geolocation_utility as gu

def check_if_id_exists(table_name, id):
    query_string = 'Select * from ' + table_name + ' where id=%s'
    result_set = DB().query(query_string, [id, ])
    if result_set.rowcount == 1:
        return True
    return False

def get_site_info(id):
    all_data = fetch_settings(id)
    if all_data is None:
        return None

    info = {'description': all_data['description'],
            'contact': all_data['contact'], 'address': all_data['address']}
    return info

def register_clienta(client_info):
    print('Registering clienta')
    client_id = client_info['site_id']
    address = client_info['address']
    description = client_info['description']
    contact = client_info['contact']
    nearest_node = client_info['nearest_node']
    is_prohibited = client_info['is_prohibited']
    position = gu.get_position_coordinates(address)

    q = 'INSERT INTO ClientA (ID,Description,Address,Contact,' \
        'NearestNode,IsProhibited,Latitude,Longitude) values(%s,%s,%s,%s,%s,%s,%s,%s)'
    DB().query(q, (client_id, description, address, contact,
                   nearest_node, is_prohibited, position['lat'], position['lng']))
    return None

def fetch_settings(site_id):
    query_string = 'Select * from ClientA where ID=%s'
    db_obj = DB()
    result_set = db_obj.query(query_string, (site_id,))
    if result_set.rowcount == 0:
        return None
    #TODO:more columns have been added
    id, description, address, contact, nearest_node, is_prohibited = result_set.fetchone()
    config_settings = {'site_id': id, 'description': description, 'address': address,
                       'contact': contact, 'nearest_node': nearest_node,
                       'isProhibited': is_prohibited}
    return config_settings

def register_clientb(client_info):
    print('Registering clientb')
    client_id = client_info['site_id']
    address = client_info['address']
    description = client_info['description']
    contact = client_info['contact']
    q = 'INSERT INTO ClientB (ID,Description,Address,Contact) values(%s,%s,%s,%s)'
    DB().query(q, (client_id, address, description, contact))
    return None

def store_new_alert(siteid, activity_recognized, cctv_location, time):
    print('recieved new alert from ' + str(siteid) + 'at ' + time)
    query_string = 'Select NearestNode,Description,Address from ClientA where ID=%s'
    db_obj = DB()
    result_set = db_obj.query(query_string, (siteid,))
    nearest_node, description, address = result_set.fetchone()
    description = cctv_location + ' ' + description

    query_string = 'Insert into Messages (SourceID,DestinationID,Time,Activity_Recognized,' \
                   'Location_Description,Location_Address) values(%s,%s,%s,%s,%s,%s)'

    DB().query(query_string, (siteid, 1, time, activity_recognized, description, address))
    DB().query(query_string,
               (siteid, nearest_node, time, activity_recognized, description, address))

def check_new_alerts(site_id, last_checked):
    query_string = 'Select * from Messages where DestinationID=%s and Time>%s'
    db_obj = DB()
    result_set = db_obj.query(query_string, (site_id, last_checked))
    message_list = []
    for (source_id, destination_id, time, location_description, activity_recognized,
            location_address) \
            in result_set:
        new_message = {'SourceID': source_id,
                       'DestinationID': destination_id,
                       'Time': time,
                       'activity_recognized': activity_recognized,
                       'location_description': location_description,
                       'location_address': location_address}
        message_list.append(new_message)

    #print(message_list)
    return message_list

def get_all_surveillance_sites():
    query_string = 'Select * from Clienta '
    db_obj = DB()
    result_set = db_obj.query(query_string, ())
    site_list = []
    for (id, nearest_node, description, address, contact, is_prohibited, latitude,
         longitude) in result_set:
        client_info = {'id': id,
                       'description': description,
                       'address': address,
                       'contact': contact,
                       'is_prohibited': is_prohibited,
                       'latitude': latitude,
                       'longitude': longitude};
        site_list.append(client_info)

    return site_list