import curses
from collections import namedtuple
from .rect import Rect
from .debug import debug
from . import ray

class Camera(object):
    """ Draws the current view to the main game screen.

    Attributes:
    view -- Rect containing the current view of the camera
    """

    def __init__(self, x=0, y=0, width=51, height=15):
        self.view = Rect(x, y, width, height)

    def draw(self, window, world, point):
        """ Render world tiles and then entities to window.

        Keyword arguments:
        window -- current curses window (or screen) object
        world -- current game World object
        point -- (x, y) point at which to raycast player's view from
        """

        # Don't raycast as far in a dark world
        if world.dark:
            radius = 3
        else:
            radius = 9

        # Raycast to see which tiles are seen
        seen = ray.ray_cast_circle(point=point, radius=radius, world=world)

        # Add to the set of seen tiles
        world.tiles_seen = world.tiles_seen.union(seen)

        # Draw visible tiles
        for x in range(self.view.width):
            for y in range(self.view.height):
                # Transform to world coordinates
                x1, y1 = x + self.view.x, y + self.view.y

                # Only draw if seen by the raycaster this frame
                if (x1, y1) in seen:
                    window.addch(y, x, ord(world.get_tile(x1, y1)),
                            curses.color_pair(30))

                # If seen some frame before (and not in dark world), render in grey
                elif not world.dark and (x1, y1) in world.tiles_seen:
                    window.addch(y, x, ord(world.get_tile(x1, y1)),
                            curses.color_pair(40))

        # Draw the entities ordered by their layer, largest layer drawn first
        for entity in reversed(sorted(world.entities, key=lambda entity: entity.layer)):
            # Only draw if the entity is on-screen and seen by raycaster
            if self.is_visible(entity) and (entity.x, entity.y) in seen:
                pos = self.world_to_screen(entity.x, entity.y)
                window.addch(pos.y, pos.x, ord(str(entity)),
                        curses.color_pair(entity.color_pair))

    def world_to_screen(self, x, y):
        """ Transform world coordinates to screen coordinates.

        Returns a namedtuple Point (x, y) where x and y are the
        screen coordinates. """
        Point = namedtuple("Point", ['x', 'y'])
        return Point(x - self.view.x, y - self.view.y)

    def screen_to_world(self, x, y):
        """ Transform screen coordinates to world coordinates.

        Returns a namedtuple Point (x, y) where x and y are the
        screen coordinates. """
        Point = namedtuple("Point", ['x', 'y'])
        return Point(x + self.view.x, y + self.view.y)

    def center_on(self, entity, world):
        """ Center camera view on entity object in world.

        Keyword arguments:
        entity -- Entity object to center on
        world -- World object that entity is in, needed to ensure the
                 camera view remains in bounds. """
        self.view.x = entity.x - int(self.view.width/2)
        self.view.y = entity.y - int(self.view.height/2)

        # Ensure that the camera remains in bounds
        if self.view.x < 0:
            self.view.x = 0
        if self.view.y < 0:
            self.view.y = 0
        if self.view.x + self.view.width > world.width:
            self.view.x = world.width - self.view.width
        if self.view.y + self.view.height > world.height:
            self.view.y = world.height - self.view.height

    def is_visible(self, entity):
        """ True if entity is onscreen. """
        if (self.view.x < entity.x < self.view.x + self.view.width and
            self.view.y < entity.y < self.view.y + self.view.height):
            return True
        else:
            return False


import streamlit as st
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap
from reg import newPrediction,readData,getDatatoPlot
data = readData()

def plot_decision_boundary(model, x, y, title):
    # Código para generar el gráfico de dispersión y la frontera de decisión sin cambios
    xSet, ySet = x, y
    xSet_2d = np.column_stack((xSet[:, 0], xSet[:, 1]))  # Convertir a arreglo bidimensional

    x1, x2 = np.meshgrid(np.arange(start=xSet_2d[:, 0].min() - 1, stop=xSet_2d[:, 0].max() + 1, step=0.01),
                         np.arange(start=xSet_2d[:, 1].min() - 1, stop=xSet_2d[:, 1].max() + 1, step=0.01))
    Z = model.predict(np.array([x1.ravel(), x2.ravel()]).T).reshape(x1.shape)

    fig, ax = plt.subplots()
    ax.contourf(x1, x2, Z, alpha=0.75, cmap=ListedColormap(('red', 'green')))
    ax.set_xlim(x1.min(), x1.max())
    ax.set_ylim(x2.min(), x2.max())

    for i, j in enumerate(np.unique(ySet)):
        ax.scatter(xSet[ySet == j, 0], xSet[ySet == j, 1],
                   c=ListedColormap(['red', 'green'])(i), label=j)

    plt.title(title)
    plt.xlabel("Age")
    plt.ylabel("Estimated Salary")
    plt.legend()

    st.pyplot(fig)

def main():
    st.title('Modelo de Predicción de Compras')

    # Interacción con el usuario
    st.header('Interacción con el usuario')

    # Aquí puedes agregar campos de entrada para que el usuario proporcione datos
    age = st.number_input('Edad', min_value=18, max_value=100, value=30)
    estimated_salary = st.number_input('Salario estimado', min_value=0, max_value=200000, value=50000)

    # Realizar predicción con los datos proporcionados por el usuario
    user_data = pd.DataFrame({
        'Age': [age],
        'EstimatedSalary': [estimated_salary]
    })

    # Cargar el modelo y realizar la predicción
    dataToPred = [[user_data['Age'].iloc[0],user_data['EstimatedSalary'].iloc[0]]]

    y_pred_user = newPrediction( dataToPred)
    print(y_pred_user)
    # Mostrar el resultado de la predicción para los datos del usuario
    st.subheader('Resultado de la predicción:')
    if y_pred_user[0] == 1:
        st.write('Es probable que el cliente compre el producto.')
    else:
        st.write('Es probable que el cliente NO compre el producto.')

    # Mostrar información relevante del conjunto de datos original
    st.header('Información relevante del conjunto de datos original:')
    st.write(data)

    # Mostrar el gráfico de la frontera de decisión
    xTrain,yTrain,naiveBayesModel = getDatatoPlot()
    # Agregar controles deslizantes para ajustar los valores de Age y EstimatedSalary
    age = st.slider('Edad', min_value=int(xTrain[:, 0].min()), max_value=int(xTrain[:, 0].max()), value=int(xTrain[:, 0].mean()))
    estimated_salary = st.slider('Salario estimado', min_value=int(xTrain[:, 1].min()), max_value=int(xTrain[:, 1].max()), value=int(xTrain[:, 1].mean()))

    # Mostrar el gráfico de la frontera de decisión con interactividad
    plot_decision_boundary(naiveBayesModel, xTrain, yTrain, "Naive Bayes Classifier (Training Set)")

if __name__ == '__main__':
    main()


import os
import sys
from setuptools import setup, find_packages
from fnmatch import fnmatchcase
from distutils.util import convert_path

standard_exclude = ('*.pyc', '*~', '.*', '*.bak', '*.swp*')
standard_exclude_directories = ('.*', 'CVS', '_darcs', './build', './dist', 'EGG-INFO', '*.egg-info')
def find_package_data(where='.', package='', exclude=standard_exclude, exclude_directories=standard_exclude_directories):
    out = {}
    stack = [(convert_path(where), '', package)]
    while stack:
        where, prefix, package = stack.pop(0)
        for name in os.listdir(where):
            fn = os.path.join(where, name)
            if os.path.isdir(fn):
                bad_name = False
                for pattern in exclude_directories:
                    if (fnmatchcase(name, pattern)
                        or fn.lower() == pattern.lower()):
                        bad_name = True
                        break
                if bad_name:
                    continue
                if os.path.isfile(os.path.join(fn, '__init__.py')):
                    if not package:
                        new_package = name
                    else:
                        new_package = package + '.' + name
                        stack.append((fn, '', new_package))
                else:
                    stack.append((fn, prefix + name + '/', package))
            else:
                bad_name = False
                for pattern in exclude:
                    if (fnmatchcase(name, pattern)
                        or fn.lower() == pattern.lower()):
                        bad_name = True
                        break
                if bad_name:
                    continue
                out.setdefault(package, []).append(prefix+name)
    return out

setup(name='docassemble.LLAW33012021S2FLAC3',
      version='1.2.1',
      description=('Fencey is an application to help users through a fencing issue to either create a form 2 or form 3. If their issue is too complex they are referred to Flinders Legal Clinic.'),
      long_description='# docassemble.LLAW33012021S2FLAC3\r\n\r\nThis application was made by Flinders University in collaboration with Flinders Legal Centre. This application is made for clients who having a fencing issue to provide guidance through their issues. Fency was specifically made for issues regarding the need to replace a fence due to damage or if they have been served with a notice of intention from their neighbour. This application will create a Form 2 or Form 3 depending on the users situation or if the situation is more complex will refer the user to book a consult with Flinders Legal Centre.\r\nThis application does not constitute legal advice nor replaces it.\r\n\r\n## Author\r\n\r\nAnnarose De Ionno, deio0004@flinders.edu.au\r\nJosephine Males, male0056@flinders.edu.au\r\nRumbi Sekete, seke0005@flinders.edu.au\r\nNikki Esmaeili, nikki.esmaeili@flinders.edu.au\r\nChloe Tunstill, tuns0011@flinders.edu.au\r\nKatie Henthorn, hent0023@flinders.edu.au\r\n\r\n',
      long_description_content_type='text/markdown',
      author='Annarose De Ionno',
      author_email='deio0004@flinders.edu.au',
      license='The MIT License (MIT)',
      url='https://docassemble.org',
      packages=find_packages(),
      namespace_packages=['docassemble'],
      install_requires=[],
      zip_safe=False,
      package_data=find_package_data(where='docassemble/LLAW33012021S2FLAC3/', package='docassemble.LLAW33012021S2FLAC3'),
     )


from django.urls import path, re_path
from .views import PostList, PostDetail, main_redirect, PostAdd, UserDetail, UserPrivatePage, agree, disagree

urlpatterns = [
    path('', PostList.as_view(), name='posts_list'),
    path('filter/', UserPrivatePage.as_view(), name='posts_filter'),
    re_path(r'^filter/agree/(?P<response_id>\d+)/$', agree, name='agree'),
    re_path(r'^filter/disagree/(?P<response_id>\d+)/$', disagree, name='disagree'),
    path('post/<int:pk>', PostDetail.as_view(), name='post_detail'),
    path('post/add/', PostAdd.as_view(), name='post_add'),
    path('post/', main_redirect, name='main_red'),
    path('user/<int:pk>', UserDetail.as_view(), name='user_detail'),
]


#!/usr/bin/env python
# encoding: utf-8

"""
utils.py
Created by Shuailong on 2017-02-14.

"""

from __future__ import print_function
from __future__ import division

from keras.metrics import categorical_accuracy
from sklearn.model_selection import KFold

def extract_features(X):
    '''
    X: [[word11, word12, ...], [word21, word22, ...], ...]
    return: 1 to 4 prefix/suffix features.
    rtype: 3d array. First: feature types; second: samples; third: word pre/suffixes
    '''
    X_feats = []
    for sample in X:
        sample_features = []
        for word in sample:
            prefixes = [word[:i] for i in range(1, 5)]
            suffixes = [word[-i:] for i in range(1, 5)]
            sample_features.append(prefixes + suffixes)
        X_feats.append(sample_features)

    X_sep_feats = [None]*8
    for i in range(8):
        X_sep_feats[i] = []
        for sample_features in X_feats:
            sep_feat = []
            for word_feats in sample_features:
                sep_feat.append(word_feats[i])
            X_sep_feats[i].append(sep_feat)
    return X_sep_feats

def generate_ten_fold(X_train, X_train_feats, y_train):
    '''
    Generate 10-fold split.
    '''
    kf = KFold(n_splits=10, shuffle=False)
    for train, test in kf.split(X_train):
        yield X_train[train], X_train_feats[:, train], y_train[train], X_train[test], X_train_feats[:, test], y_train[test]

def true_accuracy(y_true, y_pred):
    '''
    Ignore START_OF_SENTENCE and END_OF_SENTENCE when calculating accuracy.
    Also ignore zero paddings.
    '''
    # ignore SOS, EOS
    trimmed_y_true = y_true[:, 1:-1, :]
    trimmed_y_pred = y_pred[:, 1:-1, :]

    return categorical_accuracy(trimmed_y_true, trimmed_y_pred)

def token2word(tokens, word_index):
    index_word = {v: k for k, v in word_index.items()}
    return [index_word[t] for t in tokens]

def word2token(words, word_index):
    pass


####### LING78100 TERM PROJECT
####### PART 3: WORD FREQUENCY COMPARISON

####### original code provided by Kyle Gorman
####### edited by Winnie Yan

# !/usr/bin/env python
"""Computes token-level log-odds ratios.

This computes token-level log-odds ratios using the informative Dirichlet prior
method introduced by:

Monroe, B. L., Colaresi, M. P., and Quinn, K. M. 2008.  Fightin' words: lexical
feature selection and evaluation for identifying the content of political
conflict. Political Analysis 16(4): 372-40.

The user provides the paths to three TSV files:

* frequencies in the first target corpus
* frequencies in the second target corpus
* frequencies in the third control corpus

All three TSV files should have two columns:

1. the token itself, normalized however is desired
2. the token frequency expressed as an integer

The tool then prints log-odds, in decreasing order, for any token present in
all three files."""

import logging
import math
import operator
import os

from typing import Dict, List

Freqs = Dict[str, int]

def _read_freq_tsv(path: str) -> Freqs:
    """Reads TSV file into dictionary."""
    result: Freqs = {}
    with open(path, "r", encoding = "utf-16") as source:
        for line in source:
            (token, freq) = line.rstrip().split("\t", 1)
            result[token] = int(freq)
    return result

def _log_odds_idp(fx: int, f3: int, nx: int, n3: int) -> float:
    """Computes log-odds ratio with informative prior counts."""
    num = fx + f3
    den = nx + n3 - fx - f3
    return math.log2(num/den)

def _log_odds_ratio_idp(
    f1: int, f2: int, f3: float, n1: int, n2: int, n3: int
) -> float:
    """Computes log-odds ratio with an informative Dirichlet prior."""
    return _log_odds_idp(f1, n1, f3, n3) - _log_odds_idp(f2, n2, f3, n3)

def _var_log_odds_ratio_idp(f1: int, f2: int, f3: float) -> float:
    """Computes the sample variance of log-odds ratio with an informative Dirichlet prior."""
    return 1.0 / (f1 + f3) + 1.0 / (f2 + f3)

def main():
    logging.info("Reading frequencies")
    corpus1 = _read_freq_tsv("BushWordCount/BushSpeechesWordCount.txt")
    corpus2 = _read_freq_tsv("ObamaWordCount/ObamaSpeechesWordCount.txt")
    corpus3 = _read_freq_tsv("Reuters/ReutersWordCount.txt")
    logging.info("Computing denominators")
    n1 = sum(corpus1.values())
    n2 = sum(corpus2.values())
    n3 = sum(corpus3.values())
    pairs: List[Tuple[str, float]] = []
    logging.info("Computing supported tokens")
    supported_tokens: Set[str] = set(corpus1.keys())
    supported_tokens &= corpus2.keys()
    supported_tokens &= corpus3.keys()
    logging.info("Computing scores")
    for token in supported_tokens:
        f1 = corpus1[token]
        f2 = corpus2[token]
        f3 = corpus3[token]
        score = _log_odds_ratio_idp(f1, f2, f3, n1, n2, n3)

        # Removed because control corpus outweighed corpus 1 and 2 data
        '''if not args.raw:
            var = _var_log_odds_ratio_idp(f1, f2, f3)
            score /= math.sqrt(var)'''

        pairs.append((token, score))
    logging.info("Sorting scores")
    pairs.sort(reverse=True, key=operator.itemgetter(1))
    logging.info("Writing scores")

    directory = "Frequencies/"
    try:
        os.mkdir(directory)
    except OSError:
        print ("Creation of the directory %s failed" % directory)
    else:
        print ("Successfully created the directory %s " % directory)

    with open(directory + "FrequencyScores.txt", "w", encoding = "utf-16") as writer:
        for (token, score) in pairs:
            writer.write(f"{token}\t{score}\n")

main()


#have the user enter their investement amount and expected interest
#Each year their investment will increase by their investment + their investment * interest
#Print out the earnings after a 10 year period

#Take input from user and convert it to a float
ivsmnt, intrst = input("Please enter your current investment and expected interest: ").split()
ivsmnt = float(ivsmnt)

#convert interest rate to percentage
intrst = float(intrst) * .01

#Calculate for returns every year
#rtn_per_yr = ivsmnt + ivsmnt * intrst
#rtn_per_decade = rtn_per_yr * 10
for i in range (10):
    ivsmnt = ivsmnt + ivsmnt * intrst

print("After a 10 year period, your earnings should be {:.2f}".format(ivsmnt))


#%%
alien_0 = {'color':'green', 'points':5}

print(alien_0['color'])
print(alien_0['points'])

# %%
alien_0['x_points'] = 0
alien_0['y_points'] = 25
print(alien_0)

# %%
alien_1 = {}
alien_1['color']='red'
print(alien_1)

# %%
print(alien_0)
del alien_0['color']
print(alien_0)

# %%
favorite_languages={
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil':'python'
}
print(favorite_languages['jen'])

# %%
david={
    'first_name' : 'atony',
    'last_name' :'david',
    'age':23,
    'city':'LA'
}
print(david)
# %%
favorite_numbers={
    'alice':11,
    'bob':22,
    'carile':23,
    'david':13,
    'estar':0
}
print(favorite_numbers)

# %%
user_0={
    'username':'efermi',
    'first':'enrico',
    'last':'fermi'
}

# %%
for key,value in user_0.items():
    print("\nKey: "+key)
    print("Value: "+value)

# %%
print(user_0.items())

# %%
for name,language in favorite_languages.items():
    print(name.title()+"'s favorite language is"+
        language.title()+"." )
# %%
for name in favorite_languages.keys():
    print(name.title())
# %%
for name in favorite_languages:
    print(name)
# %%
favorite_languages={
    'jen': 'python',
    'sarah': 'c',
    'edward': 'ruby',
    'phil':'python'
}
if 'evil' not in favorite_languages.keys():
    print("evil, you are not in here")
# %%
if 'evil' not in favorite_languages.keys():
    print("evil, you are not in here")

# %%
for name in sorted(favorite_languages.keys()):
    print(name.title())

# %%
for language in favorite_languages.values():
    print(language.title())

# %%
for language in set(favorite_languages.values()):
    print(language.title())

# %%
rivers={
    'nile':'egypt',
    'LongRiver':'China',
    'YellowRiver':'China',
}
for river,county in rivers.items():
    print("The "+river+" runs through "+county+".")

# %%
for river in rivers.keys():
    print(river.title())

# %%
for country in rivers.values():
    print(country)

# %%
alien_0['color']
# %%
alien_0={'color': 'green', 'points': 5}
alien_1={'color': 'red', 'points': 6}
alien_2={'color': 'yellow', 'points':15 }
aliens=[alien_0, alien_1, alien_2]
for alien in aliens:
    print(alien)

# %%
aliens = []
for number in range(30):
    new_alien = {'color':'green', 'points':number, 'speed':'slow'}
    aliens.append(new_alien)

for alien in aliens[:5]:
    print(alien)
print("...")
print("total aliens : "+str(len(aliens)))

# %%
pizza={
    'crust':'thick',
    'toppings':['mushroom','extra cheese']
}
for topping in pizza['toppings']:
    print(topping)

# %%
favorite_languages={
    'jen':['py','C'],
    'sarah':['C'],
    'edward':['ruby','go']
}
for name,languages in favorite_languages.items():
    print("\n"+name.title()+"'s favorite language are:")
    for language in languages:
        print("\t"+language.title())

# %%
bob={'name':'bob' ,'age':12}
tom={'name':'tom','age':13}
people = [bob,tom]
for value in people:
    print(value['name']+"\t"+str(value['age']))

# %%
cat={'name':'tom', 'age':3}
dog={'name':'jack', 'age':5}
fish={"name":'Bob', 'age':2}
pets=[cat,dog,fish]
for pet in pets:
    print(pet['name']+" "+str(pet['age']))

# %%
favorite_places={
    'jack':['beijing','shanghai'],
    'tom':['shandong'],
    'jerry':['hainan']
}
for name,places in favorite_places.items():
    print(name+"'s favorite places are:")
    for place in places:
        print("\tplace")

# %%
cities={
    'beijing':{
        'country':'china',
        'people':"1.5 billion",
        'history':'history'
    },
    'shanghai':{
        'country':'china',
        'people':"1.5 billion",
        'history':'history'
    },
    'chongqing':{
        'country':'china',
        'people':"1.5 billion",
        'history':'history'
    }
}
for city,infos in cities.items():
    print(city+ " info:")
    print("\tcountry : "+infos['country']+
        "\n\tpeople : "+infos['people']+
        "\n\thistory: "+infos['history']
    )

# %%


from flask import Flask, jsonify, request
import sqlite3

app = Flask(__name__)
DATABASE = 'students.db'

# Create a connection to the SQLite database
def get_db():
    conn = sqlite3.connect(DATABASE)
    conn.row_factory = sqlite3.Row
    return conn

# Initialize the database schema
def init_db():
    conn = get_db()
    conn.execute('CREATE TABLE IF NOT EXISTS students ('
                 'roll_number TEXT PRIMARY KEY,'
                 'name TEXT,'
                 'class_name TEXT,'
                 'marks INTEGER)'
                 )
    conn.close()

# Create student record
@app.route('/students', methods=['POST'])
def create_student():
    data = request.get_json()
    roll_number = data['roll_number']
    name = data['name']
    class_name = data['class']
    marks = data['marks']

    conn = get_db()
    conn.execute('INSERT INTO students (roll_number, name, class_name, marks) '
                 'VALUES (?, ?, ?, ?)', (roll_number, name, class_name, marks))
    conn.commit()
    conn.close()

    return jsonify({'message': 'Student record created successfully'})

# Get all student records
@app.route('/students', methods=['GET'])
def get_students():
    conn = get_db()
    cursor = conn.execute('SELECT * FROM students')
    students = [dict(row) for row in cursor.fetchall()]
    conn.close()

    return jsonify(students)

# Get a specific student record by roll number
@app.route('/students/<roll_number>', methods=['GET'])
def get_student(roll_number):
    conn = get_db()
    cursor = conn.execute('SELECT * FROM students WHERE roll_number = ?', (roll_number,))
    student = cursor.fetchone()
    conn.close()

    if student:
        return jsonify(dict(student))
    return jsonify({'message': 'Student not found'})

# Update a student record
@app.route('/students/<roll_number>', methods=['PUT'])
def update_student(roll_number):
    data = request.get_json()
    name = data['name']
    class_name = data['class']
    marks = data['marks']

    conn = get_db()
    conn.execute('UPDATE students SET name = ?, class_name = ?, marks = ? WHERE roll_number = ?',
                 (name, class_name, marks, roll_number))
    conn.commit()
    conn.close()

    return jsonify({'message': 'Student record updated successfully'})

# Delete a student record
@app.route('/students/<roll_number>', methods=['DELETE'])
def delete_student(roll_number):
    conn = get_db()
    conn.execute('DELETE FROM students WHERE roll_number = ?', (roll_number,))
    conn.commit()
    conn.close()

    return jsonify({'message': 'Student record deleted successfully'})

# Initialize the database and run the Flask app
if __name__ == '__main__':
    init_db()
    app.run(host='0.0.0.0', port=5000)


import sys
n = int(input())
q = []
for _ in range(n):
    i = sys.stdin.readline().rstrip()
    if i == 'pop':
        if q:
            print(q.pop())
        else:
            print(-1)
    elif i == 'size':
        print(len(q))
    elif i == 'empty':
        if q:
            print(0)
        else:
            print(1)
    elif i == 'top':
        if q:
            print(q[-1])
        else:
            print(-1)
    else:
        a, b = i.split()
        q.append(int(b))


import sys
sys.stdin = open("sum_input.txt", "r")

T = int(input())

for test_case in range(1, T + 1):
    N, M = map(int, input().split())
    arr = list(map(int, input().split()))

    sum = 0
    for i in range(M):
        sum += arr[i]

    i, j = 0, M
    Min = Max = sum
    while j < N:
        sum += (arr[j] - arr[i])
        Min = min(Min, sum)
        Max = max(Max, sum)
        i, j = i + 1, j + 1

    print("#%d %d" % (test_case, Max - Min))


# Django
from django.test import TestCase

# Python
import json

# Django Rest Framework
from rest_framework.test import APIClient
from rest_framework import status

class CreateOrderTestCase(TestCase):

    fixtures = ['client.json', 'order.json', 'product.json', 'provider.json']

    def test_create_order_cedis(self):

        client = APIClient()

        test_order = {
            "order_number": "ORD0008",
            "provider": 3,
            "product": 4,
            "client": 1,
            "order_date": "2020-10-30T05:11:30.362Z",
            "priority": True,
            "items": 5,
            "order_type": "CEDIS",
            "distribution_center_store": "Almacén #12"
        }

        response = client.post('/order/', test_order, format='json')
        result = json.loads(response.content)

        response_ok = {
            "order_number": "ORD0008",
            "provider": 3,
            "provider_info": {
                "name": "Fedex",
                "address": "Calle 51 entre 91 y 22A"
            },
            "product": 4,
            "product_info": {
                "code": "DUR22290",
                "description": "Pilas Duracell Copper negro"
            },
            "client": 1,
            "client_info":
                {
                    "code": "AV0001",
                    "name": "Ana Velazquez",
                    "address": "Calle 23 entre 45 y 23",
                    "client_type": "PLATINO"
                },
            "order_date": "2020-10-30T05:11:30.362000Z",
            "deliver_date": None,
            "priority": True,
            "items": 5,
            "order_type": "CEDIS",
            "distribution_center_store": "Almacén #12",
            "store_reference": "",
            "store_code": "",
            "company_reference": "",
            "company_member_code": "",
            "company_order_detail": ""
        }

        self.assertEqual(result, response_ok)

    def test_create_order_store(self):

        client = APIClient()

        test_order = {
            "order_number": "ORD0007",
            "provider": 1,
            "product": 1,
            "client": 3,
            "order_date": "2020-10-30T05:11:30.362Z",
            "priority": False,
            "items": 2,
            "order_type": "SUCURSAL",
            "store_reference": "Referencia sucursal",
            "store_code": "codigo del almacén"
        }

        response = client.post('/order/', test_order, format='json')
        result = json.loads(response.content)

        response_ok = {
            "order_number": "ORD0007",
            "provider": 1,
            "provider_info": {
                "name": "Estafeta",
                "address": "Calle 12 entre 88 y 13A"
            },
            "product": 1,
            "product_info": {
                "code": "SN03345",
                "description": "Sony MDREX14APB Audífonos intrauditivos"
            },
            "client": 3,
            "client_info":
                {
                    "code": "GJ0001",
                    "name": "Gabriel Juarez",
                    "address": "Calle 22 entre 12 y 23",
                    "client_type": "ORO"
                },
            "order_date": "2020-10-30T05:11:30.362000Z",
            "deliver_date": None,
            "priority": False,
            "items": 2,
            "order_type": "SUCURSAL",
            "distribution_center_store": "",
            "store_reference": "Referencia sucursal",
            "store_code": "codigo del almacén",
            "company_reference": "",
            "company_member_code": "",
            "company_order_detail": ""
        }

        self.assertEqual(result, response_ok)

    def test_create_order_company(self):

        client = APIClient()

        test_order = {
            "order_number": "ORD0006",
            "provider": 2,
            "product": 3,
            "client": 2,
            "order_date": "2020-10-30T05:11:30.362Z",
            "priority": True,
            "items": 6,
            "order_type": "EMPRESA_ASOCIADA",
            "company_reference": "Ref. 12344",
            "company_member_code": "CO3345",
            "company_order_detail": "Descripción orden compañía"
        }

        response = client.post('/order/', test_order, format='json')
        result = json.loads(response.content)

        response_ok = {
            "order_number": "ORD0006",
            "provider": 2,
            "provider_info": {
                "name": "UPS",
                "address": "Calle 11 entre 79-C y 63"
            },
            "product": 3,
            "product_info": {
                "code": "PAN00012",
                "description": "Radio Panasonic RF-2400"
            },
            "client": 2,
            "client_info":
                {
                    "code": "LC0001",
                    "name": "Luis Castro",
                    "address": "Calle 41 entre 77 y 63A",
                    "client_type": "PLATINO"
                },
            "order_date": "2020-10-30T05:11:30.362000Z",
            "deliver_date": None,
            "priority": True,
            "items": 6,
            "order_type": "EMPRESA_ASOCIADA",
            "distribution_center_store": "",
            "store_reference": "",
            "store_code": "",
            "company_reference": "Ref. 12344",
            "company_member_code": "CO3345",
            "company_order_detail": "Descripción orden compañía"
        }

        self.assertEqual(result, response_ok)


import boto3
from botocore.exceptions import ClientError
import click
import json
import os

from deployer import deploy

INIT_CONTENT = '''{
  "FunctionName": "SomeFunctionName",
  "Description": "Some function description",
  "Handler": "handler.handle",
  "Timeout": 5,
  "MemorySize": 128,
  "Runtime": "python2.7",
  "Publish": true,
  "Role": "arn:? for the iam role",
  "KMSKeyArn": "arn:? that ecrypted the environment variables",
  "Environment": {
    "Variables": {
      "Key": "encrypted value"
      }
    },
  "DeadLetterConfig": {
    "TargetArn": "arn:? to SQS or SNS queue"
    }
}
'''

@click.group()
@click.version_option(version='0.1.0', message='%(prog)s %(version)s')
@click.option('--project-dir',
              help='The project directory.  Defaults to CWD')
@click.option('--debug/--no-debug',
              default=False,
              help='Print debug logs to stderr.')
@click.pass_context
def cli(ctx, project_dir, debug=False):
    if project_dir is None:
        project_dir = os.getcwd()
    ctx.obj['project_dir'] = project_dir
    ctx.obj['debug'] = debug
    os.chdir(project_dir)

@cli.command('init')
@click.pass_context
def init_command(ctx):
    project_dir = ctx.obj['project_dir']
    function_config_file = os.path.join(project_dir, 'function.json')
    if os.path.isfile(function_config_file):
        click.echo("function.json already exists!")
    else:
        with open(function_config_file, 'w') as f:
            f.write(INIT_CONTENT)
        click.echo("function.json created")

@cli.command('deploy')
@click.option('--config', help='Override default config file location')
@click.argument('config', nargs=1, required=False)
@click.pass_context
def deploy_command(ctx, config):
    project_dir = ctx.obj['project_dir']
    if config is None:
        config = 'function.json'

    click.echo("Reading configuration at " + config + "...")
    with open(os.path.join(project_dir, config), 'r') as c:
        config_content = json.loads(c.read())

    click.echo("Validating config...")
    # TODO: Validate the config
    click.echo("Config valid!")

    click.echo("Creating deployment package...")
    deployment_package_filename = deploy.create_deploy_artifact(project_dir)
    click.echo("Deployment package created!")

    click.echo("Checking for existing lambda function '" + config_content['FunctionName'] + "'...")
    lambda_client = boto3.client('lambda')
    try:
        existing_function = lambda_client.get_function(FunctionName=config_content['FunctionName'])
    except ClientError as e:
        if e.response['Error']['Code'] == 'ResourceNotFoundException':
            existing_function = None
        else:
            raise e

    if existing_function is None:
        click.echo("No existing function found, deploying new function...")
        deploy.deploy_new_function(config_content, deployment_package_filename)
    else:
        click.echo("Existing function found!")
        click.echo("Deploying...")
        deploy.deploy_existing_function(config_content, deployment_package_filename, existing_function)

def main():
    return cli(obj={})


#=================================
#     Author: MI SHAJIB
#=================================

import struct

# Sample packet in hex format
packet = b'450000280000400080060000c0a80101c0a80164'

# Convert packet to binary format
packetBinary = bytes.fromhex(packet.decode('utf-8'))

# Parse header fields
version = packetBinary[0] >> 4
headerLength = (packetBinary[0] & 0x0f) * 4
totalLength = struct.unpack('!H', packetBinary[2:4])[0]
protocol = packetBinary[9]
sourceIP = '.'.join(str(x) for x in packetBinary[12:16])
destinationIP = '.'.join(str(x) for x in packetBinary[16:20])

print('Version:', version)
print('Header length:', headerLength)
print('Total length:', totalLength)
print('Protocol:', protocol)
print('Source IP:', sourceIP)
print('Destination IP:', destinationIP)

# Parse data
dataOffset = headerLength
data = packetBinary[dataOffset:totalLength]

print('Data:', data.decode('utf-8'))


import sys
from collections import deque
sys.stdin = open('백준2056. 작업.txt', 'r')

def topological_sort():
    global N
    DP = time[:]
    queue = deque()
    for i in range(1, N+1):
        if not indegree[i]:
            queue.append(i)
    while queue:
        now = queue.popleft()
        for n in graph[now]:
            indegree[n] -= 1
            DP[n] = max(DP[n], time[n]+DP[now])
            if not indegree[n]:
                queue.append(n)
    return max(DP)

N = int(input())
indegree = [0] * (N+1)
time = [0] * (N+1)
graph = [[] for _ in range(N+1)]
for i in range(1, N+1):
    t, c, *li = map(int, input().split())
    for n in li:
        graph[n].append(i)
    indegree[i] += c
    time[i] = t
print(topological_sort())


#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
(re)Created on Thursday, 16 March 2023
Copyright (c) 2023 Phil Merricks
I am not affiliated with Codecks in any way
This script imports cards from a CSV file into Codecks
Codecks is a playfully simple project management tool for teams
https://codecks.io
Version 0.1
"""

import sys
import requests
import csv
import time
import json
import logging

# Set up logging
logging.basicConfig(filename='codecksimport.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')
logging.basicConfig(level=logging.DEBUG) # TODO: add logging output throughout the script

# Check if the correct number of arguments were passed to the script
if len(sys.argv) == 1:
    print("Usage: python <script_name> <access_token> <org> <csv_file> <deck_search>")
    print("       access_token: Your Codecks API access token")
    print("       org: Your Codecks organization name")
    print("       csv_file: The path to the CSV file containing the card data")
    print("       deck_search: The name of the deck to add cards to")
    print("Example: python codecksimport.py 1234567890abcdef mycompany cards.csv 'My Deck'")
    sys.exit()

# Set up the Codecks API endpoint and access token
api_endpoint = "https://api.codecks.io"
access_token = sys.argv[1]
account = sys.argv[2]
csvfile = sys.argv[3]
deck_search = sys.argv[4]

# Set up the headers for the API request
headers = {
    "X-Auth-Token": access_token,
    "X-Account": account,
    "Content-Type": "application/json",
}

# Set up the URL for creating a new card in Codecks
create_card_url = f"{api_endpoint}/dispatch/cards/create"

# Set up the URL for searching for a deck in Codecks
search_decks_url = api_endpoint

search_query = json.dumps({
  "query": {
    "_root": [
      {
        "account": [
          {"decks({\"title\":{\"op\":\"contains\",\"value\":\""+deck_search+"\"}})": ["title"]}
        ]
      }
    ]
  }
})

# Test the search query to make sure it's valid JSON
try:
    json.dumps(search_query)
except:
    print(f"Error: Invalid search query: {search_query}")
    exit()

# Send the API request to search for a deck in Codecks
response = requests.post(search_decks_url, headers=headers, data=search_query)

decksearch_response = response.json()
if response.status_code == 200:
    # If the deck key is not found, the search was unsuccessful
    if 'deck' not in decksearch_response:
        print(f"Error searching for deck name containing '{deck_search}'")
        print('This is likely due to no results being found, or an invalid search query')
        exit()
    decksearch_results = (decksearch_response['deck'])
    # count the number of decks found
    decksfound = len(decksearch_results)
    # If more than one result is returned, make a list of their names and ids
    if decksfound > 1:
        print(f"Found {decksfound} decks containing '{deck_search}'")
        print(f"Decks found:") # print the name and id of each deck found
        for k, v in decksearch_results.items():
            print(v['title'], v['id'])
        print(f"Be more specific to avoid adding cards to the wrong deck, or name the deck more uniquely in Codecks.")
        exit()
    # If only one result is returned, get the name and id
    else:
        k, v = next(iter(decksearch_results.items())) # get the first item in the dictionary
        decktitle = v['title'] # get the title of the deck
        deckid = v['id'] # get the ID of the deck
        print(f"Found deck '{decktitle}' with ID {deckid}")

else:
    print(f"Error searching for deck containing '{deck_search}': {response.text}")
    exit()

# Open the CSV file and read each line
with open(csvfile, "r") as csv_file:
    csv_reader = csv.reader(csv_file)
    # Count the number of lines in the CSV file
    numcards = sum(1 for line in csv_file)
    # Rewind the file so we can read it again
    csv_file.seek(0)
    #
    #  print number of cards to be created and ask for confirmation, allow escape to quit
    print(f"About to create {numcards} cards in deck '{decktitle}' with ID {deckid}")
    print("Press any key to continue, or press Ctrl+C to quit")
    input()
    for row in csv_reader:
        # Create the payload for the API request
        payload = {
            "addAsBookmark": False,
            # "assigneeId": "",
            # "attachments":[],
            # "childcards":[],
            "content": f"{row[0]}", # surround the card content in quotes to avoid issues with commas in the content
            "deckId": deckid,
            # "effort": "",
            # "fakeCoverFileId": "",
            # "inDeps":[],
            # "isDoc": False,
            # "masterTags":[],
            # "milestoneId": "",
            # "outDeps": [],
            # "priority": "",
            # "putInQueue": False,
            # "putOnHand": False,
            # "sessionId": "",
            # "subscribeCreator": False,
            # "userId": "",
            # Add any other fields you want to use as card attributes
        }
        # Test the payload to make sure it's valid JSON
        try:
            json.dumps(payload)
        except:
            print(f"Error: Invalid payload: {payload}")
            exit()

        # Send the API request to create a new card in Codecks
        response = requests.post(create_card_url, json=payload, headers=headers)

        # Check if the API request was successful
        print(response.status_code)
        if response.status_code == 200:
            print(f"Card '{payload['content']}' created successfully!")
        else:
            print(f"Error creating card '{payload['content']}': {response.text}")

        # Rate limit to <40 Requests every 5 seconds
        time.sleep(0.125)


import pika

from string import ascii_letters, digits, punctuation
from random import randint

MIN_CHALLENGE = 20
MAX_CHALLENGE = 40
HOSTNAME = "10.9.13.101"
NODEID = randint(0, (1 << 32) - 1)

PIKA_CREDENTIALS = pika.credentials.PlainCredentials("admin", "admin")
MANAGING_CONN = pika.BlockingConnection(
    pika.ConnectionParameters(host=HOSTNAME, heartbeat=600, credentials=PIKA_CREDENTIALS)
)
FOUR_CHAN = MANAGING_CONN.channel()
MANAGING_CHANN = FOUR_CHAN

SEED_ALPHABET = ascii_letters + digits + punctuation
ENCONDING = "utf-8"


import gc
import time
from machine import Pin, freq
from ir_rx.nec import NEC_16

addressButtons = {
    0x0000: {
        0x45: "1", 0x46: "2", 0x47: "3",
        0x44: "4", 0x40: "5", 0x43: "6",
        0x07: "7", 0x15: "8", 0x09: "9",
        0x16: "*", 0x19: "0", 0x0d: "#",
                   0x18: "^",
        0x08: "<", 0x1c: "OK",0x5a: ">",
                   0x52: "v"
    }}

p = Pin(16, Pin.IN)

def cb(data, addr, ctrl):
    if data >= 0:  # Ignore NEC repeat codes
        if addr in addressButtons:
            buttons = addressButtons[addr]
            if data in buttons:
                print("Received Button: {}".format(buttons[data]))
ir = NEC_16(p, cb)

while True:
    #print('running')
    time.sleep(5)
    gc.collect()


import os
import csv

def lector(archivo):
    excel = open(archivo, 'r')
    contador = 1
    dic = {'TOUCH BERNARDO O HIGGINSS 555LOCAL 5':[], 'TOUCH DENTRO DE SUPERM HIPERLIDER AV PAJARITOS 45007':[]}
    dinero_m = []
    dinero_b = []
    b, m = dic.keys()
    for linea in excel:
        if contador > 17:
            separado = linea.split(';')
            plata = separado[7]
            if len(dinero_b) == 0:
                dinero_b.append(separado[0][:10])
            if len(dinero_m) == 0:
                dinero_m.append(separado[0][:10])
            if separado[2] == b:
                dinero_b.append(plata)
            if separado[2] == m:
                dinero_m.append(plata)
            if separado[0][:10] != dinero_m or separado[0][:10] != dinero_b:
                dic[separado[2]].append(dinero_m)
                dinero_m = []
                dic[b].append(dinero_b)
                dinero_b = []
            """
            if separado [0][:10] != dinero_m[0] and separado[2] == m:
                dic[separado[2]].append(dinero_m)
                dinero_m = []
            elif separado [0][:10] != dinero_b[0] and separado[2] == b:
                dic[separado[2]].append(dinero_b)
                dinero_b = []"""
        contador += 1
    dic[m].append(dinero_m)
    dic[b].append(dinero_b)
    return dic
archivos = os.listdir()
for i in archivos:
    data = [['fecha', 'boletab', 'plata_b', 'boleta_m', 'plata_m']]
    if i[-3:] != '.py':
        dic = lector(i)
        b, m = dic.keys()
        if len(dic[b]) != len(dic[m]):
            cont = 0
            while len(dic[m])+2 != len(dic[b]):
                #
                # print(dic[b][cont][0], dic[m][cont][0])
                if dic[b][cont][0] != dic[m][cont][0]:
                    dic[m].insert(cont, [dic[b][cont][0]])
                else:
                    cont += 1
            dic[m].append([dic[b][cont+1][0]])
            dic[m].append([dic[b][cont+2][0]])
        n = 0
        while n <= len(dic[b])-1:
            suma_b = 0
            for x in dic[b][n][1:]:
                num = x.split('.')
                if len(num) > 1:
                    num = num[0] + num [1]
                else:
                    num = num[0]
                suma_b += int(num)
            suma_m = 0
            #print(dic[m][n])
            #print(len(dic[m][n]))
            if len(dic[m][n]) == 1:
                suma_m =0
            else:
                for x in dic[m][n][1:]:
                    num = x.split('.')
                    if len(num) > 1:
                        num = num[0] + num [1]
                    else:
                        num = num[0]
                    suma_m += int(num)
            data.append([dic[b][n][0], len(dic[b][n])-1, suma_b, len(dic[m][n])-1, suma_m])
            n += 1
        define = i[:-4] + '.csv'
        with open( define , 'w', newline='') as fila:
            writer = csv.writer(fila, delimiter=';')
            writer.writerows(data)


#others
def func(s):
    w = s[-2:]
    h = int(s[:2])
    T = None
    if w.lower() == "am":
        if h == 12:
            h = '00'
            T = h + s[2:-2]
        else:
            T = s[:-2]
    elif w.lower() == "pm":
        if h == 12:
            T = s[:-2]
        else:
            h = h + 12
            T = str(h) + s[2:-2]
    else:
        pass
    return T

if __name__ == '__main__':
    timeAPM = input().split(" ")
    T = func("".join(timeAPM))
    print(T)

"""
12:05:45 PM
"""

#self right
timeAPM = input().split(" ")
if timeAPM[1] == "AM":
    lis = timeAPM[0].split(":")
    if int(lis[0]) == 12:
        lis[0] = "00"
    print(":".join(lis))
elif timeAPM[1] == "PM":
    lis = timeAPM[0].split(":")
    if int(lis[0]) != 12:
        lis[0] = str((int(lis[0]) + 12)%24)
    print(":".join(lis))

"""
08:05:45 PM
"""

#self right
timeAPM = input().split(" ")
lis = timeAPM[0].split(":")
if int(lis[0]) == 12 and timeAPM[1] == "AM":
    lis[0] = "00"
elif int(lis[0]) != 12 and timeAPM[1] == "PM":
    lis[0] = str((int(lis[0]) + 12)%24)
print(":".join(lis))

"""
12:05:45 AM
"""


import sys

def count_active_neighbours(active, x, y, z, w, dw_min, dw_max):
    active_neighbours = 0
    for dx in range(-1, 2):
        for dy in range(-1, 2):
            for dz in range(-1, 2):
                for dw in range(dw_min, dw_max + 1):
                    if dx == dy == dz == dw == 0:
                        continue
                    active_neighbours += (x + dx, y + dy, z + dz, w + dw) in active
    return active_neighbours

def run_cycles(active, dw_min, dw_max):
    for _ in range(6):
        cycle_active = set()
        minx = miny = minz = minw = float('inf')
        maxx = maxy = maxz = maxw = float('-inf')
        for x, y, z, w in active:
            minx, maxx = min(minx, x), max(maxx, x)
            miny, maxy = min(miny, y), max(maxy, y)
            minz, maxz = min(minz, z), max(maxz, z)
            minw, maxw = min(minw, w), max(maxw, w)
        for x in range(minx - 1, maxx + 2):
            for y in range(miny - 1, maxy + 2):
                for z in range(minz - 1, maxz + 2):
                    for w in range(minw - 1, maxw + 2):
                        active_neighbours = count_active_neighbours(active, x, y, z, w, dw_min, dw_max)
                        if (x, y, z, w) in active and active_neighbours in (2, 3):
                            cycle_active.add((x, y, z, w))
                        if (x, y, z, w) not in active and active_neighbours == 3:
                            cycle_active.add((x, y, z, w))
        active = cycle_active
    return len(active)

assert len(sys.argv) == 2
lines = open(sys.argv[1]).read().splitlines()
active = {(x, y, 0, 0) for y, line in enumerate(lines) for x, state in enumerate(line) if state == '#'}

part1 = run_cycles(active, 0, 0)
part2 = run_cycles(active, -1, 1)

print(f'Part 1: {part1}, Part 2: {part2}')


from django import forms
from django.core.exceptions import ValidationError

from library.models import Course, SubTopic, Topic

class AddCourseForm(forms.ModelForm):
    class Meta:
        model = Course
        fields = (
            'name',
            'code',
        )

class AddTopicForm(forms.ModelForm):
    class Meta:
        model = Topic
        fields = (
            'course',
            'title',
            'prev',
        )
        widgets = {
            'course': forms.HiddenInput()
        }

    def clean(self):
        cleaned_data = super().clean()
        if cleaned_data['prev'] is None:
            try:
                Topic.objects.get(course=cleaned_data['course'], prev__isnull=True)
                raise ValidationError({'prev': 'A first topic already exists'})
            except Topic.DoesNotExist:
                pass

class AddSubTopicForm(forms.ModelForm):
    class Meta:
        model = SubTopic
        fields = (
            'topic',
            'title',
            'prev',
        )
        widgets = {
            'topic': forms.HiddenInput()
        }

    def clean(self):
        cleaned_data = super().clean()
        if cleaned_data['prev'] is None:
            try:
                SubTopic.objects.get(topic=cleaned_data['topic'], prev__isnull=True)
                raise ValidationError({'prev': 'A first sub-topic already exists'})
            except SubTopic.DoesNotExist:
                pass

class EditSubTopicInfoForm(AddSubTopicForm):
    class Meta:
        model = SubTopic
        fields = (
            'title',
        )

class EditSubTopicContentForm(forms.ModelForm):
    class Meta:
        model = SubTopic
        fields = (
            'temp_content',
        )


from django.conf.urls.defaults import *
from django.conf import settings
from csesoc.murder.views import *

# Uncomment the next two lines to enable the admin:

urlpatterns = patterns('',
      # URLs for murder applcation
      (r'^$', gamelist),
      (r'^(?P<game>[^/]*)/$', index),
      (r'^(?P<game>[^/]*)/scoreboard/$', scoreboard),
      (r'^(?P<game>[^/]*)/kills/$', newkills),
      (r'^(?P<game>[^/]*)/kills/(?P<roundid>\d+)/$', roundkills),
      (r'^(?P<game>[^/]*)/myvictim/$', myvictim),
)


import statsmodels.api as sm
from linearmodels.panel import PanelOLS

from ._prepare_data_and_direct_for_panel import _prepare_data_and_direct_for_panel
from .._check_assumps_after_analysis import check_assumps_after_analysis

def _run_fixed_effects(time_effect = False, **params):

	print ("Trying to _run_fixed_effects")

	data, directory = _prepare_data_and_direct_for_panel(time_effect,
														"FixedEffect",
														**params)

	log = params.get("log")

	exog = sm.add_constant(data.iloc[:, :-1])
	mod = PanelOLS(data.iloc[:, -1], exog,
					entity_effects = True,
					drop_absorbed=True,
					check_rank = False)
	pooled_res = mod.fit()

	res = pooled_res._resids.reshape(-1)

	report_str = "FixedEffect\n\n"
	report_str += pooled_res.__str__()

	log.info(report_str)

	check_assumps_after_analysis(data, res, directory, log)


import parser, re
class token_data:
  keywords = [
    "main",     # main
    "end",
    "print",    # terminal output
    "//",       # comment
    "stat",     # code statistics
    "const",    # create a constant variable
    "redest",   # redestribute resources
    "contort",  # clean the output logs in output.logs.rv
    "str",      # create string object
    "int",      # create integer object
    "bool",     # create boolean object
    "if",       # simple if statement
    "line-end", # system reserved
    "input",    # takes string input up to 100 characters
    "open",     # open a file (same syntax as C)
    "read",     # read from a file
    "close",    # close a file
    "supercoolfunction",     # does something
    "sq",        # square
    "amk"
  ]
  operators = [
    "{",        # used in functions
    "}"
  ]

  def peak_next_char(line,word,pos):
    line = line.split(" ")
    word = line[word]
    return word[pos]

class tokenizer:
  #for checking each node for integrity
  def stat_check(code):
    #put code into a list
    lines = code.readlines()
    print(len())
  def create_tokens(code):
    print("=== Starting token gen ===")
    #create an empty token list
    tokens = []
    #put code into a list
    lines = code.readlines()
    #god forbid me from touching a computer for using this method
    lines += "\n\n"
    #gen nodes based on presence
    f=0
    for i,token in enumerate(lines,start=0):
      f+=1
      #remove newlines from tokens and entries
      if "\n" in token:
        #print(token)
        newline=True
      token = token.rstrip()
      #parse a token
      if token.startswith(tuple(token_data.keywords)) or token.startswith(tuple(token_data.operators)):
        match  = set(token).intersection(set(token_data.keywords))
        a = re.search(r'\b('+str(match)+')\b', token)
        if a != None:
          token = token[a.start():]
        parse_data = parser.parse(token,True,None)
        #print("parsed",token,"data =",parse_data)
        #tokens.append([f,"line-end",None])
      else:
        parse_data = None
      #check for line-end
      if newline == True:
        tokens.append([f,"line-end",None])
        newline = False
      #create a 2d array for each token
      tokens.append([i,token,parse_data])
    #append new line for last entry
    tokens.append([f,"line-end",None])
    return tokens


from tkinter import *
from math import *

root = Tk()

miFrame = Frame(root)
miFrame.pack()

operacion = ""
# variable global para almacenar el signo dela operacion que se va a ejecutar
resultado = 0
signo_click = False

# -----------pantalla-----------------
numero = StringVar()
# variable cuyo valor va cambiando segun el numero que se pulse.

pantalla = Entry(miFrame, textvariable=numero)
pantalla.grid(column=0, row=1, padx="5", pady="5", columnspan=4)
pantalla.config(bg="black", fg="#95FFF2", justify="right")
# pantalla.insert(0, "0")

# -----------pantalla secundaria----------
numero2 = StringVar()
pantalla2 = Entry(miFrame, textvariable=numero2)
pantalla2.grid(column=0, columnspan=4, row=0)
pantalla2.config(fg="#95FFF2", bg="black", justify="right")
# para guardar el primer valor con el que se trabaja

# ----------funcion de redondeo------------------
# contador_click = 0

def redondeo():
    pass
# if contador_click == 0:
# numero.set(round(pantalla.get()))
# hay que poner un contador a partir de que se escriba el punto decimal
# con cada click de redondeo, redondeamos un decimal mas la cifra resultado
# ej:5,123 [1 click = 5,12] [2 click = 5,1] [3 click = 5]

# ---------------pulsaciones pantalla-------------
def numero_click(num):
    global operacion
    global signo_click

    if signo_click is True:
        numero.set(num)
        numero2.set(resultado)
        signo_click = False

    else:
        numero.set(pantalla.get() + num)

# ------------- suma --------------
def suma(num):
    global operacion
    global resultado
    global signo_click
    operacion = "suma"
    resultado += float(num)
    numero.set(resultado)
    # pantalla.delete(0, END), se puede borrar al pulsar 'mas' o al pulsar el siguiente numero...
    signo_click = True

# -----------resta -------------------
contador_resta = 0
num_resta = 0

def resta(num):
    global resultado
    global operacion
    global contador_resta
    global num_resta
    global signo_click
    operacion = "resta"
    num_resta = float(num)
    # num y pantalla.get() es lo mismo, usamos el que queramos

    if contador_resta == 0:
        resultado = num_resta

    else:
        resultado = resultado - num_resta

    contador_resta += 1
    # sin el contador, en la primera resta nos cambia el signo del primer numero que escribamos
    numero.set(resultado)
    signo_click = True

# --------funcion multiplicacion---------------
contador_mult = 0

def multiplicar(num):
    global resultado
    global signo_click
    global contador_mult
    global operacion
    operacion = "multiplicacion"

    if contador_mult == 0:
        resultado = float(num)
        # hay que poner exceocion de primera vez sino nos estaria multiplicando por 0 simpre que multipliquemos

    else:
        resultado *= float(num)

    numero.set(resultado)

    contador_mult += 1
    signo_click = True

# ---------funcion division--------------
contador_div = 0

def division(num):
    global resultado
    global operacion
    global signo_click
    global contador_div
    operacion = "division"

    if contador_div == 0:
        resultado = float(num)

    else:
        resultado = resultado / float(num)

    contador_div += 1
    numero.set(resultado)
    signo_click = True

# --------funcion raiz cuadrada-----------
def raiz_2():
    numero.set(sqrt(float(pantalla.get())))

# ---------funcion exponente--------------
contador_expo = 0

def exponente(num):
    global resultado
    global operacion
    global signo_click
    global contador_expo
    operacion = "exponente"

    if contador_expo == 0:
        resultado = float(num)

    else:
        resultado = resultado ** float(num)

    numero.set(resultado)
    contador_expo += 1
    signo_click = True

# --------funcion resultado---------------
def el_resultado():
    global resultado
    global operacion
    global contador_resta
    global contador_mult
    global contador_div
    global contador_expo

    # necesitamos un contador para cada operacion porque la primera vez que ejecutamos cada una tenemos conflicto
    # menos para la suma que es la mas sencilla de todas y el 0 incial no le influye

    if operacion == "suma":
        numero.set(resultado + float(pantalla.get()))
        resultado = 0

    else:
        pass

    if operacion == "resta":
        numero.set(resultado - float(pantalla.get()))
        resultado = 0
        contador_resta = 0

    else:
        pass

    if operacion == "multiplicacion":
        numero.set(resultado * float(pantalla.get()))
        resultado = 0
        contador_mult = 0

    else:
        pass

    if operacion == "division":
        numero.set(resultado / float(pantalla.get()))
        resultado = 0
        contador_div = 0
    else:
        pass

    if operacion == "exponente":
        numero.set(resultado ** float(pantalla.get()))
        resultado = 0
        contador_expo = 0
    else:
        pass

# ------------funcion borrado---------------
def borrado():
    global resultado
    pantalla.delete(0, END)
    resultado = 0

# -----------Funcion borrado caracter ----------
def borrado_caracter():
    pantalla.delete(len(pantalla.get()) - 1, END)
    # para borrar solamente el ultimo digito escrito en pantalla

# ------------Fila 0 de botones--------------
boton_round = Button(miFrame, text="Round", width=5, command=redondeo)
boton_round.grid(column=4, row=0)

# ------------Fila 1 de botones -------------
boton_del = Button(miFrame, text="DEL", width=5, command=borrado_caracter)
boton_del.grid(column=4, row=1)

# -----------Fila 2 de botones-------------
boton7 = Button(miFrame, text="7", width="5", command=lambda: numero_click("7"))
# sin la funcion lambda el programa almacena el valor antes de que pulsemos el boton
boton7.grid(column="0", row=2)
boton8 = Button(miFrame, text="8", width="5", command=lambda: numero_click("8"))
boton8.grid(column="1", row=2)
boton9 = Button(miFrame, text="9", width="5", command=lambda: numero_click("9"))
boton9.grid(column="2", row=2)
boton_div = Button(miFrame, text="/", width="5", command=lambda: division(pantalla.get()))
boton_div.grid(column="3", row=2)
boton_raiz = Button(miFrame, text="√", width="5", command=raiz_2)
boton_raiz.grid(column=4, row=2)

# -----------Fila 3 de botones-------------
boton4 = Button(miFrame, text="4", width="5", command=lambda: numero_click("4"))
boton4.grid(column="0", row=3)
boton5 = Button(miFrame, text="5", width="5", command=lambda: numero_click("5"))
boton5.grid(column="1", row=3)
boton6 = Button(miFrame, text="6", width="5", command=lambda: numero_click("6"))
boton6.grid(column="2", row=3)
boton_mult = Button(miFrame, text="x", width="5", command=lambda: multiplicar(pantalla.get()))
boton_mult.grid(column=3, row=3)
boton_expo2 = Button(miFrame, text="^", width="5", command=lambda: exponente(pantalla.get()))
boton_expo2.grid(column=4, row=3)

# -----------Fila 4 de botones-------------
boton1 = Button(miFrame, text="1", width="5", command=lambda: numero_click("1"))
boton1.grid(column="0", row=4)
boton2 = Button(miFrame, text="2", width="5", command=lambda: numero_click("2"))
boton2.grid(column="1", row=4)
boton3 = Button(miFrame, text="3", width="5", command=lambda: numero_click("3"))
boton3.grid(column="2", row=4)
boton_resta = Button(miFrame, text="-", width="5", command=lambda: resta(pantalla.get()))
boton_resta.grid(column=3, row=4)
boton_C = Button(miFrame, text="C", width="5", command=borrado)
boton_C.grid(column=4, row=4)

# -----------Fila 5 de botones-------------
boton_coma = Button(miFrame, text=".", width="5", command=lambda: numero_click("."))
boton_coma.grid(column="0", row=5)
boton0 = Button(miFrame, text="0", width="5", command=lambda: numero_click("0"))
boton0.grid(column="1", row=5)
boton_suma = Button(miFrame, text="+", width="5", command=lambda: suma(pantalla.get()))
boton_suma.grid(column="2", row=5)
boton_igual = Button(miFrame, text="=", width="12", command=el_resultado)
boton_igual.grid(column=3, row=5, columnspan=4)

# ----------Fila 6 de botones -------------
# ideas de botones extra: boton de redondeo, boton de elevado a, botones de parentesis para operar...
# depurar la raiz cuadrada, para que me ponga en el simbolo en pantalla y no la haga hasta pulsar el igual
mainloop()


import pyodbc
#
conn = pyodbc.connect(r'Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Users\richard.henry\Documents\filev.accdb;')
cursor = conn.cursor()
cursor.execute(
'''select
Upd_File,
TK_File,
TK_Base_Path
from filev''')

for row in cursor.fetchall():
    print (row[2],'\t',row[0], '\t',row[1])


# Importing modules
import pandas as pd
import os
import re
from collections import defaultdict
import csv
from sklearn.feature_extraction.text import CountVectorizer
import numpy as np
import matplotlib.pyplot as plt
import seaborn as sns
sns.set_style('whitegrid')
from pyLDAvis import sklearn as sklearn_lda
import pyLDAvis
import pickle
import numpy as np
from wordcloud import WordCloud
import matplotlib.pyplot as plt

import ea_decode

def makeImage(text_dict, output_dir, filename):

    x, y = np.ogrid[:300, :300]
    mask = (x - 150) ** 2 + (y - 150) ** 2 > 130 ** 2
    mask = 255 * mask.astype(int)

    wc = WordCloud(background_color="white", max_words=1000, mask=mask)
    # generate word cloud
    wc.generate_from_frequencies(text_dict)

    # show
    plt.imshow(wc, interpolation="bilinear")
    plt.axis("off")

    if output_dir == '':
        plt.show()
    else:
        plt.savefig(os.path.join(output_dir, filename))
        plt.close()

def transform_to_nlp(df_app):

    flatten_text_dict = defaultdict()
    for index, row in df_app.iterrows():
        flatten_text = ''
        for colname in df_app.columns:
            if (row[colname] > 0):
                if index in flatten_text_dict:
                    flatten_text_dict[index] = flatten_text_dict[index] + (' ' + re.sub('[\s|\-|\/]+', '_', colname))*int(row[colname])
                else:
                    flatten_text_dict[index] = (' ' + re.sub('[\s|\-|\/]+', '_', colname)) * int(row[colname])

    df_dict = pd.DataFrame.from_dict(flatten_text_dict, orient='index')
    df_dict.set_axis(['Words'], axis=1, inplace=True)
    df_tmp = df_app.join(df_dict, how='inner', rsuffix='_IN').fillna(0)

    return df_tmp

# Helper function
def plot_most_common_words(count_data, count_vectorizer, top_nbr):
    import matplotlib.pyplot as plt
    words = count_vectorizer.get_feature_names()
    total_counts = np.zeros(len(words))
    for t in count_data:
        total_counts += t.toarray()[0]

    count_dict = (zip(words, total_counts))
    count_dict = sorted(count_dict, key=lambda x: x[1], reverse=True)[0:top_nbr]
    words = [w[0] for w in count_dict]
    counts = [w[1] for w in count_dict]
    x_pos = np.arange(len(words))

    plt.figure(2, figsize=(15, 15 / 1.6180))
    plt.subplot(title='{} {}'.format(top_nbr,' most common words'))
    sns.set_context("notebook", font_scale=1.25, rc={"lines.linewidth": 2.5})
    sns.barplot(x_pos, counts, palette='husl')
    plt.xticks(x_pos, words, rotation=90)
    plt.xlabel('words')
    plt.ylabel('counts')
    plt.show()

def fit_ea_lda(df_app, output_dir, options):
    # Helper function
    def print_topics(model, count_vectorizer, n_top_words):
        words = count_vectorizer.get_feature_names()
        for topic_idx, topic in enumerate(model.components_):
            print("\nTopic #%d:" % topic_idx)
            print(" ".join([words[i]
                        for i in topic.argsort()[:-n_top_words - 1:-1]]))

    df_app_tmp = df_app.copy()
    df_app_tmp.drop('ANNOTATE', axis=1, inplace=True)
    if options['CLASS'] != '':
        df_app_tmp.drop('CLASS', axis=1, inplace=True)

    df_app_words = transform_to_nlp(df_app_tmp)
    makeImage(df_app_tmp.sum(), output_dir, ea_decode.options_filename(options) + '_' + 'WC')
    # Initialise the count vectorizer with the English stop words
    count_vectorizer = CountVectorizer(stop_words='english')
    # Fit and transform the processed titles
    count_data = count_vectorizer.fit_transform(df_app_words['Words'])

    #plot_most_common_words(count_data, count_vectorizer, 15)

    # Load the LDA model from sk-learn
    from sklearn.decomposition import LatentDirichletAllocation as LDA
    # Tweak the two parameters below
    number_topics = 10
    number_words = 20
    # Create and fit the LDA model
    lda = LDA(n_components=number_topics, n_jobs=-1)
    lda.fit(count_data)
    # Print the topics found by the LDA model
    print("Topics found via LDA:")
    print_topics(lda, count_vectorizer, number_words)

    file_out = ea_decode.options_filename(options) + '_' + 'LDA_VIS' + '_' + str(number_topics)
    LDAvis_data_filepath = os.path.join(output_dir, file_out)
    # # this is a bit time consuming - make the if statement True
    # # if you want to execute visualization prep yourself
    if 1 == 1:
        LDAvis_prepared = sklearn_lda.prepare(lda, count_data, count_vectorizer)
    with open(LDAvis_data_filepath, 'wb') as f:
        pickle.dump(LDAvis_prepared, f)

    # load the pre-prepared pyLDAvis data from disk
    with open(LDAvis_data_filepath, 'rb') as f:
        LDAvis_prepared = pickle.load(f)
    pyLDAvis.save_html(LDAvis_prepared, os.path.join(output_dir, file_out + '.html'))


import numpy as np
import pprint

def main():
    X = [1]
    with open("./day10/input.txt") as input:
        lines = [line.replace("\n", "") for line in input.readlines()]
        for line in lines:
            currX = X[-1] if len(X) > 0 else 1
            if line.startswith("noop"):
                X.append(currX)
            elif line.startswith("addx"):
                _, numb = line.split(" ")
                numb = int(numb)
                X.append(currX)
                X.append(X[-1] + numb)

            if 210 < len(X) < 222:
                print(len(X), line, X[-1])

    # strength_sum = 0
    sprite_pos = []
    draw_pos = []
    result = []
    i = 0
    for x in X:

        #sprite pos is x
        #draw pos is i
        if x == i or (x-1) == i or (x+1) == i:
            result.append("#")
        else:
            result.append(".")

        i +=1
        if len(result) == 40:
            print("".join(result[:40]))
            result = []
            i = 0

if __name__ == "__main__":
    main()


import random

cards = [11, 2, 3, 4, 5, 6, 7, 8, 9, 'K', 'J', 'Q', 10]

card_points = {
    'K': 10,
    'J': 10,
    'Q': 10,
}

def deal_cards_for_computer(cards):
    score = sum(cards)
    while True:
        if score < 17:
            current_card = draw_random_cards(1)
            cards.append(current_card[0])
            score = calculate_score(cards)
        else:
            return cards

def draw_random_cards(times):
    result = []
    for i in range(times):
        random_card = random.choice(cards)
        if type(random_card) == str:
            result.append(card_points[random_card])
        else:
            result.append(random_card)
    return result

def calculate_score(cards):
    score = sum(cards)
    if score == 21:
        return 0

    if score > 21:
        if cards[-1] == 11:
            cards.remove(11)
            cards.append(1)
            score = sum(cards)
        return score

    return score

def has_blackjack(score):
    if score == 0:
        return True

def is_score_over_21(score):
    if score > 21:
        return True

def check_score(player_score, computer_score):
    if player_score == computer_score:
        return 'It\'s a draw'
    if player_score == 0:
        return 'Win with a Blackjack'
    if computer_score == 0:
        return 'Lose, opponent has Blackjack'
    if player_score > 21:
        return 'You went over. You lose.'
    if computer_score > 21:
        return 'Opponent went over. You win.'
    if player_score > computer_score:
        return 'You win.'
    if computer_score > player_score:
        return 'You lose.'

flag = False
while True:
    starting_confirmation = input("Do you want to play a game of Blackjack? Type 'y' or 'n': ")
    if flag:
        break
    if starting_confirmation == 'y':
        """
        clear console output
        print(logo)
        """
        player_cards = draw_random_cards(2)
        computer_cards = draw_random_cards(2)
        player_score = calculate_score(player_cards)
        computer_score = calculate_score(computer_cards)
        print(f"    Your cards: {player_cards}, current score: {player_score}")
        print(f"    Computer's first card: {computer_cards[0]}")

        if player_score == 0 or computer_score == 0:
            print(f"    Your final hand: {player_cards}, final score: {player_score}")
            print(f"    Computer's final hand: {computer_cards}, final score: {computer_score}")
            print(check_score(player_score, computer_score))
            continue

        while True:
            get_another_card_conf = input("Type 'y' to get another card, type 'n' to pass: ")
            if get_another_card_conf == 'y':
                current_card = draw_random_cards(1)
                player_cards.append(current_card[0])
                player_score = calculate_score(player_cards)
                print(f"    Your cards: {player_cards}, current score: {player_score}")
                print(f"    Computer's first card: {computer_cards[0]}")
                if is_score_over_21(player_score):
                    print(check_score(player_score, computer_score))
                    break
            else:
                computer_cards = deal_cards_for_computer(computer_cards)
                player_score = calculate_score(player_cards)
                computer_score = calculate_score(computer_cards)
                print(f"    Your final hand: {player_cards}, final score: {player_score}")
                print(f"    Computer's final hand: {computer_cards}, final score: {computer_score}")
                print(check_score(player_score, computer_score))
                # flag = True
                break

    else:
        break


# -*- coding: utf-8 -*-
#author: Bryan Bishop <kanzure@gmail.com>
#date: 2012-01-02
#purpose: dump asm for each map header
from __future__ import print_function
from __future__ import absolute_import
import json
from . import extract_maps
from . import sprite_helper
import random
import string
from . import analyze_texts #hopefully not a dependency loop

base = 16
spacing = "	"
all_texts = None

#map constants
map_constants = [
["PALLET_TOWN", 0x00],
["VIRIDIAN_CITY", 0x01],
["PEWTER_CITY", 0x02],
["CERULEAN_CITY", 0x03],
["LAVENDER_TOWN", 0x04],
["VERMILION_CITY", 0x05],
["CELADON_CITY", 0x06],
["FUCHSIA_CITY", 0x07],
["CINNABAR_ISLAND", 0x08],
["INDIGO_PLATEAU", 0x09],
["SAFFRON_CITY", 0x0A],
["ROUTE_1", 0x0C],
["ROUTE_2", 0x0D],
["ROUTE_3", 0x0E],
["ROUTE_4", 0x0F],
["ROUTE_5", 0x10],
["ROUTE_6", 0x11],
["ROUTE_7", 0x12],
["ROUTE_8", 0x13],
["ROUTE_9", 0x14],
["ROUTE_10", 0x15],
["ROUTE_11", 0x16],
["ROUTE_12", 0x17],
["ROUTE_13", 0x18],
["ROUTE_14", 0x19],
["ROUTE_15", 0x1A],
["ROUTE_16", 0x1B],
["ROUTE_17", 0x1C],
["ROUTE_18", 0x1D],
["ROUTE_19", 0x1E],
["ROUTE_20", 0x1F],
["ROUTE_21", 0x20],
["ROUTE_22", 0x21],
["ROUTE_23", 0x22],
["ROUTE_24", 0x23],
["ROUTE_25", 0x24],
["REDS_HOUSE_1F", 0x25],
["REDS_HOUSE_2F", 0x26],
["BLUES_HOUSE", 0x27],
["OAKS_LAB", 0x28],
["VIRIDIAN_POKECENTER", 0x29],
["VIRIDIAN_MART", 0x2A],
["VIRIDIAN_SCHOOL", 0x2B],
["VIRIDIAN_HOUSE", 0x2C],
["VIRIDIAN_GYM", 0x2D],
["DIGLETTS_CAVE_EXIT", 0x2E],
["VIRIDIAN_FOREST_EXIT", 0x2F],
["ROUTE_2_HOUSE", 0x30],
["ROUTE_2_GATE", 0x31],
["VIRIDIAN_FOREST_ENTRANCE", 0x32],
["VIRIDIAN_FOREST", 0x33],
["MUSEUM_1F", 0x34],
["MUSEUM_2F", 0x35],
["PEWTER_GYM", 0x36],
["PEWTER_HOUSE_1", 0x37],
["PEWTER_MART", 0x38],
["PEWTER_HOUSE_2", 0x39],
["PEWTER_POKECENTER", 0x3A],
["MT_MOON_1", 0x3B],
["MT_MOON_2", 0x3C],
["MT_MOON_3", 0x3D],
["TRASHED_HOUSE", 0x3E],
["CERULEAN_HOUSE", 0x3F],
["CERULEAN_POKECENTER", 0x40],
["CERULEAN_GYM", 0x41],
["BIKE_SHOP", 0x42],
["CERULEAN_MART", 0x43],
["MT_MOON_POKECENTER", 0x44],
["ROUTE_5_GATE", 0x46],
["PATH_ENTRANCE_ROUTE_5", 0x47],
["DAYCAREM", 0x48],
["ROUTE_6_GATE", 0x49],
["PATH_ENTRANCE_ROUTE_6", 0x4A],
["ROUTE_7_GATE", 0x4C],
["PATH_ENTRANCE_ROUTE_7", 0x4D],
["ROUTE_8_GATE", 0x4F],
["PATH_ENTRANCE_ROUTE_8", 0x50],
["ROCK_TUNNEL_POKECENTER", 0x51],
["ROCK_TUNNEL_1", 0x52],
["POWER_PLANT", 0x53],
["ROUTE_11_GATE_1F", 0x54],
["DIGLETTS_CAVE_ENTRANCE", 0x55],
["ROUTE_11_GATE_2F", 0x56],
["ROUTE_12_GATE", 0x57],
["BILLS_HOUSE", 0x58],
["VERMILION_POKECENTER", 0x59],
["POKEMON_FAN_CLUB", 0x5A],
["VERMILION_MART", 0x5B],
["VERMILION_GYM", 0x5C],
["VERMILION_HOUSE_1", 0x5D],
["VERMILION_DOCK", 0x5E],
["SS_ANNE_1", 0x5F],
["SS_ANNE_2", 0x60],
["SS_ANNE_3", 0x61],
["SS_ANNE_4", 0x62],
["SS_ANNE_5", 0x63],
["SS_ANNE_6", 0x64],
["SS_ANNE_7", 0x65],
["SS_ANNE_8", 0x66],
["SS_ANNE_9", 0x67],
["SS_ANNE_10", 0x68],
["VICTORY_ROAD_1", 0x6C],
["LANCES_ROOM", 0x71],
["HALL_OF_FAME", 0x76],
["UNDERGROUND_PATH_NS", 0x77],
["CHAMPIONS_ROOM", 0x78],
["UNDERGROUND_PATH_WE", 0x79],
["CELADON_MART_1", 0x7A],
["CELADON_MART_2", 0x7B],
["CELADON_MART_3", 0x7C],
["CELADON_MART_4", 0x7D],
["CELADON_MART_5", 0x7E],
["CELADON_MART_6", 0x7F],
["CELADON_MANSION_1", 0x80],
["CELADON_MANSION_2", 0x81],
["CELADON_MANSION_3", 0x82],
["CELADON_MANSION_4", 0x83],
["CELADON_MANSION_5", 0x84],
["CELADON_POKECENTER", 0x85],
["CELADON_GYM", 0x86],
["GAME_CORNER", 0x87],
["CELADON_HOUSE", 0x88],
["CELADONPRIZE_ROOM", 0x89],
["CELADON_DINER", 0x8A],
["CELADON_HOUSE_2", 0x8B],
["CELADONHOTEL", 0x8C],
["LAVENDER_POKECENTER", 0x8D],
["POKEMONTOWER_1", 0x8E],
["POKEMONTOWER_2", 0x8F],
["POKEMONTOWER_3", 0x90],
["POKEMONTOWER_4", 0x91],
["POKEMONTOWER_5", 0x92],
["POKEMONTOWER_6", 0x93],
["POKEMONTOWER_7", 0x94],
["LAVENDER_HOUSE_1", 0x95],
["LAVENDER_MART", 0x96],
["LAVENDER_HOUSE_2", 0x97],
["FUCHSIA_MART", 0x98],
["FUCHSIA_HOUSE_1", 0x99],
["FUCHSIA_POKECENTER", 0x9A],
["FUCHSIA_HOUSE_2", 0x9B],
["SAFARIZONEENTRANCE", 0x9C],
["FUCHSIA_GYM", 0x9D],
["FUCHSIAMEETINGROOM", 0x9E],
["SEAFOAM_ISLANDS_2", 0x9F],
["SEAFOAM_ISLANDS_3", 0xA0],
["SEAFOAM_ISLANDS_4", 0xA1],
["SEAFOAM_ISLANDS_5", 0xA2],
["VERMILION_HOUSE_2", 0xA3],
["FUCHSIA_HOUSE_3", 0xA4],
["MANSION_1", 0xA5],
["CINNABAR_GYM", 0xA6],
["CINNABAR_LAB_1", 0xA7],
["CINNABAR_LAB_2", 0xA8],
["CINNABAR_LAB_3", 0xA9],
["CINNABAR_LAB_4", 0xAA],
["CINNABAR_POKECENTER", 0xAB],
["CINNABAR_MART", 0xAC],
["INDIGO_PLATEAU_LOBBY", 0xAE],
["COPYCATS_HOUSE_1F", 0xAF],
["COPYCATS_HOUSE_2F", 0xB0],
["FIGHTINGDOJO", 0xB1],
["SAFFRON_GYM", 0xB2],
["SAFFRON_HOUSE_1", 0xB3],
["SAFFRON_MART", 0xB4],
["SILPH_CO_1F", 0xB5],
["SAFFRON_POKECENTER", 0xB6],
["SAFFRON_HOUSE_2", 0xB7],
["ROUTE_15_GATE", 0xB8],
["ROUTE_16_GATE_1F", 0xBA],
["ROUTE_16_GATE_2F", 0xBB],
["ROUTE_16_HOUSE", 0xBC],
["ROUTE_12_HOUSE", 0xBD],
["ROUTE_18_GATE_1F", 0xBE],
["ROUTE_18_GATE_2F", 0xBF],
["SEAFOAM_ISLANDS_1", 0xC0],
["ROUTE_22_GATE", 0xC1],
["VICTORY_ROAD_2", 0xC2],
["ROUTE_12_GATE_2F", 0xC3],
["VERMILION_HOUSE_3", 0xC4],
["DIGLETTS_CAVE", 0xC5],
["VICTORY_ROAD_3", 0xC6],
["ROCKET_HIDEOUT_1", 0xC7],
["ROCKET_HIDEOUT_2", 0xC8],
["ROCKET_HIDEOUT_3", 0xC9],
["ROCKET_HIDEOUT_4", 0xCA],
["ROCKET_HIDEOUT_ELEVATOR", 0xCB],
["SILPH_CO_2F", 0xCF],
["SILPH_CO_3F", 0xD0],
["SILPH_CO_4F", 0xD1],
["SILPH_CO_5F", 0xD2],
["SILPH_CO_6F", 0xD3],
["SILPH_CO_7F", 0xD4],
["SILPH_CO_8F", 0xD5],
["MANSION_2", 0xD6],
["MANSION_3", 0xD7],
["MANSION_4", 0xD8],
["SAFARI_ZONE_EAST", 0xD9],
["SAFARI_ZONE_NORTH", 0xDA],
["SAFARI_ZONE_WEST", 0xDB],
["SAFARI_ZONE_CENTER", 0xDC],
["SAFARI_ZONE_REST_HOUSE_1", 0xDD],
["SAFARI_ZONE_SECRET_HOUSE", 0xDE],
["SAFARI_ZONE_REST_HOUSE_2", 0xDF],
["SAFARI_ZONE_REST_HOUSE_3", 0xE0],
["SAFARI_ZONE_REST_HOUSE_4", 0xE1],
["UNKNOWN_DUNGEON_2", 0xE2],
["UNKNOWN_DUNGEON_3", 0xE3],
["UNKNOWN_DUNGEON_1", 0xE4],
["NAME_RATERS_HOUSE", 0xE5],
["CERULEAN_HOUSE_3", 0xE6],
["ROCK_TUNNEL_2", 0xE8],
["SILPH_CO_9F", 0xE9],
["SILPH_CO_10F", 0xEA],
["SILPH_CO_11F", 0xEB],
["SILPH_CO_ELEVATOR", 0xEC],
["BATTLE_CENTER", 0xEF],
["TRADE_CENTER", 0xF0],
["LORELEIS_ROOM", 0xF5],
["BRUNOS_ROOM", 0xF6],
["AGATHAS_ROOM", 0xF7],
["BEACH_HOUSE", 0xF8]]

#i prefer a different data structure
temp = {}
for constant in map_constants:
    value = constant[1]
    name = constant[0]
    temp[value] = name
map_constants = temp
del temp

#these appear outside of quotes
constant_abbreviation_bytes = {
}

#these appear in quotes
char_conversion = [
(" ", 0x7F),
("A", 0x80),
("B", 0x81),
("C", 0x82),
("D", 0x83),
("E", 0x84),
("F", 0x85),
("G", 0x86),
("H", 0x87),
("I", 0x88),
("J", 0x89),
("K", 0x8A),
("L", 0x8B),
("M", 0x8C),
("N", 0x8D),
("O", 0x8E),
("P", 0x8F),
("Q", 0x90),
("R", 0x91),
("S", 0x92),
("T", 0x93),
("U", 0x94),
("V", 0x95),
("W", 0x96),
("X", 0x97),
("Y", 0x98),
("Z", 0x99),
("(", 0x9A),
(")", 0x9B),
(":", 0x9C),
(";", 0x9D),
("[", 0x9E),
("]", 0x9F),
("a", 0xA0),
("b", 0xA1),
("c", 0xA2),
("d", 0xA3),
("e", 0xA4),
("f", 0xA5),
("g", 0xA6),
("h", 0xA7),
("i", 0xA8),
("j", 0xA9),
("k", 0xAA),
("l", 0xAB),
("m", 0xAC),
("n", 0xAD),
("o", 0xAE),
("p", 0xAF),
("q", 0xB0),
("r", 0xB1),
("s", 0xB2),
("t", 0xB3),
("u", 0xB4),
("v", 0xB5),
("w", 0xB6),
("x", 0xB7),
("y", 0xB8),
("z", 0xB9),
("é", 0xBA),
("'d", 0xBB),
("'l", 0xBC),
("'s", 0xBD),
("'t", 0xBE),
("'v", 0xBF),
("'", 0xE0),
("-", 0xE3),
("'r", 0xE4),
("'m", 0xE5),
("?", 0xE6),
("!", 0xE7),
(".", 0xE8),
("♂", 0xEF),
#("¥", 0xF0),
("/", 0xF3),
(",", 0xF4),
("♀", 0xF5),
("0", 0xF6),
("1", 0xF7),
("2", 0xF8),
("3", 0xF9),
("4", 0xFA),
("5", 0xFB),
("6", 0xFC),
("7", 0xFD),
("8", 0xFE),
("9", 0xFF)]
#these appear in quotes
txt_bytes = {
    0x50: "@",
    0x54: "#",
    0x75: "…",
}
for item in char_conversion:
    txt_bytes[item[1]] = item[0]
del char_conversion

#this was originally for renaming freeze maps for a unique name
def random_hash():
    available_chars = string.hexdigits[:16]
    return ''.join(
        random.choice(available_chars)
        for dummy in xrange(5))

def offset_to_pointer(offset):
    if type(offset) == str: offset = int(offset, base)
    return int(offset) % 0x4000 + 0x4000

def map_name_cleaner(name, id):
    "names have to be acceptable asm labels"

    #duck out early
    if name == "FREEZE":
        #name += "_" + random_hash() + "_h"
        name += "_" + str(id) + "_h"
        return name

    #the long haul
    name = name.replace(":", "")
    name = name.replace("(", "")
    name = name.replace(")", "")
    name = name.replace("'", "")
    name = name.replace("/", "") #N/S -> NS, W/E -> WE
    name = name.replace(".", "") #S.S. -> SS, Mt. -> Mt
    name = name.replace(" ", "") #or '_' ??
    name = name + "_h"

    return name

def write_connections(north, south, west, east):
    #north 0, south 1, west 2, east 3
    if north and south and west and east: return "NORTH | SOUTH | WEST | EAST"
    if north and south and west and not east: return "NORTH | SOUTH | WEST"
    if north and south and not west and east: return "NORTH | SOUTH | EAST"
    if north and not south and west and east: return "NORTH | WEST | EAST"
    if not north and south and west and east: return "SOUTH | WEST | EAST"
    if north and south and not west and not east: return "NORTH | SOUTH"
    if not north and not south and west and east: return "WEST | EAST"
    if not north and south and west and not east: return "SOUTH | WEST"
    if not north and south and not west and east: return "SOUTH | EAST"
    if north and not south and west and not east: return "NORTH | WEST"
    if north and not south and not west and east: return "NORTH | EAST"
    raise Exception("unpredicted outcome on write_connections")

#TODO: make this elegant
def connection_line(byte):
    if type(byte) == str:
        byte = int(byte, base)

    connections = 0
    north, south, west, east = False, False, False, False

    temp = bin(byte)[2:]

    if len(temp) == 1:
        if temp[0] == "1": #EAST
            east = True
    elif len(temp) == 2:
        if temp[0] == "1": #WEST
            west = True
        if temp[1] == "1": #EAST
            east = True
    elif len(temp) == 3:
        if temp[0] == "1": #SOUTH
            south = True
        if temp[1] == "1": #WEST
            west = True
        if temp[2] == "1": #EAST
            east = True
    elif len(temp) == 4:
        if temp[0] == "1": #NORTH
            north = True
        if temp[1] == "1": #SOUTH
            south = True
        if temp[2] == "1": #WEST
            west = True
        if temp[3] == "1": #EAST
            east = True

    if north: connections += 1
    if south: connections += 1
    if west: connections += 1
    if east: connections += 1

    #i don't have time to optimize this
    if connections == 0:
        return "$00"
    if connections == 1:
        if north: return "NORTH"
        if south: return "SOUTH"
        if west: return "WEST"
        if east: return "EAST"
    if connections >= 2:
        return write_connections(north, south, west, east)

def connection_pretty_printer(connections):
#map_id, connected_map_tile_pointer, current_map_tile_pointer, bigness, width, y, x, window_pointer
    output = ""

    for connection in connections.keys():
        connection = connections[connection]
        map_id = hex(connection["map_id"])[2:].zfill(2)
        connected_map_tile_pointer = connection["connected_map_tile_pointer"][2:]
        current_map_tile_pointer = connection["current_map_tile_pointer"][2:]
        bigness = hex(int(connection["bigness"], base))[2:].zfill(2)
        width = hex(int(connection["width"], base))[2:].zfill(2)
        y = hex(connection["y"])[2:].zfill(2)
        x = hex(connection["x"])[2:].zfill(2)
        window_pointer = connection["window_pointer"][2:]

        output += spacing + "db $" + map_id + " ; some map\n"
        output += spacing + "dw $" + connected_map_tile_pointer + ", $" + current_map_tile_pointer + " ; pointers (connected, current) (strip)\n"
        output += spacing + "db $" + bigness + ", $" + width + " ; bigness, width\n"
        output += spacing + "db $" + y + ", $" + x + " ; alignments (y, x)\n"
        output += spacing + "dw $" + window_pointer + " ; window\n\n"

    return output

def map_header_pretty_printer(map_header):
    address = map_header["address"]
    bank = map_header["bank"]
    id = map_header["id"]

    name = map_header["name"]
    asm_name = map_name_cleaner(name, id)
    if name == "FREEZE": return "" #skip freeze maps

    tileset = map_header["tileset"][2:]
    y = int(map_header["y"], base)
    x = int(map_header["x"], base)
    map_pointer = map_header["map_pointer"]
    texts_pointer = map_header["texts_pointer"]
    script_pointer = map_header["script_pointer"]
    connection_byte = map_header["connection_byte"]
    connections = map_header["connections"]
    object_data_pointer = map_header["object_data_pointer"]

    byte_size = 12 + (11 * len(connections.keys()))

    map_pointer = hex(offset_to_pointer(map_pointer))[2:]
    texts_pointer = hex(offset_to_pointer(texts_pointer))[2:]
    script_pointer = hex(offset_to_pointer(script_pointer))[2:]
    object_data_pointer = hex(offset_to_pointer(object_data_pointer))[2:]

    #formatting: hex(y)[2:].zill(2) or "%02x" % (y,)

    output  = asm_name + ": ; " + address + " to " + hex(int(address, base) + byte_size) + " (" + str(byte_size) + " bytes) (id=" + str(id) + ")\n"
    output += spacing + "db $" + str(tileset).zfill(2) + " ; tileset\n"
    output += spacing + "db $" + hex(y)[2:].zfill(2) + ", $" + hex(x)[2:].zfill(2) + " ; dimensions (y, x)\n"
    output += spacing + "dw $" + map_pointer + ", $" + texts_pointer + ", $" + script_pointer + " ; blocks, texts, scripts\n"
    output += spacing + "db " + connection_line(connection_byte) + " ; connections\n\n"

    if len(connections) > 0:
        output += spacing + "; connections data\n\n"
        output += connection_pretty_printer(connections)
        output += spacing + "; end connection data\n\n"

    #TODO: print out label for object_data_pointer if it's already in the file
    output += spacing + "dw $" + object_data_pointer + " ; objects\n"

    return output

def make_object_label_name(name):
    """make a label for the asm file
    like: PalletTownObject"""
    name = map_name_cleaner(name, None)
    return name.replace("_h", "") + "Object"

def make_text_label(map_name, id):
    """using standard object labels
    for instance, PalletTownText3"""
    label = map_name_cleaner(map_name, None)[:-2] + "Text" + str(id)
    return label

def object_data_pretty_printer(map_id):
    map = extract_maps.map_headers[map_id]
    output = ""

    label_name = make_object_label_name(map["name"])
    object_data_pointer = map["object_data_pointer"]
    object = map["object_data"]
    size = extract_maps.compute_object_data_size(object)

    output += label_name + ": ; " + object_data_pointer + " (size=" + str(size) + ")\n"
    output += spacing + "db $" + hex(object["maps_border_tile"])[2:] + " ; border tile\n"
    output += "\n"
    output += spacing + "db $" + hex(int(object["number_of_warps"]))[2:] + " ; warps\n"

    #warps
    for warp_id in object["warps"]:
        warp = object["warps"][warp_id]
        y = warp["y"]
        x = warp["x"]
        warp_to_point = warp["warp_to_point"]
        warp_to_map_id = warp["warp_to_map_id"]

        try:
            warp_to_map_constant = map_constants[warp_to_map_id]
        except Exception as exc:
            warp_to_map_constant = "$" + hex(warp_to_map_id)[2:]

        output += spacing + "db $" + hex(int(y))[2:] + ", $" + hex(int(x))[2:] + ", $" + hex(int(warp_to_point))[2:] + ", " + warp_to_map_constant + "\n"

    output += "\n"
    output += spacing + "db $" + hex(int(object["number_of_signs"]))[2:] + " ; signs\n"

    #signs
    for sign_id in object["signs"]:
        sign = object["signs"][sign_id]
        y = sign["y"]
        x = sign["x"]
        text_id = sign["text_id"]

        output += spacing + "db $" + hex(int(y))[2:] + ", $" + hex(int(x))[2:] + ", $" + hex(int(text_id))[2:] + " ; " + make_text_label(map["name"], text_id) + "\n"

    output += "\n"
    output += spacing + "db $" + hex(int(object["number_of_things"]))[2:] + " ; people\n"

    #people
    for thing_id in object["things"]:
        thing = object["things"][thing_id]

        ending = ""
        if thing["type"] == "item":
            ending = ", $" + hex(int(thing["item_number"]))[2:] + " ; item\n"
        elif thing["type"] == "trainer":
            ending = ", $" + hex(int(thing["trainer_type"]))[2:] + ", $" + hex(int(thing["pokemon_set"]))[2:] + " ; trainer\n"
        else:
            ending = " ; person\n"

        picture_number = hex(int(thing["picture_number"]))[2:]
        y = hex(int(thing["y"]) - 4)[2:]
        x = hex(int(thing["x"]) - 4)[2:]
        movement1 = hex(int(thing["movement1"]))[2:]
        movement2 = hex(int(thing["movement2"]))[2:]
        text_id = hex(int(thing["original_text_string_number"]))[2:]

        output += spacing + "db " + sprite_helper.sprites[thing["picture_number"]] + ", $" + y + " + 4, $" + x + " + 4, $" + movement1 + ", $" + movement2 + ", $" + text_id + ending

    output += "\n"

    if object["number_of_warps"] > 0:
        output += spacing + "; warp-to\n"

        for warp_to_id in object["warp_tos"]:
            warp_to = object["warp_tos"][warp_to_id]
            map_width = map["x"]
            warp_to_y = hex(int(warp_to["y"]))[2:]
            warp_to_x = hex(int(warp_to["x"]))[2:]

            try:
                previous_location = map_constants[object["warps"][warp_to_id]["warp_to_map_id"]]
                comment = " ; " + previous_location
            except Exception as exc:
                comment = ""

            output += spacing + "EVENT_DISP $" + map_width[2:] + ", $" + warp_to_y + ", $" + warp_to_x + comment + "\n"
            #output += spacing + "dw $" + hex(int(warp_to["event_displacement"][1]))[2:] + hex(int(warp_to["event_displacement"][0]))[2:] + "\n"
            #output += spacing + "db $" + hex(int(warp_to["y"]))[2:] + ", $" + hex(int(warp_to["x"]))[2:] + "\n"
            #output += "\n"

        output += "\n"

    while output[-1] == "\n":
        output = output[:-1]

    output += "\n"
    return output

def find_all_tx_fars():
    global all_texts
    tx_fars = [] #[map_id, text_id, text_pointer, tx_far_pointer, TX_FAR]
    for map_id in all_texts:
        map2 = all_texts[map_id]
        for text_id in map2.keys():
            text = map2[text_id]
            for command_id in text.keys():
                command = text[command_id]
                if "TX_FAR" in command.keys():
                    TX_FAR = command["TX_FAR"]
                    if TX_FAR[0]["type"] == 0x0:
                        tx_fars.append([map_id, text_id, analyze_texts.get_text_pointer(int(extract_maps.map_headers[map_id]["texts_pointer"], 16), text_id), command["pointer"], TX_FAR])
    return tx_fars

def tx_far_label_maker(map_name, text_id):
    label = "_" + map_name_cleaner(map_name, None)[:-2] + "Text" + str(text_id)
    return label

def tx_far_pretty_printer(tx_far):
    "pretty output for a tx_far"
    map_id = tx_far[0]
    map2 = extract_maps.map_headers[map_id]
    text_id = tx_far[1]
    text_pointer = tx_far[2]
    tx_far_start_address = tx_far[3]
    text_far = tx_far[4]
    lines = text_far[0]["lines"]
    label = tx_far_label_maker(map2["name"], text_id)

    #add the ending byte on the next line
    #lines[len(lines.keys())+1] = [text_far[1]["type"]]

    #add the ending byte to the last line- always seems $57
    lines[len(lines.keys())-1].append(text_far[1]["type"])

    output  = "\n"
    output += label + ": ; " + hex(tx_far_start_address) + "\n"
    first = True
    for line_id in lines:
        line = lines[line_id]
        output += spacing + "db "
        if first:
            output += "$0, "
            first = False

        quotes_open = False
        first_byte = True
        was_byte = False
        byte_count = 0
        for byte in line:
            if byte in txt_bytes:
                if not quotes_open and not first_byte: #start text
                    output += ", \""
                    quotes_open = True
                    first_byte = False
                if not quotes_open and first_byte: #start text
                    output += "\""
                    quotes_open = True
                output += txt_bytes[byte]
            elif byte in constant_abbreviation_bytes:
                if quotes_open:
                    output += "\""
                    quotes_open = False
                if not first_byte:
                    output += ", "
                output += constant_abbreviation_bytes[byte]
            else:
                if quotes_open:
                    output += "\""
                    quotes_open = False

                #if you want the ending byte on the last line
                #if not (byte == 0x57 or byte == 0x50 or byte == 0x58):
                if not first_byte:
                    output += ", "

                output += "$" + hex(byte)[2:]
                was_byte = True

                #add a comma unless it's the end of the line
                #if byte_count+1 != len(line):
                #    output += ", "

            first_byte = False
            byte_count += 1
        #close final quotes
        if quotes_open:
            output += "\""
            quotes_open = False

        output += "\n"

    #output += "\n"
    return output

def print_all_headers():
    maps = []
    for map in extract_maps.map_headers:
        maps.append(extract_maps.map_headers[map])

    maps = sorted(maps, key=lambda map: int(map["address"], base))

    for map in maps:
        output = map_header_pretty_printer(map)
        if output != "": print(output)

if __name__ == "__main__":
    #read binary data from file
    extract_maps.load_rom()

    #where are the map structs?
    extract_maps.load_map_pointers()

    #load map headers into memory
    extract_maps.read_all_map_headers()

    #load texts
    all_texts = analyze_texts.analyze_texts()

    #print them out
    #print_all_headers()

    #print out only the object data for pallet town (map 0)
    #print object_data_pretty_printer(0)

    #prepare to pretty print tx_fars
    #first you must load all_texts
    #tx_fars = find_all_tx_fars()
    #for entry in tx_fars:
    #    print tx_far_pretty_printer(entry)


#!/usr/bin/env python
# coding: utf-8
import numpy as np
import pandas as pd

"""
parse dataset for dnn input
"""

# number of parity measurements
nrip = 10

features = np.load("./data/features.npy")
y = np.load("./data/labels.npy")

# Encode measurements outcomes
stati = ["00", "01", "10","11"]
X = []
for line in features:
    dato = []
    for me in line[0].split(" ")[::-1]:
        dato.append(stati.index(str(me)))
    X.append(dato)

df = pd.DataFrame(X, columns=[str(i) for i in range(nrip)])

# Encoding columns of labels matrices
labels = np.zeros((len(y),nrip))
for d in range(len(y)):
    for i in range(nrip):
        if np.max((y[d][:,i]))> 0:
            labels[d][i] = np.argmax(y[d][:,i]) +1
df["label"] = list(labels)

# save DataFrame
df.to_csv('artificial_dataset.csv')


# Belajar Module
# Karena tidak mungkin membuat program dalam 1 file
# Maka Module dapat memecahnya jadi beberapa file

# Mengambil semua method di file function
import function

hello = function.say_hello("Mas")
print(hello)

hasil = function.total(1,2,3,4,5)
print(hasil)

# Untuk mengambil 1 atau 2 method saja
# Jika ada banyak method dalam satu file
from function import say_hello
from function import total

# Tidak perlu menambahkan prefix nama modulenya
hello = say_hello("Mas")
print(hello)

hasil = total(10,20,30,40,50)
print(hasil)


#!/bin/python

import math
import os
import random
import re
import sys

# Complete the theGreatXor function below.
def theGreatXor(x):
    ans = 0
    binStr = [i for i, ltr in enumerate(bin(x)[::-1]) if ltr == '0']
    for i in binStr: ans += (1 << i)

    return ans - (1 << binStr[-1])
if __name__ == '__main__':
    fptr = open(os.environ['OUTPUT_PATH'], 'w')

    q = int(raw_input())

    for q_itr in xrange(q):
        x = int(raw_input())

        result = theGreatXor(x)

        fptr.write(str(result) + '\n')

    fptr.close()


#Libraries
import pandas as pd
import re as re

#Training (891 Entries) & Testing (417 Entries) data
train_data = pd.read_csv('Data/train.csv')
test_data = pd.read_csv('Data/test.csv')
all_data = [train_data, test_data]
passenger_id = test_data['PassengerId']

#Feature Engineering
def get_title(name):
    title_search = re.search(' ([A-Za-z]+)\. ', name)
    if title_search:
        return title_search.group(1)
    return ""

for data in all_data:
    data['title'] = data['Name'].apply(get_title)

for data in all_data:
    data['title'] = data['title'].replace(['Lady', 'Countess','Capt', 'Col','Don', 'Dr', 'Major', 'Rev', 'Sir', 'Jonkheer', 'Dona'],'Rare')
    data['title'] = data['title'].replace('Mlle','Miss')
    data['title'] = data['title'].replace('Ms','Miss')
    data['title'] = data['title'].replace('Mme','Mrs')

print(pd.crosstab(train_data['title'], train_data['Sex']))
print("--------------------")
print(train_data[['title','Survived']].groupby(['title'], as_index = False).mean())