# ACT 2-6

# from http://finance.yahoo.com/news/25-worst-passwords-2011-revealed-202955980.html
passwordDictionary = {'Alice':'password',
                      'Bob': '123456',
                      'Carol':'12345678',
                      'Deb':'qwerty',
                      'Emma':'abc123',
                      'Florence':'letmein',
                      'Gary':'trustno1',
                      'Hillary':'dragon',
                      'Ingrid':'baseball',
                      'Jeremy':'111111',
                      'Kyle':'iloveyou',
                      'Lou':'master',
                      'Mary':'sunshine',
                      'Ned':'ashley',
                      'Owen':'bailey',
                      'Pat':'passw0rd',
                      'Quintin':'shadow',
                      'Ryan':'123123',
                      'Sandra':'654321',
                      'Trevor':'superman',
                      'Uma':'qazwsx',
                      'Valerie':'michael',
                      'Wilbur':'football'}

# Task 1
def printDictionary(dictionary):
    '''Prints the dictionary key-value pairs from a dictionary.'''
    keyList = dictionary.keys()
    for key in keyList:
        print(key,' -> ',dictionary[key])

# Task 2
def echo():
    myInput = input('write something and hit Enter: ')
    print('You wrote:',myInput)

# Interaction is useful. You can run the same function
# several times and the user can test out different inputs.
def addOne():
    myInput = input('Give me a number and hit Enter: ')
    print('Your number plus one:', float(myInput)+1)

def addPassword(dictionary,key,value):
    '''Adds the (key,value) pair to the dictionary and returns the new dictionary'''
    if key in dictionary:
        myInput = input('Do you really want to overwrite?!:')
        if myInput == 'yes' or myInput == 'y':
            print('OK, changing your password now.')
            dictionary[key] = value
        else:
            print('OK, I won\'t change your password')
    else:
        print('Adding password for new user ', key)
        dictionary[key] = value

    return dictionary

def addPasswordSecure(dictionary,key,value):
    '''Adds the (key,value) pair to the dictionary and returns the new dictionary'''
    if key in dictionary:
        myInput = input('Type in the original password in order to make a new one:')
        if myInput == dictionary[key]:
            print('Your wish is my command. Updating the password.')
            dictionary[key] = value
        else:
            print('You entered the wrong password. I refuse to update the dictionary.')
    else:
        print('Adding password for new user ', key)
        dictionary[key] = value

    return dictionary

# Task 3
mobyString = '''Call me Ishmael.  Some years ago--never mind how long
precisely--having little or no money in my purse, and nothing particular
to interest me on shore, I thought I would sail about a little
and see the watery part of the world.  It is a way I have
of driving off the spleen and regulating the circulation.
Whenever I find myself growing grim about the mouth;
whenever it is a damp, drizzly November in my soul; whenever I
find myself involuntarily pausing before coffin warehouses,
and bringing up the rear of every funeral I meet;
and especially whenever my hypos get such an upper hand of me,
that it requires a strong moral principle to prevent me from
deliberately stepping into the street, and methodically knocking
people's hats off--then, I account it high time to get to sea
as soon as I can.  This is my substitute for pistol and ball.
With a philosophical flourish Cato throws himself upon his sword;
I quietly take to the ship.  There is nothing surprising in this.
If they but knew it, almost all men in their degree, some time
or other, cherish very nearly the same feelings towards
the ocean with me.
'''

spacey = '  fooBAR\n\n\n\n'

print(mobyString.find('November')) # lives at position 390
print(mobyString.find('October')) # should equal -1
print(mobyString.find('November', 391, len(mobyString))) # should equal -1

octMoby = mobyString.replace('November', 'October')
iMoby = mobyString.replace('I', 'Steve', 6) # Replace 6 instances of "I"

# Uncomment below to print these modified paragraphs,
# or just evaluate these variables in the interpreter
#print octMoby

print(iMoby[:20]) # just print the first 20 chars

print(spacey.strip())

# These ones trim whitespace on either side
#print spacey.lstrip()
#print spacey.rstrip()

# How about we take the output of lstrip('  foo'),
# which is the string 'BAR\n\n\n\n' and then rstrip() that output
# string to remove the '\n\n\n\n'. We can do this in one line if
# we don't want to use variables for the partial results.
print(spacey.lstrip('  foo').rstrip())

mobyWords = mobyString.split()
delim = ':' # any string you want to use to glue the words together
delim = ' ' # a basic choice...
delim = ',' # if we want to make a csv...
delim = '\t' # or tab-separated values (tsv)...
delim = ' <3 ' # more exciting
delim = '...uuhhhh...' # less articulate

print(delim.join(mobyWords)[:100]) # just print the first 100 chars


##########################################

# Now I'll quickly show an example of grabbing data from the web
# and using it in a Python program.

# First, import the module that lets us read from a URL
import urllib.request

# Let's look at Google Movies, which loads a listing of movie
# times near my location. Google knows your location based on the
# address from which you are connected to the internet. You are
# probably on a computer network at or near Brown University,
# in Providence, RI, USA.
myURL = 'http://google.com/movies'

# We can connect to the URL (similar to opening a file)
# by calling a function that is defined in the module urllib.
# When you use your own functions, you don't need the module-period
# notation, because you are calling them from within the same
# file. If you wanted to call your functions from a different
# Python file, it might look like this.
print('Opening connection to: ', myURL)
loaded = urllib.request.urlopen(myURL)

print('Reading movie data')
stringFromURL = loaded.read().decode('utf-8')

# We must close the connection after grabbing the string,
# just like with a file
loaded.close()
print('Closed connection to: ', myURL)

# Now let's do something with the movie data.
# Let's see if somewhere in the string, which is the HTML encoding
# of the webpage, is a mention of "The Imitation Game". I am assuming
# that if "The Imitation Game" is listed on the page, then that string
# will be a substring of the whole HTML string. So, if we find the
# the title "The Imitation Game" at some position in stringFromURL, the
# movie is probably listed on the page, and probably playing near us.

# At the time of writing this (February 28, 2014), this film IS playing
# at a theater in downtown Providence.

movieTitle = 'The Imitation Game'
movieNamePosition = stringFromURL.find(movieTitle)

# If find() turns up nothing, it returns -1
if movieNamePosition == -1:
    print(movieTitle, 'is *NOT* playing now in nearby theaters :(')
else:
    print(movieTitle, '*IS* playing now in nearby theaters. Let\'s go see it!')

# Try to modify the above code to ask the user for a specific movie,
# instead of "hard coding" in 'The Imitation Game'. You can use the
# raw_input() function from class, which will return a string version
# of whatever the user inputs.

# Remember NOT to print all of stringFromURL, which is probably a
# very long string (> 10000 chars). That will crash IDLE.
# You can process the whole string; just don't print/evaluate it in
# the shell. If you want to print, try only a substring, like:
# stringFromURL[:5000]

