from flask import Flask, request, render_template
from py_and_coffee import coffee_country

# create a flask object
app = Flask(__name__)

# creates an association between the / page and the entry_page function (defaults to GET)
@app.route('/')
def entry_page():
    return render_template('index.html')

# creates an association between the /predict_recipe page and the render_message function
# (includes POST requests which allow users to enter in data via form)
@app.route('/coffee_origin/', methods=['GET', 'POST'])
def render_message():

    # user-entered ingredients
    ingredients = ['aroma', 'flavor', 'aftertaste', 'acidity', 'body', 'balance', 'sweetness']

    # error messages to ensure correct units of measure
    messages = ["The aroma must be between 0 and 10",
                "The flavor must be between 0 and 10",
                "The aftertaste must be between 0 and 10",
                "The acidity must be between 0 and 10",
                "The body must be between 0 and 10",
                "The balance must be between 0 and 10",
                "The sweetness must be between 0 and 10"]

    # hold all amounts as floats
    amounts = []

    # takes user input and ensures it can be turned into a floats
    for i, ing in enumerate(ingredients):
        user_input = request.form[ing]
        try:
            float_ingredient = float(user_input)
        except:
            return render_template('index.html', message=messages[i])
        amounts.append(float_ingredient)

    # show user final message
    final_message = coffee_country(amounts)
    return render_template('index.html', message=final_message)

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


#!/bin/python3

"""
Copyright 2017 Samuel Cowen <samuel.cowen@camelsoftware.com>

Permission is hereby granted, free of charge, to any person obtaining a copy of
this software and associated documentation files (the "Software"), to deal in
the Software without restriction, including without limitation the rights to
use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
of the Software, and to permit persons to whom the Software is furnished to do
so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
"""

import sys
import json
import shutil
from pprint import pprint

def is_an_enum(name, data):
    for i in data["enums"]:

        if(i["title"] == name):
            print(i["title"] + " " + name)
            print("returning true")
            return True
    return False

def build_docs(data):
    file = open("c3/index.html", "w")
    file.write("""

        <link rel="stylesheet" href="style.css" />
        <title>""")
    file.write(data["project"]["title"])
    file.write("""</title>

""")
    file.write(data["project"]["title"])
    file.write("

")
    file.write(data["project"]["description"])
    file.write("

Version: ")
    file.write(data["project"]["version"])
    file.write("

")

    file.write("

Index

Enumerations

")
    for i in data["enums"]:
        file.write("
" + i["title"] + "
")

    file.write("

Packets

")
    for i in data["packets"]:
        file.write("
" + i["title"] + "
")

    file.write("

")

    file.write("
Enumerations
")
    for i in data["enums"]:
        file.write("
" + i["title"] + "
")
        file.write("
" + i["description"] + "
")
        for f in i["fields"]:
            file.write("" + f + "
")

    file.write("
Packets
")
    for i in data["packets"]:
        file.write("
" + i["title"] + "
")
        file.write("" + i["description"] + "
")
        if(i["owner"] == "both"):
            file.write("Received by both local and remote.")
        if(i["owner"] == "remote"):
            file.write("Received by local.")
        if(i["owner"] == "local"):
            file.write("Received by remote.")
        file.write("

Name	Type	Description
")
        for j in i["fields"]:
            file.write("
" + j["name"] + "	" + j["type"] + "	")
            if "description" in j:
                file.write(j["description"])
            file.write("
")

        file.write("
")

    file.write("""
""")
    file.close()

def build_enums_header(data):
    file = open("c3/c3_enums.h", "w")
    file.write("""
#ifndef C3_ENUMS_H
#define C3_ENUMS_H

#include <stdint.h>
namespace ccc {

""")
    for i in data["enums"]:
        file.write("enum " + i["title"] + " : uint8\n{\n\t")
        for f in i["fields"]:
            file.write(i["title"] + "_" + f + ",\n\t")
        file.write(i["title"] + "_NULL\n};\n\n")

    file.write("enum PACKETS : uint8\n{\n\t")
    file.write("ACK_PACK,\n\t")
    for i in data["packets"]:
        file.write(i["title"].upper() + "_PACK,\n\t")
    file.write("NULL_PACK\n};\n\n")
    file.write("}\n\n#endif\n")

def build_packets_header(data):
    file = open("c3/c3_packets.h", "w")
    file.write("""
#ifndef C3_PULLS_IN_PACKETS
#error Do not include c3_packets.h. Only include "c3.h"
#endif

""")
    for i in data["packets"]:
        file.write("class " + i["title"].lower() +
                   "_pack : public base_pack\n")
        file.write("{\npublic:\n\t")
        file.write(i["title"].lower() +
                   "_pack(uint8 sync) : base_pack(sync) { }\n\t")
        file.write("static constexpr uint16 id = " +
                   i["title"].upper() + "_PACK;\n\n\t")

        for v in i["fields"]:
            file.write(v["type"] + " " + v["name"] + ";\n\t")

        if(len(i["fields"]) == 0):
            file.write("uint8 size() { return 0; }\n\t")
        else:
            file.write("uint8 size()\n\t{\n\t\treturn (")
            for v in i["fields"][:-1]:
                if(v["type"][:9] == "etk::List"):
                    file.write(v["name"] + ".size()+1")
                elif(v["type"][:17] == "etk::StaticString"):
                    file.write(v["name"] + ".length()")
                else:
                    file.write("sizeof(" + v["name"] + ") + \n\t\t")

            if(i["fields"][-1]["type"][:9] == "etk::List"):
                file.write(i["fields"][-1]["name"] + ".size()+1);\n\t}\n\t")
            elif( i["fields"][-1]["type"][:17] == "etk::StaticString"):
                file.write( i["fields"][-1]["name"] + ".length());\n\t}\n\t")
            else:
                file.write("sizeof(" +  i["fields"][-1]["name"] + "));\n\t}\n\t")

        file.write(
            "bool ack_required() { return " + i["ack_required"] + "; }\n\t")
        file.write("uint16 get_id() { return id; }\n\t")

        file.write("uint16 to_bytes(uint8* bytes)\n\t{\n\t\t")
        file.write("uint16 pos = 4;\n\t\t")
        file.write("uint8 temp = 0;\n\t\t")
        file.write("base_pack::gen_header(bytes);\n\t\t")
        if(len(i["fields"]) > 0):

            for v in i["fields"]:
                if(is_an_enum(v["type"], data) == True):
                    file.write("temp = static_cast<uint8>(" + v["name"] + ");\n\t\t")
                    file.write("base_pack::to_bytes(bytes, pos, temp);\n\t\t")
                else:
                    file.write("base_pack::to_bytes(bytes, pos, ")
                    file.write(v["name"] + ");\n\t\t")
        file.write("return pos;\n\t}\n\t")

        file.write("void from_bytes(uint8* bytes)\n\t{\n\t")
        file.write("uint8 temp = 0;\n\t\t")
        if(len(i["fields"]) > 0):
            file.write("\tuint16 pos = 0;\n\t\t")
            for v in i["fields"]:
                if(is_an_enum(v["type"], data) == True):
                    file.write("base_pack::from_bytes(bytes, pos, temp);\n\t\t");
                    file.write(v["name"] + " = static_cast<" + v["type"] + ">(temp);\n\t\t")
                else:
                    file.write("base_pack::from_bytes(bytes, pos, ")
                    file.write(v["name"] + ");\n\t\t")
        file.write("}")

        file.write("\n};\n\n")

    file.close()

def build_handlers_header(data):
    file = open("c3/c3_both_handlers.h", "w")
    file.write("""#ifndef C3_PULLS_IN_BOTH_HANDLERS
#error Do not include c3_both_handlers.h. Only include "c3.h"
#endif
""")
    for i in data["packets"]:
        if(i["owner"] == "both"):
            file.write("case " + i["title"].upper() + "_PACK:\n{\n\t")
            file.write(i["title"].lower() + "_pack pack(sync_in);\n\t")
            file.write("pack.from_bytes(&(data_buf[4]));\n\t")
            if(i["setting"] == "true"):
                for v in i["fields"]:
                    file.write("settings." +
                               v["name"] + " = pack." + v["name"] + ";\n\t")
                file.write(
                    "static_cast<T*>(this)->on_setting_changed(msg_id);\n")
            else:
                file.write("static_cast<T*>(this)->" +
                           i["title"] + "_pack_handler(pack);\n")
            if(i["ack_required"] == "true"):
                file.write(
                    "send_ack(" + i["title"].upper() + "_PACK, sync_in);\n")
            file.write("}\nbreak;\n")
    file.close()

    file = open("c3/c3_remote_handlers.h", "w")
    file.write("""#ifndef C3_PULLS_IN_REMOTE_HANDLERS
#error Do not include c3_remote_handlers.h. Only include "c3.h"
#endif
""")
    for i in data["packets"]:
        if(i["owner"] == "local"):
            file.write("case " + i["title"].upper() + "_PACK:\n{\n\t")
            file.write(i["title"].lower() + "_pack pack(sync_in);\n\t")
            file.write("pack.from_bytes(&(data_buf[4]));\n\t")
            if(i["setting"] == "true"):
                for v in i["fields"]:
                    file.write("settings." +
                               v["name"] + " = pack." + v["name"] + ";\n\t")
                file.write(
                    "static_cast<T*>(this)->on_setting_changed(msg_id);\n\t")
            else:
                file.write("static_cast<T*>(this)->" +
                           i["title"] + "_pack_handler(pack);\n\t")
            if(i["ack_required"] == "true"):
                file.write(
                    "send_ack(" + i["title"].upper() + "_PACK, sync_in);\n")
            file.write("\n}\nbreak;\n")
    file.close()

    file = open("c3/c3_local_handlers.h", "w")
    file.write("""#ifndef C3_PULLS_IN_LOCAL_HANDLERS
#error Do not include c3_local_handlers.h. Only include "c3.h"
#endif
""")
    for i in data["packets"]:
        if(i["owner"] == "remote"):
            file.write("case " + i["title"].upper() + "_PACK:\n{\n\t")
            file.write(i["title"].lower() + "_pack pack(sync_in);\n\t")
            file.write("pack.from_bytes(&(data_buf[4]));\n\t")
            if(i["setting"] == "true"):
                for v in i["fields"]:
                    file.write("settings." +
                               v["name"] + " = pack." + v["name"] + ";\n\t")
                file.write(
                    "static_cast<T*>(this)->on_setting_changed(msg_id);\n")
            else:
                file.write("static_cast<T*>(this)->" +
                           i["title"] + "_pack_handler(pack);\n")
            if(i["ack_required"] == "true"):
                file.write(
                    "send_ack(" + i["title"].upper() + "_PACK, sync_in);\n")
            file.write("}\nbreak;\n")
    file.close()

def build_settings_header(data):
    file = open("c3/c3_settings.h", "w")
    file.write("""#ifndef C3_SETTINGS_H
#define C3_SETTINGS_H

#include <etk.h>
#include "c3.h"

namespace ccc
{

class Settings
{
public:
    static Settings& get()
    {
        static Settings settings;
        return settings;
    }

    """)
    for i in data["packets"]:
        if(i["setting"] == "true"):
            for v in i["fields"]:
                file.write(v["type"] + " " + v["name"] + ";\n\t")

    file.write("""
private:
    Settings() {}
    Settings(const Settings& s) { (void)(s); }
    ~Settings() { }
};

}

#endif
""")
    file.close()

if(len(sys.argv) < 2):
    print("No input file specified!")
    exit()

file = open(sys.argv[1], "r")
data = json.load(file)

build_enums_header(data)
build_packets_header(data)
build_handlers_header(data)
build_settings_header(data)
build_docs(data)
shutil.copy2("./c3.h", "./c3/c3.h")


import os
#declaracion de datos
trabajador,dias,pago="",0.0,0.0
limite=False

#imput
trabajador=os.sys.argv[1]
dias=int(os.sys.argv[2])
pago=float(os.sys.argv[3])

#processing
total=(dias*pago)
limite=(total>1000)

#output
print("nombre del trabajador:",trabajador)
print("dias trabajados:",dias)
print("pago por dias:",pago)
print("total pagado",total)

#condicional doble
#si el empleado gano mas de 1000 tiene vvacaciones pagadas

if(limite):
    print("us.acaba de ganar vacaciones pagadas")
else:
    print("Buen trabajo")
#fin_if


import torch
import torch.nn as nn
from transformers import BertPreTrainedModel, BertModel, BertConfig
PRETRAINED_MODEL_NAME = 'allenai/scibert_scivocab_uncased'

class swish(nn.Module):
    def __init__(self):
        super(swish, self).__init__()

    def forward(self, x):
        x = x * nn.Sigmoid()(x)
        return x

class BertforMultilabel(BertPreTrainedModel):
    def __init__(self, conf, num_class, dropout=0.2):
        super(BertforMultilabel, self).__init__(conf)
        self.Y = num_class
        self.dropout = dropout
        self.embedding_dim = conf.hidden_size
        self.bert = BertModel.from_pretrained(PRETRAINED_MODEL_NAME)
        self.dropout = nn.Dropout(p=dropout)
        self.hidden1 = nn.Linear(self.embedding_dim, self.embedding_dim//2)
        self.final = nn.Linear(self.embedding_dim//2, self.Y)

    def key_padding_mask_bert(self, x, pad_num=0):
        atten_mask = x.masked_fill(x != pad_num, 1)
        return atten_mask

    def forward(self, batch):
        _, x = self.bert(input_ids=batch.content,
                         attention_mask=self.key_padding_mask_bert(batch.content))
        x = self.dropout(x)
        x = swish()(self.hidden1(x))
        x = self.dropout(x)
        x = self.final(x)
        return x


#!/usr/bin/env python

import os
import argparse
import numpy as np
import pandas as pd
import shutil

import comptools as comp
from comptools.composition_encoding import composition_group_labels, encode_composition_groups

def extract_dataframe(input_file, config, datatype):
    with pd.HDFStore(input_file, mode='r') as store:
        series_size = store.get_storer('NStations').nrows
        # Dictionary of key: pd.Series pairs to get converted to pd.DataFrame
        series_dict = {}
        # For data stored in that can be accessed via a value column
        value_keys = ['IceTopMaxSignal',
                      'IceTopMaxSignalInEdge',
                      'IceTopMaxSignalString',
                      'IceTopNeighbourMaxSignal',
                      'NStations',
                      'StationDensity',
                      'FractionContainment_Laputop_IceTop',
                      'FractionContainment_Laputop_InIce',
                      'passed_IceTopQualityCuts',
                      'passed_InIceQualityCuts',
                      'avg_inice_radius',
                      'std_inice_radius',
                      'median_inice_radius',
                      'frac_outside_one_std_inice_radius',
                      'frac_outside_two_std_inice_radius',
                      ]

        for cut in ['MilliNCascAbove2', 'MilliQtotRatio', 'MilliRloglBelow2', 'NCh_CoincLaputopCleanedPulsesAbove7', 'StochRecoSucceeded']:
            value_keys += ['passed_{}'.format(cut)]

        min_dists = np.arange(0, 1125, 125)
        for min_dist in min_dists:
            value_keys += ['IceTop_charge_beyond_{}m'.format(min_dist)]

        dom_numbers = [1, 15, 30, 45, 60]
        for min_DOM, max_DOM in zip(dom_numbers[:-1], dom_numbers[1:]):
            key = '{}_{}'.format(min_DOM, max_DOM)
            value_keys += ['NChannels_'+key,
                           'NHits_'+key,
                           'InIce_charge_'+key,
                           'max_qfrac_'+key,
                           ]
        key = '1_60'
        value_keys += ['NChannels_'+key,
                       'NHits_'+key,
                       'InIce_charge_'+key,
                       'max_qfrac_'+key,
                       ]
        if datatype == 'sim':
            # Add MC containment
            value_keys += ['FractionContainment_MCPrimary_IceTop',
                           'FractionContainment_MCPrimary_InIce',
                           'angle_MCPrimary_Laputop',
                           ]
        for key in value_keys:
            series_dict[key] = store[key]['value']

        if datatype == 'sim':
            # Get MCPrimary information
            for key in ['x', 'y', 'energy', 'zenith', 'azimuth', 'type']:
                series_dict['MC_{}'.format(key)] = store['MCPrimary'][key]
            # Add simulation set number and corresponding composition
            # sim_num = int(os.path.splitext(input_file)[0].split('_')[-1])
            sim_num = int(os.path.basename(input_file).split('_')[1])
            series_dict['sim'] = pd.Series([sim_num] * series_size, dtype=int)
            composition = comp.simfunctions.sim_to_comp(sim_num)
            series_dict['MC_comp'] = pd.Series([composition] * series_size, dtype=str)
            # Add composition class
            MC_comp_class = 'light' if composition in ['PPlus', 'He4Nucleus'] else 'heavy'
            series_dict['MC_comp_class'] = pd.Series([MC_comp_class] * series_size, dtype=str)

        # Get timing information
        series_dict['start_time_mjd'] = store['I3EventHeader']['time_start_mjd']
        series_dict['end_time_mjd'] = store['I3EventHeader']['time_end_mjd']

        # Get Laputop information
        laputop = store['Laputop']
        laputop_params = store['LaputopParams']
        lap_keys = ['zenith', 'azimuth', 'x', 'y']
        # if datatype == 'data':
        #     lap_keys += ['ra', 'dec']
        for key in lap_keys:
            series_dict['lap_{}'.format(key)] = laputop[key]
        lap_param_keys = ['s50', 's80', 's125', 's180', 's250', 's500',
                          'ndf', 'beta', 'rlogl']
        for key in lap_param_keys:
            series_dict['lap_{}'.format(key)] = laputop_params[key]
        series_dict['lap_energy'] = laputop_params['e_h4a']
        series_dict['lap_chi2'] = laputop_params['chi2'] / laputop_params['ndf']
        series_dict['lap_fitstatus_ok'] = store['lap_fitstatus_ok']['value'].astype(bool)

        # # Get DDDDR information
        # d4r_params = store['I3MuonEnergyLaputopParams']
        # d4r_keys = ['N', 'b', 'gamma', 'peak_energy', 'peak_sigma', 'exists', 'mean', 'median']
        # for key in d4r_keys:
        #     series_dict['d4r_{}'.format(key)] = d4r_params[key]

        series_dict['eloss_1500_standard'] = store['Stoch_Reco']['eloss_1500']
        # Get number of high energy stochastics
        # series_dict['n_he_stoch_standard'] = store['Stoch_Reco']['n_he_stoch']
        # series_dict['n_he_stoch_strong'] = store['Stoch_Reco2']['n_he_stoch']
        # series_dict['eloss_1500_strong'] = store['Stoch_Reco2']['eloss_1500']
        series_dict['mil_rlogl'] = store['MillipedeFitParams']['rlogl']
        series_dict['mil_qtot_measured'] = store['MillipedeFitParams']['qtotal']
        series_dict['mil_qtot_predicted'] = store['MillipedeFitParams']['predicted_qtotal']

        # Construct unique index from run/event/subevent info in I3EventHeader
        runs = store['I3EventHeader']['Run']
        events = store['I3EventHeader']['Event']
        sub_events = store['I3EventHeader']['SubEvent']
        if datatype == 'sim':
            index = ['{}_{}_{}_{}'.format(sim_num, run, event, sub_event)
                     for run, event, sub_event in zip(runs, events, sub_events)]
        else:
            index = ['{}_{}_{}_{}'.format(config, run, event, sub_event)
                     for run, event, sub_event in zip(runs, events, sub_events)]

        # Extract measured charge for each DOM
        charges_list, columns, tank_charges_index = [], [], []
        grouped = store['tank_charge_v_dist'].groupby(['Run', 'Event', 'SubEvent'])
        for name, group in grouped:
            # if not columns:
            #     columns = ['ldf_{}'.format(i) for i in range(len(group['item']))]
            charges_list.append(group['item'].values)
            if datatype == 'sim':
                tank_charges_index.append('{}_{}_{}_{}'.format(sim_num, *name))
            else:
                tank_charges_index.append('{}_{}_{}_{}'.format(config, *name))
        df_tank_charges = pd.DataFrame(charges_list)
        df_tank_charges.index = tank_charges_index

    df = pd.DataFrame(series_dict)
    df.index = index
    for col in df_tank_charges:
        df['ldf_{}'.format(col)] = df_tank_charges[col]

    return df

def add_extra_columns(df, datatype='sim'):
    '''
    Function to add to new columns to DataFrame that are commonly used

    Parameters
    ----------
    df : pandas.DataFrame
        Input DataFrame
    datatype : str, optional
        Specify whether this is a DataFrame based on simulation or data
        (default is 'sim').

    Returns
    -------
    df : pandas.DataFrame
        Returns DataFrame with added columns
    '''
    if datatype == 'sim':
        df['MC_log_energy'] = np.nan_to_num(np.log10(df['MC_energy']))
        # Add composition group labels
        for num_groups in [2, 3, 4]:
            label_key = 'comp_group_{}'.format(num_groups)
            df[label_key] = composition_group_labels(df['MC_comp'],
                                                     num_groups=num_groups)
            target_key = 'comp_target_{}'.format(num_groups)
            df[target_key] = encode_composition_groups(df[label_key],
                                                       num_groups=num_groups)
    # Add log-scale columns to df
    df['lap_log_energy'] = np.nan_to_num(np.log10(df['lap_energy']))
    df['lap_cos_zenith'] = np.cos(df['lap_zenith'])
    for dist in ['50', '80', '125', '180', '250', '500']:
        df['log_s'+dist] = np.log10(df['lap_s'+dist])
    df['log_dEdX'] = np.log10(df['eloss_1500_standard'])

    return df

def process_i3_hdf(files, config, datatype):
    for input_file in files:
        df = extract_dataframe(input_file, config, datatype)
        df = comp.io.apply_quality_cuts(
                df, datatype=datatype, log_energy_min=None,
                log_energy_max=None, verbose=False)
        df = add_extra_columns(df, datatype=datatype)

        yield df

if __name__ == "__main__":

    parser = argparse.ArgumentParser(
        description='Converts input hdf5 files (from save_hdf.py) to a well-formatted pandas dataframe object')
    parser.add_argument('-c', '--config', dest='config',
                        default='IC86.2012',
                        help='Detector configuration')
    parser.add_argument('--type', dest='type',
                        choices=['data', 'sim'],
                        default='sim',
                        help='Option to process simulation or data')
    parser.add_argument('-i', '--input', dest='input', nargs='*',
                        help='Path to input hdf5 files')
    parser.add_argument('-o', '--output', dest='output',
                        help='Path to output hdf5 file')
    args = parser.parse_args()

    # Validate input config
    if (args.type == 'sim' and
            args.config not in comp.simfunctions.get_sim_configs()):
        raise ValueError(
            'Invalid simulation config {} entered'.format(args.config))
    elif (args.type == 'data' and
            args.config not in comp.datafunctions.get_data_configs()):
        raise ValueError('Invalid data config {} entered'.format(args.config))

    # Check if running on condor. If so, write to a local directory on the
    # worker node and copy after output file is written.
    if os.getenv('_CONDOR_SCRATCH_DIR'):
        on_condor = True
        local_outdir = os.getenv('_CONDOR_SCRATCH_DIR')
        outfile = os.path.join(local_outdir, os.path.basename(args.output))
    else:
        on_condor = False
        comp.check_output_dir(args.output)
        outfile = args.output

    # Open HDFStore for output hdf5 file
    with pd.HDFStore(outfile, mode='w') as output_store:
        for df in process_i3_hdf(args.input, args.config, args.type):
            # min_itemsize = {'index': 30}
            # if args.type == 'sim':
            #     min_itemsize['MC_comp'] = 15
            #     for num_groups in [2, 3, 4]:
            #         min_itemsize['comp_group_{}'.format(num_groups)] = 15
            # Add dataframe to output_store
            output_store.append('dataframe', df, format='table',
                                data_columns=True, min_itemsize=30)
                                # data_columns=True, min_itemsize=min_itemsize)

    # If on condor, transfer from worker machine to desired destination
    if on_condor:
        comp.check_output_dir(args.output)
        shutil.move(outfile, args.output)


from meta_policy_search.envs.base import MetaEnv

import numpy as np
from gym.spaces import Box

class MetaPointEnvMomentumModes(MetaEnv):
    """
    Simple 2D point meta environment. Each meta-task corresponds to a different goal / corner
    (one of the 4 points (-2,-2), (-2, 2), (2, -2), (2,2)) which are sampled with equal probability
    """

    def __init__(self, reward_type='dense', sparse_reward_radius=2):
        assert reward_type in ['dense', 'dense_squared', 'sparse']
        self.reward_type = reward_type
        print("Point Env reward type is", reward_type)
        self.sparse_reward_radius = sparse_reward_radius
        self.corners = np.array(
            [[-5, -5], [5, -5], [-5, 5], [5, 5]], dtype=np.float32)
        self.noise_scale = 2.0
        self.set_task(self.sample_tasks(1)[0])
        self.observation_space = Box(low=-np.inf, high=np.inf, shape=(4,))
        self.action_space = Box(low=-0.1, high=0.1, shape=(2,))

    def step(self, action):
        """
        Run one timestep of the environment's dynamics. When end of episode
        is reached, reset() should be called to reset the environment's internal state.

        Args:
            action : an action provided by the environment
        Returns:
            (observation, reward, done, info)
            observation : agent's observation of the current environment
            reward [Float] : amount of reward due to the previous action
            done : a boolean, indicating whether the episode has ended
            info : a dictionary containing other diagnostic information from the previous action
        """
        prev_state = self._state
        self._velocity += np.clip(action, -0.1, 0.1)
        self._state = prev_state + self._velocity
        reward = self.reward(prev_state, action, self._state)
        done = False # self.done(self._state)
        next_observation = np.hstack((self._state, self._velocity))
        return next_observation, reward, done, {}

    def reset(self):
        """
        Resets the state of the environment, returning an initial observation.
        Outputs
        -------
        observation : the initial observation of the space. (Initial reward is assumed to be 0.)
        """
        self._state = np.random.uniform(-0.2, 0.2, size=(2,))
        self._velocity = np.random.uniform(-0.1, 0.1, size=(2,))
        observation = np.hstack((self._state, self._velocity))
        return observation

    def done(self, obs):
        if obs.ndim == 1:
            return self.done(np.array([obs]))
        elif obs.ndim == 2:
            goal_distance = np.linalg.norm(obs[:2] - self.goal_pos[None,:], axis=1)
            return np.max(self._state) > 3

    def reward(self, obs, act, obs_next):
        if obs_next.ndim == 2:
            goal_distance = np.linalg.norm(obs_next[:2] - self.goal_pos[None,:], axis=1)[0]
            if self.reward_type == 'dense':
                return - goal_distance
            elif self.reward_type == 'dense_squared':
                return - goal_distance**2
            elif self.reward_type == 'sparse':
                return np.maximum(self.sparse_reward_radius - goal_distance, 0)

        elif obs_next.ndim == 1:
            return self.reward(np.array([obs]), np.array([act]), np.array([obs_next]))
        else:
            raise NotImplementedError

    def log_diagnostics(self, *args):
        pass

    def sample_tasks(self, n_tasks):
        goals = self.corners[np.random.randint(0, 4, n_tasks)]
        goals += np.random.randn(n_tasks, 2)
        return goals

    def set_task(self, task):
        """
        Args:
            task: task of the meta-learning environment
        """
        self.goal_pos = task

    def get_task(self):
        """
        Returns:
            task: task of the meta-learning environment
        """
        return self.goal_pos

if __name__ == "__main__":
    env = MetaPointEnvMomentumModes()
    while True:
        env.set_task(env.sample_tasks(1)[0])
        env.reset()
        for _ in range(100):
            # env.render()
            _, reward, _, _ = env.step(env.action_space.sample())  # take a random action
            print(reward, env.goal_pos)


#coding=utf-8

from selenium import webdriver
import selenium.webdriver.support.ui as ui
import time
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
import requests
from bs4 import BeautifulSoup
from urllib.request import urlopen

downloadDir = 'D:\\py35\\copyTxt\\'#下载后存放目录

class lewen():

    #搜索小说，定位到目标小说页:返回一个章节链接的列表
    def search(bookName):
        driver = webdriver.Firefox()
        base_url = "http://www.lewenxiaoshuo.com"
        driver.get(base_url)
        driver.find_element_by_id("searchkey").clear()
        driver.find_element_by_id("searchkey").send_keys(bookName)#这里可以改成传参:摇欢
        driver.find_element_by_id("searchsubmit").click()
        #解决报错：元素不能定位，等待5秒。直到元素可以定位
        wait = ui.WebDriverWait(driver,5)
        wait.until(lambda driver: driver.find_element_by_xpath(".//*[@id='main']/div[1]/ul/li/span[2]/a"))
        a = driver.find_element_by_xpath(".//*[@id='main']/div[1]/ul/li/span[2]/a")
        target_href = a.get_attribute("href")  #获取目标小说的链接
        print("目标小说链接：" + target_href)
        now_handle = driver.current_window_handle #初始窗口
        print("初始窗口：" + now_handle)
        a.click()  #进入新的窗口
        driver.implicitly_wait(20)

        all_handles = driver.window_handles #获取所有窗口句柄
        for handle in all_handles:
            if handle != now_handle:
                #输出待选择的窗口句柄
                print("新窗口：" + handle)
                driver.switch_to_window(handle)#跳转到新的窗口
                time.sleep(1)
        #print(all_handles[1])这种写法数组越界，不造为嘛

        #urls = driver.find_element_by_xpath(".//*[@id='list']/dl/dd[1]/a")#通过css_selector定位不到，不造为嘛
        a_s = driver.find_elements_by_xpath(".//*[@id='list']/dl/dd[*]/a")#获取小说所有章节链接列表所在的标签a
        driver.implicitly_wait(20)
        urls = [] #保存小说所有章节链接列表
        #由于小说的章节链接地址不连续的，故需要保存所有章节链接
        for a in a_s:
            chapter_href = a.get_attribute("href")#章节链接
            #chapter_title = a.get_attribute("title")#章节标题
            urls.append(chapter_href)
        print("小说章节总数：",len(urls))
        return urls

    #按章节通过链接爬取小说
    def get_name_content(urls):
        chapters = []
        for url in urls:
            response = urlopen(url)
            html = response.read()
            soup = BeautifulSoup(html,"html5lib")
            title = soup.findAll('h1')[0].text
            print("爬取章节：" + title)
            chapters.append(title)
            content = soup.findAll(id="content")[0]
            for string in content:
                st = str(string)
                #st = string.__str__()，和上面函数功能相同
                if (len(st.split('
')) > 1):#不太懂！！
                    pass
                else:
                    chapters.append(st)
        return chapters

    #清洗文本格式，一次性写入txt文件：关键是调整格式
    def save_book(bookName,chapters):
        now =time.strftime("%Y%m%d%H%M%S", time.localtime())#当前时间，纯字符串格式
        bookname = downloadDir  + bookName + now + '.txt'
        file = open(bookname, 'w+', encoding='utf-8')
        for i in chapters:
            #file.write('\t')
            for ii in i.split('  '):#i.split('  ')用多个空白符分割字符串，保留一个空格部分；''表示空，
                if ii.startswith('<div'):#去掉每章开头多余的

                    ii = ""
                ii = ii.replace("

","")  #去掉每章最后多余的

                file.write(ii)
            file.write('\n')  #每写完一句，换行，控制文本格式

if __name__ == "__main__":
    chapter_urls = lewen.search("我从来没有谈过恋爱")
    chapters = lewen.get_name_content(chapter_urls)
    lewen.save_book("我从来没有谈过恋爱",chapters)


import pyowm
import discord
from discord.ext import commands as eolas
from functools import partial

owm_key = ('YOUR_OWM_API_KEY')

class Weather:
    def __init__(self, eolas):
        self.eolas = eolas

        # ?meteo <location> - Print the forecast of a specific location.
        @eolas.command()
        async def meteo(*, name):
            """<location> - Print the forecast of a specific location."""
            owm = pyowm.OWM(owm_key, language='fr')

            observation = owm.weather_at_place(name)
            weather = observation.get_weather()
            location = observation.get_location()
            get_temperature = weather.get_temperature(unit='celsius')
            get_wind = weather.get_wind()

            await eolas.say('Lieu: {}'.format(location.get_name())
                            + '\n'
                            + ('Température: {}'.format(get_temperature['temp'])
                               + u'\N{DEGREE SIGN}C')
                            + '\n'
                            + ('Vitesse du vent: {}'.format(get_wind['speed']) + ' m/s')
                            + '\n'
                            + ('Description: {}'.format(weather.get_detailed_status()))
                            )

def setup(eolas):
    eolas.add_cog(Weather(eolas))


import pandas as pd
import numpy as np
from datetime import date
from config import DISTRIBUTOR_WATCHLIST, MODELS_WATCHLIST, LOCATIONS, INPUT_FILE, OUTPUT_LOCATION

def filter_demo_models(initial_models):
    models = []

    for model in initial_models:
        if 'demo' not in model.lower():
            models.append(model)

    return models

def filter_distributors(initial_distributors):
    distributors = []
    if not DISTRIBUTOR_WATCHLIST:
        return initial_distributors

    for distributor in initial_distributors:
        for watchlist in DISTRIBUTOR_WATCHLIST:
            if watchlist.lower() in distributor.lower():
                distributors.append(distributor)
    return distributors

def generate_dos_template(filtered_df, value_to_use):
    dos_table = pd.pivot_table(filtered_df, values=value_to_use, index=['Territory', 'Statistics Model'],
                        columns=['Distributor'], aggfunc=np.sum, fill_value=0)
    dos_table = dos_table.reset_index()
    dos_table.index.name = None

    d = {'Statistics Model': MODELS_WATCHLIST}
    watchlist_df = pd.DataFrame(data=d)
    for territory in LOCATIONS:
        watchlist_df['Territory'] = territory
        dos_table = pd.merge(dos_table, watchlist_df, how='outer', on=['Territory', 'Statistics Model'])

    dos_table = dos_table.sort_values(["Territory", "Statistics Model"])
    dos_table = dos_table.replace(np.nan, 0)
    return dos_table

def generate_dos_file(filtered_df, date):
    filtered_df.loc[~filtered_df["Statistics Model"].isin(MODELS_WATCHLIST), "Statistics Model"] = "Other Models"

    inventory_dos = generate_dos_template(filtered_df, 'Distributor Stock')
    sales_dos = generate_dos_template(filtered_df, 'Sales Volume')

    writer = pd.ExcelWriter(f'{OUTPUT_LOCATION}/National-DOS-{date}.xlsx', engine='openpyxl')
    inventory_dos.to_excel(writer, sheet_name='Inventory', index=False)
    sales_dos.to_excel(writer, sheet_name='Sales', index=False)
    writer.save()

def generate_distributor_file(filtered_df, date):
    for key, value in filtered_df.groupby('Distributor'):
        writer = pd.ExcelWriter(f'{OUTPUT_LOCATION}/{key.lower().replace(" ", "-")}-{date}.xlsx', engine='openpyxl')
        for territory, territory_df in value.groupby('Territory'):
            territory_pivot = pd.pivot_table(territory_df, values='Distributor Stock', index=['Statistics Model'], columns=['Store/Warehouse'], aggfunc=np.sum, fill_value=0)
            territory_pivot = territory_pivot.replace(0, np.nan)
            territory_pivot.to_excel(writer, sheet_name=territory)
        writer.save()

def get_raw_data():
    """
        Get initial raw data from the file location in config.py.
        Will also do some initial preprocessing.
        (remove last row and make negative data to zero)
    """
    df = pd.read_excel(f'{INPUT_FILE}')
    df = df[:-1]
    num = df._get_numeric_data()
    num[num < 0] = 0
    df = df.fillna(0)
    return df

def main():
    today = date.today().strftime("%b-%d-%Y")

    df = get_raw_data()
    distributors = filter_distributors(df.Distributor.unique().tolist())
    models = filter_demo_models(df['Statistics Model'].unique().tolist())

    filtered_df = df[(df['Distributor'].isin(distributors)) & (df['Statistics Model'].isin(models))]
    generate_dos_file(filtered_df, today)
    generate_distributor_file(filtered_df, today)

if __name__ == "__main__":
    main()


import unittest
import json
from grano.test.util import make_app, teardown_app
from grano.model import User

class UsersTestCase(unittest.TestCase):

    def setUp(self):
        self.app = make_app()

    def tearDown(self):
        teardown_app(self.app)

    def test_user_from_browserid(self):
        user = User.from_browserid({'email': 'fake@something.com', 'issuer': 'pudo.org'})
        assert user is not None, user
        assert User.objects.count()==1, User.objects.all()

    def test_user_session(self):
        user = User.from_browserid({'email': 'fake@something.com', 'issuer': 'pudo.org'})

        data = json.loads(self.app.get('/api/1/sessions').get_data())
        assert not data.get('logged_in'), data

        with self.app.session_transaction() as sess:
            sess['user_id'] = user.email
            sess['_fresh'] = True

        data = json.loads(self.app.get('/api/1/sessions').get_data())
        assert data.get('logged_in'), data
        assert data.get('user').get('email')==user.email


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

import pygame
import time
import os
import sys
from pygame.locals import *

#Initialisation de Pygame

screen_width = 1000
screen_height = 600
screen = pygame.display.set_mode((screen_width,screen_height))
game_icon = pygame.image.load("pictures/icon_game.png").convert_alpha()
screen_icon = pygame.display.set_icon(game_icon)
pygame.display.set_caption('STEX JOURNEY')
clock = pygame.time.Clock()
pygame.init()

#Chargement des données du jeu

wallpaper = pygame.image.load("pictures/wallpaper.png").convert()
blur_wallpaper = pygame.image.load("pictures/blur_wallpaper.png").convert_alpha()
blur_menu1 = pygame.image.load("pictures/blur_menu_out.png").convert_alpha()
credits_screen = pygame.image.load("pictures/screen_credits.png").convert_alpha()
commands_screen = pygame.image.load("pictures/screen_commands.png").convert_alpha()
fondingame = pygame.image.load("pictures/fondingame.png").convert()
game_intro = pygame.image.load("pictures/game_intro.png").convert()
loading_1 = pygame.image.load("pictures/loading_1.png").convert()
loading_2 = pygame.image.load("pictures/loading_2.png").convert()
loading_3 = pygame.image.load("pictures/loading_3.png").convert()
first_house = pygame.image.load("pictures/first_house.png").convert()
second_house = pygame.image.load("pictures/second_house.png").convert()
up_house = pygame.image.load("pictures/up_house.png").convert()

luffy_d = pygame.image.load("pictures/avatar/luffy_d.png").convert_alpha()
luffy_d_blur = pygame.image.load("pictures/avatar/luffy_d_blur.png").convert_alpha()
luffy_d1 = pygame.image.load("pictures/avatar/luffy_d1.png").convert_alpha()
luffy_d2 = pygame.image.load("pictures/avatar/luffy_d2.png").convert_alpha()
luffy_d3 = pygame.image.load("pictures/avatar/luffy_d3.png").convert_alpha()
luffy_d4 = pygame.image.load("pictures/avatar/luffy_d4.png").convert_alpha()

luffy_u = pygame.image.load("pictures/avatar/luffy_u.png").convert_alpha()
luffy_u1 = pygame.image.load("pictures/avatar/luffy_u1.png").convert_alpha()
luffy_u2 = pygame.image.load("pictures/avatar/luffy_u2.png").convert_alpha()
luffy_u3 = pygame.image.load("pictures/avatar/luffy_u3.png").convert_alpha()
luffy_u4 = pygame.image.load("pictures/avatar/luffy_u4.png").convert_alpha()

luffy_r = pygame.image.load("pictures/avatar/luffy_r.png").convert_alpha()
luffy_r1 = pygame.image.load("pictures/avatar/luffy_r1.png").convert_alpha()
luffy_r2 = pygame.image.load("pictures/avatar/luffy_r2.png").convert_alpha()
luffy_r3 = pygame.image.load("pictures/avatar/luffy_r3.png").convert_alpha()
luffy_r4 = pygame.image.load("pictures/avatar/luffy_r4.png").convert_alpha()

luffy_l = pygame.image.load("pictures/avatar/luffy_l.png").convert_alpha()
luffy_l1 = pygame.image.load("pictures/avatar/luffy_l1.png").convert_alpha()
luffy_l2 = pygame.image.load("pictures/avatar/luffy_l2.png").convert_alpha()
luffy_l3 = pygame.image.load("pictures/avatar/luffy_l3.png").convert_alpha()
luffy_l4 = pygame.image.load("pictures/avatar/luffy_l4.png").convert_alpha()

villager = pygame.image.load("pictures/avatar/bot.png").convert_alpha()

mcdo = pygame.image.load("pictures/items/mcdo.png").convert_alpha()
mcdo2 = pygame.image.load("pictures/items/mcdo2.png").convert_alpha()
mcdo3 = pygame.image.load("pictures/items/mcdo3.png").convert_alpha()
mcdo4 = pygame.image.load("pictures/items/mcdo4.png").convert_alpha()

potion = pygame.image.load("pictures/items/potion.png").convert_alpha()
potion2 = pygame.image.load("pictures/items/potion2.png").convert_alpha()
potion3 = pygame.image.load("pictures/items/potion3.png").convert_alpha()
potion4 = pygame.image.load("pictures/items/potion4.png").convert_alpha()

shield = pygame.image.load("pictures/items/shield.png").convert_alpha()
shield2 = pygame.image.load("pictures/items/shield2.png").convert_alpha()
shield3 = pygame.image.load("pictures/items/shield3.png").convert_alpha()
shield4 = pygame.image.load("pictures/items/shield4.png").convert_alpha()

sword = pygame.image.load("pictures/items/sword.png").convert_alpha()
sword2 = pygame.image.load("pictures/items/sword2.png").convert_alpha()
sword3 = pygame.image.load("pictures/items/sword3.png").convert_alpha()
sword4 = pygame.image.load("pictures/items/sword4.png").convert_alpha()

nothing = pygame.image.load("pictures/nothing.png").convert_alpha()

game_title = pygame.image.load("buttons/home_title.png").convert_alpha()
play_1 = pygame.image.load("buttons/jouer_1.png").convert_alpha()
play_2 = pygame.image.load("buttons/jouer_2.png").convert_alpha()
settings_1 = pygame.image.load("buttons/options_1.png").convert_alpha()
settings_2 = pygame.image.load("buttons/options_2.png").convert_alpha()
commands_1 = pygame.image.load("buttons/commandes_1.png").convert_alpha()
commands_2 = pygame.image.load("buttons/commandes_2.png").convert_alpha()
credits_1 = pygame.image.load("buttons/credits_1.png").convert_alpha()
credits_2 = pygame.image.load("buttons/credits_2.png").convert_alpha()
back_button = pygame.image.load("buttons/retour.png").convert_alpha()
son_on = pygame.image.load("buttons/son_on.png").convert_alpha()
son_off = pygame.image.load("buttons/son_off.png").convert_alpha()

play_r = play_1.get_rect()
play_r.x, play_r.y = 0,240
settings_r = settings_1.get_rect()
settings_r.x, settings_r.y = 0,320
commands_r = commands_1.get_rect()
commands_r.x, commands_r.y = 0,405
credits_r = credits_1.get_rect()
credits_r.x, credits_r.y = 0,490
back_r = back_button.get_rect()
back_r.x, back_r.y = 925,25
son_r = son_on.get_rect()
son_r.x, son_r.y = 325,200

#Fontions

def LoadingMenu():
    screen_wallpaper = screen.blit(wallpaper,(0,-45))
    screen_title = screen.blit(game_title,(0,0))
    play_btn = screen.blit(play_1,(0,240))
    options_btn = screen.blit(settings_1,(0,320))
    commandes_btn = screen.blit(commands_1,(0,405))
    credits_btn = screen.blit(credits_1,(0,490))
    global CurrentMenu
    CurrentMenu = "LoadingMenu"
    print(CurrentMenu + ' loaded')

def Play_intro():
    screen_wallpaper = screen.blit(game_intro,(0,0))
    screen_luffy = screen.blit(luffy_d,(xluffy,yluffy))
    sword_display = screen.blit(sword,(254,128))
    pygame.mouse.set_visible(False)
    pygame.key.set_repeat(True)
    pygame.display.flip()
    global CurrentMenu
    CurrentMenu = "PlayMenu"
    print(CurrentMenu + 'loaded')

def Settings_on():
    screen_blur = screen.blit(blur_wallpaper,(0,-45))
    screen_title = screen.blit(game_title,(0,0))
    screen_back = screen.blit(back_button,(925,25))
    screen_sonon = screen.blit(son_on,(325,200))
    pygame.display.flip()
    global CurrentMenu
    CurrentMenu = "SettingsMenu_on"
    print(CurrentMenu + ' loaded')

def Settings_off():
    screen_blur = screen.blit(blur_wallpaper,(0,-45))
    screen_title = screen.blit(game_title,(0,0))
    screen_back = screen.blit(back_button,(925,25))
    screen_sonoff = screen.blit(son_off,(325,200))
    pygame.display.flip()
    global CurrentMenu
    CurrentMenu = "SettingsMenu_off"
    print(CurrentMenu + ' loaded')

def Commands():
    screen_blur = screen.blit(blur_wallpaper,(0,-45))
    screen_commands = screen.blit(commands_screen,(0,0))
    screen_title = screen.blit(game_title,(0,0))
    screen_back = screen.blit(back_button,(925,25))
    pygame.display.flip()
    global CurrentMenu
    CurrentMenu = "CommandsMenu"
    print(CurrentMenu + ' loaded')

def Credits():
    screen_blur = screen.blit(blur_wallpaper,(0,-45))
    screen_credits = screen.blit(credits_screen,(0,0))
    screen_title = screen.blit(game_title,(0,0))
    screen_back = screen.blit(back_button,(925,25))
    pygame.display.flip()
    global CurrentMenu
    CurrentMenu = "CreditsMenu"
    print(CurrentMenu + ' loaded')

def WhichOneIsOnHover():
    if play_r.collidepoint(pygame.mouse.get_pos()) and n != 1:
        screen_wallpaper = screen.blit(wallpaper,(0,-45))
        screen_title = screen.blit(game_title,(0,0))
        play_btn = screen.blit(play_2,(0,240))
        options_btn = screen.blit(settings_1,(0,320))
        commandes_btn = screen.blit(commands_1,(0,405))
        credits_btn = screen.blit(credits_1,(0,490))
        pygame.display.flip()

    if settings_r.collidepoint(pygame.mouse.get_pos()) and n != 1:
        screen_wallpaper = screen.blit(wallpaper,(0,-45))
        screen_title = screen.blit(game_title,(0,0))
        play_btn = screen.blit(play_1,(0,240))
        options_btn = screen.blit(settings_2,(0,320))
        commandes_btn = screen.blit(commands_1,(0,405))
        credits_btn = screen.blit(credits_1,(0,490))
        pygame.display.flip()

    if commands_r.collidepoint(pygame.mouse.get_pos()) and n != 1:
        screen_wallpaper = screen.blit(wallpaper,(0,-45))
        screen_title = screen.blit(game_title,(0,0))
        play_btn = screen.blit(play_1,(0,240))
        options_btn = screen.blit(settings_1,(0,320))
        commandes_btn = screen.blit(commands_2,(0,405))
        credits_btn = screen.blit(credits_1,(0,490))
        pygame.display.flip()

    if credits_r.collidepoint(pygame.mouse.get_pos()) and n != 1:
        screen_wallpaper = screen.blit(wallpaper,(0,-45))
        screen_title = screen.blit(game_title,(0,0))
        play_btn = screen.blit(play_1,(0,240))
        options_btn = screen.blit(settings_1,(0,320))
        commandes_btn = screen.blit(commands_1,(0,405))
        credits_btn = screen.blit(credits_2,(0,490))
        pygame.display.flip()

def PairImpair(x):
    if x%2 == 0:
        return True
    if x%2 !=0:
        return False

def LoadingGame():
    for nb in range(3):
        screen_load_1 = screen.blit(loading_1,(0,0))
        pygame.display.flip()
        time.sleep(0.4)
        screen_load_2 = screen.blit(loading_2,(0,0))
        pygame.display.flip()
        time.sleep(0.4)
        screen_load_3 = screen.blit(loading_3,(0,0))
        pygame.display.flip()
        time.sleep(0.4)

def LuffyPos():
    if luffy_pos == luffy_d:
        screen_luffy = screen.blit(luffy_d_blur,(xluffy,yluffy))

xleft_upforest1 = 56
xleft_upforest2 = 184
yleft_upforest = 229

xleft_house1 = 248
xleft_house2 = 568
yleft_house = 189

xstairs = 504
ystairs = 109

xright_house1 = 632
xright_house2 = 824
yright_house = 269

xleft_stairs = 504
yleft_stairs = 149

xleft_downforest1 = 56
xleft_downforest2 = 120
yleft_downforest = 349

xmiddle_downforest1 = 184
xmiddle_downforest2 = 760
ymiddle_downforest = 469

xright_downforest = 824
yright_downforest = 349

yleft_forestborder1_1 = 229
yleft_forestborder1_2 = 349
xleft_forestborder1 = 56

yleft_forestborder2_1 = 389
yleft_forestborder2_2 = 469
xleft_forestborder2 = 184

yleft_forestborder3_1 = 109
yleft_forestborder3_2 = 189
xleft_forestborder3 = 248

yright_righthouse1 = 189
yright_righthouse2 = 229
xright_righthouse = 568

yright_forest1 = 389
yright_forest2 = 469
xright_forest = 760

yright_map1 = 269
yright_map2 = 349
xright_map = 824

def left_upforest():
    if xluffy >= xleft_upforest1 and xluffy <= xleft_upforest2 and yluffy > yleft_upforest:
        return True
    else:
        return False

def left_house():
    if xluffy >= xleft_house1 and xluffy <= xleft_house2 and yluffy > yleft_house:
        return True
    else:
        return False

def stairs():
    if xluffy == xstairs and yluffy > ystairs:
        return True
    else:
        return False

def right_house():
    if xluffy >= xright_house1 and xluffy <= xright_house2 and yluffy > yright_house:
        return True
    else:
        return False

def left_downforest():
    if xluffy >= xleft_downforest1 and xluffy <= xleft_downforest2 and yluffy < yleft_downforest:
        return True
    else:
        return False

def middle_downforest():
    if xluffy >= xmiddle_downforest1 and xluffy <= xmiddle_downforest2 and yluffy < ymiddle_downforest:
        return True
    else:
        return False

def right_downforest():
    if xluffy == xright_downforest and yluffy < yright_downforest:
        return True
    else:
        return False

def left_stairs():
    if xluffy == xleft_stairs and yluffy == yleft_stairs:
        return False

def left_forestborder1():
    if yluffy >= yleft_forestborder1_1 and yluffy <= yleft_forestborder1_2 and xluffy > xleft_forestborder1:
        return True
    else:
        return False

def left_forestborder2():
    if yluffy >= yleft_forestborder2_1 and yluffy <= yleft_forestborder2_2 and xluffy > xleft_forestborder2:
        return True
    else:
        return False

def left_forestborder3():
    if yluffy >= yleft_forestborder3_1 and yluffy <= yleft_forestborder3_2 and xluffy > xleft_forestborder3:
        return True
    else:
        return False

def right_righthouse():
    if yluffy >= yright_righthouse1 and yluffy <= yright_righthouse2 and xluffy < xright_righthouse:
        return True
    else:
        return False

def right_forest():
    if yluffy >= yright_forest1 and yluffy <= yright_forest2 and xluffy < xright_forest:
        return True
    else:
        return False

def right_map():
    if yluffy >= yright_map1 and yluffy <= yright_map2 and xluffy < xright_map:
        return True
    else:
        return False

def inHouse1():
    global lc
    if lc == 1:
        potion_display = screen.blit(potion,(542,163))

def inHouse2():
    global lc
    if lc == 2:
        mcdo_display = screen.blit(mcdo,(371,140))

def inUphouse():
    global lc
    if lc == 3:
        shield_display = screen.blit(shield,(400,207))

def outdoor():
    global lc
    if lc == 0:
        sword_display = screen.blit(sword,(254,128))

mcdo_list = [mcdo2, mcdo3, mcdo4]
potion_list = [potion2, potion3, potion4]
shield_list = [shield2, shield3, shield4]
sword_list = [sword2, sword3, sword4]

def mcdo_found():
    for i in range(3):
        screen_wallpaper = screen.blit(game_intro,(0,0))
        screen.blit(mcdo_list[i],(371,140))
        screen_luffy = screen.blit(luffy_u,(xluffy,yluffy))
        pygame.display.update()
        time.sleep(0.2)
    screen_wallpaper = screen.blit(game_intro,(0,0))
    screen_luffy = screen.blit(luffy_u,(xluffy,yluffy))
    pygame.display.update()

def potion_found():
    for i in range(3):
        screen_wallpaper = screen.blit(game_intro,(0,0))
        screen.blit(potion_list[i],(542,163))
        screen_luffy = screen.blit(luffy_u,(xluffy,yluffy))
        pygame.display.update()
        time.sleep(0.2)
    screen_wallpaper = screen.blit(game_intro,(0,0))
    screen_luffy = screen.blit(luffy_u,(xluffy,yluffy))
    pygame.display.update()

def shield_found():
    for i in range(3):
        screen_wallpaper = screen.blit(game_intro,(0,0))
        screen.blit(shield_list[i],(400,207))
        screen_luffy = screen.blit(luffy_u,(xluffy,yluffy))
        pygame.display.update()
        time.sleep(0.2)
    screen_wallpaper = screen.blit(game_intro,(0,0))
    screen_luffy = screen.blit(luffy_u,(xluffy,yluffy))
    pygame.display.update()

def sword_found():
    for i in range(3):
        screen_wallpaper = screen.blit(game_intro,(0,0))
        screen.blit(sword_list[i],(254,128))
        screen_luffy = screen.blit(luffy_u,(xluffy,yluffy))
        pygame.display.update()
        time.sleep(0.2)
    screen_wallpaper = screen.blit(game_intro,(0,0))
    screen_luffy = screen.blit(luffy_u,(xluffy,yluffy))
    pygame.display.update()

#Lancement de la boucle Menu

menu_run = True
n = 0
x = 0
o = 0

if n == 0:
    LoadingMenu()

while menu_run:
    for event in pygame.event.get():
        if event.type == QUIT:
            menu_run = False
            pygame.quit()
            sys.exit()

        if back_r.collidepoint(pygame.mouse.get_pos()) and event.type == MOUSEBUTTONDOWN and n == 1:
            LoadingMenu()
            n = 0

        if play_r.collidepoint(pygame.mouse.get_pos()) and event.type == MOUSEBUTTONDOWN and n != 1:
            menu_run = False
            n = 2

        if settings_r.collidepoint(pygame.mouse.get_pos()) and event.type == MOUSEBUTTONDOWN and n != 1:
            if PairImpair(x) == False:
                Settings_on()
            if PairImpair(x) == True:
                Settings_off()
            n = 1
            o = 1

        if commands_r.collidepoint(pygame.mouse.get_pos()) and event.type == MOUSEBUTTONDOWN and n != 1:
            Commands()
            n = 1

        if credits_r.collidepoint(pygame.mouse.get_pos()) and event.type == MOUSEBUTTONDOWN and n != 1:
            Credits()
            n = 1

        if son_r.collidepoint(pygame.mouse.get_pos()) and event.type == MOUSEBUTTONDOWN and o == 1:
            if PairImpair(x) == True:
                Settings_on()
            if PairImpair(x) == False:
                Settings_off()
            x += 1
            print(x)

        if n == 0:
            o = 0

    WhichOneIsOnHover()
    pygame.display.flip()

#Chargement du jeu

LoadingGame()

#Lancemant de la boucle du jeu "In Game"

ingame = True
i = 0
s1 = 0
lc = 0
itm_mcdo = 0
itm_potion = 0
itm_shield = 0
itm_sword = 0
xluffy = 824
yluffy = 349
luffy_pos = luffy_d

Play_intro()

while ingame:
    for event in pygame.event.get():
        if event.type == QUIT:
            ingame = False
            pygame.quit()
            sys.exit()

        if xluffy == 56 and yluffy == 309 or yluffy == 349 and event.type == KEYDOWN and event.key == K_LEFT:
            if itm_mcdo and itm_potion and itm_shield and itm_sword == 1:
                LoadingGame()
                ingame = False
                pygame.quit()
                sys.exit()

        if xluffy == 371 and yluffy == 173 and lc == 2 and itm_mcdo == 0:
            mcdo_found()
            itm_mcdo = 1
            mcdo = nothing

        if xluffy == 540 and yluffy == 174 and lc == 1 and itm_potion == 0:
            potion_found()
            itm_potion = 1
            potion = nothing

        if xluffy == 400 and yluffy == 230 and lc == 3 and itm_shield == 0:
            shield_found()
            itm_shield = 1
            shield = nothing

        if xluffy == 248 and yluffy == 149 and lc == 0 and itm_sword == 0:
            sword_found()
            itm_sword = 1
            sword = nothing

        if xluffy == 696 and yluffy == 269 and event.type == KEYDOWN and event.key == K_UP:
            s1 += 1
            lc = 2

            xleft_upforest1 = 243
            xleft_upforest2 = 691
            yleft_upforest = 173

            xleft_house1 = 243
            xleft_house2 = 691
            yleft_house = 173

            xstairs = 0
            ystairs = 0

            xright_house1 = 243
            xright_house2 = 691
            yright_house = 173

            xleft_downforest1 = 243
            xleft_downforest2 = 243
            yleft_downforest = 333

            xmiddle_downforest1 = 307
            xmiddle_downforest2 = 627
            ymiddle_downforest = 413

            xright_downforest = 691
            yright_downforest = 333

            xleft_stairs = 0
            yleft_stairs = 0

            yleft_forestborder1_1 = 373
            yleft_forestborder1_2 = 413
            xleft_forestborder1 = 307

            yleft_forestborder2_1 = 173
            yleft_forestborder2_2 = 333
            xleft_forestborder2 = 243

            yleft_forestborder3_1 = 173
            yleft_forestborder3_2 = 333
            xleft_forestborder3 = 243

            yright_righthouse1 = 373
            yright_righthouse2 = 413
            xright_righthouse = 627

            yright_forest1 = 173
            yright_forest2 = 333
            xright_forest = 691

            yright_map1 = 173
            yright_map2 = 333
            xright_map = 691

            if s1 == 1:
                game_intro = second_house
                screen_wallpaper = screen.blit(game_intro,(0,0))
                mcdo_display = screen.blit(mcdo,(371,140))
                xluffy = 435
                yluffy = 413
                screen_luffy = screen.blit(luffy_u,(xluffy,yluffy))
                pygame.display.flip()

        if xluffy == 435 and yluffy == 413 and event.type == KEYDOWN and event.key == K_DOWN and s1 == 1:
            s1 = 0
            lc = 0

            xleft_upforest1 = 56
            xleft_upforest2 = 184
            yleft_upforest = 229

            xleft_house1 = 248
            xleft_house2 = 568
            yleft_house = 189

            xstairs = 504
            ystairs = 109

            xright_house1 = 632
            xright_house2 = 824
            yright_house = 269

            xleft_downforest1 = 56
            xleft_downforest2 = 120
            yleft_downforest = 349

            xmiddle_downforest1 = 184
            xmiddle_downforest2 = 760
            ymiddle_downforest = 469

            xright_downforest = 824
            yright_downforest = 349

            xleft_stairs = 504
            yleft_stairs = 149

            yleft_forestborder1_1 = 229
            yleft_forestborder1_2 = 349
            xleft_forestborder1 = 56

            yleft_forestborder2_1 = 389
            yleft_forestborder2_2 = 469
            xleft_forestborder2 = 184

            yleft_forestborder3_1 = 109
            yleft_forestborder3_2 = 189
            xleft_forestborder3 = 248

            yright_righthouse1 = 189
            yright_righthouse2 = 229
            xright_righthouse = 568

            yright_forest1 = 389
            yright_forest2 = 469
            xright_forest = 760

            yright_map1 = 269
            yright_map2 = 349
            xright_map = 824

            game_intro = pygame.image.load("pictures/game_intro.png").convert()
            screen_wallpaper = screen.blit(game_intro,(0,0))
            sword_display = screen.blit(sword,(254,128))
            xluffy = 696
            yluffy = 269
            screen_luffy = screen.blit(luffy_d,(xluffy,yluffy))
            pygame.display.flip()

        if xluffy == 376 and yluffy == 189 and event.type == KEYDOWN and event.key == K_UP:
            s1 += 1
            lc = 1

            xleft_upforest1 = 284
            xleft_upforest2 = 668
            yleft_upforest = 174

            xleft_house1 = 284
            xleft_house2 = 668
            yleft_house = 174

            xstairs = 0
            ystairs = 0

            xright_house1 = 284
            xright_house2 = 668
            yright_house = 174

            xleft_downforest1 = 284
            xleft_downforest2 = 284
            yleft_downforest = 334

            xmiddle_downforest1 = 348
            xmiddle_downforest2 = 668
            ymiddle_downforest = 414

            xright_downforest = 0
            yright_downforest = 0

            xleft_stairs = 0
            yleft_stairs = 0

            yleft_forestborder1_1 = 374
            yleft_forestborder1_2 = 414
            xleft_forestborder1 = 348

            yleft_forestborder2_1 = 174
            yleft_forestborder2_2 = 334
            xleft_forestborder2 = 284

            yleft_forestborder3_1 = 174
            yleft_forestborder3_2 = 334
            xleft_forestborder3 = 284

            yright_righthouse1 = 174
            yright_righthouse2 = 414
            xright_righthouse = 668

            yright_forest1 = 174
            yright_forest2 = 414
            xright_forest = 668

            yright_map1 = 174
            yright_map2 = 414
            xright_map = 668

            if s1 == 1:
                game_intro = first_house
                screen_wallpaper = screen.blit(game_intro,(0,0))
                potion_display = screen.blit(potion,(542,163))
                xluffy = 540
                yluffy = 414
                screen_luffy = screen.blit(luffy_u,(xluffy,yluffy))
                pygame.display.flip()

        if xluffy == 540 and yluffy == 414 and event.type == KEYDOWN and event.key == K_DOWN and s1 == 1:
            s1 = 0
            lc = 0

            xleft_upforest1 = 56
            xleft_upforest2 = 184
            yleft_upforest = 229

            xleft_house1 = 248
            xleft_house2 = 568
            yleft_house = 189

            xstairs = 504
            ystairs = 109

            xright_house1 = 632
            xright_house2 = 824
            yright_house = 269

            xleft_downforest1 = 56
            xleft_downforest2 = 120
            yleft_downforest = 349

            xmiddle_downforest1 = 184
            xmiddle_downforest2 = 760
            ymiddle_downforest = 469

            xright_downforest = 824
            yright_downforest = 349

            xleft_stairs = 504
            yleft_stairs = 149

            yleft_forestborder1_1 = 229
            yleft_forestborder1_2 = 349
            xleft_forestborder1 = 56

            yleft_forestborder2_1 = 389
            yleft_forestborder2_2 = 469
            xleft_forestborder2 = 184

            yleft_forestborder3_1 = 109
            yleft_forestborder3_2 = 189
            xleft_forestborder3 = 248

            yright_righthouse1 = 189
            yright_righthouse2 = 229
            xright_righthouse = 568

            yright_forest1 = 389
            yright_forest2 = 469
            xright_forest = 760

            yright_map1 = 269
            yright_map2 = 349
            xright_map = 824

            game_intro = pygame.image.load("pictures/game_intro.png").convert()
            screen_wallpaper = screen.blit(game_intro,(0,0))
            sword_display = screen.blit(sword,(254,128))
            xluffy = 376
            yluffy = 189
            screen_luffy = screen.blit(luffy_d,(xluffy,yluffy))
            pygame.display.flip()

        if xluffy == 504 and yluffy == 109 and event.type == KEYDOWN and event.key == K_LEFT:
            s1 += 1
            lc = 3

            xleft_upforest1 = 272
            xleft_upforest2 = 592
            yleft_upforest = 230

            xleft_house1 = 272
            xleft_house2 = 592
            yleft_house = 230

            xstairs = 656
            ystairs = 270

            xright_house1 = 272
            xright_house2 = 592
            yright_house = 230

            xleft_stairs = 0
            yleft_stairs = 0

            xleft_downforest1 = 272
            xleft_downforest2 = 592
            yleft_downforest = 430

            xmiddle_downforest1 = 272
            xmiddle_downforest2 = 592
            ymiddle_downforest = 430

            xright_downforest = 656
            yright_downforest = 310

            yleft_forestborder1_1 = 230
            yleft_forestborder1_2 = 440
            xleft_forestborder1 = 272

            yleft_forestborder2_1 = 230
            yleft_forestborder2_2 = 440
            xleft_forestborder2 = 272

            yleft_forestborder3_1 = 230
            yleft_forestborder3_2 = 440
            xleft_forestborder3 = 272

            yright_righthouse1 = 230
            yright_righthouse2 = 230
            xright_righthouse = 592

            yright_forest1 = 350
            yright_forest2 = 430
            xright_forest = 592

            yright_map1 = 270
            yright_map2 = 310
            xright_map = 656

            if s1 == 1:
                game_intro = up_house
                screen_wallpaper = screen.blit(game_intro,(0,0))
                shield_display = screen.blit(shield,(400,207))
                xluffy = 592
                yluffy = 230
                screen_luffy = screen.blit(luffy_l,(xluffy,yluffy))
                pygame.display.flip()

        if xluffy == 592 and yluffy == 230 and event.type == KEYDOWN and event.key == K_RIGHT and s1 == 1:
            s1 = 0
            lc = 0

            xleft_upforest1 = 56
            xleft_upforest2 = 184
            yleft_upforest = 229

            xleft_house1 = 248
            xleft_house2 = 568
            yleft_house = 189

            xstairs = 504
            ystairs = 109

            xright_house1 = 632
            xright_house2 = 824
            yright_house = 269

            xleft_downforest1 = 56
            xleft_downforest2 = 120
            yleft_downforest = 349

            xmiddle_downforest1 = 184
            xmiddle_downforest2 = 760
            ymiddle_downforest = 469

            xright_downforest = 824
            yright_downforest = 349

            xleft_stairs = 504
            yleft_stairs =149

            yleft_forestborder1_1 = 229
            yleft_forestborder1_2 = 349
            xleft_forestborder1 = 56

            yleft_forestborder2_1 = 389
            yleft_forestborder2_2 = 469
            xleft_forestborder2 = 184

            yleft_forestborder3_1 = 109
            yleft_forestborder3_2 = 189
            xleft_forestborder3 = 248

            yright_righthouse1 = 189
            yright_righthouse2 = 229
            xright_righthouse = 568

            yright_forest1 = 389
            yright_forest2 = 469
            xright_forest = 760

            yright_map1 = 269
            yright_map2 = 349
            xright_map = 824

            game_intro = pygame.image.load("pictures/game_intro.png").convert()
            screen_wallpaper = screen.blit(game_intro,(0,0))
            sword_display = screen.blit(sword,(254,128))
            xluffy = 504
            yluffy = 109
            screen_luffy = screen.blit(luffy_d,(xluffy,yluffy))
            pygame.display.flip()

        if event.type == KEYDOWN and event.key == K_RIGHT:
            if right_righthouse() or right_forest() or right_map():
                luffy_pos = luffy_r
                xluffy += 8
                screen_wallpaper = screen.blit(game_intro,(0,0))
                inHouse1()
                inHouse2()
                inUphouse()
                outdoor()
                screen_luffy = screen.blit(luffy_r1,(xluffy,yluffy))
                pygame.display.flip()
                time.sleep(0.075)

                if event.type == KEYDOWN and event.key == K_RIGHT:
                    xluffy += 8
                    screen_wallpaper = screen.blit(game_intro,(0,0))
                    inHouse1()
                    inHouse2()
                    inUphouse()
                    outdoor()
                    screen_luffy = screen.blit(luffy_r2,(xluffy,yluffy))
                    pygame.display.flip()
                    time.sleep(0.075)

                    if event.type == KEYDOWN and event.key == K_RIGHT:
                        xluffy += 8
                        screen_wallpaper = screen.blit(game_intro,(0,0))
                        inHouse1()
                        inHouse2()
                        inUphouse()
                        outdoor()
                        screen_luffy = screen.blit(luffy_r1,(xluffy,yluffy))
                        pygame.display.flip()
                        time.sleep(0.075)

                        if event.type == KEYDOWN and event.key == K_RIGHT:
                            xluffy += 8
                            screen_wallpaper = screen.blit(game_intro,(0,0))
                            inHouse1()
                            inHouse2()
                            inUphouse()
                            outdoor()
                            screen_luffy = screen.blit(luffy_r,(xluffy,yluffy))
                            pygame.display.flip()
                            time.sleep(0.075)

                            if event.type == KEYDOWN and event.key == K_RIGHT:
                                xluffy += 8
                                screen_wallpaper = screen.blit(game_intro,(0,0))
                                inHouse1()
                                inHouse2()
                                inUphouse()
                                outdoor()
                                screen_luffy = screen.blit(luffy_r3,(xluffy,yluffy))
                                pygame.display.flip()
                                time.sleep(0.075)

                                if event.type == KEYDOWN and event.key == K_RIGHT:
                                    xluffy += 8
                                    screen_wallpaper = screen.blit(game_intro,(0,0))
                                    inHouse1()
                                    inHouse2()
                                    inUphouse()
                                    outdoor()
                                    screen_luffy = screen.blit(luffy_r4,(xluffy,yluffy))
                                    pygame.display.flip()
                                    time.sleep(0.075)

                                    if event.type == KEYDOWN and event.key == K_RIGHT:
                                        xluffy += 8
                                        screen_wallpaper = screen.blit(game_intro,(0,0))
                                        inHouse1()
                                        inHouse2()
                                        inUphouse()
                                        outdoor()
                                        screen_luffy = screen.blit(luffy_r3,(xluffy,yluffy))
                                        pygame.display.flip()
                                        time.sleep(0.075)

                                        if event.type == KEYDOWN and event.key == K_RIGHT:
                                            xluffy += 8
                                            screen_wallpaper = screen.blit(game_intro,(0,0))
                                            inHouse1()
                                            inHouse2()
                                            inUphouse()
                                            outdoor()
                                            screen_luffy = screen.blit(luffy_r,(xluffy,yluffy))
                                            pygame.display.flip()
                                            time.sleep(0.075)

        print(xluffy)
        print(yluffy)

        if event.type == KEYDOWN and event.key == K_LEFT:
            if left_forestborder1() or left_forestborder2() or left_forestborder3() or left_stairs():
                luffy_pos = luffy_l
                xluffy -= 8
                screen_wallpaper = screen.blit(game_intro,(0,0))
                inHouse1()
                inHouse2()
                inUphouse()
                outdoor()
                screen_luffy = screen.blit(luffy_l1,(xluffy,yluffy))
                pygame.display.flip()
                time.sleep(0.075)

                if event.type == KEYDOWN and event.key == K_LEFT:
                    xluffy -= 8
                    screen_wallpaper = screen.blit(game_intro,(0,0))
                    inHouse1()
                    inHouse2()
                    inUphouse()
                    outdoor()
                    screen_luffy = screen.blit(luffy_l2,(xluffy,yluffy))
                    pygame.display.flip()
                    time.sleep(0.075)

                    if event.type == KEYDOWN and event.key == K_LEFT:
                        xluffy -= 8
                        screen_wallpaper = screen.blit(game_intro,(0,0))
                        inHouse1()
                        inHouse2()
                        inUphouse()
                        outdoor()
                        screen_luffy = screen.blit(luffy_l1,(xluffy,yluffy))
                        pygame.display.flip()
                        time.sleep(0.075)

                        if event.type == KEYDOWN and event.key == K_LEFT:
                            xluffy -= 8
                            screen_wallpaper = screen.blit(game_intro,(0,0))
                            inHouse1()
                            inHouse2()
                            inUphouse()
                            outdoor()
                            screen_luffy = screen.blit(luffy_l,(xluffy,yluffy))
                            pygame.display.flip()
                            time.sleep(0.075)

                            if event.type == KEYDOWN and event.key == K_LEFT:
                                xluffy -= 8
                                screen_wallpaper = screen.blit(game_intro,(0,0))
                                inHouse1()
                                inHouse2()
                                inUphouse()
                                outdoor()
                                screen_luffy = screen.blit(luffy_l3,(xluffy,yluffy))
                                pygame.display.flip()
                                time.sleep(0.075)

                                if event.type == KEYDOWN and event.key == K_LEFT:
                                    xluffy -= 8
                                    screen_wallpaper = screen.blit(game_intro,(0,0))
                                    inHouse1()
                                    inHouse2()
                                    inUphouse()
                                    outdoor()
                                    screen_luffy = screen.blit(luffy_l4,(xluffy,yluffy))
                                    pygame.display.flip()
                                    time.sleep(0.075)

                                    if event.type == KEYDOWN and event.key == K_LEFT:
                                        xluffy -= 8
                                        screen_wallpaper = screen.blit(game_intro,(0,0))
                                        inHouse1()
                                        inHouse2()
                                        inUphouse()
                                        outdoor()
                                        screen_luffy = screen.blit(luffy_l3,(xluffy,yluffy))
                                        pygame.display.flip()
                                        time.sleep(0.075)

                                        if event.type == KEYDOWN and event.key == K_LEFT:
                                            xluffy -= 8
                                            screen_wallpaper = screen.blit(game_intro,(0,0))
                                            inHouse1()
                                            inHouse2()
                                            inUphouse()
                                            outdoor()
                                            screen_luffy = screen.blit(luffy_l,(xluffy,yluffy))
                                            pygame.display.flip()
                                            time.sleep(0.075)

        print(xluffy)
        print(yluffy)

        if event.type == KEYDOWN and event.key == K_UP:
            if left_upforest() or left_house() or right_house() or stairs():
                luffy_pos = luffy_u
                yluffy -= 5
                screen_wallpaper = screen.blit(game_intro,(0,0))
                inHouse1()
                inHouse2()
                inUphouse()
                outdoor()
                screen_luffy = screen.blit(luffy_u1,(xluffy,yluffy))
                pygame.display.flip()
                time.sleep(0.075)

                if event.type == KEYDOWN and event.key == K_UP:
                    yluffy -= 5
                    screen_wallpaper = screen.blit(game_intro,(0,0))
                    inHouse1()
                    inHouse2()
                    inUphouse()
                    outdoor()
                    screen_luffy = screen.blit(luffy_u2,(xluffy,yluffy))
                    pygame.display.flip()
                    time.sleep(0.075)

                    if event.type == KEYDOWN and event.key == K_UP:
                        yluffy -= 5
                        screen_wallpaper = screen.blit(game_intro,(0,0))
                        inHouse1()
                        inHouse2()
                        inUphouse()
                        outdoor()
                        screen_luffy = screen.blit(luffy_u1,(xluffy,yluffy))
                        pygame.display.flip()
                        time.sleep(0.075)

                        if event.type == KEYDOWN and event.key == K_UP:
                            yluffy -= 5
                            screen_wallpaper = screen.blit(game_intro,(0,0))
                            inHouse1()
                            inHouse2()
                            inUphouse()
                            outdoor()
                            screen_luffy = screen.blit(luffy_u,(xluffy,yluffy))
                            pygame.display.flip()
                            time.sleep(0.075)

                            if event.type == KEYDOWN and event.key == K_UP:
                                yluffy -= 5
                                screen_wallpaper = screen.blit(game_intro,(0,0))
                                inHouse1()
                                inHouse2()
                                inUphouse()
                                outdoor()
                                screen_luffy = screen.blit(luffy_u3,(xluffy,yluffy))
                                pygame.display.flip()
                                time.sleep(0.075)

                                if event.type == KEYDOWN and event.key == K_UP:
                                    yluffy -= 5
                                    screen_wallpaper = screen.blit(game_intro,(0,0))
                                    inHouse1()
                                    inHouse2()
                                    inUphouse()
                                    outdoor()
                                    screen_luffy = screen.blit(luffy_u4,(xluffy,yluffy))
                                    pygame.display.flip()
                                    time.sleep(0.075)

                                    if event.type == KEYDOWN and event.key == K_UP:
                                        yluffy -= 5
                                        screen_wallpaper = screen.blit(game_intro,(0,0))
                                        inHouse1()
                                        inHouse2()
                                        inUphouse()
                                        outdoor()
                                        screen_luffy = screen.blit(luffy_u3,(xluffy,yluffy))
                                        pygame.display.flip()
                                        time.sleep(0.075)

                                        if event.type == KEYDOWN and event.key == K_UP:
                                            yluffy -= 5
                                            screen_wallpaper = screen.blit(game_intro,(0,0))
                                            inHouse1()
                                            inHouse2()
                                            inUphouse()
                                            outdoor()
                                            screen_luffy = screen.blit(luffy_u,(xluffy,yluffy))
                                            pygame.display.flip()
                                            time.sleep(0.075)

        print(xluffy)
        print(yluffy)

        if event.type == KEYDOWN and event.key == K_DOWN:
            if left_downforest() or middle_downforest() or right_downforest():
                luffy_pos = luffy_d
                yluffy += 5
                screen_wallpaper = screen.blit(game_intro,(0,0))
                inHouse1()
                inHouse2()
                inUphouse()
                outdoor()
                screen_luffy = screen.blit(luffy_d1,(xluffy,yluffy))
                pygame.display.flip()
                time.sleep(0.075)

                if event.type == KEYDOWN and event.key == K_DOWN:
                    yluffy += 5
                    screen_wallpaper = screen.blit(game_intro,(0,0))
                    inHouse1()
                    inHouse2()
                    inUphouse()
                    outdoor()
                    screen_luffy = screen.blit(luffy_d2,(xluffy,yluffy))
                    pygame.display.flip()
                    time.sleep(0.075)

                    if event.type == KEYDOWN and event.key == K_DOWN:
                        yluffy += 5
                        screen_wallpaper = screen.blit(game_intro,(0,0))
                        inHouse1()
                        inHouse2()
                        inUphouse()
                        outdoor()
                        screen_luffy = screen.blit(luffy_d1,(xluffy,yluffy))
                        pygame.display.flip()
                        time.sleep(0.075)

                        if event.type == KEYDOWN and event.key == K_DOWN:
                            yluffy += 5
                            screen_wallpaper = screen.blit(game_intro,(0,0))
                            inHouse1()
                            inHouse2()
                            inUphouse()
                            outdoor()
                            screen_luffy = screen.blit(luffy_d,(xluffy,yluffy))
                            pygame.display.flip()
                            time.sleep(0.075)

                            if event.type == KEYDOWN and event.key == K_DOWN:
                                yluffy += 5
                                screen_wallpaper = screen.blit(game_intro,(0,0))
                                inHouse1()
                                inHouse2()
                                inUphouse()
                                outdoor()
                                screen_luffy = screen.blit(luffy_d3,(xluffy,yluffy))
                                pygame.display.flip()
                                time.sleep(0.075)

                                if event.type == KEYDOWN and event.key == K_DOWN:
                                    yluffy += 5
                                    screen_wallpaper = screen.blit(game_intro,(0,0))
                                    inHouse1()
                                    inHouse2()
                                    inUphouse()
                                    outdoor()
                                    screen_luffy = screen.blit(luffy_d4,(xluffy,yluffy))
                                    pygame.display.flip()
                                    time.sleep(0.075)

                                    if event.type == KEYDOWN and event.key == K_DOWN:
                                        yluffy += 5
                                        screen_wallpaper = screen.blit(game_intro,(0,0))
                                        inHouse1()
                                        inHouse2()
                                        inUphouse()
                                        outdoor()
                                        screen_luffy = screen.blit(luffy_d3,(xluffy,yluffy))
                                        pygame.display.flip()
                                        time.sleep(0.075)

                                        if event.type == KEYDOWN and event.key == K_DOWN:
                                            yluffy += 5
                                            screen_wallpaper = screen.blit(game_intro,(0,0))
                                            inHouse1()
                                            inHouse2()
                                            inUphouse()
                                            outdoor()
                                            screen_luffy = screen.blit(luffy_d,(xluffy,yluffy))
                                            pygame.display.flip()
                                            time.sleep(0.075)

            print(xluffy)
            print(yluffy)


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

from __future__ import print_function

import math
import os

from IPython import display
from matplotlib import cm  #color map
from matplotlib import gridspec
from matplotlib import pyplot as plt
import numpy as np
import pandas as pd
from sklearn import metrics
import tensorflow as tf
from tensorflow.python.data import Dataset

tf.logging.set_verbosity(tf.logging.ERROR)
pd.options.display.max_rows = 10
pd.options.display.float_format = '{:.1f}'.format

# current working directory
cwd = os.getcwd()

training_file_path = cwd + "//california_housing_train.csv"
Testing_file_path = cwd +  "//california_housing_test.csv"

california_housing_dataframe = pd.read_csv(training_file_path, sep = ",")
california_housing_dataframe = california_housing_dataframe.reindex(
	np.random.permutation(california_housing_dataframe.index))

def preprocess_features(california_housing_dataframe):
	ColNums = california_housing_dataframe.shape[1]
	selected_features = california_housing_dataframe.iloc[:, 0:ColNums-1]  #select the first ColNums-1 features
	processed_features = selected_features.copy()

	# Create a synthetic feature
	processed_features["rooms_per_person"] = (
		california_housing_dataframe["total_rooms"]/
		california_housing_dataframe["population"])

	return processed_features

def preprocess_targets(california_housing_dataframe):
	#output_targets = california_housing_dataframe.copy()
	output_targets = pd.DataFrame()
	output_targets["median_house_value"] = (california_housing_dataframe["median_house_value"]/1000.0)
	return output_targets

training_examples = preprocess_features(california_housing_dataframe.head(12000))
#print(training_examples.describe())

training_targets = preprocess_targets(california_housing_dataframe.head(12000))
#print(training_targets.describe())

validation_examples = preprocess_features(california_housing_dataframe.tail(5000))
#print(validation_examples.describe())

validation_targets = preprocess_targets(california_housing_dataframe.tail(5000))
#print(validation_targets.describe())

# plot the input feature and targets
plt.figure(figsize = (13, 8)) # a figure instance with size (13, 8) in inch
ax = plt.subplot(1,2,1)
ax.set_title("Validation Data")

ax.set_autoscaley_on(False)
ax.set_ylim([32, 43])
ax.set_autoscalex_on(False)
ax.set_xlim([-126, -112])

plt.scatter(validation_examples["longitude"],
			validation_examples["latitude"],
			cmap = "coolwarm",
			c = validation_targets["median_house_value"]/ validation_targets["median_house_value"].max())

ax = plt.subplot(1,2,2)
ax.set_title("Training Data")

ax.set_autoscaley_on(False)
ax.set_ylim([32, 43])
ax.set_autoscalex_on(False)
ax.set_xlim([-126, -112])
plt.scatter(training_examples["longitude"],
			training_examples["latitude"],
			cmap = "coolwarm",
			c = training_targets["median_house_value"] / training_targets["median_house_value"].max())

_ = plt.plot()
plt.show()

def my_input_fn(features, targets, batch_size = 1, shuffle = True, num_epochs = None):
	# convert pandas data into a dict of np arrays
	features = {key: np.array(value) for key, value in dict(features).items()}

	# Construct a dataset, and configure batching/repeating
	ds = Dataset.from_tensor_slices((features, targets))
	ds = ds.batch(batch_size).repeat(num_epochs)

	if shuffle:
		ds = ds.shuffle(100000)

	# return the next batch of data
	features, labels = ds.make_one_shot_iterator().get_next()
	return features, labels

def construct_feature_columns(input_features):
	return set([tf.feature_column.numeric_column(my_feature) for my_feature in input_features])

def train_model(
	learning_rate,
	steps,
	batch_size,
	training_examples,
	training_targets,
	validation_examples,
	validation_targets):

	periods = 10
	steps_per_period = steps/periods

	muy_optimizer = tf.train.GradientDescentOptimizer(learning_rate = learning_rate)
	muy_optimizer = tf.contrib.estimator.clip_gradients_by_norm(muy_optimizer, 5.0)

	linear_regressor = tf.estimator.LinearRegressor(
		feature_columns = construct_feature_columns(training_examples),
		optimizer = muy_optimizer)

	# create input function
	trainging_input_fn = lambda: my_input_fn(training_examples, training_targets["median_house_value"], batch_size = batch_size)

	predict_training_input_fn = lambda: my_input_fn(training_examples, training_targets["median_house_value"], num_epochs = 1, shuffle = False)

	predict_validation_input_fn = lambda: my_input_fn(validation_examples, validation_targets["median_house_value"], num_epochs = 1, shuffle = False)

	print("Training model...")
	print("RMSE (on training data): ")

	training_rmse = []
	validation_rmse = []

	for period in range(0, periods):
		linear_regressor.train(input_fn = trainging_input_fn, steps = steps_per_period)

		# Take a break and compute predictions
		training_predictions = linear_regressor.predict(input_fn = predict_training_input_fn)
		training_predictions = np.array([item['predictions'][0] for item in training_predictions])

		validation_predictions = linear_regressor.predict(input_fn = predict_validation_input_fn)
		validation_predictions = np.array([item['predictions'][0] for item in validation_predictions])

		#print("Trainig Prediction : ")
		#print(training_predictions)

		#print("Training Targets : ")
		#print(training_targets)

		# compute training and validation loss
		training_root_mean_squared_error = math.sqrt(
				metrics.mean_squared_error(training_predictions, training_targets))

		validation_root_mean_squared_error = math.sqrt(
				metrics.mean_squared_error(validation_predictions,validation_targets))

		print("  period %02d  :  %02f"  % (period, training_root_mean_squared_error))

		training_rmse.append(training_root_mean_squared_error)
		validation_rmse.append(validation_root_mean_squared_error)

	print("Model training finished.")

	plt.ylabel("RMSE")
	plt.xlabel("Periods")
	plt.title("Root Mean Squared Error vs . Periods")
	plt.tight_layout()
	plt.plot(training_rmse, label = "training")
	plt.plot(validation_rmse, label = "validation")
	plt.legend()
	plt.show()
	return linear_regressor

linear_regressor = train_model(
	learning_rate = 0.00003,
	steps = 500,
	batch_size = 5,
	training_examples = training_examples,
	training_targets = training_targets,
	validation_examples = validation_examples,
	validation_targets = validation_targets)

califonia_housing_test_data = pd.read_csv(Testing_file_path)

test_example = preprocess_features(califonia_housing_test_data)
test_targets = preprocess_targets(califonia_housing_test_data)

predict_test_input_fn = lambda: my_input_fn(test_example, test_features("median_house_value"),
	num_epochs = 1, shuffle = False)

test_predictions = linear_regressor.predict(input_fn = predict_test_input_fn)
test_predictions = np.array([item("predictions")[0] for item in test_predictions])

root_mean_squared_error = math.sqrt(
	metrics.mean_squared_error(test_predictions, test_targets))

print("Final RMSE (on the data): %0.2f"  % root_mean_squared_error)