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

from cleo.commands.command import Command, CommandError
from cleo.application import Application
from cleo.inputs.input_definition import InputDefinition
from cleo.inputs.input_argument import InputArgument
from cleo.inputs.input_option import InputOption
from cleo.inputs import ListInput
from cleo.outputs import NullOutput
from cleo.helpers import FormatterHelper
from cleo.testers import CommandTester
from cleo.validators import Integer, Boolean
from .. import CleoTestCase
from ..fixtures.some_command import SomeCommand
from ..fixtures.no_configure_command import NoConfigureCommand
from ..fixtures.signature_command import SignatureCommand
from ..fixtures.inherited_command import ChildCommand

class CommandTest(CleoTestCase):

    NON_CALLABLE = None

    def test_init(self):
        """
        Command.__init__() behaves properly
        """
        self.assertRaises(Exception, Command)

        command = Command('foo:bar')
        self.assertEqual(
            'foo:bar',
            command.get_name(),
            msg='__init__() takes the command name as its first argument'
        )

    def test_command_name_cannot_be_empty(self):
        """
        A command name cannot be empty.
        """
        self.assertRaises(
            Exception,
            Command
        )

    def test_set_application(self):
        """
        Command.set_application() sets the current application
        """
        application = Application()
        command = SomeCommand()
        command.set_application(application)
        self.assertEqual(application, command.get_application(), msg='.set_application() sets the current application')

    def test_set_get_definition(self):
        """
        Command.get/set_definition properly sets and gets definition
        """
        command = SomeCommand()
        definition = InputDefinition()
        ret = command.set_definition(definition)
        self.assertEqual(command, ret, msg='.set_definition() implements a fluent interface')
        self.assertEqual(definition, command.get_definition(),
                         msg='.set_definition() sets the current InputDefinition instance')
        command.set_definition([InputArgument('foo'), InputOption('bar')])
        self.assertTrue(command.get_definition().has_argument('foo'),
                        msg='.set_definition() also takes an array of InputArguments and InputOptions as an argument')
        self.assertTrue(command.get_definition().has_option('bar'),
                        msg='.set_definition() also takes an array of InputArguments and InputOptions as an argument')
        command.set_definition(InputDefinition())

    def test_add_argument(self):
        """
        Command.add_argument() adds an argument to command.
        """
        command = SomeCommand()
        ret = command.add_argument('foo')

        self.assertEqual(ret, command)
        self.assertTrue(command.get_definition().has_argument('foo'))

    def test_add_option(self):
        """
        Command.add_option() adds an option to command.
        """
        command = SomeCommand()
        ret = command.add_option('foo')

        self.assertEqual(ret, command)
        self.assertTrue(command.get_definition().has_option('foo'))

    def test_get_namespace_get_name_set_name(self):
        command = SomeCommand()
        self.assertEqual('namespace:name', command.get_name())

        command.set_name('foo')
        self.assertEqual('foo', command.get_name())

        ret = command.set_name('foobar:bar')
        self.assertEqual(ret, command)
        self.assertEqual('foobar:bar', command.get_name())

    def test_invalid_command_names(self):
        data = ['', 'foo:']

        command = SomeCommand()

        for d in data:
            self.assertRaisesRegexp(
                CommandError,
                'Command name "%s" is invalid.' % d,
                command.set_name,
                d
            )

    def test_set_get_description(self):
        command = SomeCommand()

        self.assertEqual('description', command.get_description())

        ret = command.set_description('description1')
        self.assertEqual(ret, command)
        self.assertEqual('description1', command.get_description())

    def test_set_get_help(self):
        command = SomeCommand()

        self.assertEqual('help', command.get_help())

        ret = command.set_description('help1')
        self.assertEqual(ret, command)
        self.assertEqual('help1', command.get_description())

    def test_get_processed_help(self):
        command = SomeCommand()

        command.set_help('The %command.name% command does... Example: python %command.full_name%.')
        self.assertRegex(
            command.get_processed_help(),
            'The namespace:name command does...'
        )
        self.assertNotRegex(
            command.get_processed_help(),
            '%command.full_name%'
        )

    def test_set_get_aliases(self):
        command = SomeCommand()

        self.assertEqual(['name'], command.get_aliases())

        ret = command.set_aliases(['name1'])
        self.assertEqual(ret, command)
        self.assertEqual(['name1'], command.get_aliases())

    def test_get_synposis(self):
        command = SomeCommand()
        command.add_argument('bar')
        command.add_option('foo')

        self.assertEqual(
            'namespace:name [--foo] [--] [<bar>]',
            command.get_synopsis()
        )

    def test_get_helper(self):
        application = Application()
        command = SomeCommand()
        command.set_application(application)
        formatter_helper = FormatterHelper()

        self.assertEqual(
            formatter_helper.get_name(),
            command.get_helper('formatter').get_name()
        )

    def test_merge_application_definition(self):
        """
        Command.merge_application_definition() merges command and application.
        """
        application1 = Application()
        application1.get_definition().add_arguments([InputArgument('foo')])
        application1.get_definition().add_options([InputOption('bar')])
        command = SomeCommand()
        command.set_application(application1)
        command.set_definition(
            InputDefinition([
                InputArgument('bar'),
                InputOption('foo')
            ])
        )

        command.merge_application_definition()
        self.assertTrue(command.get_definition().has_argument('foo'))
        self.assertTrue(command.get_definition().has_option('foo'))
        self.assertTrue(command.get_definition().has_argument('bar'))
        self.assertTrue(command.get_definition().has_option('bar'))

        # It should not merge the definitions twice
        command.merge_application_definition()
        self.assertEqual(3, command.get_definition().get_argument_count())

    def test_merge_application_definition_without_args_then_with_args_adds_args(self):
        application1 = Application()
        application1.get_definition().add_arguments([InputArgument('foo')])
        application1.get_definition().add_options([InputOption('bar')])
        command = SomeCommand()
        command.set_application(application1)
        command.set_definition(InputDefinition())

        command.merge_application_definition(False)
        self.assertFalse(command.get_definition().has_argument('foo'))
        self.assertTrue(command.get_definition().has_option('bar'))

        command.merge_application_definition(True)
        self.assertTrue(command.get_definition().has_argument('foo'))

        # It should not merge the definitions twice
        command.merge_application_definition()
        self.assertEqual(2, command.get_definition().get_argument_count())

    def test_run_interactive(self):
        tester = CommandTester(SomeCommand())

        tester.execute([], {'interactive': True})

        self.assertEqual(
            'interact called\nexecute called\n',
            tester.get_display()
        )

    def test_run_non_interactive(self):
        tester = CommandTester(SomeCommand())

        tester.execute([], {'interactive': False})

        self.assertEqual(
            'execute called\n',
            tester.get_display()
        )

    def test_execute_method_needs_to_be_overwridden(self):
        command = Command('foo')
        self.assertRaises(
            NotImplementedError,
            command.run,
            ListInput([]),
            NullOutput()
        )

    def test_run_with_invalid_option(self):
        command = SomeCommand()
        tester = CommandTester(command)

        self.assertRaises(
            Exception,
            'The "--bar" option does not exist.',
            tester.execute,
            [('--bar', True)]
        )

    def test_run_returns_integer_exit_code(self):
        command = SomeCommand()
        exit_code = command.run(ListInput([]), NullOutput())
        self.assertEqual(0, exit_code)

        command = SomeCommand()
        command.execute = self.mock().MagicMock(return_value=2.3)
        exit_code = command.run(ListInput([]), NullOutput())
        self.assertEqual(2, exit_code)

    def test_set_code(self):
        command = SomeCommand()
        ret = command.set_code(lambda c: c.line('from the code...'))
        self.assertEqual(ret, command)

        tester = CommandTester(command)
        tester.execute([])
        self.assertEqual(
            'interact called\nfrom the code...\n',
            tester.get_display()
        )

        command = SomeCommand()
        command.set_code(self.callable_method)
        tester = CommandTester(command)
        tester.execute([])
        self.assertEqual(
            'interact called\nfrom the code...\n',
            tester.get_display()
        )

    def test_set_code_with_non_callable(self):
        command = SomeCommand()

        self.assertRaisesRegexp(
            Exception,
            'Invalid callable provided to Command.setCode().',
            command.set_code,
            self.NON_CALLABLE
        )

    def test_without_configure(self):
        command = NoConfigureCommand()

        self.assertEqual('no:configure', command.get_name())
        self.assertEqual('description', command.get_description())
        self.assertEqual('help', command.get_help())
        self.assertEqual(2, command.get_definition().get_argument_count())
        self.assertEqual(2, len(command.get_definition().get_options()))

    def test_with_signature(self):
        command = SignatureCommand()

        self.assertEqual('signature:command', command.name)
        self.assertEqual('description', command.description)
        self.assertEqual('help', command.help)
        self.assertEqual(2, command.get_definition().get_argument_count())
        self.assertEqual(2, len(command.get_definition().get_options()))
        self.assertIsInstance(command.get_definition().get_argument('foo').get_validator(), Integer)
        self.assertIsInstance(command.get_definition().get_option('baz').get_validator(), Boolean)

    def callable_method(self, c):
        c.line('from the code...')

    def test_signature_inheritance(self):
        command = ChildCommand()

        assert 'parent' == command.name
        assert 'Parent Command.' == command.description


# requires: pip install asciimatics
# tutorials from:
# https://github.com/peterbrittain/asciimatics
# https://ludusrusso.cc/2018/04/04/python-scrivere-terminal-gui/
#
# Docs: http://asciimatics.readthedocs.io/en/stable/

from asciimatics.effects import Cycle, Stars
from asciimatics.renderers import FigletText
from asciimatics.scene import Scene
from asciimatics.screen import Screen
from random import randint

def demo_stars(screen):
	#effects is an array that contains the effects we want to apply to our UI
	#2 Cycle Effects and 1 Stars

	effects = [
		#Cycle let cycle the color of the text we are passing it
		Cycle(
			screen,
			FigletText("Rensykes", font='big'), #you can use other Figlet
			int(screen.height / 2 - 8)),
		Cycle(
			screen,
			FigletText("Learn asciimatics!", font='small'),
			int(screen.height / 2 + 3)),
		Stars(screen, 500) #draw a certain ammpunt of stars
	]
	screen.play([Scene(effects, 500)]) #renderize the scene with the effects
	ev = screen.get_key() #use it to get the key pressed
	if ev in (ord('Q'), ord('q')):
		return
	screen.refresh()

def demo_helloWorld(screen):
	while True:
		screen.print_at('Hello world!',
					randint(0, screen.width), randint(0, screen.height),
					colour=randint(0, screen.colours - 1),
					bg=randint(0, screen.colours - 1))
		ev = screen.get_key()
		if ev in (ord('Q'), ord('q')):
			 return
		screen.refresh()

Screen.wrapper(demo_helloWorld)


#!/usr/bin/env python3
from numpy import random

class Story:
    @staticmethod
    def hit_wall():
        """:returns: String"""
        messages = [
            'You walk straight into a wall. "I wonder if that wall was there all the time?", you think to yourself.',
            'Your attention span breaks. While distracted you manage to walk straight into a wall.',
            'I wonder what it would feel like to chew on a cactus, you ponder as you walk face first into the wall.',
            'As you fumble around in the dark you slam your face into the wall',
            '"How could it be?", you think to your self, '
            '"That I am fully capable of fighting monsters, but I can\'t seem to stop hitting these walls!"',
            'You slip and fall face first into the wall, '
            '"I must be more careful in the future", you mumble to yourself.',
            '"Bumping into all these walls will surely give me brain damage", you sneer into the darkness.',
            'As you walk in the dim lights surrounding you, you can\'t seem to help walking into a wall.'
        ]

        return messages[random.randint(len(messages))]

    @staticmethod
    def find_stairs():
        """:returns: String"""
        messages = [
            'You have reached a set of stairs, '
            'you are hesitant but somehow you know that this might be your only way out.',
            'You see an old set of stairs not to far away from where you are standing '
            'and decide to see where they will lead you.',
            '"There are lights at the end of these stairs", you think to yourself, "I wonder where they\'ll take me?"',
            'As you come closer you can see a wooden ladder. You decide to climb it into the abyss.'
        ]

        return messages[random.randint(len(messages))]

    @staticmethod
    def death():
        """:returns: String"""
        messages = [
            'As you slowly sink in, you draw your last breath. At last you can have some peace.',
            '"So close ...", you whisper in the dark, "So close ..."',
            'Of all the things in your life that you regret, you regret not being more careful the most.',
            'As you become sleepy and your body feels warm and limp, as you hear the sound of dragging feet which are '
            ' closing in, you know there was never a chance. "At last I will have some peace ..."',
            'And my soul from out that shadow that lies floating on the floor, Shall be lifted - nevermore!',
            'While I thought that I was learning how to live, I have been learning how to die.'
        ]

        return messages[random.randint(len(messages))]

    @staticmethod
    def go_east():
        """:returns: String"""
        messages = [
            'After considering your options you decide to continue to the East.',
            'You go to the East.',
            '"Well, I guess I will continue to the East", you mutter to yourself.',
            'There was never really an option but continuing to the East.',
            'Slowly you move toward the east, hopefully it will take you away from this dreaded place.',
            'Quickly you run towards the East.',
            'A light in the other room helps you decide to continue your journey towards the East.'
        ]

        return messages[random.randint(len(messages))]

    @staticmethod
    def go_west():
        """:returns: String"""
        messages = [
            'After considering your options you decide to continue to the West.',
            'You go to the West.',
            '"Well, I guess I will continue to the West", you mutter to yourself.',
            'There was never really an option but continuing to the West.',
            'Slowly you move toward the West, hopefully it will take you away from this dreaded place.',
            'Quickly you run towards the West.',
            'A light in the other room helps you decide to continue your journey towards the West.',
            ''
        ]

        return messages[random.randint(len(messages))]

    @staticmethod
    def go_north():
        """:returns: String"""
        messages = [
            'After considering your options you decide to continue to the North.',
            'You go to the North.',
            '"Well, I guess I will continue to the North", you mutter to yourself.',
            'There was never really an option but continuing to the North.',
            'Slowly you move toward the North, hopefully it will take you away from this dreaded place.',
            'Quickly you run towards the North.',
            'A light in the other room helps you decide to continue your journey towards the North.',
            ''
        ]

        return messages[random.randint(len(messages))]

    @staticmethod
    def go_south():
        """:returns: String"""
        messages = [
            'After considering your options you decide to continue to the South.',
            'You go to the South.',
            '"Well, I guess I will continue to the South", you mutter to yourself.',
            'There was never really an option but continuing to the South.',
            'Slowly you move toward the South, hopefully it will take you away from this dreaded place.',
            'Quickly you run towards the South.',
            'A light in the other room helps you decide to continue your journey towards the South.',
            ''
        ]

        return messages[random.randint(len(messages))]

    @staticmethod
    def power_up():
        messages = [
            'You found an old magic potion, you drank it. All of your HP was restored.'
        ]

        return messages[random.randint(len(messages))]

    @staticmethod
    def trap(dmg):
        messages = [
            'As you touch the wall, you hear a small click. You suddenly feel a sharp pain in your side as a knife '
            'cut through your flesh you take {} damage'.format(dmg),
            'You stumble in the dark, and in the last second you realise that you just triggered a tripwire.'
            'While dodging the trap you cut yourself on a spear and receive {} damage'.format(dmg)
        ]

        return messages[random.randint(len(messages))]

    @staticmethod
    def storyline(level):
        story = [
            'The sound of water dripping from the ceiling catch your attention.\n'
            'At first, it is just distant drumming, but as you gradually gain consciousness,\n'
            'you can hear the sound of the water hitting the cold rock ground beneath you.\n'
            'The smell is cold and damp, but you cannot recall how you could have ended up here.\n'
            'A sound in the distance which bears resemblance of a rabid animal, makes the hairs in your neck reach '
            'for the walls\nand sends chills down your spine.\nThe electrical impulses in your brain tell you '
            'it is time to open your eyes and run.\n\nSlowly you open your eyelids in a dimly lit room with no real '
            'recollection of who you are\nor how you got here. Your throat feels dry, and your bones are '
            'aching,\nyou need to find a way out but where do you start?\n\n',
            'The insecurity hits you like a brick as you enter the room and witness your only way out dissolve like '
            'an illusion in-front of you.\n There is no way back, at least not the way you came from. '
            'There is nothing to do but to continue moving in the only direction ahead.\nYou curse your god while '
            'you are pondering what to do next.\n\n',
            ""
        ]

        return story[level]

    @staticmethod
    def monster_spawn(kind, sound):
        messages = [
            'As you enter the door, a loud {} tears through the room and a {} appears from the shadows.'.format(sound, kind)
        ]

        return messages[random.randint(len(messages))]

    @staticmethod
    def miss():
        messages = [
            'You swing against your enemy, but the attack fails.',
            'With crushing power your attack misses it\'s target and you go pounding your weapon to the ground.',
            'The sound of your missed attack leaves a bitter taste in your mouth.'
        ]

        return messages[random.randint(len(messages))]

    @staticmethod
    def attack(dmg):
        messages = [
            'You attack your opponent, in your fury you deal a whooping {} damage.'.format(dmg)
        ]

        return messages[random.randint(len(messages))]

    @staticmethod
    def monster_dead(monster):
        messages = [
            'The {} hits the ground while one last {}, '
            'is heard before the silence of death is all that is left in the room'.format(monster.get_kind(), monster.get_sound())
        ]

        return messages[random.randint(len(messages))]

    @staticmethod
    def monster_attack(monster, dmg):
        messages = [
            'The {} attacks with it\'s {}, and deals {} of damage'.format(monster.get_kind(), monster.get_weapon(), dmg)
        ]

        return messages[random.randint(len(messages))]

    @staticmethod
    def monster_miss(monster):
        messages = [
            'The {}\'s attack misses'.format(monster.get_kind()),
            'As your opponent takes a swing at you, '
            'you use your swift reflexes to dodge the attack in a crucial moment.'
        ]

        return messages[random.randint(len(messages))]


""" This is the final version of my Integration project
This is a Trivia Game that also serves as a GUI
revolving around JOJO's Bizzare adventures.
__author__ = Christian Apostoli
This program utilizes the external module created by John Zelle.
"""
# Christian Apostoli
# This will  be a trivia quiz which has
# a main theme based on JOJO's Bizzare Adventures.
# The game has two sets of questions: one with
# a level of difficulty dependent on the user and
# a gauntlet style set of questions.
# Caution: If you are not a fan you will not get these right.

# Notes:
# Use dictionary for answers
# use function for seeing if player is right
# use a lag function for if the player is right

from graphics import *

# ------------- POP UP Graphics----------------------
win = GraphWin("JOJO Trivia Game", 600, 600)

def make_new_scene(message):
    """
    make_new_scene passes the message argument as text to the screen
    and will also place the logo above the text.
    :param message: The text on the GUI window
    """
    # make_new_scene uses functions from the graphics module to create the
    # and input text on to the screen along with the logo. It initializes the
    # txt object and configures the color and size
    win.setBackground(color_rgb(0, 0, 0))

    txt = Text(Point(250, 350), message)
    txt.setTextColor(color_rgb(0, 255, 200))
    txt.setSize(15)
    txt.draw(win)

    img = Image(Point(250, 180), "Jojo.png")
    img.draw(win)

    win.getMouse()

def clear():
    """
    Clear erases the screen for the scene.
    """
    # Clears the screen for the next scene by placing a rectangle in
    # with the same size as the window to simulate erasing
    # the content on the screen

    rect = Rectangle(Point(0, 0), Point(600, 600))
    rect.setOutline(color_rgb(0, 0, 0))
    rect.setFill(color_rgb(0, 0, 0))
    rect.draw(win)

## def text_box(message):
##    Function that creates textbox for the user to enter info
##    Function was very difficult to incorporate with other
##    code, so it was commented for possible future use
##
##    win.setBackground(color_rgb(0,0,0))
##
##    txt = Text(Point(250,300), message)
##    txt.setTextColor(color_rgb(0,255, 200))
##    txt.setSize(15)
##    txt.draw(win)
##
##    img = Image(Point(250,180), "Jojo.png")
##    img.draw(win)
##
##    input_box = Entry(Point(250, 400), 15)
##    input_box.draw(win)
##    answer = input_box.getText()
##
##    while True:
##        txt.setText(input_box.getText())
##
##    win.getMouse()

def set_one(n, arr):
    """
    This is the first set of questions. The question will vary based on the
    user's desired difficulty. Then the function will see if the user got
    the question correct or not.
    :param n: The desired level of difficulty.
    :param arr: The array that the function appends 1 to create a score.
    :return: The question of certain difficulty that the user will answer.
    """
    # The passed parameter n will be from the input function inside the while
    # loop. The function will create a new scene with text inside the game
    # window and the python shell. If the user inputs the correct answer,
    # arr will append 1 to it which will be how many questions were answered
    # correctly.
    if n == 0:
        answer = input("In what part did Johnathan Joestar die? ")
        if answer == '1' or answer == 'part 1' or answer == 'Part 1':
            make_new_scene("Correct. Click to Continue.")
            clear()
            arr.append(1)
        else:
            make_new_scene("Sorry, incorrect. Click to continue.")
            clear()
    elif n == 1:
        answer = input("Who was Joseph's German friend\n" +
                       "who helped him defeat the pillar men? ")
        if (answer == 'Stronheim') or (answer == 'Victor Von Stronheim'):
            make_new_scene("Correct, Click to continue.")
            clear()
            arr.append(1)
        else:
            make_new_scene("Sorry, incorrect. Click to continue.")
            clear()
    elif n == 2:
        answer = input("What was the tarot card of the Ship stand in part 3? ")
        if answer == 'Strength':
            make_new_scene("Correct. Click to Continue.")
            clear()
            arr.append(1)
        else:
            make_new_scene("Sorry, incorrect. Click to continue.")
            clear()
    elif n == 3:
        answer = input("What famous phrase does DIO\n" +
                       "say as he is about to fight Jotaro? ")
        if answer == 'oh, so you are approaching me':
            make_new_scene("Correct. Click to continue.")
            clear()
            arr.append(1)
        else:
            make_new_scene("Sorry, incorrect. Click to continue.")
            clear()
    elif n == 4:
        answer = input("What is the final opening to part 4" +
                       "(Just say the first two words)? ")
        if (answer == 'Breakdown') or (answer == 'Shining Justice'):
            make_new_scene("Correct. Click to continue.")
            clear()
            arr.append(1)
        else:
            make_new_scene("Sorry, incorrect. Click to continue.")
            clear()
    elif n == 5:
        answer = input("What is Giorno Giovana's famous line (in Japanese)? ")
        if answer == 'kono giorno giovana niwa yume ga aru':
            make_new_scene("Correct. Click to continue.")
            clear()
            arr.append(1)
        else:
            make_new_scene("Sorry, incorrect. Click to continue.")
            clear()

# -------------------------------------------------

def main():
    """
    Initializes the game and continues the game until the user is finished.
    """
    make_new_scene("Hello user, welcome to my JOJO Trivia Game!\n" +
                   "Continue the game by clicking the black window.")
    clear()

    make_new_scene(
        "All new players will start out with a score of " + str(0) + ".")
    clear()

    make_new_scene(
        "A player's final score will be determined by the number\n" +
        "of questions correct divided by the number of total questions.")
    clear()

    # The next four lines performs the arithmetic behind
    # the example for the user's score.
    num_correct = 100
    num_questions = 100
    score_final = num_correct / num_questions
    score_final *= 100

    make_new_scene("For example, a perfect score" +
                   " will result in a " + str(score_final) + ".")
    clear()

    make_new_scene(
        "First we will begin with a question that depends on your\n" +
        "desired difficulty, then we will move on to a set of five\n" +
        "         questions. Please remember to answer your questions ASAP.")
    clear()

    make_new_scene(
        "What question level would you like to start at for your\n" +
        "first set? Please return to the Python shell to insert your\n" +
        "          input and drag the shell window beside the game window")
    clear()

    # The program asks the user what level they would like to start at for
    # their first set of questions. The while loop will further validate
    # the user's input.
    n = int(input("What question level would you like to start\n" +
                  "at for your first set? (0-5, whole number)"))
    input_bad = True
    while input_bad:
        try:
            # If the user inputs a number out of range
            while n > 5 or n < 0:
                print("Number is out of range")
                n = int(input("What question level would you like to start\n" +
                              "at for your first set? (0-5, whole number)"))
            input_bad = False
        # If the user does not input a whole number
        except ValueError:
            print("This is not a whole number")

    # This array is created to see if the user answered the question correctly
    # by inserting a value in the array and checking  if the value is present.
    arr = []

    set_one(n, arr)

    score = (arr.count(1) * 100)
    make_new_scene("Your Score for your first set is " + str(score) + ".")
    clear()

    make_new_scene("Now time for your second set! There \n" +
                   "will be five questions. Click to continue.")
    clear()

    make_new_scene("Remember to click until the question appears\n" +
                   "on the shell and then put in your answer.")
    clear()

    # The following two arrays contain the questions
    # and answers for the next set of questions.
    second_set = ["What is the stand of Fugo in part 5? ",
                  "What is D'arby the younger's stand in part 3?  ",
                  "What is Shigechi's stand in part 4? ",
                  "What does Jotaro have a PhD in? ",
                  "What was the name of the supposed alien from part 4? "]

    second_set_answers = ["Purple Haze", "Atum", "Harvest", "Marine Biology",
                          "Mikitaka"]

    # If the user got the first set correct then
    # a point is added to this next array.
    score_arr = []
    if arr.count(1) == 1:
        score_arr.append(1)

    is_on = True

    while is_on:
        #   Loop will iterate through second_set
        #   and validate if the user's response is correct by seeing
        #   if it is the same as the corresponding value in second_set_answers.
        for i in range(len(second_set)):
            make_new_scene(second_set[i] + "\nClick to continue.")
            clear()
            question = input(second_set[i])
            if question == second_set_answers[i]:
                make_new_scene("That's correct. Click to continue.")
                clear()
                print("That's correct")
                score_arr.append(1)
            else:
                print("Sorry, incorrect.")
                make_new_scene("That's not correct. Click to continue")
                clear()

        is_on = False
    # The score is calculated by checking how many times
    # 1 is present in the score_arr array.
    score_final = (int(score_arr.count(1)) / 6.0) * 100
    print("Your final score is: ", format(score_final, '.2f'))
    make_new_scene("Your final score is: " + format(score_final, '.2f'))
    clear()
    make_new_scene("Thanks for playing!")
    win.close()

main()


# making and printing an address. Moving through.
p_i = {
    'fname': 'Kenneth',
    'lname': 'Sherwood',
    'house': '1133',
    'st': 'School Street',
    'town': 'Indiana',
    'state': 'Pennsylvania',
    'zip': '15701'}
# print(pers_info)

print(p_i['fname'] + ' ' + p_i['lname'] + '\n')

print(p_i['house']+ ' '+ p_i['st'] + '\n')

print(p_i['town']+ ', '+ p_i['zip'])

### alt


from uuid import uuid4

import factory
from django.db.models.signals import post_save
from django.utils import timezone

from questions.models import FileUpload, ImageUpload, Submission

from .utils import get_dummy_file

class TimestampedModelFactory(factory.django.DjangoModelFactory):

    modified_at = factory.Faker(
        "date_time_between", tzinfo=timezone.utc, start_date="-1m", end_date="now"
    )
    created_at = factory.Faker(
        "date_time_between", tzinfo=timezone.utc, start_date="-2m", end_date="-1m"
    )

@factory.django.mute_signals(post_save)
class SubmissionFactory(TimestampedModelFactory):
    class Meta:
        model = Submission

    id = factory.LazyAttribute(lambda x: uuid4())
    questions = {}
    answers = {}

@factory.django.mute_signals(post_save)
class ImageUploadFactory(TimestampedModelFactory):
    class Meta:
        model = ImageUpload

    id = factory.LazyAttribute(lambda x: uuid4())

    @factory.post_generation
    def image(self, create, extracted, **kwargs):
        if extracted:
            file_name, file = extracted
        else:
            file_name = "image.png"
            file = get_dummy_file(file_name)

        self.image.save(file_name, file)

@factory.django.mute_signals(post_save)
class FileUploadFactory(TimestampedModelFactory):
    class Meta:
        model = FileUpload

    id = factory.LazyAttribute(lambda x: uuid4())

    @factory.post_generation
    def file(self, create, extracted, **kwargs):
        if extracted:
            file_name, file = extracted
        else:
            file_name = "doc.pdf"
            file = get_dummy_file(file_name)

        self.file.save(file_name, file)


import numpy as np

def sigmoid(x):
    return 1 / (1 + np.exp(-x))

def norm_sigmoid(n, r):
    y = sigmoid(np.linspace(-r, r, n))
    y = y - y.min()
    y = y / y.max()
    return y

def _combine(m1, m2, overlap, r):
    n1, y = m1.shape
    n2 = m2.shape[0]

    w = int(np.round((n1 + n2) * overlap))
    n = n1 + n2 - w

    M1 = np.zeros((n, y))
    M1[:n1] = m1

    M2 = np.zeros((n, y))
    M2[-n2:] = m2

    a = n - n2
    b = n1

    W = np.zeros((n, 1))
    W[:a] = 1
    W[a:b, 0] = 1 - norm_sigmoid(b - a, r)
    W[b:] = 0

    M = ((M1 * W) + (M2 * (1 - W)))
    return M

def traj_as_array(traj):
    return np.array(list(traj.values())).T

def combine(*trajs, overlap=0.1, r=5):
    motors = set([tuple(t.keys()) for t in trajs])
    if len(motors) != 1:
        raise ValueError('All trajs must use the same motors!')
    motors = motors.pop()

    moves = [traj_as_array(t) for t in trajs]

    m1 = moves[0]

    for m2 in moves[1:]:
        m1 = _combine(m1, m2, overlap, r)

    return {
        m: m1[:, i]
        for i, m in enumerate(motors)
    }


"""
Construct user utility model or retrieve from database and update with
augmented trips. Store in database and return the model.
"""

from user_utility_model import UserUtilityModel

def build_user_model(user_id, augmented_trips):
  model = UserUtilityModel.find_from_db(user_id)

  if model:
    model.update(augmented_trips)
  else:
    model = UserUtilityModel(user_id, augmented_trips)

  model.store_in_db()
  return model


"""
#------------------------------------------------------------------------------
# Create ZV-IC Shaper
#
# This script will take a generalized input from an undamped second order system subject
# to nonzero initial conditions and solve the minimum-time ZV shaper using optimization
#
# Created: 6/20/17 - Daniel Newman -- dmn3669@louisiana.edu
#
# Modified:
#   * 6/20/17 - DMN -- dmn3669@louisiana.edu
#			- Added documentation for this script
#------------------------------------------------------------------------------
"""

# Ignore user warnings to keep the terminal clean
import warnings
warnings.simplefilter("ignore", UserWarning)

# Import the necessary python library modules
import numpy as np
from control import matlab
import os
import sys
import pdb

# Add my local path to the relevant modules list
sys.path.append('/Users/Daniel/Github/Crawlab-Student-Code/Daniel Newman/Python Modules')

# Import my python modules
import InputShaping as shaping
import Generate_Plots as genplt
import ic_linear as ic

folder = 'Figures/{}/'.format(
												sys.argv[0],
												)

dt = 0.001
t = np.arange(0,2,dt)
modeled_freq = 14.28
zeta = 0.00748

#Designed Values
detected_phase = 5 * np.pi/4
design_amp = 0.5

velocity_conversion = 1000000 # Counts per meter

# Actuator constraints
design_Vmax = 1. # m/s
design_Amax = 100. # m/s^2

# Time over which the system accelerates to maximum velocity
tacc = design_Vmax / design_Amax

# Undamped period of oscillation
tau = 2 * np.pi / modeled_freq

# Normalized acceleration time by period
tacc_norm = tacc / tau

def phase_shift(norm_tacc):
	return np.pi * norm_tacc

design_phase = detected_phase + phase_shift(tacc_norm)

def amplitude_shift(norm_tacc):
	return (0.64781685 * norm_tacc**3 -1.30590826 * norm_tacc**2 -0.34197296*norm_tacc + 1) \
		    / (0.35026643 * norm_tacc**2 -0.34197296*norm_tacc + 1)

# The position response of a linear second-order system subject to damping
def position_response(t,omega_n,Vmax,normalized_amp,shift=0.):
	return -np.exp(-zeta * omega_n * t) * np.cos(omega_n * (t - shift) * np.sqrt(1 - zeta**2)) * normalized_amp * Vmax

def velocity_response(t,omega_n,Vmax,normalized_amp):
	return omega_n * np.exp(-zeta * omega_n * t) * normalized_amp * Vmax \
		   * np.sqrt(1 - zeta**2) * np.sin(omega_n * t * np.sqrt(1 - zeta**2))

# Response used to generate desired initial conditions
modeled_response = position_response(t,modeled_freq,design_Vmax,design_amp)
modeled_response_deriv = velocity_response(t,modeled_freq,design_Vmax,design_amp)

ic_time = detected_phase / (modeled_freq)
ic_time_step = np.round(ic_time / (t[1] - t[0])).astype(int)

ic_init_pos = modeled_response[ic_time_step]
ic_init_vel = modeled_response_deriv[ic_time_step]

#---------------------------------------------------------------------------------------------
#
#						Create the Pole-Zero Initial Condition Shaper
#
#---------------------------------------------------------------------------------------------

shaper_freq = modeled_freq / (2 * np.pi)

p = [ic_init_pos,ic_init_vel,design_Amax,design_Vmax,1,modeled_freq,True]

res,siic_shaper = ic.si(2, 1., None, shaper_freq - 0.2 * shaper_freq, shaper_freq + 0.2 * shaper_freq, 0.05, 0.01,p,zeta,iterating=True,amp_type='Sens')
res,zvic_shaper = ic.si(0, 1., None, shaper_freq, shaper_freq, 0.0, 0.001,p,zeta,iterating=False)

unshaped = np.array([[0.0,1.0]])

print('SI-IC shaper: {}'.format(siic_shaper))

frequency,siic_amp = ic.ic_sensplot(siic_shaper, 0.01 * shaper_freq, 2.5 * shaper_freq, shaper_freq, p,zeta)
frequency,zvic_amp = ic.ic_sensplot(zvic_shaper, 0.01 * shaper_freq, 2.5 * shaper_freq, shaper_freq, p,zeta)

frequency_small,siic_amp_small = ic.ic_sensplot(siic_shaper, 0.5 * shaper_freq, 1.5 * shaper_freq, shaper_freq, p,zeta)
frequency_small,zvic_amp_small = ic.ic_sensplot(zvic_shaper, 0.5 * shaper_freq, 1.5 * shaper_freq, shaper_freq, p,zeta)

ic_init_pos /= modeled_freq**2
ic_init_vel /= modeled_freq**2

print('Desired initial position: {}'.format(ic_init_pos))
print('Desired initial velocity: {}'.format(ic_init_vel))

#---------------------------------------------------------------------------------------------
#
#						Grab the Experimental Results
#
#---------------------------------------------------------------------------------------------

genplt.compare_responses(frequency * 2 * np.pi / modeled_freq,
						 siic_amp[:,0],r'SI-IC ($I=0.4$)',
						 zvic_amp[:,0],'ZV-IC',
 						 name_append='Large_Range',
						 xlabel=r'Normalized Frequency $\frac{\omega_n}{\omega_m}$',ylabel='Percent Vibration',
						 folder=folder,grid=True,save_data=False,ncol=2,legend_loc='top',ymax=0.1,
						)

genplt.compare_responses(frequency_small * 2 * np.pi / modeled_freq,
						 siic_amp_small[:,0],r'SI-IC ($I=0.4$)',
						 zvic_amp_small[:,0],'ZV-IC',
 						 name_append='Small_Range',
						 xlabel=r'Normalized Frequency $\frac{\omega_n}{\omega_m}$',ylabel='Percent Vibration',
						 folder=folder,grid=True,save_data=False,ncol=2,legend_loc='top',ymax=0.1,
						)

#---------------------------------------------------------------------------------------------
#
#						Plot the Shaped and Unshaped responses
#
#---------------------------------------------------------------------------------------------


#!/usr/bin/python

import tf_codes.robust_pruning_mlp_cifar as rp

SAMPLES = 1000

# Enable benchmarking mode will skip adversarial assessment to speed up the pruning process
benchmarking_mode = 0
activation = 'relu'

hyperparameters = [0.75] # L1 norm in sigmoid mode is not important

# Omit baseline for the mass testing stage
rp.robust_pruning(mode='baseline', size=SAMPLES, benchmarking=benchmarking_mode, activation=activation, adversarial_epsilons=[0.01, 0.05])

for index, item in enumerate(hyperparameters):
    rp.robust_pruning(mode='stochastic', size=SAMPLES,
        benchmarking=benchmarking_mode, activation=activation, alpha=item, adversarial_epsilons=[0.01, 0.05])

print('Task accomplished')


#!/usr/bin/env python3
from itertools import islice, tee
from operator import add

def fib_recursive(num):
	"""
	Recursive function for finding a Fibonnaci sequence given a
	positive integer.

	F(n) = F(n-2) + F(n-1)
	"""
	if num < 2:
		return num
	else:
		return fib_recursive(num - 1) + fib_recursive(num - 2)

def fib_rec_memo(num, fib_memo={0: 0, 1: 1}):
	"""
	Recursive function for finding a Fibonnaci sequence given a
	positive integer and store the key/value pair in a dictionary.
	If the value is is present, simply return the value

	F(n) = F(n-2) + F(n-1)
	"""
	if num not in fib_memo:
		fib_memo[num] = fib_rec_memo(num - 1, fib_memo=fib_memo) + \
						fib_rec_memo(num - 2, fib_memo=fib_memo)

	return fib_memo[num]

def fib_iterative(num):
	"""
	Iterative function for finding a Fibonnaci sequence given a
	positive integer.

	F(n) = F(n-2) + F(n-1)
	"""
	a, b = 0, 1
	for x in range(0, num):
		a, b = b, a + b

	return a

def fib_iter_memo(num, fib_memo={0: 0, 1: 1}):
	"""
	Iterative function for finding a Fibonnaci sequence given a
	positive integer and store the key/value pair in a dictionary.
	If the value is is present, simply return the value

	F(n) = F(n-2) + F(n-1)
	"""
	if num not in fib_memo:
		for x in range(2, num + 1):
			if x not in fib_memo:
				fib_memo[x] = fib_memo[x - 1] + fib_memo[x - 2]

	return fib_memo

def take(n, iterable):
		"""Return elements from 0 to n in a list."""
		return list(islice(iterable, 0, n))

def fib_lazy_haskell_python_3():
	"""A Haskell-style recursive function for finding the N-th
	fibonacci number as laid out by Joel Grus' blog post:
	http://joelgrus.com/2015/07/07/haskell-style-fibonacci-in-python/

	The function is 'lazy' in respect that it only calculates values
	when needed.

	In Haskell, this function would look like:

	fibs :: [Int]
	fibs = 1 : 1 : zipWith (+) fibs (tail fibs)

	Prelude> take 10 fibs
	[1,1,2,3,5,8,13,21,34,55]

	Note: the 'take' function must be written to create/access
	the values created by this function. In python 3, it's pretty
	simple; create a function that passes in 'n' and returns
	'list(islice(iterable, 0, n)'.
	"""

	def tail(iterable):
		"""Return elements from 1 to forever."""
		return islice(iterable, 1, None)

	yield 1
	yield 1
	# essentially adds memoization to function, much more efficient
	fibs1, fibs2 = tee(fib_lazy_haskell_python_3())

	try:
		# 'yield from' was added in Python 3.3 (PEP 308)
		eval('yield from map(add, fibs1, tail(fibs2))')
	except SyntaxError:
		# To make this work in Python versions < 3.3
		# Note: 'map' evaluates lazily in Python 3, in Python 2 use 'imap'
		for value in map(add, fibs1, tail(fibs2)):
			yield value

	# Uncomment below if you want a much slower non-tee version
	#yield from map(add, fib_lazy_haskell_python_3(), tail(fib_lazy_haskell_python_3()))


from collections import defaultdict

def read_file(name):
    with open(f"input.txt") as f:
        content = f.readlines()
    return [x.strip() for x in content]

class Painter:
    def __init__(self, prog):
        self.prog = prog
        self.ip = 0
        self.output = 0
        self.rel_base = 0
        self.halt = False

def split_instruction(instruction):
    instruction = f"{instruction:05}"
    return instruction[3:], instruction[0:3]

def get_values(input, pos, op, modes, painter):
    mode_a, mode_b, mode_c = modes
    values = []
    offset = 0

    if op in ["01", "02", "04", "05", "06", "07", "08", "09"]:
        if mode_c == "0":
            values.append(input[input[pos + 1]])
        elif mode_c == "1":
            values.append(input[pos + 1])
        elif mode_c == "2":
            values.append(input[input[pos + 1] + painter.rel_base])

        if op in ["01", "02", "05", "06", "07", "08"]:
            if mode_b == "0":
                values.append(input[input[pos + 2]])
            elif mode_b == "1":
                values.append(input[pos + 2])
            elif mode_b == "2":
                values.append(input[input[pos + 2] + painter.rel_base])

            if op in []:
                if mode_a == "0":
                    values.append(input[input[pos + 3]])
                elif mode_a == "1":
                    values.append(input[pos + 3])
                elif mode_a == "2":
                    values.append(input[input[pos + 3] + painter.rel_base])

    if op in ["01", "02", "07", "08"]:
        if mode_a == "2":
            offset = painter.rel_base

    if op in ["03"]:
        if mode_c == "2":
            offset = painter.rel_base

    return values, offset

def run_booster(input, painter):
    while painter.prog[painter.ip] != 99:
        op, modes = split_instruction(painter.prog[painter.ip])
        values, offset = get_values(painter.prog, painter.ip, op, modes, painter)

        if op == "01":  # Addition
            painter.prog[painter.prog[painter.ip + 3] + offset] = values[0] + values[1]
            painter.ip += 4

        if op == "02":  # Multiplication
            painter.prog[painter.prog[painter.ip + 3] + offset] = values[0] * values[1]
            painter.ip += 4

        if op == "03":  # Read and Store input
            painter.prog[painter.prog[painter.ip + 1] + offset] = input
            painter.ip += 2

        if op == "04":  # Print Output
            painter.output = values[0]
            # print(painter.output)
            painter.ip += 2
            return painter

        if op == "05":  # Jump-if-True
            if values[0]:
                painter.ip = values[1]
            else:
                painter.ip += 3

        if op == "06":  # Jump-if-False
            if not values[0]:
                painter.ip = values[1]
            else:
                painter.ip += 3

        if op == "07":  # Less than
            if values[0] < values[1]:
                painter.prog[painter.prog[painter.ip + 3] + offset] = 1
            else:
                painter.prog[painter.prog[painter.ip + 3] + offset] = 0
            painter.ip += 4

        if op == "08":  # Equals
            if values[0] == values[1]:
                painter.prog[painter.prog[painter.ip + 3] + offset] = 1
            else:
                painter.prog[painter.prog[painter.ip + 3] + offset] = 0
            painter.ip += 4

        if op == "09":  # Adjust Relative Base
            painter.rel_base += values[0]
            painter.ip += 2

    painter.halt = True
    return painter

def create_program(input):
    prog = defaultdict(int)

    for i in range(len(input)):
        prog[i] = int(input[i])

    return prog

def turn_and_move(pos, dir, turn):
    if turn == 0:
        dir = (dir - 1) % 4
    else:
        dir = (dir + 1) % 4

    if dir == 0:  # up
        pos = (pos[0], pos[1] + 1)
    elif dir == 1:  # right
        pos = (pos[0] + 1, pos[1])
    elif dir == 2:  # down
        pos = (pos[0], pos[1] - 1)
    elif dir == 3:  # left
        pos = (pos[0] - 1, pos[1])

    return pos, dir

def solve():
    input = read_file("11")[0].split(",")
    prog = create_program(input)

    panel = defaultdict(int)
    painted = defaultdict(int)
    painter = Painter(prog)

    dir = 0
    pos = (0, 0)

    while not painter.halt:
        painter = run_booster(panel[pos], painter)
        color = painter.output
        painter = run_booster(panel[pos], painter)
        turn = painter.output

        painted[pos] = 1
        panel[pos] = color

        pos, dir = turn_and_move(pos, dir, turn)

    return len(painted)

print(solve())


from math import sqrt, exp
import numpy as np

file = open('input.txt')

f1 = file.readlines()

numFeatures, numClass, datasetLen = 0, 0, 0

dataset = []

count = 0
for line in f1:
    if count == 0:
        var = line.split()
        numFeatures = int(var[0])
        numClass = int(var[1])
        datasetLen = int(var[2])
    else:
        var = line.split()
        dataset.append([int(x) for x in var])
    count += 1

average = []

for i in range(numFeatures):
    sum = 0
    for vector in dataset:
        sum += vector[i]

    average.append(float(sum/datasetLen))

print(average)

# individual co-varience

co_varience = []

for i in range(numFeatures):
    sum = 0
    for vector in dataset:
        sum += (vector[i] - average[i])**2

    co_varience.append(float(sum/datasetLen))

standard_deviation = [sqrt(x) for x in co_varience]

print(co_varience)

# co-varience matrix

co_varience_matrix = []

for i in range(numFeatures):
    row = []
    for j in range(numFeatures):
        sum = 0
        for vector in dataset:
            sum += (vector[i]-average[i])*(vector[j]-average[j])
        row.append(float(sum/datasetLen))
    co_varience_matrix.append(row)

print(co_varience_matrix)

co_varience_matrix = np.matrix(co_varience_matrix)

print(co_varience_matrix)

inverse_co_varience_matrix = np.linalg.inv(co_varience_matrix)

print(inverse_co_varience_matrix)

feature_vectors = []

for data in dataset:
    data.pop()
    feature_vector = np.matrix(data)
    feature_vector = np.transpose(feature_vector)
    feature_vectors.append(feature_vector)

average = np.matrix(average).transpose()

det = np.linalg.det(co_varience_matrix)

normal_distribution_values = []

for vector in feature_vectors:
    x_u = np.matrix(vector-average)
    value = (1/(((2*3.1416)**(float(numFeatures/2)))*sqrt(det)))*(exp(-0.5 *(x_u.transpose()*(inverse_co_varience_matrix*x_u))))
    normal_distribution_values.append(value)

print(normal_distribution_values)


from django.core.mail import EmailMessage
from django.shortcuts import render

from cloud.forms import ContactForm

def contacts(request):
    if request.method == "POST":
        form = ContactForm(request.POST)
        if form.is_valid():
            name = form.cleaned_data['contact_name']
            email = form.cleaned_data['contact_email']
            subject = form.cleaned_data['subject']
            content = form.cleaned_data['content']
            mail_msg = content + " <<< " + email + " >>>" + "(((" + name + ")))"
            email = EmailMessage(subject, mail_msg, email, to=["itmo.cloud@gmail.com"])
            email.send()
            msg = "Спасибо! Письмо отправлено. Ваше обращение будет рассмотрено в ближайшее время."
            return render(request, 'message.html', {'message': msg})
        else:
            msg = "Форма заполнена неправильно. Письмо не было отправлено."
            return render(request, 'message.html', {'message': msg})
    else:
        form = ContactForm()
        return render(request, 'contacts.html', {'form': form})


# Logging
import importlib
from homeassistant.components.notify import (
    ATTR_DATA,
    ATTR_TARGET,
    # PLATFORM_SCHEMA,
    BaseNotificationService,
)

import logging
_LOGGER = logging.getLogger(__name__)

# import voluptuous as vol
# import homeassistant.helpers.config_validation as cv
# PLATFORM_SCHEMA = PLATFORM_SCHEMA.extend(
#     {
#         # vol.Required(CONF_HOST): cv.string,
#         # vol.Optional(CONF_FILENAME, default=WEBOSTV_CONFIG_FILE): cv.string,
#         # vol.Optional(CONF_ICON): cv.string,
#     }
# )

def get_service(hass, config, discovery_info=None):
    """Return the notify service."""
    return ZhiPlusNotificationService(config['targets'])

class ZhiPlusNotificationService(BaseNotificationService):
    """Implement the notification service."""

    def __init__(self, targets):
        """Initialize the service."""
        self._targets = targets

    @property
    def targets(self):
        return self._targets

    async def async_send_message(self, message="", **kwargs):
        """Send a message."""
        try:
            conf = kwargs.get(ATTR_TARGET)[0]
            data = kwargs.get(ATTR_DATA)
            target = conf['target']
            mod = importlib.import_module('.' + target + 'tify', __package__)
            async_send = getattr(mod, 'async_send')
            await async_send(conf, message, data)
        except:
            import traceback
            _LOGGER.error(traceback.format_exc())


# -*- coding: utf-8 -*-
"""
Created on Fri Jan 26 10:28:05 2018

@author: Alexander
"""
#%%
"""
Задача 1
"""

def summ35(n):
    s = 0
    for i in range(n):
        if (i%3==0) or (i%5==0):
            s = s + i
    return(s)

#%%
"""
Задача 2
"""

def fibo(n):
    if n < 2:
        return n
    return fibo(n-2) + fibo(n-1)
# 173402521172797813159685037284371942044301

#%%
"""
Задача 3
"""

import pandas
name = "words-list-russian.txt"
df = (pandas.read_table(name, header = None))[0].tolist()
def anagrams(s):
    n=len(s)
    if n == 1:
        return s
    sb=[]
    for i in range(n):
        sb.append(s[i])
        rval=anagrams(s[0:i]+s[i+1:n])
        if isinstance(rval,str):
            sb[i]=sb[i]+rval
        if isinstance(rval,list):
            c=sb[i]
            sb[i]=[c + rval[x] for x in range(len(rval))]
    if(n==2):
        return sb
    else:
        c=[sb[x][h] for x in range(len(sb)) for h in range(len(sb[x]))]
        return c

#%%

"""
Задача 4
"""

#%%

"""
Задача 5
"""
name = "words-list-russian.txt"
ds = (pandas.read_table(name, header = None))[0].tolist()
import pandas
import random
n=5
#making a list contains only 5-letters words
ds5 = [i for i in ds if len(i) == 5]
#def datasort(n):
#    n = len(a[i])
#    for i in range(n):
#
def complet(letters, user):
    lst = [0]
    for correct, guess in zip(letters, user):
        if guess in letters:
            lst[0] += 1
    return tuple(lst)
words = random.choice(ds5)
letters = set(words)
playing = True
print("Хочешь развлечься,шалун?;-)")
guesses = 0
while playing:
    print(words)
    user = input("Начинай веселье!\n")
    if user == "Не хочу":
        break
    lettercount = complet(letters, user)
    guesses += 1
    print("Всего %s букв!Давай еще!" % lettercount)

    if lettercount[0] == 5:
        playing = False
        print("Красауа, отгадал с %s попыток!"
                % (guesses))


"""
Created on Aug 24, 2016

MongoDB connector for water level receiver

@author: Levan Tsinadze
"""
from __future__ import absolute_import
from __future__ import division
from __future__ import print_function

import datetime

from org.maxin.mongo.abstract_mongo_connector import CONTAINER_KEY, INERT_ERROR, INERT_OK, LEVEL_KEY, RECORD_TIME, INERT_NONEED
from org.maxin.mongo.abstract_mongo_connector import abstract_mongo_receiver

class mongo_receiver(abstract_mongo_receiver):
  """MongoDB client for water level database"""

  def __init__(self, host='localhost', port=27017):
    super(mongo_receiver, self).__init__(host, port)

  def init_collection(self):
    """Initializes water level collection
      from database
      Return:
        level_collection - water level collection
    """

    db = self.init_database()
    level_collection = db.level_collection

    return level_collection

  def create_record(self, level_info, container_id):
    """Creates water level record for database
      Args:
        level_info - water level
        container_id - identifier of water container
      Return:
        mongo_record - water level record
    """
    return {
              CONTAINER_KEY: container_id,
              LEVEL_KEY: level_info,
              RECORD_TIME: datetime.datetime.utcnow()
            }

  def init_last_record_query(self, container_id):
    """Initializes last record query
      Args:
        container_id - container identifier
      Return:
        last record query
    """
    return {'$query': {CONTAINER_KEY:container_id},
            '$orderby': {RECORD_TIME:-1}}
  # Inserts record to database
  def insert_data(self, level_info, container_id):
    """Inserts water level info
      Args:
        level_info - water level
        container_id - identifier of water container
      Return:
        level_id - assigned unique identifier of record
    """

    mongo_record = self.create_record(level_info, container_id)
    level_collection = self.init_collection()
    level_id = level_collection.insert_one(mongo_record).inserted_id
    print(level_id)

    if level_id is not None:
      result_value = INERT_OK
    else:
      result_value = INERT_ERROR

    return result_value

  def read_last_record(self, container_id):
    """Reads last record from database by container identifier
      Args:
        container_id - container identifier
      Return:
        level_record - water level info
    """

    level_collection = self.init_collection()
    lr_query = self.init_last_record_query(container_id)
    level_record = level_collection.find_one(lr_query)

    return level_record

  def validate_level(self, ext_info, level_info):
    """Validates where level info should be inserted
      Args:
        ext_info - existed level info
        level_info new level info
    """
    ext_number = float(ext_info)
    return ext_number - 1 > level_info or ext_number + 1 < level_info

  def validate_and_insert(self, level_info, container_id):
    """Validates and adds water level info to database
      Args:
        level_info - water level
        container_id - identifier of water container
      Return:
        level_id - assigned unique identifier of record
    """

    if level_info is None:
      level_number = -1
    else:
      level_number = float(level_info)
    level_record = self.read_last_record(container_id)
    if level_record is None or self.validate_level(level_record[LEVEL_KEY], level_number) :
      result_value = self.insert_data(level_number, container_id)
    else:
      result_value = INERT_NONEED

    return result_value


import numpy as np
import pandas as pd

from bokeh.plotting import figure, show
from bokeh.models import ColumnDataSource, Panel

def boxplot_tab(data_frame_nasa):
    cats = ["duringTime"]
    df = pd.DataFrame(dict(score=data_frame_nasa['duringTime'], group='duringTime'))

    # find the quartiles and IQR for each category
    groups = df.groupby('group')
    q1 = groups.quantile(q=0.25)
    q2 = groups.quantile(q=0.5)
    q3 = groups.quantile(q=0.75)
    iqr = q3 - q1
    upper = q3 + 1.5 * iqr
    lower = q1 - 1.5 * iqr

    # find the outliers for each category
    def outliers(group):
        cat = group.name
        return group[(group.score > upper.loc[cat]['score']) | (group.score < lower.loc[cat]['score'])]['score']

    out = groups.apply(outliers).dropna()

    # prepare outlier data for plotting, we need coordinates for every outlier.
    if not out.empty:
        outx = list(out.index.get_level_values(0))
        outy = list(out.values)

    p = figure(tools="", background_fill_color="#efefef", x_range=cats, toolbar_location=None)

    # if no outliers, shrink lengths of stems to be no longer than the minimums or maximums
    qmin = groups.quantile(q=0.00)
    qmax = groups.quantile(q=1.00)
    upper.score = [min([x, y]) for (x, y) in zip(list(qmax.loc[:, 'score']), upper.score)]
    lower.score = [max([x, y]) for (x, y) in zip(list(qmin.loc[:, 'score']), lower.score)]

    # stems
    p.segment(cats, upper.score, cats, q3.score, line_color="black")
    p.segment(cats, lower.score, cats, q1.score, line_color="black")

    # boxes
    p.vbar(cats, 0.7, q2.score, q3.score, fill_color="#E08E79", line_color="black")
    p.vbar(cats, 0.7, q1.score, q2.score, fill_color="#3B8686", line_color="black")

    # whiskers (almost-0 height rects simpler than segments)
    p.rect(cats, lower.score, 0.2, 0.01, line_color="black")
    p.rect(cats, upper.score, 0.2, 0.01, line_color="black")

    # outliers
    if not out.empty:
        p.circle(outx, outy, size=6, color="#F38630", fill_alpha=0.6)

    p.xgrid.grid_line_color = None
    p.ygrid.grid_line_color = "white"
    p.grid.grid_line_width = 2
    p.xaxis.major_label_text_font_size = "16px"

    tab = Panel(child=p, title='Boxplot')

    return tab


#!/usr/bin/python
'''
  Send openshift and docker versions with miq_metric tag to metric_sender

  Example:
  ./cron-send-docker-oc-versions.py -u oc_username -p oc_password
'''
# Disabling invalid-name because pylint doesn't like the naming conention we have.
# pylint: disable=invalid-name,import-error

from docker import AutoVersionClient
import subprocess
import argparse
from openshift_tools.monitoring.metric_sender import MetricSender

def parse_args():
    '''Parse the arguments for this script'''
    parser = argparse.ArgumentParser(description="Tool to send docker and openshift versions")
    parser.add_argument('-d', '--debug', default=False, action="store_true", help="debug mode")
    parser.add_argument('-v', '--verbose', default=False, action="store_true", help="Verbose?")

    args = parser.parse_args()
    return args

def main():
    '''get docker and openshift versions and send to metric sender
    '''

    args = parse_args()
    mts = MetricSender(verbose=args.verbose, debug=args.debug)

    # Get docker version
    cli = AutoVersionClient(base_url='unix://var/run/docker.sock', timeout=120)
    docker_version = cli.version()["Version"]
    mts.add_metric({"docker.version": docker_version}, key_tags={'miq_metric': 'true'})

    # Get openshift version
    try:
        return_value = subprocess.check_output("oc version", stderr=subprocess.STDOUT, shell=True)
        oc_version = return_value.split('\n')[0].split(' ')[1]
        mts.add_metric({"oc.version": oc_version}, key_tags={'miq_metric': 'true'})

    except subprocess.CalledProcessError as error:
        print ("Failed to get openshift version: ", error.output)

if __name__ == '__main__':
    main()


"""
思路：先根据左端点排序，然后遍历合并排序nlogn，遍历n，故为O(nlogn)
"""
# Definition for an interval.
# class Interval:
#     def __init__(self, s=0, e=0):
#         self.start = s
#         self.end = e

class Solution:
    def merge(self, intervals):
        """
        :type intervals: List[Interval]
        :rtype: List[Interval]
        """
        if len(intervals) == 0 or len(intervals) == 1:
            return intervals
        self.quickSort(intervals, 0, len(intervals)-1)
        result = [intervals[0]]
        for i in range(1, len(intervals)):
            if intervals[i].start <= result[-1].end:
                if intervals[i].end > result[-1].end:
                    result[-1].end = intervals[i].end
            else:
                result.append(intervals[i])
        return result

    def quickSort(self, intervals, left, right):
        if left >= right:
            return
        i = left
        j = right
        pivot = intervals[left]
        while i < j:
            while i < j and intervals[j].start >= pivot.start:
                j -= 1
            if i < j:
                intervals[i] = intervals[j]
            while i < j and intervals[i].start <= pivot.start:
                i += 1
            if i < j:
                intervals[j] = intervals[i]
        intervals[i] = pivot
        self.quickSort(intervals, left, i-1)
        self.quickSort(intervals, i+1, right)


"""
Has list of words
picks a random word
determines if the guess from the jumper is in the word
either cuts his parachute or displays the letter of the word
"""
import random

class Cutter:

    def __init__(self):

        self.guessed_letters = ['', '']
        self.blanks = []
        self.letters = []
        self.word_to_guess = ''
        self.parachute_index = 0
        self.clean_list = ''

        self.words = ['ribbon', 'peak', 'hardware', 'card', 'chain', 'adult', 'restaurant', 'failure',\
            'cheese', 'tape', 'celebration', 'memorial', 'victory', 'coding', 'water', 'chicken', 'portrait',\
            'accept', 'aluminium', 'choke', 'write', 'explosion', 'relate', 'discount', 'integrity', \
            'instrument', 'delicate', 'golf', 'computer', 'answer', 'potential', 'earthquake', 'education']

        self.parachute = ['''
             ___
            /___\
            \   /
             \ /
              0
             /|\
             / \ ''',
             '''
            /___\
            \   /
             \ /
              0
             /|\
             / \ ''',
             '''
            \   /
             \ /
              0
             /|\
             / \ ''',
             '''
             \ /
              0
             /|\
             / \ ''',
             '''
              X
             /|\
             / \ '''
             ]

    def pick_random_word(self):
        print(self.parachute[self.parachute_index])

        #gets a random number and uses that to find a random index of the list of words
        num_words = len(self.words) - 1
        num = random.randint(0, num_words)
        word = self.words[num]

        self.word_to_guess = word
        self.letters = list(word)

    def para_print(self):
        print(self.parachute[self.parachute_index])

    def blank_spaces(self):
        #determines amount of blanks to create
        num_blanks = len(self.word_to_guess)
        blanks = '_' * num_blanks

        self.blanks = list(blanks)
        self.clean_list = ' '.join(self.blanks)

        return (' '.join(self.blanks))

    def word_check(self, letter_guess):
        #check to see if the guessed letter is in the word

        if letter_guess in self.letters and letter_guess not in self.guessed_letters:
            self.guessed_letters.append(letter_guess)
            self.change_blanks()
            return ('Nice Job!')
        elif letter_guess in self.guessed_letters:
            return ('You already Guessed that letter')
        else:
            self.guessed_letters.append(letter_guess)
            self.parachute_index = self.parachute_index + 1
            if self.parachute_index == 4:
                return 'Game Over'
            else:
                return('Try again')

    def change_blanks(self):
        self.guess = self.guessed_letters[-1]
        length = len(self.blanks)

        for index in range(length):
            if self.guess == self.letters[index]:
                self.blanks[index] = self.guess
        self.clean_list =(' '.join(self.blanks))

    def win_check(self):
        if '_' not in self.blanks:
            return True
        else:
            return False


import cherrypy
from splunk.appserver.mrsparkle.controllers import BaseController
from splunk.appserver.mrsparkle.lib.decorators import expose_page

import formencode
from formencode import validators
import logging

logger = logging.getLogger('splunk.appserver.controllers.prototype')

class YearBornValidator(validators.FancyValidator):
    """
    An example of a custom form validator
    you can use this as
    userage = YearBornValidator()
    or
    yearborn = YearBornValidator(min_age=21, max_age=110)
    """
    min_age = 12
    max_age = 100
    messages = {
        'invalid': 'Please enter a valid year between %(minYear)i and %(maxYear)i',
    }
    def _to_python(self, value, state):
        import time
        thisyear = time.localtime()[0]
        minyear = thisyear - self.max_age
        maxyear = thisyear - self.min_age
        try:
            year = int(value)
        except (ValueError, TypeError):
            raise formencode.api.Invalid(self.message('invalid', state, minYear=minyear, maxYear=maxyear), value, state)
        if year < minyear or year > maxyear:
            raise formencode.api.Invalid(self.message('invalid', state, minYear=minyear, maxYear=maxyear), value, state)
        return year

    _from_python = _to_python

class TestForm(formencode.Schema):
    """
    Example form used with PrototypeController.form1
    Have a look at validators.py to see all the other available validators
    """
    allow_extra_fields = False
    email = validators.Email() # match an email address, could also add resolve_domain=True for additional checks
    name = formencode.All( # require all enclosed validators to pass, could also use formencode.Any
        validators.String(not_empty=True, min=2, max=50),
        validators.PlainText()
        )
    yearborn = YearBornValidator()

class PrototypeController(BaseController):
    """
    Handle experimental ideas and code
    """

    @expose_page(False, methods=['GET', 'POST'])
    def form1(self, **kw):
        """A simple example of using form validation"""
        form = TestForm()
        form_errors = {}
        form_defaults = {}
        error = None
        if cherrypy.request.method == 'POST':
            try:
                form_data = form.to_python(kw)
                return """Form Parsed OK"""
            except formencode.api.Invalid as e:
                form_defaults = kw
                if e.error_dict:
                    form_errors = e.error_dict
                else:
                    error = e.msg

        return self.render_template('prototype/form1.html', {
                'error' : error,
                'form_defaults' : form_defaults,
                'form_errors' : form_errors
        })

    @expose_page(False)
    def sparklines(self):
        """Example jquery.sparkline.js usage"""
        return self.render_template('prototype/sparklines.html')

    @expose_page(False)
    def scroll_performance(self):
        """Test page for scroll bar performance testing"""
        return self.render_template('prototype/scroll_performance.html')

    @expose_page(False)
    def new_layout(self):
        return self.render_template('prototype/new_layout.html')


import pandas as pd
import numpy as np
import math
from operator import itemgetter
from collections import defaultdict,deque,namedtuple

Customer = pd.read_excel (r'C:\Users\ASUS\Downloads\Dataaa.xlsx' , sheet_name='Customer')
Hub = pd.read_excel (r'C:\Users\ASUS\Downloads\Dataaa.xlsx' , sheet_name='Hubs')
Warehouse = pd.read_excel (r'C:\Users\ASUS\Downloads\Dataaa.xlsx' , sheet_name='Warehouse')

customerID = np.array(Customer.id.values)
customerLatitude = np.array(Customer.Latitude.values)
customerLongitude = np.array(Customer.Longitude.values)
hubID = np.array(Hub.Hub.values)
hubLatitude = np.array(Hub.Latitude.values)
hubLongitude = np.array(Hub.Longitude.values)
warehouseID = np.array(Warehouse.Warehouse.values)
warehouseLatitude = np.array(Warehouse.Latitude.values)
warehouseLongitude = np.array(Warehouse.Longitude.values)

def computeDist(x1,y1,x2,y2):
    return math.sqrt( ((float(x2)-float(x1))**2)+((float(y2)-float(y1))**2) )

inf = float('inf')
Edge = namedtuple('Edge', 'start, end, cost')

def make_edge(start, end, cost=1):
  return Edge(start, end, cost)

class Graph:
    def __init__(self, edges):
        wrong_edges = [i for i in edges if len(i) not in [2, 3]]
        if wrong_edges:
            raise ValueError('Wrong edges data: {}'.format(wrong_edges))

        self.edges = [make_edge(*edge) for edge in edges]

    @property
    def vertices(self):
        return set(
            sum(
                ([edge.start, edge.end] for edge in self.edges), []
            )
        )

    def get_node_pairs(self, n1, n2, both_ends=True):
        if both_ends:
            node_pairs = [[n1, n2], [n2, n1]]
        else:
            node_pairs = [[n1, n2]]
        return node_pairs

    def remove_edge(self, n1, n2, both_ends=True):
        node_pairs = self.get_node_pairs(n1, n2, both_ends)
        edges = self.edges[:]
        for edge in edges:
            if [edge.start, edge.end] in node_pairs:
                self.edges.remove(edge)

    def add_edge(self, n1, n2, cost=1, both_ends=True):
        node_pairs = self.get_node_pairs(n1, n2, both_ends)
        for edge in self.edges:
            if [edge.start, edge.end] in node_pairs:
                return ValueError('Edge {} {} already exists'.format(n1, n2))

        self.edges.append(Edge(start=n1, end=n2, cost=cost))
        if both_ends:
            self.edges.append(Edge(start=n2, end=n1, cost=cost))

    @property
    def neighbours(self):
        neighbours = {vertex: set() for vertex in self.vertices}
        for edge in self.edges:
            neighbours[edge.start].add((edge.end, edge.cost))

        return neighbours

    def dijkstra(self, source, dest):
        assert source in self.vertices, 'Such source node doesn\'t exist'
        distances = {vertex: inf for vertex in self.vertices}
        previous_vertices = {
            vertex: None for vertex in self.vertices
        }
        distances[source] = 0
        vertices = self.vertices.copy()

        while vertices:
            current_vertex = min(
                vertices, key=lambda vertex: distances[vertex])
            vertices.remove(current_vertex)
            if distances[current_vertex] == inf:
                break
            for neighbour, cost in self.neighbours[current_vertex]:
                alternative_route = distances[current_vertex] + cost
                if alternative_route < distances[neighbour]:
                    distances[neighbour] = alternative_route
                    previous_vertices[neighbour] = current_vertex

        path, current_vertex = deque(), dest
        while previous_vertices[current_vertex] is not None:
            path.appendleft(current_vertex)
            current_vertex = previous_vertices[current_vertex]
        if path:
            path.appendleft(current_vertex)

        distance_between_nodes = 0
        for index in range(1, len(path)):
            for thing in self.edges:
                if thing.start == path[index - 1] and thing.end == path[index]:
                    distance_between_nodes += thing.cost
        path2 = list(path)
        return path2, distance_between_nodes

class customer:
    def __init__(self, id, custLong, custLat, number):
        self.id = id
        self.custLong = custLong
        self.custLat = custLat
        self.nearestHub = self.nearestHub
        self.number = number
    def nearestHub(self):
        self.custToHub = list([computeDist(self.custLong, self.custLat, hubLongitude[i], hubLatitude[i]), hubID[i]] for i in range(0,len(hubID)))
        self.cTHSorted = sorted(self.custToHub, key = itemgetter(0))
        return self.cTHSorted[0]

customersList = [customer(customerID[i], customerLongitude[i], customerLatitude[i], i) for i in range(0,len(customerID))]

class hub:
    def __init__(self, id, hubLong, hubLat, number):
        self.id = id
        self.hubLong = hubLong
        self.hubLat = hubLat
        self.nearestHub = self.nearestHub
        self.nearestWarehouse = self.nearestWarehouse
        self.number = number
    def nearestHub(self):
        self.hubToHub = list([computeDist(self.hubLong, self.hubLat, hubLongitude[i], hubLatitude[i]), hubID[i]] for i in range(0,len(hubID)))
        self.hTHSorted = sorted(self.hubToHub, key = itemgetter(0))
        return self.hTHSorted[1]
    def nearestWarehouse(self):
        self.hubToWarehouse = list([computeDist(self.hubLong, self.hubLat, warehouseLongitude[i], warehouseLatitude[i]), warehouseID[i]] for i in range(0,len(warehouseID)))
        self.hTWSorted = sorted(self.hubToWarehouse, key = itemgetter(0))
        return self.hTWSorted[0]
hubsList = [hub(hubID[i], hubLongitude[i], hubLatitude[i], (i+len(customerID))) for i in range(0, len(hubID))]

class warehouse:
    def __init__(self, id, wareLong, wareLat,number):
        self.id = id
        self.wareLong = wareLong
        self.wareLat = wareLat
        self.number = number
warehouseList = [warehouse(warehouseID[i], warehouseLongitude[i], warehouseLatitude[i], (i+len(customerID) +len(hubID))) for i in range(0, len(warehouseID))]

grapharray = []

for i in range(0,len(hubID)):
    for j in range(0,len(hubID)):
        if(hubsList[i].id != hubsList[j].id):
            grapharray.append((hubsList[i].id, hubsList[j].id, computeDist(hubsList[i].hubLong,hubsList[i].hubLat,hubsList[j].hubLong,hubsList[j].hubLat)))
        else:
            pass

for j in range(0,len(hubID)):
    for k in range(0,len(warehouseID)):
        grapharray.append((hubsList[j].id, warehouseList[k].id, computeDist(hubsList[j].hubLong,hubsList[j].hubLat,warehouseList[k].wareLong,warehouseList[k].wareLat)))

graph = Graph(grapharray)
grapharr = []
for i in range(0,len(hubID)):
    for j in range(0,len(warehouseID)):
        defGraph = graph.dijkstra(hubsList[i].id,warehouseList[j].id)
        grapharr.append(defGraph)

graphArrSorted = sorted(grapharr, key = itemgetter(1))
dist = []
thisprint = ()
totDist = 0
#print(graphArrSorted)
for i in range (0, len(customerID)):
    print(customersList[i].id, " -> ", customersList[i].nearestHub()[1], " -> ", end = ' ')
    dist.append(customersList[i].nearestHub()[0])
    totDist += customersList[i].nearestHub()[0]
    for j in range (0, len(graphArrSorted)):
        if(customersList[i].nearestHub()[1].lower == graphArrSorted[j][0][0].lower):
            dist[i] += graphArrSorted[j][1]
            totDist += graphArrSorted[j][1]
            print(graphArrSorted[j][0][1], " with distance ", dist[i])
            break
        else:
            pass

print (totDist, " or " , totDist*111.699, " km.")

    # for j in range (0,len(hubID)):
    #     kappa = False
    #     if(str.strip(customersList[i].nearestHub()[1]) == str.strip(hubsList[j].nearestWarehouse()[1])):
    #         dist[i] += hubsList[j].nearestWarehouse()[0]
    #         kappa = True
    #         thisprint1 = (hubsList[j].nearestWarehouse()[1], " with distance = ", dist[i])
    #     elif(customersList[i].nearestHub != hubsList[j].nearestWarehouse()[1]):
    #         for k in range(1, len(warehouseID)):
    #             if(hubsList[j].nearestHub()[1][0] < hubsList[j].nearestWarehouse()[0]):
    #                 if(hubsList[j].nearestHub()[k][1] == hubsList[j].nearestWarehouse()[1]):
    #                     thisprint = hubsList[j].nearestHub()[k][1]
    #             elif(hubsList[j].nearestHub()[1][0] >= hubsList[j].nearestWarehouse()[0]):
    #                 thisprint = hubsList[k].nearestWarehouse()[1]
    # if(kappa):
    #     print(thisprint1)
    # elif(kappa == False):
    #     print(thisprint)

Team 5 - Andreas Kevin Ghinaya Zahra/Final Project Science Management.py


import requests, re, zipfile, shutil, os

server_dir = './journey\'s-end'

# Get current version from file.
current_version = int(open('./bin/current_version.txt', 'r').read())

# Download wiki page that contains the downloads, then use regex to get all download links for the server files.
open('./bin/html_page','wb').write(requests.get("https://terraria.gamepedia.com/Server", allow_redirects=True).content)
terraria_links = re.findall('https:\/\/www.terraria.org\/system\/dedicated_servers.+.zip\?\d+', open('./bin/html_page','r').read())

#print(terraria_links)

# Get available versions from list of links gathered above
available_versions = []
for link in terraria_links:
    available_versions.append(int(re.search('-\d+', link).group(0).strip('-')))

# Determine if server is out of date by comparing the version number of the file link to the current version
# stored in the 'current_version.txt' file.
if max(available_versions) <= current_version : print("Server is up to date.")
else :
    print("Updating server to Terraria "+str(max(available_versions))+'.\nDownloading server files from '+terraria_links[len(terraria_links)-1]+'...')
    open('./bin/terraria-server-'+str(max(available_versions))+'.zip', 'wb').write(requests.get(terraria_links[len(terraria_links)-1]).content)

    # Remove old server files.
    print('Removing old server files from '+server_dir+'...')
    folder = './journey\'s-end'
    for filename in os.listdir(folder):
        file_path = os.path.join(folder, filename)
        try:
            if os.path.isfile(file_path) or os.path.islink(file_path):
                os.unlink(file_path)
            elif os.path.isdir(file_path):
                shutil.rmtree(file_path)
        except Exception as e:
            print('Failed to delete %s. Reason: %s' % (file_path, e))

    # Unzip file for copying.
    print('Unziping server files...')
    with zipfile.ZipFile('./bin/terraria-server-'+str(max(available_versions))+'.zip','r') as zip_ref:
        zip_ref.extractall('./bin')

    # Copy files into server dir.
    print('Copying Linux server files to '+server_dir+'...')
    files = os.listdir('./bin/1404/Linux')
    for file in files :
        name = os.path.join('./bin/1404/Linux', file)
        if os.path.isfile(name) :
            print('\tcopying '+name)
            shutil.copy(name, './journey\'s-end')
        elif os.path.isdir(name) :
            print('\tcopying '+name+'/*')
            shutil.copytree(name, './journey\'s-end/'+name.split('/')[len(name.split('/'))-1])

    print('Cleaning up:')
    print('\tremoving ./bin/'+str(max(available_versions)))
    shutil.rmtree('./bin/'+str(max(available_versions)))
    print('\tremoving ./bin/terraria-server-'+str(max(available_versions)))
    os.unlink('./bin/terraria-server-'+str(max(available_versions))+'.zip')
    print('\tremoving ./bin/html_page')
    os.unlink('./bin/html_page')

    # Update the 'current_version.txt' listed version to the newly installed version.
    open('current_version.txt', 'w').write(str(max(available_versions)))

    print('Update Completed. Please remember to update the server file permissions.')


from tkinter import filedialog
import datetime
import pandas
import numpy
import os

def getAllPuntsAndFGs():
	#pfrPage = 'C:/Users/Josh/Documents/Python/nfl/ravens/games/'
	pfrPage = 'C:/Users/Josh/Documents/python/nfl/ravens/games/need YAC/'
	punts = pandas.DataFrame()
	fgs = pandas.DataFrame()
	for contents in (os.scandir(pfrPage)):
		if contents.is_dir() and contents.name != 'need timing adjustment' and contents.name != 'need YAC':
			for file in (os.scandir(pfrPage+contents.name)):
				if file.name == 'fg.csv':
					fileName = (pfrPage+contents.name+'/'+file.name)
					fg = pandas.read_csv(fileName, index_col='Unnamed: 0')
					fgs = fgs.append(fg)
				elif file.name == 'punts.csv':
					fileName = (pfrPage+contents.name+'/'+file.name)
					punt = pandas.read_csv(fileName, index_col='Unnamed: 0')
					punts = punts.append(punt)
	fgs[['Date', 'Quarter', 'Time', 'Detail', 'Kicker', 'Distance', 'Good', 'Blocked']].to_csv(pfrPage+'allFGs.csv')
	punts[['Date', 'Quarter', 'Time', 'Detail', 'Punter', 'Blocked', 'Distance', 'TB', 'FC', 'OOB']].to_csv(pfrPage+'allpunts.csv')

getAllPuntsAndFGs()


import cv2
import numpy as np
import os

def resize_padding_oneline(image):
    h, w, _ = image.shape
    ratio = 64.0/h
    new_w = int(w*ratio)

    if new_w < 256:
        image = cv2.resize(image, (new_w, 64), interpolation=cv2.INTER_CUBIC)
        pad_img = np.ones((64, 256-new_w, 3), dtype=np.uint8)*127
        image = np.concatenate((image, pad_img), axis=1)
    else:
        image = cv2.resize(image, (256, 64), interpolation=cv2.INTER_CUBIC)
    return image

def resize_padding_twoline(image):
    h, w, _ = image.shape
    ratio = 128.0/h
    new_w = int(w*ratio)

    if new_w < 256:
        image = cv2.resize(image, (new_w, 128), interpolation=cv2.INTER_CUBIC)
    else:
        image = cv2.resize(image, (256, 128), interpolation=cv2.INTER_CUBIC)
    return image

def preprocess(img, plate_shape):
    if plate_shape == 1:
        img = resize_padding_oneline(img)
        pad_img = np.ones((64, 256, 3), dtype=np.uint8)*127
        img = np.concatenate((img, pad_img), axis=0)
        # pad = (128-64)//2
        # img = np.pad(img, [(pad,), (0,)], mode='constant', constant_values=127)
    else:
        img = resize_padding_twoline(img)
        h, w, _ = img.shape
        pad = (256-w)//2
        img = np.pad(img, [(0,), (pad,), (0,)], mode='constant', constant_values=127)
        if (256 - w) % 2 == 1:
            pad_img = np.ones((h, 1, 3), dtype=np.uint8)*127
            img = np.concatenate((img, pad_img), axis=1)
    #img = cv2.cvtColor(img, cv2.COLOR_GRAY2BGR)
    return img


import numpy as np
import time

def decision_step(Rover):

    # Vision data check
    if Rover.nav_angles is not None:
        # Check for Rover.mode status
        if Rover.mode == 'forward':
            # Check navigable terrain
            if Rover.vel < 0.2 and Rover.throttle != 0:
                # If velocity is still 0 with throttle rover is stuck
                if time.time() - Rover.stuck_time > Rover.max_stuck:
                    # Set stuck mode
                    Rover.mode = 'stuck'
                    return Rover
            else:
                # Reset stuck timer
                Rover.stuck_time = time.time()
            if Rover.sample_seen:
                if Rover.picking_up != 0:
                    print('Sample picked up')
                    Rover.sample_seen = False
                    Rover.sample_timer = time.time()
                    return Rover
                if time.time() - Rover.sample_timer > Rover.sample_max_search:
                    print('Cannot find sample')
                    Rover.sample_seen = False
                    Rover.sample_timer = time.time()
                    return Rover
                avg_rock_angle = np.mean(Rover.rock_angle * 180/np.pi)
                if -15 < avg_rock_angle < 15:
                    if max(Rover.rock_dist) < 20:
                        Rover.throttle = 0
                        Rover.brake = Rover.brake_set
                        Rover.steer = avg_rock_angle
                    else:
                        Rover.throttle = Rover.throttle_set
                        Rover.steer = avg_rock_angle
                elif -50 < avg_rock_angle < 50:
                    print('Turning toward sample')
                    if Rover.vel > 0 and max(Rover.rock_dist) < 50:
                        Rover.throttle = 0
                        Rover.brake = Rover.brake_set
                        Rover.steer = 0
                    else:
                        Rover.throttle = 0
                        Rover.brake = 0
                        Rover.steer = avg_rock_angle/6
                else:
                    print('Lost sample on camera')
                    Rover.sample_seen = False
            elif len(Rover.nav_angles) > 50:
                if Rover.vel < Rover.max_vel:
                    Rover.throttle = Rover.throttle_set
                else:
                    Rover.throttle = 0
                Rover.brake = 0
                Rover.steer = np.clip(np.mean(Rover.nav_angles * 180/np.pi),
                                              -15, 15)
            else:
                Rover.throttle = 0
                Rover.brake = Rover.brake_set
                Rover.steer = 0
                Rover.mode = 'stop'

        elif Rover.mode == 'stop':
            if Rover.vel > 0.2:
                Rover.throttle = 0
                Rover.brake = Rover.brake_set
                Rover.steer = 0
            elif Rover.vel <= 0.2:
                if len(Rover.nav_angles) < 100:
                    Rover.throttle = 0
                    Rover.brake = 0
                    Rover.steer = -15
                else:
                    Rover.throttle = Rover.throttle_set
                    Rover.brake = 0
                    Rover.steer = np.clip(np.mean(Rover.nav_angles * 180/np.pi),
                                          -15, 15)
                    Rover.mode = 'forward'
    else:
        Rover.throttle = Rover.throttle_set
        Rover.steer = 0
        Rover.brake = 0

    # Rover is stuck
    if Rover.mode == 'stuck':
        print('Stuck')
        if time.time() - Rover.stuck_time > (Rover.max_stuck + 1):
            Rover.mode = 'forward'
            Rover.stuck_time = time.time()
        else:
            # Turn to get unstuck
            Rover.throttle = 0
            Rover.brake = 0
            Rover.steer = -15
        return Rover

    # Send pickup command
    if Rover.near_sample and Rover.vel == 0 and not Rover.picking_up:
        Rover.send_pickup = True
        Rover.sample_seen = False
    return Rover


from PyQt5.QtWidgets import QLabel, QPushButton
from PyQt5.QtWidgets import QGridLayout
from PyQt5.QtGui import QPixmap, QPalette, QColor, QFont
from PyQt5.QtWidgets import QWidget

class HowToPlay(QWidget):

    def __init__(self):
        super().__init__()

        pal = QPalette()
        pal.setColor(QPalette.Background, QColor(0, 0, 0))
        self.setPalette(pal)

        self.initUI()

    def initUI(self):
        self.grid = QGridLayout()

        self.playLabel = QLabel()
        self.setMinimumHeight(404)
        self.setMinimumWidth(650)
        pixmap = QPixmap('gamerule.png')
        pixmap = pixmap.scaledToHeight(404)
        self.playLabel.setPixmap(pixmap)

        self.close_Btn = QPushButton("CLOSE")

        self.close_Btn.clicked.connect(self.end_window)

        self.grid.addWidget(self.playLabel, 0, 0, 8, 2)
        self.grid.addWidget(self.close_Btn, 8, 0, 1, 2)

        self.setLayout(self.grid)
        self.setWindowTitle('how To play Game?')
        self.setGeometry(620, 170, 680, 650)
        self.show()

    def end_window(self):
        self.deleteLater()


from apps.roles.models import Rol
from django.contrib.auth.models import User, Permission
from django.contrib.auth.forms import UserCreationForm
from django import forms
class Registrorol(forms.ModelForm):
    class Meta:
        model= Rol
        fields = [
            'Nombre',
            'privilegios',

        ]
        widgets = {
            'Nombre': forms.TextInput(attrs={'class': 'form-control', 'required':'true'}),
            'privilegios': forms.CheckboxSelectMultiple(),

        }