from django.contrib.auth.models import User
from adventure.models import Player, Room

Room.objects.all().delete()

# courtyards and such

r_campus_welcome_center = Room(title="Lambda Welcome Center",
description="""The Lambda School journey begins here""")

r_campus_courtyard_south = Room(title="Campus Courtyard South",
description="""The south end of Lambda's massive courtyard""")

r_campus_courtyard_north = Room(title="Campus Courtyard North",
description="""The north end of Lambda's massive courtyard""")

r_campus_courtyard_mid = Room(title="Campus Courtyard center",
description="""The middle grounds of Lambda's massive courtyard""")

r_campus_courtyard_east = Room(title="Campus Courtyard East",
description="""The East end of Lambda's massive courtyard""")

r_campus_courtyard_west = Room(title="Campus Courtyard West",
description="""The West end of Lambda's massive courtyard""")

r_path_housing = Room(title="Housing Path",
description="""The path leading towards campus housing, passing
the Community Gardens and the Recreation Fields""")

r_garden = Room(title="Community Gardens",
description="""Community garden right off the path to campus housing making
easy access to fresh vegetables and herbs""")

r_rec_fields = Room(title="Recreation Fields",
description="""Massive grass field used for extracurricular activities like soccer and
football. """)

r_housing_square = Room(title="Campus Housing Square",
description="""Square connecting all the Campus housing to the rest of campus""")

#data building

r_ds_building = Room(title="Data Science Department Main Building",
description="""Here students come to learn about the wonders of Data.""")

r_ds_help = Room(title="Data Science Help Center",
description="""Student's come here for an assist in data related work.""")

r_ds_u1 = Room(title="Data Science Unit 1 Classroom",
description="""Here students study the first unit of Data Science.""")

r_ds_u2 = Room(title="Data Science Unit 2 Classroom",
description="""Here students study the second unit of Data Science.""")

r_ds_u3 = Room(title="Data Science Unit 3 Classroom",
description="""Here students study the third unit of Data Science.""")

r_ds_u4 = Room(title="Data Science Unit 4 Classroom",
description="""Here students study the fourth unit of Data Science.""")

r_ds_hall = Room(title="Data Science Building Back Hallway",
description="""Leads to the back of the Data Science Building where
the higher level classes are held""")

#web building

r_web_building = Room(title="Web Development Department Main Building",
description="""Here students come to learn about the wonders of full stack web development.""")

r_web_help = Room(title="Web Development Help Center",
description="""Student's come here for an assist in web dev related work.""")

r_web_u1 = Room(title="Web Development Unit 1 Classroom",
description="""Here students study the first unit of web development.""")

r_web_u2 = Room(title="Web Development Unit 2 Classroom",
description="""Here students study the second unit of web development.""")

r_web_u3 = Room(title="Web Development Unit 3 Classroom",
description="""Here students study the third unit of web development.""")

r_web_u4 = Room(title="Web Development Unit 4 Classroom",
description="""Here students study the fourth unit of web development.""")

r_web_hall = Room(title="Web Development Building Back Hallway",
description="""Leads to the back of the Web Development Building where
the higher level classes are held""")

#android building

r_and_building = Room(title="Android Development Department Main Building Ruins",
description="""Here students used to come to learn about the wonders of Android Developmet before
it was destroyed in a fire.""")

r_and_help = Room(title="Android Development Help Center",
description="""Student's came here for an assist in android dev related work.""")

r_and_u1 = Room(title="Android Development Unit 1 Classroom",
description="""Students used to study the first unit of Android Development here
before the fire.""")

r_and_u2 = Room(title="Android Development Unit 2 Classroom",
description="""Students used to study the second unit of Android Development here
before the fire.""")

r_and_u3 = Room(title="Android Development Unit 3 Classroom",
description="""Students used to study the third unit of Android Development here
before the fire.""")

r_and_u4 = Room(title="Android Development Unit 4 Classroom",
description="""Students used to study the fourth unit of Android Development here
before the fire.""")

r_and_hall = Room(title="Android Development Building Back Hallway Ruins",
description="""Leads to the back of the Android Development Building where
the higher level classes were held before the fire""")

#ios building

r_ios_building = Room(title="IOS Development Department Main Building",
description="""Here students come to learn about the wonders of Data.""")

r_ios_help = Room(title="IOS Development Help Center",
description="""Student's come here for an assist in ios dev related work.""")

r_ios_u1 = Room(title="IOS Development Unit 1 Classroom",
description="""Here students study the first unit of IOS Development.""")

r_ios_u2 = Room(title="IOS Development Unit 2 Classroom",
description="""Here students study the second unit of IOS Development.""")

r_ios_u3 = Room(title="Data Science Unit 3 Classroom",
description="""Here students study the third unit of IOS Development.""")

r_ios_u4 = Room(title="Data Science Unit 4 Classroom",
description="""Here students study the fourth unit of IOS Development.""")

r_ios_hall = Room(title="IOS Development Building Back Hallway",
description="""Leads to the back of the IOS Development Building where
the higher level classes are held""")

#ux building

r_ux_building = Room(title="UX Design Department Main Building",
description="""Here students come to learn about the wonders of UX Design.""")

r_ux_help = Room(title="UX Design Help Center",
description="""Student's come here for an assist in ios dev related work.""")

r_ux_u1 = Room(title="UX Design Unit 1 Classroom",
description="""Here students study the first unit of UX Design.""")

r_ux_u2 = Room(title="UX Design Unit 1 Classroom",
description="""Here students study the second unit of UX Design.""")

r_ux_u3 = Room(title="UX Design Unit 1 Classroom",
description="""Here students study the third unit of UX Design.""")

r_ux_u4 = Room(title="UX Design Unit 4 Classroom",
description="""Here students study the fourth unit of UX Design.""")

r_ux_hall = Room(title="UX Design Building Back Hallway",
description="""Leads to the back of the UX Design Building where
the higher level classes are held""")

#cs building

r_cs_building = Room(title="Computer Science Department Main Building",
description="""Here students come to learn about the wonders of Computer Science.""")

r_cs_help = Room(title="Computer Science Help Center",
description="""Student's come here for an assist in Computer Science related work.""")

r_cs_u1 = Room(title="Computer Science Unit 1 Classroom",
description="""Here students study the first unit of Computer Science.""")

r_cs_u2 = Room(title="Computer Science Unit 2 Classroom",
description="""Here students study the second unit of Computer Science.""")

r_cs_bw1_gal = Room(title="Unit 1 Gallery",
description="""A wonderful gallery displaying the amazing projects built in the
first build week of Lambda's Computer Science Program.""")

r_cs_bw2_gal = Room(title="Unit 2 Gallery",
description="""A wonderful gallery displaying the amazing projects built in the
second build week of Lambda's Computer Science Program.""")

r_cs_hall = Room(title="Computer Science Building Back Hallway",
description="""Leads to the back of the Computer Science Building""")

#labs building

r_labs_building = Room(title="Lambda Labs Department Main Building",
description="""Here students come to grind along other developers on
extensive projects getting true real world experience.""")

r_labs_help = Room(title="Lambda Labs Help Center",
description="""Student's come here for an assist in Computer Science related work.""")

r_labs_team_room = Room(title="Lambda Labs Team Room",
description="""Teams use this room to plan and execute their ideas.""")

r_labs_ds_display = Room(title="Lambda Labs Data Science Gallery",
description="""A wonderful gallery displaying the amazing projects built in
Lambda Labs with a Data Science focus.""")

r_labs_web_display = Room(title="Lambda Labs Web Gallery",
description="""A wonderful gallery displaying the amazing projects built in
Lambda Labs with a Web App focus.""")

r_labs_mobile_display = Room(title="Lambda Labs Mobile Gallery",
description="""A wonderful gallery displaying the amazing projects built in
Lambda Labs with a Mobile App focus.""")

r_labs_hall = Room(title="Lambda Labs Building Back Hallway",
description="""Leads to the back of the Lambda Labs Building
where it's galleries are held""")

#student center building

r_student_center = Room(title="Lambda Student Center Building",
description="""Here students come in the rare occurences they aren't behind their computer.""")

r_game_rooms = Room(title="Lambda Gaming Center",
description="""Student's come here to win glory.""")

r_cafeteria = Room(title="Lambda Cafeteria",
description="""Stay away from the chili...""")

r_pool = Room(title="Lambda Pool",
description="""Students can swim here""")

r_gym = Room(title="Lambda Gym",
description="""Students can pump iron here.""")

r_bb_court = Room(title="Lambda Basketball Court",
description="""Students try to ball up here.(keyword=try)""")

r_student_hall = Room(title="Student Center Back Hallway",
description="""Leads to the back of the Student Center Building""")

#admin building

r_admin = Room(title="Lambda Administration Department Main Building",
description="""Lambda Employees main place of operation.""")

r_tl_lounge = Room(title="Lambda Team Lead Lounge",
description="""Team Leads little getaway.""")

r_teacher_lounge = Room(title="Lambda Teacher Lounge",
description="""Teachers hide from students here.""")

r_office1 = Room(title="Ryan Allred's Office",
description="""Here is where Ryan romes.""")

r_office2 = Room(title="Austen Allred's Office",
description="""Here is where Austen get's it done.""")

r_office3 = Room(title="Ben Nelson's Office",
description="""Here is where Ben is Ben.""")

r_admin_hall = Room(title="Administration Building Back Hallway",
description="""Leads to the back of the Admin Building""")

#careers building

r_career_building = Room(title="Lambda Careers Building",
description="""Here students come for help on the job search.""")

r_career_help = Room(title="Careers Help Office",
description="""Here students can pop in for general career questions""")

r_career_office_ux = Room(title="UX Career Office",
description="""Student's come here for UX related career questions.""")

r_career_office_web = Room(title="Web Career Office",
description="""Student's come here for Web related career questions.""")

r_career_office_ios = Room(title="IOS Career Office",
description="""Student's come here for IOS related career questions.""")

r_career_office_ds = Room(title="Data Science Career Office",
description="""Student's come here for Data Science related career questions.""")

r_career_hall = Room(title="Career Building Back Hallway",
description="""Leads to the back of the Career Building""")

#student housing building

r_housing_student = Room(title="Lambda Student Housing",
description="""This is the main part of the student housing building.""")

r_housing_student_lounge = Room(title="Student Housing Lounge",
description="""Students come here to chill.""")

r_housing_student_kitchen = Room(title="Student Housing Kitchen",
description="""Students try to make their own food here.""")

r_housing_student_hall = Room(title="Student Housing Back Hall",
description="""Hall provides access to the different housing wings""")

r_housing_student_alpha = Room(title="Student Housing Alpha Wing",
description="""How those living in the Alpha Wing of the Student Building
access their Quarters. You must be living here to go further.""")

r_housing_student_beta = Room(title="Student Housing Beta Wing",
description="""How those living in the Beta Wing of the Student Building
access their Quarters. You must be living here to go further.""")

r_housing_student_charlie = Room(title="Student Housing Charlie Wing",
description="""How those living in the Charlie Wing of the Student Building
access their Quarters. You must be living here to go further.""")

#staff housing building

r_housing_staff = Room(title="Lambda Staff Housing",
description="""This is the main part of the staff housing building.""")

r_housing_staff_lounge = Room(title="Staff Housing Lounge",
description="""Staff come here to chill.""")

r_housing_staff_kitchen = Room(title="Staff Housing Kitchen",
description="""Staff make their own food here.""")

r_housing_staff_hall = Room(title="Staff Housing Back Hall",
description="""Hall provides access to the different staff housing wings""")

r_housing_staff_alpha = Room(title="Staff Housing Alpha Wing",
description="""How those living in the Alpha Wing of the Staff Building
access their Quarters. You must be living here to go further.""")

r_housing_staff_beta = Room(title="Staff Housing Beta Wing",
description="""How those living in the Beta Wing of the Staff Building
access their Quarters. You must be living here to go further.""")

r_housing_staff_charlie = Room(title="Staff Housing Charlie Wing",
description="""How those living in the Charlie Wing of the Staff Building
access their Quarters. You must be living here to go further.""")

#admin housing building

r_housing_admin = Room(title="Lambda Administration Housing",
description="""This is the main part of the administration housing building.""")

r_housing_admin_lounge = Room(title="Administration Housing Lounge",
description="""Administration come here to chill.""")

r_housing_admin_kitchen = Room(title="Administration Housing Kitchen",
description="""Administration make their own food here.""")

r_housing_admin_hall = Room(title="Administration Housing Back Hall",
description="""Hall provides access to the different administration housing wings""")

r_housing_admin_alpha = Room(title="Administration Housing Alpha Wing",
description="""How those living in the Alpha Wing of the Administration Building
access their Quarters. You must be living here to go further.""")

r_housing_admin_beta = Room(title="Administration Housing Beta Wing",
description="""How those living in the Beta Wing of the Administration Building
access their Quarters. You must be living here to go further.""")

r_housing_admin_charlie = Room(title="Administration Housing Charlie Wing",
description="""How those living in the Charlie Wing of the Administration Building
access their Quarters. You must be living here to go further.""")

#all saves below

r_campus_welcome_center.save()
r_campus_courtyard_south.save()
r_campus_courtyard_north.save()
r_campus_courtyard_mid.save()
r_campus_courtyard_east.save()
r_campus_courtyard_west.save()

r_ds_building.save()
r_ds_help.save()
r_ds_u1.save()
r_ds_u2.save()
r_ds_u3.save()
r_ds_u4.save()
r_ds_hall.save()

r_web_building.save()
r_web_help.save()
r_web_u1.save()
r_web_u2.save()
r_web_u3.save()
r_web_u4.save()
r_web_hall.save()

r_and_building.save()
r_and_help.save()
r_and_u1.save()
r_and_u2.save()
r_and_u3.save()
r_and_u4.save()
r_and_hall.save()

r_ios_building.save()
r_ios_help.save()
r_ios_u1.save()
r_ios_u2.save()
r_ios_u3.save()
r_ios_u4.save()
r_ios_hall.save()

r_ux_building.save()
r_ux_help.save()
r_ux_u1.save()
r_ux_u2.save()
r_ux_u3.save()
r_ux_u4.save()
r_ux_hall.save()

r_cs_building.save()
r_cs_help.save()
r_cs_u1.save()
r_cs_u2.save()
r_cs_bw1_gal.save()
r_cs_bw2_gal.save()
r_cs_hall.save()

r_labs_building.save()
r_labs_help.save()
r_labs_team_room.save()
r_labs_hall.save()
r_labs_ds_display.save()
r_labs_web_display.save()
r_labs_mobile_display.save()

r_student_center.save()
r_game_rooms.save()
r_cafeteria.save()
r_student_hall.save()
r_bb_court.save()
r_pool.save()
r_gym.save()

r_admin.save()
r_tl_lounge.save()
r_teacher_lounge.save()
r_office1.save()
r_office2.save()
r_office3.save()
r_admin_hall.save()

r_career_building.save()
r_career_help.save()
r_career_office_ux.save()
r_career_office_ios.save()
r_career_office_web.save()
r_career_office_ds.save()
r_career_hall.save()

r_path_housing.save()
r_garden.save()
r_rec_fields.save()

r_housing_square.save()
r_housing_student.save()
r_housing_staff.save()
r_housing_admin.save()

r_housing_student_lounge.save()
r_housing_student_kitchen.save()
r_housing_student_hall.save()
r_housing_student_alpha.save()
r_housing_student_beta.save()
r_housing_student_charlie.save()

r_housing_staff_lounge.save()
r_housing_staff_kitchen.save()
r_housing_staff_hall.save()
r_housing_staff_alpha.save()
r_housing_staff_beta.save()
r_housing_staff_charlie.save()

r_housing_admin_lounge.save()
r_housing_admin_kitchen.save()
r_housing_admin_hall.save()
r_housing_admin_alpha.save()
r_housing_admin_beta.save()
r_housing_admin_charlie.save()

# Link welcome center

r_campus_welcome_center.connectRooms(r_campus_courtyard_south, "n")
r_campus_courtyard_south.connectRooms(r_campus_welcome_center, "s")

#connect courtyards

r_campus_courtyard_south.connectRooms(r_campus_courtyard_mid, "n")
r_campus_courtyard_mid.connectRooms(r_campus_courtyard_south, "s")

r_campus_courtyard_mid.connectRooms(r_campus_courtyard_north, "n")
r_campus_courtyard_north.connectRooms(r_campus_courtyard_mid, "s")

r_campus_courtyard_mid.connectRooms(r_campus_courtyard_east, "e")
r_campus_courtyard_east.connectRooms(r_campus_courtyard_mid, "w")

r_campus_courtyard_mid.connectRooms(r_campus_courtyard_west, "w")
r_campus_courtyard_west.connectRooms(r_campus_courtyard_mid, "e")

#connect buildings

#south
r_campus_courtyard_south.connectRooms(r_student_center, "e")
r_student_center.connectRooms(r_campus_courtyard_south, "w")

#housing path
r_campus_courtyard_south.connectRooms(r_path_housing, "w")
r_path_housing.connectRooms(r_campus_courtyard_south, "e")

r_path_housing.connectRooms(r_garden, "n")
r_garden.connectRooms(r_path_housing, "s")

r_path_housing.connectRooms(r_rec_fields, "s")
r_rec_fields.connectRooms(r_path_housing, "n")

r_path_housing.connectRooms(r_housing_square, "w")
r_housing_square.connectRooms(r_path_housing, "e")

r_housing_square.connectRooms(r_housing_staff, "n")
r_housing_staff.connectRooms(r_housing_square, "s")

r_housing_square.connectRooms(r_housing_student, "s")
r_housing_student.connectRooms(r_housing_square, "n")

r_housing_square.connectRooms(r_housing_admin, "w")
r_housing_admin.connectRooms(r_housing_square, "e")

#east
r_campus_courtyard_east.connectRooms(r_ios_building, "e")
r_ios_building.connectRooms(r_campus_courtyard_east, "w")

r_campus_courtyard_east.connectRooms(r_web_building, "n")
r_web_building.connectRooms(r_campus_courtyard_east, "s")

r_campus_courtyard_east.connectRooms(r_and_building, "s")
r_and_building.connectRooms(r_campus_courtyard_east, "n")

#west
r_campus_courtyard_west.connectRooms(r_ds_building, "n")
r_ds_building.connectRooms(r_campus_courtyard_west, "s")

r_campus_courtyard_west.connectRooms(r_cs_building, "s")
r_cs_building.connectRooms(r_campus_courtyard_west, "n")

r_campus_courtyard_west.connectRooms(r_ux_building, "w")
r_ux_building.connectRooms(r_campus_courtyard_west, "e")

#north
r_campus_courtyard_north.connectRooms(r_admin, "n")
r_admin.connectRooms(r_campus_courtyard_north, "s")

r_campus_courtyard_north.connectRooms(r_labs_building, "e")
r_labs_building.connectRooms(r_campus_courtyard_north, "w")

r_campus_courtyard_north.connectRooms(r_career_building, "w")
r_career_building.connectRooms(r_campus_courtyard_north, "e")

#south
#student center -- courtyard is west
r_student_center.connectRooms(r_student_hall, "e")
r_student_hall.connectRooms(r_student_center, "w")

r_student_center.connectRooms(r_game_rooms, "n")
r_game_rooms.connectRooms(r_student_center, "s")

r_student_center.connectRooms(r_cafeteria, "s")
r_cafeteria.connectRooms(r_student_center, "n")

r_student_hall.connectRooms(r_bb_court, "e")
r_bb_court.connectRooms(r_student_hall, "w")

r_student_hall.connectRooms(r_gym, "n")
r_gym.connectRooms(r_student_hall, "s")

r_student_hall.connectRooms(r_pool, "s")
r_pool.connectRooms(r_student_hall, "n")

#east
#ios -- courtyard is w
r_ios_building.connectRooms(r_ios_hall, "e")
r_ios_hall.connectRooms(r_ios_building, "w")

r_ios_building.connectRooms(r_ios_help, "s")
r_ios_help.connectRooms(r_ios_building, "n")

r_ios_building.connectRooms(r_ios_u1, "n")
r_ios_u1.connectRooms(r_ios_building, "s")

r_ios_hall.connectRooms(r_ios_u2, "n")
r_ios_u2.connectRooms(r_ios_hall, "s")

r_ios_hall.connectRooms(r_ios_u3, "e")
r_ios_u3.connectRooms(r_ios_hall, "w")

r_ios_hall.connectRooms(r_ios_u4, "s")
r_ios_u4.connectRooms(r_ios_hall, "n")

#web -- courtyard is s
r_web_building.connectRooms(r_web_help, "e")
r_web_help.connectRooms(r_web_building, "w")

r_web_building.connectRooms(r_web_u1, "w")
r_web_u1.connectRooms(r_web_building, "e")

r_web_building.connectRooms(r_web_hall, "n")
r_web_hall.connectRooms(r_web_building, "s")

r_web_hall.connectRooms(r_web_u2, "e")
r_web_u2.connectRooms(r_web_hall, "w")

r_web_hall.connectRooms(r_web_u3, "w")
r_web_u3.connectRooms(r_web_hall, "e")

r_web_hall.connectRooms(r_web_u4, "n")
r_web_u4.connectRooms(r_web_hall, "s")

#android -- courtyard is n
r_and_building.connectRooms(r_and_help, "e")
r_and_help.connectRooms(r_and_building, "w")

r_and_building.connectRooms(r_and_u1, "w")
r_and_u1.connectRooms(r_and_building, "e")

r_and_building.connectRooms(r_and_hall, "s")
r_and_hall.connectRooms(r_and_building, "n")

r_and_hall.connectRooms(r_and_u2, "e")
r_and_u2.connectRooms(r_and_hall, "w")

r_and_hall.connectRooms(r_and_u3, "w")
r_and_u3.connectRooms(r_and_hall, "e")

r_and_hall.connectRooms(r_and_u4, "s")
r_and_u4.connectRooms(r_and_hall, "n")

#west
#ds -- courtyard is s
r_ds_building.connectRooms(r_ds_help, "e")
r_ds_help.connectRooms(r_ds_building, "w")

r_ds_building.connectRooms(r_ds_u1, "w")
r_ds_u1.connectRooms(r_ds_building, "e")

r_ds_building.connectRooms(r_ds_hall, "n")
r_ds_hall.connectRooms(r_ds_building, "s")

r_ds_hall.connectRooms(r_ds_u2, "e")
r_ds_u2.connectRooms(r_ds_hall, "w")

r_ds_hall.connectRooms(r_ds_u3, "w")
r_ds_u3.connectRooms(r_ds_hall, "e")

r_ds_hall.connectRooms(r_ds_u4, "n")
r_ds_u4.connectRooms(r_ds_hall, "s")

#cs -- courtyard is n
r_cs_building.connectRooms(r_cs_bw1_gal, "e")
r_cs_bw1_gal.connectRooms(r_cs_building, "w")

r_cs_building.connectRooms(r_cs_bw2_gal, "w")
r_cs_bw2_gal.connectRooms(r_cs_building, "e")

r_cs_building.connectRooms(r_cs_hall, "s")
r_cs_hall.connectRooms(r_cs_building, "n")

r_cs_hall.connectRooms(r_cs_u2, "e")
r_cs_u2.connectRooms(r_cs_hall, "w")

r_cs_hall.connectRooms(r_cs_u1, "w")
r_cs_u1.connectRooms(r_cs_hall, "e")

r_cs_hall.connectRooms(r_cs_help, "s")
r_cs_help.connectRooms(r_cs_hall, "n")

#ux -- courtyard is e
r_ux_building.connectRooms(r_ux_hall, "w")
r_ux_hall.connectRooms(r_ux_building, "e")

r_ux_building.connectRooms(r_ux_help, "s")
r_ux_help.connectRooms(r_ux_building, "n")

r_ux_building.connectRooms(r_ux_u1, "n")
r_ux_u1.connectRooms(r_ux_building, "s")

r_ux_hall.connectRooms(r_ux_u2, "n")
r_ux_u2.connectRooms(r_ux_hall, "s")

r_ux_hall.connectRooms(r_ux_u3, "w")
r_ux_u3.connectRooms(r_ux_hall, "e")

r_ux_hall.connectRooms(r_ux_u4, "s")
r_ux_u4.connectRooms(r_ux_hall, "n")

#north
#admin -- courtyard is s
r_admin.connectRooms(r_tl_lounge, "e")
r_tl_lounge.connectRooms(r_admin, "w")

r_admin.connectRooms(r_teacher_lounge, "w")
r_teacher_lounge.connectRooms(r_admin, "e")

r_admin.connectRooms(r_admin_hall, "n")
r_admin_hall.connectRooms(r_admin, "s")

r_admin_hall.connectRooms(r_office1, "n")
r_office1.connectRooms(r_admin_hall, "s")

r_admin_hall.connectRooms(r_office2, "w")
r_office2.connectRooms(r_admin_hall, "e")

r_admin_hall.connectRooms(r_office3, "e")
r_office3.connectRooms(r_admin_hall, "w")

#labs -- courtyard is w
r_labs_building.connectRooms(r_labs_help, "n")
r_labs_help.connectRooms(r_labs_building, "s")

r_labs_building.connectRooms(r_labs_team_room, "s")
r_labs_team_room.connectRooms(r_labs_building, "n")

r_labs_building.connectRooms(r_labs_hall, "e")
r_labs_hall.connectRooms(r_labs_building, "w")

r_labs_hall.connectRooms(r_labs_ds_display, "e")
r_labs_ds_display.connectRooms(r_labs_hall, "w")

r_labs_hall.connectRooms(r_labs_mobile_display, "n")
r_labs_mobile_display.connectRooms(r_labs_hall, "s")

r_labs_hall.connectRooms(r_labs_web_display, "s")
r_labs_web_display.connectRooms(r_labs_hall, "n")

#careers -- courtyard is e
r_career_building.connectRooms(r_career_hall, "w")
r_career_hall.connectRooms(r_career_building, "e")

r_career_building.connectRooms(r_career_help, "n")
r_career_help.connectRooms(r_career_building, "s")

r_career_building.connectRooms(r_career_office_ux, "s")
r_career_office_ux.connectRooms(r_career_building, "n")

r_career_hall.connectRooms(r_career_office_ds, "w")
r_career_office_ds.connectRooms(r_career_hall, "e")

r_career_hall.connectRooms(r_career_office_ios, "n")
r_career_office_ios.connectRooms(r_career_hall, "s")

r_career_hall.connectRooms(r_career_office_web, "s")
r_career_office_web.connectRooms(r_career_hall, "n")

#housing student courtyard is n
r_housing_student.connectRooms(r_housing_student_hall, "s")
r_housing_student_hall.connectRooms(r_housing_student, "n")

r_housing_student.connectRooms(r_housing_student_kitchen, "e")
r_housing_student_kitchen.connectRooms(r_housing_student, "w")

r_housing_student.connectRooms(r_housing_student_lounge, "w")
r_housing_student_lounge.connectRooms(r_housing_student, "e")

r_housing_student_hall.connectRooms(r_housing_student_alpha, "e")
r_housing_student_alpha.connectRooms(r_housing_student_hall, "w")

r_housing_student_hall.connectRooms(r_housing_student_beta, "w")
r_housing_student_beta.connectRooms(r_housing_student_hall, "e")

r_housing_student_hall.connectRooms(r_housing_student_charlie, "s")
r_housing_student_charlie.connectRooms(r_housing_student_hall, "n")

#housing staff courtyard is south
r_housing_staff.connectRooms(r_housing_staff_hall, "n")
r_housing_staff_hall.connectRooms(r_housing_staff, "s")

r_housing_staff.connectRooms(r_housing_staff_kitchen, "e")
r_housing_staff_kitchen.connectRooms(r_housing_staff, "w")

r_housing_staff.connectRooms(r_housing_staff_lounge, "w")
r_housing_staff_lounge.connectRooms(r_housing_staff, "e")

r_housing_staff_hall.connectRooms(r_housing_staff_alpha, "e")
r_housing_staff_alpha.connectRooms(r_housing_staff_hall, "w")

r_housing_staff_hall.connectRooms(r_housing_staff_beta, "w")
r_housing_staff_beta.connectRooms(r_housing_staff_hall, "e")

r_housing_staff_hall.connectRooms(r_housing_staff_charlie, "n")
r_housing_staff_charlie.connectRooms(r_housing_staff_hall, "s")

#housing admin courtyard is east
r_housing_admin.connectRooms(r_housing_admin_hall, "w")
r_housing_admin_hall.connectRooms(r_housing_admin, "e")

r_housing_admin.connectRooms(r_housing_admin_kitchen, "n")
r_housing_admin_kitchen.connectRooms(r_housing_admin, "s")

r_housing_admin.connectRooms(r_housing_admin_lounge, "s")
r_housing_admin_lounge.connectRooms(r_housing_admin, "n")

r_housing_admin_hall.connectRooms(r_housing_admin_alpha, "n")
r_housing_admin_alpha.connectRooms(r_housing_admin_hall, "s")

r_housing_admin_hall.connectRooms(r_housing_admin_beta, "w")
r_housing_admin_beta.connectRooms(r_housing_admin_hall, "e")

r_housing_admin_hall.connectRooms(r_housing_admin_charlie, "s")
r_housing_admin_charlie.connectRooms(r_housing_admin_hall, "n")

players=Player.objects.all()
for p in players:
  p.currentRoom=r_campus_welcome_center.id
  p.save()


"""
ODBC Data Source Name
"""

import sys
import lib_common
import lib_util
import lib_credentials
import pyodbc
from lib_properties import pc
from sources_types import odbc as survol_odbc
from sources_types.sqlserver import dsn as survol_sqlserver_dsn
from sources_types.oracle import db as oracle_db

# On Linux pyodbc is installed with, for example:
# yum install unixODBC-devel
# https://stackoverflow.com/questions/31353137/sql-h-not-found-when-installing-pyodbc-on-heroku

def Graphic_colorfill():
	return "#CCFF11"

def Graphic_colorbg():
	return "#CCFF11"

def EntityOntology():
	return ( [ survol_odbc.CgiPropertyDsn() ], )

def MakeUri(dsnName):
	# sys.stderr.write("MakeUri dsnName=%s\n"%dsnName)
	return lib_common.gUriGen.UriMakeFromDict("odbc/dsn", { survol_odbc.CgiPropertyDsn() : dsnName })

def EntityName(entity_ids_arr):
	# sys.stderr.write("EntityName entity_ids_arr=%s\n"%str(entity_ids_arr))
	return survol_odbc.CgiPropertyDsn().ValueDisplay(entity_ids_arr[0])

# This expects a DSN as a simple string.
def MakeOdbcConnectionStringFromDsn(dsnNam):
	pairUsrnamPass = lib_credentials.GetCredentials("ODBC",dsnNam)
	# With SqlServer, there is some implicit connection if this is the local machine.
	if pairUsrnamPass[0] == "":
		# Maybe we could add ";Trusted_Connection=yes"
		connectStr = "DSN=%s" % dsnNam
	else:
		connectStr = "DSN=%s;UID=%s;PWD=%s" % (dsnNam,pairUsrnamPass[0],pairUsrnamPass[1])

	return connectStr

# This can be just a string, a DSN. Or a connection string.
# This function is very tolerant.
def MakeOdbcConnectionString(dsnNam):
	# sys.stderr.write("MakeOdbcConnectionString dsnNam=%s\n"%dsnNam)
	splitTokens = [ strpTok.strip().split("=") for strpTok in dsnNam.split(";") ]

	# Maybe this is a single string, so we add "DSN" and look for username/password.
	if len(splitTokens) == 1:
		if len(splitTokens[0]) == 1:
			return MakeOdbcConnectionStringFromDsn(splitTokens[0][0])

	# Otherwise it assumes that it contains all needed connection parameters: User, password.
	# This might be checked, or if it contains FileDsn=... etc.

	# Otherwise it assumes a connection string, returned "as is".
	return dsnNam

def GetDatabaseEntityTypeFromConnection(cnxn):
	# "Oracle", "Microsoft SQL Server"
	prm_value = cnxn.getinfo(pyodbc.SQL_DBMS_NAME)

	dictDbToEntity = {
		"Oracle":"oracle",
		"Microsoft SQL Server": "sqlserver"
	}

	try:
		return dictDbToEntity[prm_value]
	except KeyError:
		# TODO: Or maybe return "sql" to be consistent with the concept of vendor-neutral database.
		return ""

def GetDatabaseEntityType(dsnNam):
	ODBC_ConnectString = MakeOdbcConnectionString(dsnNam)

	cnxn = pyodbc.connect(ODBC_ConnectString)

	return GetDatabaseEntityTypeFromConnection(cnxn)

# This displays abort link to the Oracle database, but not seen from ODBC,
# so we can have more specific queries.
def AddInfo(grph,node,entity_ids_arr):
	dsnNam = entity_ids_arr[0]

	ODBC_ConnectString = MakeOdbcConnectionString(dsnNam)

	try:
		cnxn = pyodbc.connect(ODBC_ConnectString)
	except:
		exc = sys.exc_info()[1]
		grph.add( ( node, pc.property_information, lib_common.NodeLiteral(str(exc)) ) )
		return

	dbEntityType = GetDatabaseEntityTypeFromConnection(cnxn)

	sys.stderr.write("AddInfo dbEntityType=%s\n" % dbEntityType )
	if dbEntityType == "oracle":
		# For example "XE".
		server_name = cnxn.getinfo(pyodbc.SQL_SERVER_NAME)
		node_oradb = oracle_db.MakeUri( server_name )

		grph.add( ( node, pc.property_oracle_db, node_oradb ) )

	elif dbEntityType == "sqlserver":
		# We stick to the DSN because it encloses all the needed information.
		node_sqlserverdb = survol_sqlserver_dsn.MakeUri( dsnNam )

		grph.add( ( node, pc.property_sqlserver_db, node_sqlserverdb ) )
		sys.stderr.write("AddInfo dbEntityType=%s ADDING NODE\n" % dbEntityType )

		#grph.add( ( node, pc.property_pid, lib_common.NodeLiteral(pidProc) ) )

# TODO: Maybe should decode ????
def GetDsnNameFromCgi(cgiEnv):
	keyWordDsn = survol_odbc.CgiPropertyDsn()
	dsnCoded = cgiEnv.m_entity_id_dict[keyWordDsn]
	dsnDecoded = keyWordDsn.ValueDecode(dsnCoded)

	# sys.stderr.write("GetDsnNameFromCgi dsnCoded=%s dsnDecoded=%s\n"%(dsnCoded,dsnDecoded))
	return dsnDecoded

def DatabaseEnvParams(processId):
	# TODO: We could use the process id to check if the process executable is linked
	# with the SQLServer shareable library.

	# We do not list sources in lib_credentials because some ODBC sources
	# can be accessed without pass word (With Windows validation).
	sourcesData = pyodbc.dataSources()

	# {
	# 	'MyNativeSqlServerDataSrc': 'SQL Server Native Client 11.0',
	# 	'Excel Files': 'Microsoft Excel Driver (*.xls, *.xlsx, *.xlsm, *.xlsb)',
	# 	'SqlSrvNativeDataSource': 'SQL Server Native Client 11.0',
	# 	'mySqlServerDataSource': 'SQL Server',
	# 	'MyOracleDataSource': 'Oracle in XE',
	# 	'SysDataSourceSQLServer': 'SQL Server',
	# 	'dBASE Files': 'Microsoft Access dBASE Driver (*.dbf, *.ndx, *.mdx)',
	# 	'OraSysDataSrc' : 'Oracle in XE',
	# 	'MS Access Database': 'Microsoft Access Driver (*.mdb, *.accdb)'
	# }

	dsnList = ( { survol_odbc.CgiPropertyDsn(): "DSN=" + dsn } for dsn in sourcesData )

	return ( "sqlserver/query", dsnList )


from models.mlp import model
import torch
import numpy as np
from sklearn import preprocessing

def get_prediction(data):
    data = np.array(data).reshape(1, len(data))

    data = preprocessing.normalize(data)
    data = torch.from_numpy(data)

    output = model(data.float())
    _, predicted = torch.max(output.data, 1)
    prediction = int(predicted[0])

    if prediction == 0:
        print('Пациент здоров')
    else:
        print('Имеется заболевание сердца')

# Loading model parametrs
checkpoint = torch.load('stats\\model800.ckpt')
model.load_state_dict(checkpoint)
model.eval()

# Number of features
n = 13

data = []
for i in range(n):
    x = float(input())
    data.append(x)

get_prediction(data)


import numpy
import os, sys

if len(sys.argv)!=2 and len(sys.argv)!=3:
    print("Usage: python calculateVNA.py measurementName [plotFigures]")
    print("plotFigures is optional and can have values plot for plotting figures or save to plot and save the figures")
    exit(1)

startFreq = 2.3e9
endFreq = 2.6e9
nPoints = 101
measName = sys.argv[1]

saveFig = False
plotFig = False
if len(sys.argv)==3:
    if sys.argv[2]=="plot":
        plotFig = True
    if sys.argv[2]=="save":
        plotFig = True
        saveFig = True

if plotFig:
    from matplotlib.pyplot import *
    import smithplot
    from smithplot.smithaxes import update_scParams
    import warnings
    warnings.filterwarnings("ignore", module="matplotlib")

fMin=startFreq
fMax=endFreq

#############################################################################
# Auxiliary functions

def readFile(fileName, fMin=0, fMax=1e20):
    inFile = open(fileName, 'r')
    res = [ [], [], [] ]
    for line in inFile:
        if line[0]=="#":
            continue
        line = line.strip()
        if line=="":
            continue
        tmp = line.split()
        if float(tmp[0])<fMin or float(tmp[0])>fMax:
            continue
        res[0].append( float(tmp[0]) )
        res[1].append( float(tmp[1]) )
        res[2].append( float(tmp[2]) )
    inFile.close()
    return [ numpy.array(res[0]), numpy.array(res[1]), numpy.array(res[2]) ]

def filterData(f, data, fMin=0, fMax=1e20):
    res = []
    for i in range(0, len(f)):
        if f[i]>fMin and f[i]<fMax:
            res.append(data[i])
    return numpy.array(res)

def unwrap(phase):
    # Unwrap the phase
    phase_unwrap = []
    intAng = 0
    for i in range(0,len(phase)-1):
        phase_unwrap.append(phase[i]+intAng)
        dph = phase[i+1]-phase[i]

        if abs(dph)>150:
            if dph>0:
                    intAng += -180
            else:
                    intAng += 180
    phase_unwrap.append(phase[-1]+intAng)
    phase_unwrap=numpy.array(phase_unwrap)

    # Second pass
    phase_unwrap2 = []
    intAng = 0
    for i in range(0,len(phase_unwrap)-1):
        phase_unwrap2.append(phase_unwrap[i]+intAng)
        dph = phase_unwrap[i+1]-phase_unwrap[i]
        if dph<-150:
            phase_unwrap[i+1] += 180

        if dph>10 and dph<45:
            intAng += -45
        if dph>45 and dph<135:
            intAng += -90
        if dph>135 and dph<180:
            intAng += -180
        if dph>180:
            intAng += -360
    phase_unwrap2.append(phase_unwrap[-1]+intAng)
    phase_unwrap2=numpy.array(phase_unwrap2)
    return phase_unwrap2
#############################################################################

# Read the measurement resutls
dutFileName = 'vna_'+measName+'_DUT_'+str(startFreq)+'_'+str(endFreq)+'_'+str(nPoints)+'.txt'
shortFileName = 'vna_'+measName+'_short_'+str(startFreq)+'_'+str(endFreq)+'_'+str(nPoints)+'.txt'

dutData = readFile(dutFileName)
shortData = readFile(shortFileName)

freq = dutData[0]
f = freq

dutPhase = unwrap(dutData[2]) * numpy.pi/180
shortPhase = unwrap(shortData[2]) * numpy.pi/180

if plotFig:
    plot(numpy.array(f)/1e9,shortPhase)
    xlabel('f [GHz]')
    ylabel('Short Phase')
    grid()
    show()
    plot(numpy.array(f)/1e9,dutPhase, linewidth=1.5, aa=True)
    xlabel('f [GHz]')
    ylabel('DUT Phase')
    grid()
    show()

dutData[1] = 20.0*numpy.log10(dutData[1])
shortData[1] = 20.0*numpy.log10(shortData[1])

measGammaDut = numpy.power(10.0, dutData[1]/20) * numpy.exp(1j * dutPhase)#/2)
measGammaShort = numpy.power(10.0, shortData[1]/20) * numpy.exp(1j * shortPhase)#/2)

GammaShort = numpy.array([-1.0] * len(f)) # assume ideal short

returnLoss = dutData[1] - shortData[1]

vswr = (10**(-returnLoss/20)+1)/(10**(-returnLoss/20)-1)
if plotFig:
    plot(numpy.array(f)/1e9,vswr)
    title('VSWR')
    xlabel('f [GHz]')
    ylabel('VSWR')
    grid()
    show()

gammaMag = numpy.power(10.0, returnLoss/20.0)
dutPhase = dutPhase - shortPhase + numpy.pi
GammaDut = gammaMag * numpy.exp(1j * dutPhase)
ZDut = (1.0 + GammaDut)/(1.0 - GammaDut)

if plotFig:
    plot(numpy.array(f)/1e9, 20*numpy.log10( numpy.abs(GammaDut)), color='b', linewidth=1.5, aa=True)
    xlabel('f [GHz]')
    ylabel('S11 [dB]')
    grid()
    if saveFig:
        savefig(measName+'_s11.png')
    show()

    figure(figsize=(24, 16))
    subplot(1, 1, 1, projection='smith',grid_major_fancy=True,
                       grid_minor_fancy=True, plot_hacklines=True)
    ZDutPlot = filterData(freq, ZDut, fMin, fMax)
    plot(ZDutPlot, markevery=1, label="S11", color='b', linewidth=1.5, aa=True)
    if saveFig:
        savefig(measName+'_smith.png')
    show()

outFileName = measName + '.s1p'
outFile = open(outFileName, 'w')
outFile.write('# Hz S RI R 50\n')
for i in range(0, len(GammaDut)):
    outFile.write(str(f[i])+"\t"+str(numpy.real(GammaDut[i]))+"\t"+str(numpy.imag(GammaDut[i]))+"\n")
outFile.close()


from Tkinter import *
from ttk import *
import arduino
#import check as check
#import delete_files as delete_files
#import drive as drive
import process

class Example(Frame):

    def __init__(self, parent):
        Frame.__init__(self, parent)

        self.parent = parent

        self.initUI()

        shotnumberinput = IntVar()
        ShotNumWidget = Entry(self, textvariable = shotnumberinput)
        ShotNumWidget.pack()

        ShotNumEntry = int(ShotNumWidget.get())

        prepareButton = Button(self, text="Prepare")
        prepareButton.pack(side = LEFT)
        prepareButton.configure(command = arduino.turn_on)

        recordButton = Button (self, text = "Press 'record' button")
        recordButton.pack(side = LEFT)
        recordButton.configure(command = arduino.record_button)

        nextButton = Button(self, text = "Press 'next' button")
        nextButton.pack(side = LEFT)
        nextButton.configure(command = arduino.next_button)

        trigger = Button(self, text = "Trigger")
        trigger.pack(side = RIGHT)
        trigger.configure(command = process.process)

        connect = Button(self, text = "Connect USB")
        connect.pack(side = LEFT)
        connect.configure(command = arduino.connect_usb)

        disconnect_usb = Button(self, text = "Disconnect USB")
        disconnect_usb.pack(side = LEFT)
        disconnect_usb.configure(command = arduino.disconnect_usb)

        turn_off = Button(self, text = "Turn Off")
        turn_off.pack(side = TOP)
        turn_off.configure(command = arduino.turn_off)

    def initUI(self):
        self.parent.title("Camera GUI")
        self.pack(fill=BOTH, expand=1)

        self.style = Style()
        #self.style.theme_use("default")

        frame = Frame(self, relief=RAISED, borderwidth=1)
        frame.pack(fill=BOTH,expand=1)

        self.pack(fill=BOTH, expand=1)

def main():

        root = Tk()
        root.geometry("700x300+300+300")
        app = Example(root)
        root.mainloop()

if __name__ == '__main__':
    main()


import csv
import sys
import json
import codecs
from influxdb import InfluxDBClient

flowsid = 0

def ainflux(flow_list):
	global flowsid
	#global json_body
	dic = {}
	json_body =[]
	#json_body.clear()
	#for flujo in range(len(flow_list)):
		#print("")
		#print("")
		#print ("La tabla de flujos que estoy comparando es",flow_list[flujo])
		#print("")
		#print("")#,json_body[item]["data"]["1IP_src"] )

	#	json_body.insert(flujo,{

	#		"measurement": "Medidas",
	#		"tags": {
	#			"flowid":str(flujo),
	#			"6Host":flow_list[flujo][4]},
	#		"fields":{
	#			"1IP_src":flow_list[flujo][0],
	#			"2IP_dst":flow_list[flujo][1],
	#			"3Port_src":flow_list[flujo][2],
	#			"4Port_dst":flow_list[flujo][3],
				#"5Protocol":flow_list[flujo][4],
				#"6Host":flow_list[flujo][5],
	#			"5#Bytes":int(flow_list[flujo][5]),
	#			"7#Paquetes":flow_list[flujo][6]}
	#		})

	json_body.insert(flowsid,{

		"measurement": "Cosas",
		"tags": {
			#"flowid":str(flowsid),
			"6Host":flow_list[4]},
		"fields":{
			"1IP_src":flow_list[0],
			"2IP_dst":flow_list[1],
			"3Port_src":flow_list[2],
			"4Port_dst":flow_list[3],
			#"5Protocol":flow_list[flujo][4],
			"5#Bytes":int(flow_list[5]),
			"7#Paquetes":flow_list[6]}
		})
		#print ("QUIIIITO",json_body.pop(flujo))
	#print(json.dumps(json_body, indent=4,separators=(". ", " = "),sort_keys=True))
	#print("La longitud de json_body es:",len(json_body))
	client.write_points(json_body, protocol='json') # , tags = dic,
	flowsid = flowsid + 1

client = InfluxDBClient(host='localhost', port=8086)

client.drop_database('tshark_flows')
client.create_database('tshark_flows')
client.get_list_database()

client.switch_database('tshark_flows')
cont_g = 0

flujos = []

with codecs.open('salidatshark.csv','r', encoding='utf-8', errors='replace') as File:
	reader = csv.reader(File,delimiter=";")
	for row in reader:
		coincidencias = []
		pcks = 0

		#print("La fila a tratar es es:",row)
		#print ("Cont es ---> ",cont)
		#Primer flujo de la captura no puedo comparar con nada
		if cont_g == 0:
			#print("Debes entrar en el primerisimo if")
			row.append(pcks+1)
			flujos.append(row[2:])
			ainflux(flujos[0])
			cont_g+=1
		else:
			cont = 0
			for x in range(len(flujos)):
				#print ("COMPARO:",row[2:6],"CON",flujos[x][0:4])
				#print ("cont",cont)
				if row[2:6] == flujos[x][0:4]:
					#print ("Entra en el if")
					coincidencias.append(1)
					cont+=1
				else:
					#print ("Entra en el else")
					coincidencias.append(0)
					cont+=1

			#Poner el host en el flujo bidireccional
			tupla_inversa = []
			#tupla_inversa.append(row[0])
			#tupla_inversa.append(row[1])
			tupla_inversa.append(row[3])
			tupla_inversa.append(row[2])
			tupla_inversa.append(row[5])
			tupla_inversa.append(row[4])
			#tupla_inversa.append(row[6])
			#print ("TUPLA INVERSA para ponerle host ES ",tupla_inversa)

			# Mirar si lo ultimo que tengo que hacer es escribir en flujos para no duplicar
			# Veo en que posicion se repite y en funcion de eso sumo 1 paquete y los bytes que correspondan
			try:
				#print("Entras en TRY---")
				indice = coincidencias.index(1)
				#print("0----------flujos[indice][-2]----------0",flujos[indice][-2])
				flujos[indice][-1] = flujos[indice][-1]+1
				flujos[indice][-2] = int(flujos[indice][-2])
				flujos[indice][-2] = int(flujos[indice][-2]) + int(row[-1])
				#print ("LLEGA",flujos[indice][-1])
				#print("----VAS DE CAMINO AL IFFFF")
				if row[6] == 'none': # Si me viene con el campo vacío, pero ya sabemos que host se lo ponemos
					#print ("")

					for j in range(len(flujos)):
						#print ("COMPARO:",row[2:6],"CON flujos[j]",flujos[j][0:4])#

						if row[2:6] == flujos[j][0:4] or tupla_inversa == flujos[j][0:4]:

							row[6] = flujos[j][4]
							#print("1-ELROWWWW EEES.",row)
							ainflux(flujos[j])
							break
						else:
							#print ("No existe ninguna entrada con el campo HOST en la tabla")
							pass
				else:
					for j in range(len(flujos)): # Si no viene con campo none, si no con HOST se lo ponemos

						if row[2:6] == flujos[j][0:4] or tupla_inversa == flujos[j][0:4]:
							#print ("Entra en el if 3")
							flujos[j][4] = row[6]
							#print("LLegas al punto de influx",flujos[j])
							ainflux(flujos[j])
							break

						else:
							#print ("2No existe ninguna entrada con el campo HOST en la tabla")
							pass
			except:
				#print("Entras en EXCEPT---")
				#print ("*********De momento no hay flujos coincidentes.")
				if row[6] == 'none': # Si viene con campo none

					row.append(pcks+1)
					flujos.append(row[2:]) #Necesario 2 columnas al principio (timestamp y pkt number)
					ainflux(flujos[-1])

				else:
					#Hacer esto bien en el caso de que el host no este en la lista de tuplas y no sea none
					row.append(pcks+1)
					flujos.append(row[2:])
					ainflux(flujos[-1])

			else:
				#print("No ha habido problemas en el try")
				pass

			#print ("1LAS TUPLAS DE LA FUNCION SON:",flujos)

		#print("ELROWWWW EEES.",row)
		#print ("LAS TUPLAS DE LA FUNCION CON HOST SI LO TIENEN:",flujos)
		#print()
		#print()
		#print()
		#print()
		#print()
		#print()
		#print()

		#ainflux(flujos) #Enviamos solo el ultimo elmento, y por tanto el mas nuevo.. pero si hay actulizaciones?...


import numpy as np
import pandas as pd
from datetime import datetime, timedelta
import matplotlib.pyplot as plt
from matplotlib.figure import Figure
import panel as pn

np.random.seed(42)

def portfolio_by_retirement(portfolio, initial_investment, withdraw_type, withdraw_number, years_to_retirement):
    portfolio.iloc[2,:] = portfolio.iloc[2,:]/sum(portfolio.iloc[2,:])
    portfolio_dimension = portfolio.shape

    for stock in range(portfolio_dimension[1]):
        globals()['stock_%s' % stock]= np.random.normal(portfolio.iloc[0,stock],
                                                        portfolio.iloc[1,stock],
                                                        (252*30,500) )   #.reshape(252*30,500)

    #initialize variables
    next_beginning_balance = np.ones((1,500))
    Portfolio_30_year = np.ones((1,500))

    withdraw_amount = withdraw_number/initial_investment
    withdraw_rate = withdraw_number

    for year in range(30):
        #initialize for each year
        Portfolio_1_year = np.ones((1,500))

        for month in range(12):
            #initialize for each month
            portfolio_monthly_return = np.zeros((22,500))
            for stock in range(portfolio_dimension[1]):
                stock_month_daily_return = np.concatenate((next_beginning_balance,
                                                           (globals()['stock_%s' % stock][year*12*21+month*21:year*12*21+(month+1)*21])+1),
                                                          axis = 0)
                portfolio_monthly_return += np.cumprod(stock_month_daily_return, axis = 0)*portfolio.iloc[2,stock]

            #get balance for rebalancing in next loop.
            next_beginning_balance = (portfolio_monthly_return[-1,:]).reshape(1,500)

            Portfolio_1_year = np.concatenate((Portfolio_1_year,portfolio_monthly_return[1:,:]), axis = 0)

        if withdraw_type != 'fixed amount':
            next_beginning_balance = (portfolio_monthly_return[-1,:]).reshape(1,500)*(1-withdraw_rate)
        else:
            next_beginning_balance =(portfolio_monthly_return[-1,:]).reshape(1,500)-withdraw_amount

        Portfolio_30_year = np.concatenate((Portfolio_30_year,Portfolio_1_year[1:,:]), axis = 0)
    Portfolio_30_year_simulation = pd.DataFrame(Portfolio_30_year[1:])
    return Portfolio_30_year_simulation.iloc[:years_to_retirement*252]*initial_investment

def quantile_chart(portfolio, initial_investment, withdraw_type, withdraw_number, years_to_retirement):
    daily_quantiles = portfolio_by_retirement(portfolio,initial_investment, withdraw_type, withdraw_number, years_to_retirement).quantile(q=(0.10,0.5,0.9), axis = 1).T
    if withdraw_number <0:
        withdraw_deposit = 'deposit'
        withdraw_deposit_number = -withdraw_number
    else:
        withdraw_deposit = 'withdraw'
        withdraw_deposit_number = withdraw_number
    fig = Figure(figsize=(7, 5))
    ax = fig.subplots()
    ax.plot(daily_quantiles)
    title = f"Investment of ${initial_investment}, {withdraw_deposit} {withdraw_type} by {withdraw_deposit_number} in {years_to_retirement} years."
    ax.set_title(title)
    return fig

def simulation_chart(portfolio, initial_investment, withdraw_type, withdraw_number, years_to_retirement):
    fig = Figure(figsize=(7, 5))
    ax = fig.subplots()
    ax.plot(portfolio_by_retirement(portfolio,initial_investment, withdraw_type, withdraw_number, years_to_retirement))
    title = "Portfolio simulation"
    ax.set_title(title)
    return fig

def confidence_interval(portfolio, initial_investment, withdraw_type, withdraw_number, years_to_retirement):
    investment_ending_price = portfolio_by_retirement(portfolio,initial_investment, withdraw_type, withdraw_number, years_to_retirement).iloc[-1]
    quantile_result = investment_ending_price.quantile(q=[0.05, 0.95])
    fig = Figure(figsize=(7, 5))
    ax = fig.subplots()
    ax.hist(investment_ending_price)
    title="90% confidence interval for tails"
    ax.set_title(title)
    ax.axvline(quantile_result.iloc[0], color='r')
    ax.axvline(quantile_result.iloc[1], color='r')
    return fig

def search_withdraw_amount(portfolio, initial_investment, years_to_retirement, target_amount):
    result = {}
    try:
        min_withdraw = round(-initial_investment) #round(-initial_investment)
        max_withdraw = round(initial_investment)
        learning_rate = round(initial_investment/50)
        for change in range(min_withdraw, max_withdraw, learning_rate):
            investment_ending_price = portfolio_by_retirement(portfolio,initial_investment,'fixed amount', change, years_to_retirement).iloc[-1]
            quantile_result = investment_ending_price.quantile(q=[0.10]).astype(int)
                #print(f"If withdrawing ${change} annually, the 10% percentile return will be ${quantile_result.iloc[0]}.")
            if quantile_result.iloc[0]<target_amount:
                break
            desired_withdraw_amount = change
            ending_10_percentile_balance = quantile_result.iloc[0]
        if desired_withdraw_amount < 0:
            to_print = (f"Rather than withdrawing, you should deposit ${-desired_withdraw_amount} annually, and ending 10% percentile balance after {years_to_retirement} years would be ${ending_10_percentile_balance}.")
        else:
            to_print = (f"The desired withdraw amount is ${desired_withdraw_amount} annually, and ending 10% percentile balance after {years_to_retirement} years would be ${ending_10_percentile_balance}.")
        #chart = quantile_chart(portfolio,initial_investment, 'fixed amount', desired_withdraw_amount, years_to_retirement)
    except:
        to_print = "Your target return is out of bound.  Please input reasonable numbers!"
    result['a'] = to_print
    result['b'] = desired_withdraw_amount
    return result

def search_withdraw_rate(portfolio, initial_investment, years_to_retirement, target_amount):
    result = {}

    try:
        min_withdraw = -1000
        max_withdraw = 1000
        learning_rate = 10
        for change in range(min_withdraw, max_withdraw, learning_rate):
            investment_ending_price = portfolio_by_retirement(portfolio,initial_investment,'fixed rate', change/1000, years_to_retirement).iloc[-1]
            quantile_result = investment_ending_price.quantile(q=[0.10]).astype(int)
                    #print(f"If withdrawing ${change} annually, the 10% percentile return will be ${quantile_result.iloc[0]}.")
            if quantile_result.iloc[0]<target_amount:
                break
            desired_withdraw_rate = change/1000
            ending_10_percentile_balance = quantile_result.iloc[0]
        if desired_withdraw_rate < 0:
            to_print = (f"Rather than withdrawing, you should deposit {-desired_withdraw_rate*100}% annually, and ending 10% percentile balance after {years_to_retirement} years would be ${ending_10_percentile_balance}.")
        else:
            to_print = (f"The desired withdraw rate is {desired_withdraw_rate*100}% annually, and ending 10% percentile balance after {years_to_retirement} years would be ${ending_10_percentile_balance}.")
    except:
        to_print = "Your target return is out of bound.  Please input reasonable numbers!"
    result['a'] = to_print
    result['b'] = desired_withdraw_rate
    return result


#! /usr/bin/env python

# Script to craft a packet for testing flow entries
# February 2017 - Martin Roedvand

import sys
import argparse
import logging
import random
import datetime
import os
from scapy.all import *
from subprocess import call

# Commandline arguments
parser = argparse.ArgumentParser(description='Craft a packet to test flow entries.')
parser.add_argument('-d', nargs='?', required=True, help='the destination address of the packet', metavar='DST')
parser.add_argument('-p', nargs=1, choices=['icmp', 'udp', 'tcp'], default=['tcp'], help='the protocol used in the packet')
parser.add_argument('-dp', nargs=1, help='the destination port to be used in the packet', metavar='DPORT')
parser.add_argument('-sp', nargs=1, help='the source port to be used in the packet', metavar='SPORT')
parser.add_argument('-t', action='store_true', help='show packet trace')
parser.add_argument('-v', action='store_true', help='for verbose output. May be helpful under debugging')

args = parser.parse_args()

dest = args.d
prot = args.p[0]
trace = args.t

if args.dp:
	port = int(args.dp[0])
else:
	port = '-1'

if args.sp:
	sourceport = int(args.sp[0])
else:
	sourceport = random.randint(1, 65535)

# Logging
verbose = args.v

if verbose:
	logging.basicConfig(level=logging.DEBUG)
else:
	logging.basicConfig(level=logging.INFO)

# Start crafting a packet with SCAPY
logging.debug("Attempting to craft packet")
logging.debug("CMD arguments: " + str(args))

if prot == 'icmp':
	logging.debug("We're in ICMP")
	packet = IP(dst=dest)/ICMP()/"Hello World"

if prot == 'tcp':
	logging.debug("We're in TCP")
	logging.debug(port)
	if port == '-1':
		logging.warning("Port is not defined. Port is required for TCP.")
		sys.exit(1)
	packet = IP(dst=dest)/TCP(sport=sourceport,dport=port)

if prot == 'udp':
	print

logging.debug("Going for a send")

# Start the trace with ./dump.sh
if trace:
	# Create a time stamp for logging
	timestamp = '{:%Y%m%d%H%M}'.format(datetime.now())
	outfile = open("logs/" + timestamp, 'w')
	logging.debug("Timestamp: " + timestamp)
	logging.debug("Current directory " + os.getcwd())
	logCode = call(["./dump.sh dst host " + dest + "> logs/" + timestamp + " &"], shell=True)
	logging.debug("Call Error Code: " + str(logCode))

	if logCode != 0:
		logging.info("TCPdump returned with error code " + str(logCode))

sr(packet, timeout=1)


class Node(object):
    def __init__(self,item):
        self.item = item
        self.next = None

class SingleLink(object):
    def __init__(self):
        self._head = None

    def is_empty(self):

        return self._head == None

    def length(self):
        count = 0
        curr = self._head
        while curr != None:
            count += 1
            curr = curr.next

        return count

    def travel(self):
        curr = self._head
        while curr != None:
            print(curr.item)
            curr = curr.next
        print('')

    def append(self,item):
        node = Node(item)
        if self.is_empty():
            self._head = node
        else:
            curr = self._head
            while curr.next != None:
                curr = curr.next
            curr.next = node

    def add(self,item):
        node = Node(item)
        node.next == self._head
        self._head = node

    def insert(self,pos,item):
        node = Node(item)
        if pos <= 0:
            self.add(item)
        elif pos > self.length()-1:
            self.append(item)
        else:
            node = Node(item)
            curr = self._head
            count = 0
            while count != pos-1:
                curr = curr.next
                count += 1
            node.next = curr.next
            curr.next = node

    def remove(self,item):
        #两个游标，pre为curr的前一个节点
        curr = self._head
        pre = None
        while curr != None:
            if curr.item == item:
                if not pre:
                    self._head = curr.next
                else:
                    pre.next = curr.next
                break
            else:
                #往后移动
                pre = curr
                curr = curr.next

    def search(self, item):
        curr = self._head
        while curr != None:
            if curr.item == item:
                return True
            curr = curr.next

        return False

if __name__ == '__main__':
    s = SingleLink()
    print(s.is_empty())
    s.add(1)
    print(s.is_empty())
    s.append(1)
    print(s.travel())


from fabric.api import cd
from fabric.api import put
from fabric.api import run
from fabric.api import sudo
from fabric.api import task

@task
def install():
    """
    Nginx from source
    """
    version = '1.4.1'
    url = 'http://nginx.org/download/nginx-{0}.tar.gz'.format(version)
    sudo('apt-get install -y libpcre3')
    sudo('apt-get install -y libpcre3-dev')
    sudo('apt-get install -y libssl-dev')
    sudo('apt-get install -y zlib1g')
    sudo(('adduser '
          '--system '
          '--no-create-home '
          '--disabled-login '
          '--disabled-password '
          '--group nginx'))
    sudo('mkdir -p /var/www')
    run('mkdir -p ~/tmp')
    run('wget -P ~/tmp {0}'.format(url))
    with cd('~/tmp'):
        run('tar xvzf nginx-{0}.tar.gz'.format(version))
    with cd('~/tmp/nginx-{0}'.format(version)):
        run(('./configure '
             '--prefix=/opt/nginx '
             '--user=nginx '
             '--group=nginx '
             '--with-http_ssl_module '
             '--without-http_scgi_module '
             '--without-http_uwsgi_module '
             '--without-http_fastcgi_module'))
        run('make')
        sudo('make install')
    run('rm -rf ~/tmp')
    put('../configuration/etc-init.d-nginx', '/etc/init.d/nginx', use_sudo=True)
    sudo('chmod +x /etc/init.d/nginx')
    sudo('update-rc.d nginx defaults')
    sudo('service nginx start')

@task
def configure():
    """
    Create the config file to host the application
    """
    sudo('touch /opt/nginx/conf/nginx.conf')
    sudo('mkdir -p /opt/nginx/conf/backup')
    sudo('mv --backup=numbered /opt/nginx/conf/nginx.conf /opt/nginx/conf/backup')
    put('../configuration/nginx.conf', '/opt/nginx/conf/nginx.conf', use_sudo=True)
    sudo('service nginx stop')
    sudo('service nginx start')


from flask import Flask, render_template, request, redirect, url_for

import secrets
import os

app = Flask(__name__)

def save_paste(paste):
    paste_id = secrets.token_hex(16)
    with open("paste/{}".format(paste_id), "w") as f:
        f.write(paste)
    return paste_id

def get_paste(paste_id=None):
    try:
        with open("paste/{}".format(paste_id), "r") as f:
            paste = f.read()
        return paste
    except FileNotFoundError:
        return None

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

@app.route("/paste/", methods=["GET", "POST"])
@app.route("/paste/<paste_id>")
def paste(paste_id=None):
    for root, dirs, files in os.walk("paste"):
        pasted_files = files[::-1]

    if request.method == "POST":
        # Save the paste in the form to a file
        paste_id = save_paste(request.form["paste"])
        return redirect(url_for("paste") + paste_id)
    paste = get_paste(paste_id)
    return render_template("paste.html", paste_id=paste_id, paste=paste, files=pasted_files)

@app.route("/about/")
def about():
    return render_template("about.html")

@app.errorhandler(404)
def page_not_found(error):
    return render_template("page_not_found.html"), 404

if __name__ == "__main__":
    app.run()


from gymlabyrinth.envs.labyrinthBaseEnv import LabyrinthBase

class LabyrinthRandomDoors(LabyrinthBase):
    def __init__(self, screen_size=(120,120)):
        super(LabyrinthRandomDoors, self).__init__(screen_size, 'random')

if __name__ == '__main__':
    env = LabyrinthRandomDoors((800, 800))
    env.play()