def __init__(self):
        ##analyze frequencies
        piglatinObject = Piglatin.PigLatinTranslate()
        #print(__name__)
        if __name__ == "__main__":
            #print("from commandline")
            piglatinObject.piglatinTranslate(_("hello"))
            print(_("testing with hello == "), piglatintext)

            print(_("sentence translation"))
            piglatinObject.piglatinTranslateSentence(_("i am gowri and you are you"))

            print(_("frequency analysis"))
            print("%s" %(piglatinObject.frquencyAnalysis()))
        elif __name__ == "Piglatin_UI":
            #print("from module - testingPiglatin_commandline being the name of the module in this case")

            #Internationalization
            t = gettext.translation('English', '/locale')
            _ = t.ugettext
            
            texttotranslate = input(_("Enter text - a word: "))
            print("translated = ", piglatinObject.piglatinTranslate(texttotranslate))
            
            sentencetotranslate = input(_("Enter text - a sentence: "))
            print(_("translated text = "), piglatinObject.piglatinTranslateSentence(sentencetotranslate))

            print(_("frequency analysis"))
            print(piglatinObject.frquencyAnalysis())
Example #2
0
def add_entry():
    """Adds an entry to the diary"""
    title_string = "Title (press %s when finished)" % finish_key
    # print(title_string)
    puts(colored.yellow(title_string))
    puts(colored.green("="*len(title_string)))
    title = sys.stdin.read().strip()
    if title:
        entry_string = "\nEnter your entry: (press %s when finished)" % finish_key
        puts(colored.yellow(entry_string))
        puts(colored.green("="*len(entry_string)))
        # reads all the data entered from the user
        data = sys.stdin.read().strip()
        if data:    # if something was actually entered
            puts(colored.yellow(
                "\nEnter comma separated tags(if any!): (press %s when finished) : " % finish_key))
            puts(colored.green("="*(len(title_string)+33)))
            tags = sys.stdin.read().strip()
            tags = processTags(tags)
            puts(colored.green("\n"+"="*len(entry_string)))
            # anything other than 'n'
            if input("\nSave entry (y/n) : ").lower() != 'n':
                DiaryEntry.create(content=data, tags=tags, title=title)
                puts(colored.green("Saved successfully"))
    else:
        puts(
            colored.red("No title entered! Press Enter to return to main menu"))
        input()
        clear()
        return
Example #3
0
def testcalculator():
#Simple test average calculator that you can exit by not inputting a number or by typing 0.
    total = 0
    count = 0
    average = 0
    data = 1


    while data != 0:
        try:
            data = int(input("Enter a number or press 0 to quit: "))
            if data == 0:
                break
            else:

                try:
                
                    count += 1
                    number = data
                    total += int(number)
                    average = total / count
                    data = int(input("Enter a number or press 0 to quit: "))
                
                except ValueError:
                    break
        except ValueError:
            break

    print("The sum is {0}. The average is {1}.".format(total, average))
Example #4
0
def escribir():
    print("Has elegido añadir un registro a la agenda")
    nombre = input("Introduce el nombre de contacto: ")
    telefono = input("Introduce su teléfono: ")

    agenda = open("agendatelefonica.csv")
    for n in range(1,40):
        linea = agenda.readline()
        lineapartida = linea.split(",")
##        print(lineapartida[0])
        if lineapartida[0] != "":
            memoria = lineapartida[0]
##    print("El numero máximo es",memoria)
    agenda.close()
    memonum = int(memoria)
    posicion = 0
    posicion = memonum + 1
    postr = str(posicion)
    print("Se ha guardado en la agenda el contacto: ",nombre,"con el número de teléfono",telefono)
    agenda = open("agendatelefonica.csv",'a')
    agenda.write(postr)
    agenda.write(",")
    agenda.write(nombre)
    agenda.write(",")
    agenda.write(telefono)
    agenda.write(",")
    agenda.write("\n")
    agenda.close()
Example #5
0
def write_func():            ###Get input from user and append to table file
    
    dbase = []

    dealer = raw_input("Dealer:  ")
    hirer = raw_input("Hirer's Name:  ")
    ###     acNum to test for duplicate number
    acNum = raw_input("Loan Number:   ")
    with open('/Users/Michael/Documents/GitHub/Int-Projection/projection.csv', 'r') as compare:
        reader = csv.reader(compare)
        for row in reader:
            if str(row) == str(acNum):
                acNum = raw_input("Duplicate Loan No! Recheck and try again!")
                    
    details = raw_input("Loan Details:  ")
    agg_date = str(raw_input("Agreement Date (yyyymmdd):"))
    ###     While loop to ensure correct date format for ease of processing
    while len(agg_date) != 8:
        agg_date = str(raw_input("Invalid Date Format! Try again (yyyymmdd):"))
        
    format_date = agg_date[6:8] + '-' + agg_date[4:6] + '-' + agg_date[0:4]  #format for human eye
    amount = input("Loan Amount:   ")
    interest = input("Loan Interest:  %")
    tenure = input("No of Months: ")


    dbase = [dealer, acNum, hirer, details, amount, interest, format_date, tenure]

    with open('/Users/Michael/Documents/GitHub/Int-Projection/projection.csv', 'a') as b:
        writer = csv.writer(b)
        writer.writerow(dbase)
Example #6
0
def get_input(choices: List[Tuple]):
    all_tiles = set()
    all_commands = set()
    all_lines = set()
    for command, lines, tiles in choices:
        all_lines |= set(lines)
        all_commands.add(command)
        all_tiles |= set(tiles)
        # tile_list = ', '.join([f'{t.var} ({t.id})' for t in tiles])
        #
        # print(f"{command} ({command.id})")
        #       f"    lines: {str(lines)[1:-1]}\n"
        #       f"    tiles: {tile_list}")

    print(str(all_lines)[1:-1])
    print(', '.join([f"{c[0]} ({c[0].id})" for c in choices]))
    print(', '.join([f'{t.var} ({t.id})' for t in all_tiles]))

    while True:
        line = int(input('line: '))
        cmd_id = int(input('command: '))
        tile_id = int(input('tile: '))

        try:
            command = [c for c in all_commands if c.id == cmd_id][0]
            tile = [t for t in all_tiles if t.id == tile_id][0]
            break
        except (IndexError, ValueError):
            pass

    return line, command, tile
Example #7
0
def display(spectrum):
	template = np.ones(len(spectrum))

	#Get the plot ready and label the axes
	pyp.plot(spectrum)
	max_range = int(math.ceil(np.amax(spectrum) / standard_deviation))
	for i in range(0, max_range):
		pyp.plot(template * (mean + i * standard_deviation))
	pyp.xlabel('Units?')
	pyp.ylabel('Amps Squared')    
	pyp.title('Mean Normalized Power Spectrum')
	if 'V' in Options:
		pyp.show()
	if 'v' in Options:
		tokens = sys.argv[-1].split('.')
		filename = tokens[0] + ".png"
		input = ''
		if os.path.isfile(filename):
			input = input("Error: Plot file already exists! Overwrite? (y/n)\n")
			while input != 'y' and input != 'n':
				input = input("Please enter either \'y\' or \'n\'.\n")
			if input == 'y':
				pyp.savefig(filename) 
			else:
				print("Plot not written.")
		else:
			pyp.savefig(filename) 
def imc_creds():
    ''' This function prompts user for IMC server information and credentuials and stores
    values in url and auth global variables'''
    global url, auth, r
    imc_protocol = input(
        "What protocol would you like to use to connect to the IMC server: \n Press 1 for HTTP: \n Press 2 for HTTPS:")
    if imc_protocol == "1":
        h_url = 'http://'
    else:
        h_url = 'https://'
    imc_server = input("What is the ip address of the IMC server?")
    imc_port = input("What is the port number of the IMC server?")
    imc_user = input("What is the username of the IMC eAPI user?")
    imc_pw = input('''What is the password of the IMC eAPI user?''')
    url = h_url + imc_server + ":" + imc_port
    auth = requests.auth.HTTPDigestAuth(imc_user, imc_pw)
    test_url = '/imcrs'
    f_url = url + test_url
    try:
        r = requests.get(f_url, auth=auth, headers=headers)
    # checks for requests exceptions
    except requests.exceptions.RequestException as e:
        print("Error:\n" + str(e))
        print("\n\nThe IMC server address is invalid. Please try again\n\n")
        imc_creds()
    if r.status_code != 200:  # checks for valid IMC credentials
        print("Error: \n You're credentials are invalid. Please try again\n\n")
        imc_creds()
    else:
        print("You've successfully access the IMC eAPI")
Example #9
0
def kullanici_adini_guncelle():
    """Kullanıcıdan isim alıp ayarlara yazdırmaya gönderir"""
    veri = ayar_oku()
    veri["son_kullanan"] = input("Kullanıcı Adınız: ")
    while not veri["son_kullanan"] or len(veri["son_kullanan"]) > 9:
        veri["son_kullanan"] = input("1 ile 9 karakter uzunluğunda yazın: ")
    ayar_yaz(veri)
Example #10
0
def mentre3(): #Definim la funcio mentre3, que es una funcio secundaria de mentre
    suma = 0 #La variable "suma" tindra aquest valor"
    n = input("Sumarem tots els nombres que introduiu fins que poseu 999: ") #Definim la variable "n" com un input. Sera interpretat com un nombre.
    while n != 999: #Mentre es compleixi aquesta condicio
            suma = suma + n #La variable suma augmentara en funcio de "n"
            n = input("Fins que no introdueixis 999 seguirem sumant nombres: ") #Tornem a definir la variable "n" com un input. Sera interpretat com un nombre.
    print "\nLa suma dels nombres es: ", suma #Quan les condicions del while no es compleixin, imprimirem el resultat
Example #11
0
def vending_machine():
    deposit = 0 
    #get the cost of the item(s) purchased
    cost = eval(input('Enter the cost (in cents):\n'))
    #ask for money to pay when cost is greater than 0 and ask for more deposit when not enough
    while deposit < cost:
        deposit += eval(input('Deposit a coin or note (in cents):\n'))
    change = deposit - cost
    #Give change when due
    if change > 0:
        print('Your change is:')
        
        for i in (100, 25, 10, 5, 1):
            #check decreasingly if one of the possible coin is part of the change
            if change >= i:
                #specify for change more than or equal to $1 as in dollar               
                if i == 100:
                    print(change//i, ' x ', '$1',sep = '')
                else:
                    print(change//i, ' x ', i,'c',sep = '')
                change -= (change//i)*i
                #check until chanege is 0 then break loop
                if change == 0:
                    break
            else:
                continue
Example #12
0
def main():
	board = chess.Board()
	move_selector = MoveSelector(MAX_ITER_MTD, MAX_DEPTH, config.MAX_SCORE)

	color_choice = input("Do you want to play as black or white? [W/B]: ")
	while color_choice is not "W" and color_choice is not "B":
		color_choice = input("Invalid choice, please enter W for white or B for black: ")

	print(pp_board(board))

	if color_choice == "W":
		while True:
			if board.is_game_over():
				break

			handle_human_move(board)

			if board.is_game_over():
				break

			handle_ai_move(board, move_selector)
	else:
		while True:
			if board.is_game_over():
				break

			handle_ai_move(board, move_selector)

			if board.is_game_over():
				break

			handle_human_move(board)

	print(board.result())
Example #13
0
def main():
    T = int(input())
    
    for _ in range(T):
        n = int(input())
        side_lengths = list(map(int, input().split()))
        print('Yes' if is_valid(side_lengths) else 'No')
def main():
    n = int(input())
    xs = [int(i) for i in input().strip().split()]
    assert len(xs) == n

    result = solve(xs)
    print(result)
def playPerformance(selection, performance, expression, segmentation, name='ExpressivePerformance'):
    # Store?
    # Play again?
    # View first x notes?
    while True:
        choice = util.menu('What do you want to do?', ['Play performance', 'Store expression', 'Store midi', 'View first notes of performance', 'Plot performance', 'Save plot', 'View segmentation', 'Make segmentation audible', 'Quit'])
        if choice == 0:
            seq = Sequencer()
            seq.play(performance)
        elif choice == 1:
            n = input("Enter a name for saving this performance. [{0}]\n".format(name))
            if not n == '': name = n
            tools.savePerformance(selection, expression, name)
        elif choice == 2:
            n = input("Enter a name for saving this performance. [{0}.mid]\n".format(name))
            if not n == '': name = n
            performance.exportMidi('output/{0}.mid'.format(name))
        elif choice == 3:
            for note in performance[:30]:
                print(note)
        elif choice == 4: # Plot
            visualize(segmentation, expression)
        elif choice == 5: # Save plot
            n = input("Enter a name for saving this performance. [{0}.mid]\n".format(name))
            if not n == '': name = n
            visualize(segmentation, expression, store=name)
        elif choice == 6: # View segments
            pass
        elif choice == 7: # Play segments
            pass
        elif choice == 8: # Quit
            break
Example #16
0
    def liquidateAssets(self, player, other, amount):
        """Prompts player to liquidate his assets until given cash amount is
        reached."""
        print("{}'s Properties".format(player))
        print('=' * (len(player) + 13))

        player = self.view.getPlayer(player)
        for tile in player.properties:
            print(tile)

        while player.cash < amount:
            print("Amount needed: {}{}".format(self.view.currency['symbol'],
                                               amount - player.cash))
            if not player.properties:
                print("Looks like you're out of properties to mortgage. Bankrupt!")
                self.view.playerBankrupt(player.name, other)
                break
            else:
                print("\nEnter the names of properties you wish to mortgage.\n"
                      "Type DONE when you're done.")
                mortgageList = []
                prop = input(prompt)

                while prop != 'DONE':
                    mortgageList.append(prop)
                    prop = input(prompt)

                for tile in mortgageList:
                    self.view.controller.playerMortgage(player.name, tile)

                print("You now have {}{}.".format(self.view.currency['symbol'],
                                                  player.cash))
def pickchar():
	exampleprimes= [1009, 1013, 1019, 1021, 1031, 1033, 1039, 1049, 1051, 1061, 1063, 1069, 1087, 1091, 1093, 1097, 1103,
	                1109, 1117, 1123, 1129, 1151, 1153, 1163, 1171, 1181, 1187, 1193, 1201, 1213, 1217, 1223, 1229, 1231,
	                1237, 1249, 1259, 1277, 1279, 1283, 1289, 1291, 1297, 1301, 1303, 1307, 1319, 1321, 1327, 1361, 1367,
	                1373, 1381, 1399, 1409, 1423, 1427, 1429, 1433, 1439, 1447, 1451, 1453, 1459, 1471, 1481, 1483, 1487,
	                1489, 1493, 1499, 1511, 1523, 1531, 1543, 1549, 1553, 1559, 1567, 1571, 1579, 1583, 1597, 1601, 1607,
	                1609, 1613, 1619, 1621, 1627, 1637, 1657, 1663, 1667, 1669, 1693, 1697, 1699, 1709, 1721, 1723, 1733,
	                1741, 1747, 1753, 1759, 1777, 1783, 1787, 1789, 1801, 1811, 1823, 1831, 1847, 1861, 1867, 1871, 1873,
	                1877, 1879, 1889, 1901, 1907, 1913, 1931, 1933, 1949, 1951, 1973, 1979, 1987, 1993, 1997, 1999]
	while 1:
		try:
			char= int(input('What should be the characteristic of the ring? ')) # should input 0 or a prime number
			if char== 0 or char in exampleprimes:
				return char
			elif char< 0:
				print('That was not a valid entry. Please try again.')
				continue
			elif char< 1000 or char> 2000:
				conf= str(input('Caution: This program does not check to ensure a characteristic is prime unless it is between 1000 and 2000. Are you sure you want to use this number? Y/N: '))
				if conf in ['Y', 'Yes', 'y', 'yes']:
					return char
				else:
					continue
			else:
				print('The number you entered is not prime. Plese try again.')
				continue
		except ValueError:
			print('That was not a valid entry. Please try again.')
Example #18
0
    def preloop(self):
        print("You are playing Monopoly!\n"
              "Style: {}\n"
              "Begin game?".format(self.view.style))

        if not self.confirmAction():
            raise SystemExit

        print("Enter the number of players (> 1).")
        while True:
            num = input(self.prompt)
            try:
                num = int(num)
                if num <= 1:
                    raise ValueError

                self.view.numPlayers = num
            except ValueError:
                print("Try again.")
                continue

            break

        for i in range(self.view.numPlayers):
            print("Player #{}".format(i + 1))
            print("What is your name?")
            name = input(self.prompt)
            print("What piece will you use?")
            piece = input(self.prompt)
            self.view.playerAdd(PlayerRep(name, piece, 0, self.view.currency['defaultAmount']))

        print("\nIt's {}'s turn.".format(self.view.players[self.turn].name))
Example #19
0
def main():
    filename = time.strftime('%A-%Y%m%d-%H-%M-%S') + '.txt'  # filename with system date time format
    f = open(filename , 'w') # opening the file with write 'w' permission
    
    f.write('+++++++++++++++++++++++++++++++++\n') # decoration with +++
    print('+++++++++++++++++++++++++++++++++')
            #To add the characters/decorating output
    days = int(input("Please enter number of days: ") )   #Asking user input
    f.write('days:  %s'%days)                             # Writing the user input 'days' to the text file
    if ( days > 0 and days <= 366 ):                      #condition to check valid days in a year
        n = math.pow(2, days-1)                           #power function ...2^n-1
        m = n / 100                                       #Converting cents to dollars
        f.write('\n+++++++++++++++++++++++++++++++++\n')
        print('+++++++++++++++++++++++++++++++++')
        f.write(' Day   Today\'s Salary \n------  -----------------\n %s    $%s'%(days,m))   #%s-substitution %(days,m) using variable to display output
        print(' Day   Today\'s Salary \n------  -----------------\n %s    $%s'%(days,m))    #%s-substitution %(days,m) using variable to display output 
    else:
        while True:                                                    #looping to check whether user has entered valid data
            f.write("\nInvalid number of days\n")               # Writing invalid number of days to text file
            print("Invalid number of days\n")
            f.write('+++++++++++++++++++++++++++++++++\n')      # decoration with +++ in the text file
            print('+++++++++++++++++++++++++++++++++\n')
            days = int(input("Please enter number of days: ") ) #Asking user input
            f.write('days:  %s'%days)
            #print ('------------------------------')  
            if ( days > 0 and days <= 366 ):
                n = int(math.pow(2, days-1))
                m = n / 100
                print ('+++++++++++++++++++++++++++++++++\n')
                f.write('\n+++++++++++++++++++++++++++++++++\n')
                f.write(' Day   Today\'s Salary\n------  -------------------\n %s    $%s'%(days,m))
                print(' Day   Today\'s Salary\n------  -------------------\n %s    $%s'%(days,m))
                break                                                      #breaking the loop
Example #20
0
def main():
    # We load the spector dataset as a pandas dataframe
    # Of course, you can load your own datasets 
    data = sm.datasets.spector.load_pandas()
    
    # We define y as the endogenous variable, and x as the 
    # exogenous variable.
    # Note that if you load your own data, the methods endog 
    # and exog will not be available and you will have to 
    # explicitly define the endogenous and exogenous variables
    y, x = data.endog, data.exog
    
    # We do the regression
    reg = sm.OLS(y, x).fit()
    
    # And here we can see the results in a very nice looking table
    print('SUMMARY -------------------------------------------')
    print((reg.summary()))
    
    # We can only take a look at the parameter values though
    print('PARAMETERS ----------------------------------------')
    print((reg.params))
    
    # We can also extract the residuals
    print('RESIDUALS -----------------------------------------')
    print((reg.resid))
    
    # This line is just to prevent the output from vanishing when you
    # run the program by double-clicking
    input('Done - Hit any key to finish.')
Example #21
0
def Dish_get_info() -> Dish:
    """ Prompt user for fields of Dish; create and return.
    """
    return Dish(
        input("Please enter the name of the dish:  "),
        float(input("Please enter the price of that dish:  ")),
        float(input("Please enter the number of calories in the dish:  ")))
Example #22
0
def prompt_create():
    """Prompt user to obtain data for request"""
    name = input("Name: ")
    sshkey = input("SSH Key: ")
    comment = input("Comment: ")

    return {"<name>": name, "<sshkey>": sshkey, "--comment": comment}
Example #23
0
def work():
  power2 = lambda x: x*x
  try:
    acts = input("выход - 0, квадрат - 1, таблица - 2: ")
    act = int(acts)
    if act == 0:
      return
    #Проверка на ошибки
    if act < 0 or act > 2:
      raise Exception()
    #Ввод числа
    s = input("введите число: ")
    f = float(s)
    #Вывод квадрата
    if act == 1:
      print("квадрат: {}", power2(f))
    #Вывод таблицы
    elif act == 2:
      clen = 15
      for y in range(5):
        s = ""
        for x in range(5):
          s += str(f*x*y) + (" " * (clen-len(str(f*x*y))+1))
        print(s)
  except:
    print("ошибка ввода")
Example #24
0
def main():
    try:
        
        #Change min_time HERE!!
        min_time = 4
        
        schedule_csv = input("Enter the name of the Schedule file: ") +".csv"
        transaction_csv = input("Enter the name of the Transaction file: ") +".csv"
        save_file_name = input("Enter the name of the file to which we should save: ")+".csv"
        schedule_list = create_list_from_csv(schedule_csv)
        transaction_list = create_list_from_csv(transaction_csv)

        
        #schedule_list = create_list_from_csv("Raw-Schedule-Adherance-347.csv")
        #transaction_list = create_list_from_csv("Boardings and Tag-offs by Stop.csv")
        bus_list = create_bus_list(schedule_list)
        bus_dict = create_bus_dict_from_list(bus_list)
        route_dict = generate_bus_route_dict(bus_dict, schedule_list)
        #stop_list = create_stop_list(schedule_list)
        #print(transaction_list)
        stop_dict = create_stop_dict(schedule_list)
        add_stops_to_bus_dict_from_dict(bus_dict, stop_dict, route_dict)
        add_start_leave_times(bus_dict, schedule_list)
        add_transaction_times_to_bus_dict(bus_dict, transaction_list, min_time)
        #print(time_comparison("7:17:59", "7:18:01", "7:19:15", 4, "2/03/2015", "2/03/2015"))
        
        #save_summary_to_file("347 Route Summary.txt", bus_dict, route_dict, stop_dict)
        
        save_summary_to_file(save_file_name, bus_dict, route_dict, stop_dict)
    except:
        print(traceback.format_exc())
        input("Something went bad, get Richard")
Example #25
0
 def chosePlayerOrServant(self, enemy, choice = True):
     print("\nVoulez vous attaquer le joueur ennemie ou ses serviteurs ?")
     while True :
         if choice == True :
             target = input("Joueur ou serviteur ?\n").lower()
             if target == "joueur" :
                 #choiceTarget = True
                 return enemy
             elif target == "serviteur" :
                 #choiceTarget = True
                 print("\nQuel serviteur ennemie voulez vous attaquer ?")
                 nameServantTarget = ""
                 while True:
                     nameServantTarget = input("Choisisez le nom du serviteur a attaquer\n").lower()
                     for cardEnemy in enemy.field :
                         if nameServantTarget == cardEnemy.name.lower() and cardEnemy not in enemy.camoField :
                             return cardEnemy
         else :
             print("\nQuel serviteur ennemie voulez vous attaquer ?")
             nameServantTarget = ""
             while True:
                 nameServantTarget = input("Choisisez le nom du serviteur a attaquer\n").lower()
                 for cardEnemy in enemy.field :
                     if nameServantTarget == cardEnemy.name.lower() and cardEnemy not in enemy.camoField :
                         return cardEnemy
def if_not_stuff():
    x = input("Please enter some text")
    if x:
        print("You entered '{}'". format(x))
    else:
        print("You did not enter anything")

    # doesn't work in terminal
    print(not False)
    print(not True)

    age = int(input("How old are you?"))
    if not(age < 18):
        print("""You are old enough to vote.
            Please put an X in the box""")
    else:
        print("Please come back in {0} years". format(18 - age))

    parrot_type = "Norwegian Blue"
    letter = input("Enter a character: ")
    if letter in parrot_type:
        print("Give me a {}, Bob". format(letter))
    else:
        print("I don't need that letter")
    return "Just more thins with if, else and not"
Example #27
0
 def auth_dialog(self):
     try:
         with open(CONF_FILE) as conf:
             token = json.load(conf)
     except (OSError, json.JSONDecodeError, KeyError):
         print("Your token file doesn't exist or is malformed.")
         print("If you WANT to proceed anonymously, pass"
               "`-a/--anonymous` on the command line.")
         print("Or you can create a new token now. "
               "Create token? [y/n] ", end='')
         if input().lower() in ('y', 'yes'):
             username = input('Username: ')
             password = getpass.getpass()
             note = 'gist3_{}'.format(id_gen())
             resp = req.post(API_BASE + '/authorizations',
                             auth=(username, password),
                             json={'scopes': ['gist'],
                                   'note': note})
             if resp.status_code == req.codes.created:
                 token = resp.json()['token']
                 with open(CONF_FILE, 'w') as conf:
                     json.dump(token, conf)
                 print('Token created & saved to {}'.format(CONF_FILE))
             else:
                 print('There was an error from github: ')
                 print(json.dumps(resp.json(), sort_keys=True, indent=4))
                 sys.exit(2)
         else:
             print('Aborting...')
             sys.exit(0)
     return AccessTokenAuth(token)
Example #28
0
def main():
    file = input("Enter a filename here: ");
    if os.path.exists(file):
        loadfile = open(file, "r");
        fc = loadfile.readlines();
        loadfile.close();
        newfc = [];
        for line in fc:
            line = line.replace("<female>","&#9792;");
            line = line.replace("<female/>","&#9792;");
            line = line.replace("<male>","&#9794;");
            line = line.replace("<male/>","&#9794;");
            line = line.replace("<+->","&#177;");
            line = line.replace("<+-/>","&#177;");
            line = line.replace("<plusminus>","&#177;");
            line = line.replace("<plusminus/>","&#177;");
            line = line.replace("<plusminus/>","&#177;");
            line = line.replace("<copyright>","&#169;");
            line = line.replace("<copyright/>","&#169;");
            newfc.append(line);
        loadfile = open(file, "w");
        loadfile.write("");
        loadfile.close();
        loadfile = open(file, "a");
        for line in newfc:
            loadfile.write(line);
        loadfile.close();
            
    else:
        input("Fail.");
def get_number(lower, upper):
    number = input("Enter a number between ({} - {}):")

    if number < lower or number > upper or number.isdecimal():
        print("Invalid number!")
        number = input("Enter a number between ({} - {}):")
    return int(number)
Example #30
0
def create_player():
    global player
    player = Character(input("What is your name, Mr/Ms Would-be Hero?: "))
    if player.name == "Mr. Would-be Hero" or player.name == "Ms. Would-be Hero":
        print("Wow, just TOO unoriginal, I'm sorry - try again.")
        player = Character(input("What is your name, Mr/Ms Would-be Hero?: "))
    print("OK " + player.name + "! Let's go on a totally radical adventure!")