Ejemplo n.º 1
0
def user_turn(board,turn):
	col = raw_input("It's your turn! Which column would you like to play in?\n>>>   ").upper()
	if (isValidCol(col)):
		found = False
		for i in range(len(BOTTOM_LABELS)):
			if ((col == BOTTOM_LABELS[i]) and found==False):
				col = i
				found = True
		for row in range(BOARD_HEIGHT,-1,-1):
			if board[row][col] != 0:
				continue
			else:
				if (turn):
					board[row][col] = 3
				else:
					board[row][col] = 2
				return board,True
		print color('Invalid input, column is full','red')
		done = False
		# if turn:
		# 	turn = False
		# else:
		# 	turn = True
		return board,True
	else:
		if col.upper()=='Q':
			print 'Quitting...'
			return board,False
		else:
			print color('Invalid input, must be A-G','red')
			return board,True
Ejemplo n.º 2
0
def item(key='bullet'):
  '''
  Looks for a formatting string in a dictionary.

  Parameters:
  ----------
  A string among the ones available in the function:

    - bullet
    - warn
    - error
    - success

  Returns:
  -------
  A byte object.

  '''
  dictionary = {
    'bullet': color(u' →', 'blue', attrs=['bold']),
    'warn': color(u' WARN:', 'yellow', attrs=['bold']),
    'error':  color(u' ERROR:', 'red', attrs=['bold']),
    'success': color(u' SUCCESS:', 'green', attrs=['bold'])
  }

  return dictionary[key]
Ejemplo n.º 3
0
def dir_exists(dirname):
    if not os.path.exists(dirname):
        msg = "No directory:"
        print color(msg, 'red')
        print dirname
        return False
    return True
Ejemplo n.º 4
0
 def handlePM(self, msgBody, usr):
     if self.canReply:
         if usr not in self.pmCmdTimers or time.time() - self.pmCmdTimers[usr] > 3.:
             inputs = msgBody.split(' ')
             if usr in self.hinderances and self.hinderances[usr]:
                 if inputs[0][1:] not in ['stopHinder', 'stophinder']:
                     self.hinderances[usr] -= 1
                     inputs[0] = '!' + rng.choice(RObotLib.hinderRNG)
             else:
                 if inputs[0][1:] in ['stopHinder', 'stophinder']:
                     inputs = ['!stophinder', 'err']
             handled = RObotLib.handler(inputs[0][1:], usr, inputs[1:])
             if handled is not None:
                 if inputs[0][1:] == 'hinder':
                     if len(inputs) > 1 and canIntConvert(inputs[1]):
                         nRands = inputs[1]
                     else:
                         nRands = rng.randint(1,5+1)
                     self.hinderances[usr] = nRands
                 elif inputs[0][1:] in ['stopHinder', 'stophinder']:
                     self.hinderances[usr] = 0
                 responses, replyMsgs = handled
                 for i in range(len(responses)):
                     time.sleep(1.2)
                     print(color('PM TO {}: {}'.format(usr, replyMsgs[i]), pmColor))
                     if self.logFilename:
                         with codecs.open(self.logFilename, 'a', 'utf-8') as lf:
                             lf.write('pm to,{},{},{}\n'.format(usr, time.time(), replyMsgs[i]))
                     self.send_raw(responses[i])
                 self.pmCmdTimers[usr] = time.time()
             else:
                 print(color('got past checkForCommands, but handler returned None', 'yellow'))
                 print(color(msgBody, 'yellow'), usr)
def addRem(x, y):
    decide = 0
    while (True):
        print("")
        decide = input("Add (a) or remove (b) an x and y value: ").lower()

        if (decide == 'a'):
            while (True):
                try:
                    print("")
                    addX = input("Enter a number to add it to x-values: ")
                    addX = float(addX)
                    print("")
                    addY = input("Enter a number to add it to y-values: ")
                    addY = float(addY)
                except (ValueError):
                    print("")
                    print(color("Please enter only numbers", "red"))
                    continue
                else:
                    break
            x.append(addX)
            y.append(addY)
            break
        elif (decide == 'b'):
            x = x.pop()
            y = y.pop()

            print("")
            print("Removed the last items")
            break
        else:
            print("")
            print(color("Please enter a or b", "red"))
Ejemplo n.º 6
0
def item(key='bullet'):
    '''
  Looks for a formatting string in a dictionary.

  Parameters:
  ----------
  A string among the ones available in the function:

    - bullet
    - warn
    - error
    - success

  Returns:
  -------
  A byte object.

  '''
    dictionary = {
        'bullet': color(u' →', 'blue', attrs=['bold']),
        'warn': color(u' WARN:', 'yellow', attrs=['bold']),
        'error': color(u' ERROR:', 'red', attrs=['bold']),
        'success': color(u' SUCCESS:', 'green', attrs=['bold'])
    }

    return dictionary[key]
Ejemplo n.º 7
0
def check_columns(args, columns=None, select=None, msg=None):
    """ Abstract base function for checking a column"""
    global counter
    f, nfiles, band = args

    with counter.get_lock():
        counter.value += 1
    print_running(counter.value, nfiles, indent=4, step=1)

    try:
        data = fitsio.read(f, columns=columns)
    except ValueError as e:
        msg = "Couldn't read %(columns)s from %(filename)s"
        msg = msg % dict(columns=columns, filename=f)
        print color(msg, 'red')
        return True

    sel = select(data)
    if np.any(sel):
        #if not msg: msg = "Bad %(columns)s value in %(filename)s"
        #msg = msg%dict(columns=columns,filename=f)
        if msg:
            print msg % dict(columns=columns, filename=f)
        if not isinstance(sel, (bool, type(np.bool))):
            msg = "Bad %(columns)s value in %(filename)s"
            print msg % dict(columns=columns, filename=f)
            print 4 * ' ' + bad_values_str(data[sel])
        return True

    return False
def item(i):
    dictionary = {
        "prompt_bullet": color(" →", "blue", attrs=["bold"]),
        "prompt_error": color(" ERROR:", "red", attrs=["bold"]),
        "prompt_success": color(" SUCCESS:", "green", attrs=["bold"]),
    }
    return dictionary[i]
Ejemplo n.º 9
0
 def select(x):
     nobjs = float(len(x))
     frac = (x > 0).sum() / nobjs
     bad = (frac < 0.1) and (nobjs > 1e4)
     if bad:
         msg = 'Match fraction = %.2f;' % frac
         print color(msg, 'yellow'),
     return bad
Ejemplo n.º 10
0
def _format_traceback(path, line, fn, text, i, count, highlight):
    template = '\t{i} {fn} [{l}] in {p}{t}'
    indent = ('└─' if i == count-1 else '├─') + '──'*i
    filename = path.rsplit('/thinc/', 1)[1] if '/thinc/' in path else path
    text = _format_user_error(text, i, highlight) if i == count-1 else ''
    return template.format(l=str(line), i=indent, t=text,
                           fn=color(fn, attrs=['bold']),
                           p=color(filename, attrs=['underline']))
Ejemplo n.º 11
0
def _format_traceback(path, line, fn, text, i, count, highlight):
    template = '\t{i} {fn} [{l}] in {p}{t}'
    indent = ('└─' if i == count-1 else '├─') + '──'*i
    filename = path.rsplit('/thinc/', 1)[1] if '/thinc/' in path else path
    text = _format_user_error(text, i, highlight) if i == count-1 else ''
    return template.format(l=str(line), i=indent, t=text,
                           fn=color(fn, attrs=['bold']),
                           p=color(filename, attrs=['underline']))
Ejemplo n.º 12
0
 def privateMessage(self, msg):
     # self.fwtAnnounce()
     return
     m = str(msg)
     tmp = RObotLib.decryptPM(m)
     if tmp is not None:
         msgText, sendTo = tmp
         if self.logFilename:
             with codecs.open(self.logFilename, 'a', 'utf-8') as lf:
                 lf.write('pm from,{},{},{}\n'.format(
                     sendTo, time.time(), msgText))
         print(
             color(
                 '{}  PM FROM {}: {}'.format(
                     time.strftime("%X", time.localtime()), sendTo,
                     msgText), pmColor))
         msgBody = checkForCommands(msgText)
         if msgBody and sendTo != 'RevelationOrange':
             self.handlePM(msgBody, sendTo)
         elif msgText == 'help':
             self.handlePM('!' + msgText, sendTo)
         elif sendTo == 'RevelationOrange':
             inputs = msgBody.split(' ')
             if inputs[0] == '!say':
                 chatTxt = ' '.join(inputs[1:])
                 resprepl = "<message to='*****@*****.**' from='[email protected]/xiff' type='groupchat' id='dc96ae0e-27ec-40e5-83f2-b4a013d5ec0a' xmlns='jabber:client'><body>{}</body><x xmlns='jabber:x:event'><composing/></x></message>"
                 resp = resprepl.format(chatTxt)
                 print(chatTxt)
                 xmpp.send_raw(resp)
             elif inputs[0] == '!msgs':
                 print(self.pmCmdTimers)
             elif inputs[0] == '!yay':
                 for y in self.yays:
                     print(time.ctime(y))
                 resp = RObotLib.formulateResponse('yay!™', sendTo)
                 if self.logFilename:
                     with codecs.open(self.logFilename, 'a', 'utf-8') as lf:
                         lf.write('pm to,{},{},{}\n'.format(
                             sendTo, time.time(), 'yay!™'))
                 print(
                     color('PM TO {}: {}'.format(sendTo, 'yay!™'), pmColor))
                 xmpp.send_raw(resp)
             elif inputs[0] == '!hinders':
                 for x in self.hinderances:
                     print(
                         color('{}: {}'.format(x, self.hinderances[x]),
                               'blue'))
             elif inputs[0] == '!timers':
                 for t in self.publicCooldowns:
                     print(
                         color(
                             "{}: {}".format(
                                 t, time.ctime(self.publicCooldowns[t])),
                             "blue"))
             elif inputs[0] in ['!disconnect', '!dc']:
                 self.logout()
             else:
                 self.handlePM(msgBody, sendTo)
Ejemplo n.º 13
0
def prompt(ptype):
    dictionary = {
        'bullet': color(" →", "blue", attrs=['bold']),
        'error':  color(" ERROR:", "red", attrs=['bold']),
        'success': color(" SUCCESS:", "green", attrs=['bold']),
        'warn': color(" WARN:", "yellow", attrs=['bold'])
    }

    return dictionary[ptype].decode('utf-8')
Ejemplo n.º 14
0
def refreshEnv():
    clear()
    for i in range(0, env_wid):
        for j in range(0, env_len):
            if (env[i][j] == 1):
                print(color(env[i][j], 'red', 'on_red'), " ", end='')
            else:
                print(color(env[i][j], 'white', 'on_white'), " ", end='')
        print("\n")
Ejemplo n.º 15
0
def item(i):
  dictionary = {
    'prompt_bullet': color(" →", "blue", attrs=['bold']),
    'prompt_error':  color(" ERROR:", "red", attrs=['bold']),
    'prompt_success': color(" SUCCESS:", "green", attrs=['bold']),
    'prompt_warn': color(" WARN:", "yellow", attrs=['bold']),
    'prompt_deleted': color(" DELETED:", "yellow", attrs=['bold'])
  }
  return dictionary[i]
Ejemplo n.º 16
0
def item(i):
  dictionary = {
    'bullet': color(u" →", "blue", attrs=['bold']),
    'error':  color(u" ERROR:", "red", attrs=['bold']),
    'success': color(u" SUCCESS:", "green", attrs=['bold']),
    'warn': color(u" WARN:", "yellow", attrs=['bold'])
  }

  return dictionary[i]
Ejemplo n.º 17
0
def item(i):
  dictionary = {
    'prompt_bullet': color(u" →", "blue", attrs=['bold']),
    'prompt_error':  color(u" ERROR:", "red", attrs=['bold']),
    'prompt_success': color(u" SUCCESS:", "green", attrs=['bold']),
    'prompt_warn': color(u" WARN:", "yellow", attrs=['bold']),
    'prompt_ping': color(u" *", "green", attrs=['bold'])
  }
  return dictionary[i].encode('utf-8')
Ejemplo n.º 18
0
 def saveout(self):
     plt.figure(1)
     plt.savefig('../output/' + self.current_file_name + '_scatter')
     plt.figure(2)
     plt.savefig('../output/' + self.current_file_name + '_distribution')
     print(
         color("Plots saved as ", 'green') + self.current_file_name +
         '_scatter.png' + color(" and ", 'green') + self.current_file_name +
         '_distribution.png' + color(" in ", 'green') + "../output/ " +
         color("directory\n", 'green'))
Ejemplo n.º 19
0
 def _log(self, tag, message, printTag):
     if tag in self.enabled and not self.enabled[tag]:
         return
     tagColor = self.tagColors[tag]
     messageColor = self.messageColors[tag]
     spaceCount = self.maxTagSize - len(tag)
     if printTag:
         print('%s %s %s' % (color('[' + tag + ']', tagColor), ' ' * spaceCount, color(message, messageColor, attrs=['bold'])))
     else:    
         print(' %s  %s %s' % (color(' ' * len(tag), tagColor), ' ' * spaceCount, color(message, messageColor, attrs=['bold'])))
     self.splitted = False
Ejemplo n.º 20
0
 def privateMessage(self, msg):
     m = str(msg)
     tmp = RObotLib.decryptPM(m)
     if tmp is not None:
         msgText, sendTo = tmp
         if self.logFilename:
             with codecs.open(self.logFilename, 'a', 'utf-8') as lf:
                 lf.write('pm from,{},{},{}\n'.format(
                     sendTo, time.time(), msgText))
         print(color('PM FROM {}: {}'.format(sendTo, msgText), pmColor))
         msgBody = checkForCommands(msgText)
         if msgBody and sendTo != 'RevelationOrange':
             self.handlePM(msgBody, sendTo)
         elif msgText == 'help':
             self.handlePM('!' + msgText, sendTo)
         elif sendTo == 'RevelationOrange':
             inputs = msgBody.split(' ')
             if inputs[0] == '!say':
                 chatTxt = ' '.join(inputs[1:])
                 resprepl = "<message to='*****@*****.**' from='[email protected]/xiff' type='groupchat' id='dc96ae0e-27ec-40e5-83f2-b4a013d5ec0a' xmlns='jabber:client'><body>{}</body><x xmlns='jabber:x:event'><composing/></x></message>"
                 resp = resprepl.format(chatTxt)
                 print(chatTxt)
                 print(resp)
                 xmpp.send_raw(resp)
             elif inputs[0] == '!msgs':
                 print(self.pmCmdTimers)
             elif inputs[0] == '!yay':
                 for y in self.yays:
                     print(time.ctime(y))
                 resp = RObotLib.formulateResponse('yay!™', sendTo)
                 if self.logFilename:
                     with codecs.open(self.logFilename, 'a', 'utf-8') as lf:
                         lf.write('pm to,{},{},{}\n'.format(
                             sendTo, time.time(), 'yay!™'))
                 print(
                     color('PM TO {}: {}'.format(sendTo, 'yay!™'), pmColor))
                 xmpp.send_raw(resp)
             elif inputs[0] == '!hinders':
                 for x in self.hinderances:
                     print(
                         color('{}: {}'.format(x, self.hinderances[x]),
                               'blue'))
             elif inputs[0] == '!ads':
                 for ad in RObotLib.townAdsList:
                     print(color(ad, 'green'))
             else:
                 rMsg = '[construction zone]'
                 resp = RObotLib.formulateResponse(rMsg, sendTo)
                 if self.logFilename:
                     with codecs.open(self.logFilename, 'a', 'utf-8') as lf:
                         lf.write('pm to,{},{},{}\n'.format(
                             sendTo, time.time(), rMsg))
                 xmpp.send_raw(resp)
Ejemplo n.º 21
0
def item(i):
  '''Selecting a prompt item to decorate stdout.'''

  #
  # Dictionary of prompt items.
  #
  dictionary = {
    'prompt_bullet': color(" →", "blue", attrs=['bold']),
    'prompt_error':  color(" ERROR:", "red", attrs=['bold']),
    'prompt_success': color(" SUCCESS:", "green", attrs=['bold']),
    'prompt_warn': color(" WARN:", "yellow", attrs=['bold'])
  }
  return dictionary[i]
Ejemplo n.º 22
0
def Main():
  '''Wrapper'''

  #
  # Setting up configuration: dev = development; prod = production.
  #
  p = LoadConfig(os.path.join(os.path.split(dir)[0], 'config', 'prod.json'))
  if p is not False:

    print "--------------------------------------------------"
    print '%s HDX Site: %s' % (I('bullet'), p['hdx_site'])

    #
    # Deleting all datasets from org.
    #
    if p['delete_datasets']:
      try:
        delete.DeleteAllDatasetsFromOrg(organization='opennepal', hdx_site=p['hdx_site'], apikey=p['hdx_key'], verbose=p['verbose'])

      except Exception as e:
        print e
        return False

    try:
      #
      # Loading JSON data.
      #
      dataset_dict = load.LoadData(os.path.join(p['json_folder'], 'datasets.json'))
      resource_dict = load.LoadData(os.path.join(p['json_folder'], 'resources.json'))
      # gallery_dict = load.LoadData(os.path.join(p['json_folder'], 'gallery.json'))

      # Delete resources before running:
      if p['delete_resources']:
        delete.DeleteResources(dataset_dict=dataset_dict, hdx_site=p['hdx_site'], apikey=p['hdx_key'], verbose=p['verbose'])

      if p['update_all_datasets']:
        print '--------------------------------------------------'
        print color(u" ATTENTION:", "blue", attrs=['bold']) + ' Updating ALL datasets.'
        print '--------------------------------------------------'

      #
      # Create datasets, resources, and gallery items.
      #
      create.CreateDatasets(dataset_dict=dataset_dict, hdx_site=p['hdx_site'], apikey=p['hdx_key'], verbose=p['verbose'], update_all_datasets=p['update_all_datasets'])
      create.CreateResources(resource_dict=resource_dict, hdx_site=p['hdx_site'], apikey=p['hdx_key'], verbose=p['verbose'], update_all_datasets=p['update_all_datasets'])
      # create.CreateGalleryItems(gallery_dict=gallery_dict, hdx_site=p['hdx_site'], apikey=p['hdx_key'], verbose=p['verbose'], update_all_datasets=p['update_all_datasets'])

    except Exception as e:
      print e
      return False
Ejemplo n.º 23
0
def check_files(explist, files):
    exp = explist
    nfiles = len(files)
    unit = np.array([basename(f).split('_')[0] for f in files])
    missing = ~np.in1d(exp['unitname'], unit)
    extra = ~np.in1d(unit, exp['unitname'])

    print_running(nfiles, nfiles, indent=4)
    if missing.sum():
        msg = "Missing %s file(s):" % missing.sum()
        print color(msg, 'red')
        print 4 * ' ' + '%s' % exp['unitname'][missing]
    elif extra.sum():
        msg = "  Found %s extra file(s):" % extra.sum()
        print color(msg, 'red')
        print 4 * ' ' + '%s' % unit[extra]
    else:
        print OK

    print_running(nfiles, nfiles, indent=4)
    if missing.sum():
        msg = "Missing %s file(s):" % missing.sum()
        print color(msg, 'red')
        print 4 * ' ' + '%s' % exp['unitname'][missing]
    elif extra.sum():
        msg = "Extra %s file(s):" % extra.sum()
        print color(msg, 'red')
        print 4 * ' ' + '%s' % unit[extra]
    else:
        print OK
Ejemplo n.º 24
0
def print_board(board):
	for r in range(BOARD_HEIGHT + 1):
		row = '|'
		for c in range(BOARD_WIDTH):
			if (board[r][c] == 0):
				row += '   |'
			elif (board[r][c] == 3):
				row += ' 0 |'
				LAST_MOVE = [r,c]
			elif (board[r][c] == 2):
				row += ' X |'
				LAST_MOVE = [r,c]
			else:
				row += (' ' + BOTTOM_LABELS[c] + ' |')
		print color(row,'white')
Ejemplo n.º 25
0
def get_bins(dat, ext_col_idx):
    while True:
        my_range = input('Input the range of the x axis histogram bins: \n'
                         '(Leave blank to bin automatically)').rstrip()
        print(color('You Chose: ', 'green') + my_range + '\n')
        try:
            if my_range:
                my_range = float(my_range)
                bin_edges = np.arange(0, max(dat[:, ext_col_idx]), my_range)
            else:
                bin_edges = 20
        except ValueError:
            print(color("Input must be number or null (empty)!\n", 'red'))
        else:
            break
    return bin_edges
Ejemplo n.º 26
0
def menu_cmd(v):
    OPTIONS = {
        "bins":
        dict(desc="Change bins of currently active distribution plot",
             func=None),
        "save":
        dict(desc="Save currently active plots as images", func=cmd_save),
        "csv":
        dict(desc="Export currently active plots to csv file", func=cmd_csv),
        "next":
        dict(desc="Select next data column (retains volume column selection)",
             func=cmd_next),
        "report":
        dict(desc="Runs pyPSD_report.py to generate a report of the data",
             func=cmd_report),
        "quit":
        dict(desc="Exits the program", func=cmd_quit)
    }

    while sig == True:
        print("\nPlease choose an option:")
        for key in OPTIONS.keys():
            print("\t" + key + "\t" + OPTIONS[key]["desc"])
        cmd = input('Selection: ').rstrip()
        if not cmd in OPTIONS.keys():
            print(color("Invalid selection", 'red') + '\n')
        elif cmd == 'bins':
            return
        elif (cmd == 'save') or (cmd == 'csv'):
            OPTIONS[cmd]["func"](v)
        else:
            OPTIONS[cmd]["func"]()
    return
def create_trie_index(dataset=None):

    if dataset == None:
        raise NameError('No dataset given for trie index to be initialized.')

    with open(dataset, mode='r') as f:
        file = f.readlines()
        data = [
            word.replace('\r',
                         '\n').replace('\u000D\u000A',
                                       '\n').replace('(',
                                                     '\n').replace(')', '\n')
            for word in file
        ]

    t = Trie()

    for word in data:
        try:
            word = prepair_word(
                word.replace(' ',
                             '_').replace('-', '_').replace('\r', '').replace(
                                 '\u000D\u000A', '\n').replace('\u000D', '\n'))
            # replace spaces with _ and - with _
            t.insert(word)

        except:
            from termcolor import colored as color
            print(
                color(
                    'The following place can not be included in the search:{} from the file: {}'
                    .format(word, dataset), 'red'))
    return t
Ejemplo n.º 28
0
def error(errcode, message, exitcode=1, fail=False):
    if fail:
        statusFail()
    print(
        color("Error", "red") + ": " + message + " (code " + str(errcode) +
        ")")
    exit(exitcode)
Ejemplo n.º 29
0
def get_error(title, *args, **kwargs):
    template = '\n\n\t{title}{info}{tb}\n'
    info = '\n'.join(['\t' + l for l in args]) if args else ''
    highlight = kwargs['highlight'] if 'highlight' in kwargs else False
    tb = _get_traceback(kwargs['tb'], highlight) if 'tb' in kwargs else ''
    return template.format(title=color(title, 'red', attrs=['bold']),
                           info=info, tb=tb).encode('utf8')
Ejemplo n.º 30
0
def get_error(title, *args, **kwargs):
    template = '\n\n\t{title}{info}{tb}\n'
    info = '\n'.join(['\t' + l for l in args]) if args else ''
    highlight = kwargs['highlight'] if 'highlight' in kwargs else False
    tb = _get_traceback(kwargs['tb'], highlight) if 'tb' in kwargs else ''
    return template.format(title=color(title, 'red', attrs=['bold']),
                           info=info, tb=tb)
def tableValue(val):
    while (True):
        try:
            if (val == 'x'):
                x = input("Enter the x-values seperated by commas: ")
                x = x.replace(" ", "")
                x = x.split(",")
                x = [float(i) for i in x]
                return x
            elif (val == 'y'):
                y = input("Enter the y-values spereated by commas: ")
                y = y.replace(" ", "")
                y = y.split(",")
                y = [float(i) for i in y]
                return y
            else:
                decimal = input(
                    "Enter the amount of decimal points you would want to add: "
                )
                decimal = int(decimal)
                return decimal
        except:
            print("")
            print(color("Please enter numbers", "red"))
            print("")
            continue
        else:
            break
Ejemplo n.º 32
0
def _get_traceback(tb, highlight):
    template = '\n\n\t{title}\n\t{tb}'
    # Prune "check.py" from tb (hacky)
    tb = [record for record in tb if not record[0].endswith('check.py')]
    tb_range = tb[-5:-2]
    tb_list = [_format_traceback(p, l, fn, t, i, len(tb_range), highlight) for i, (p, l, fn, t) in enumerate(tb_range)]
    return template.format(title=color('Traceback:', 'blue', attrs=['bold']),
                           tb='\n'.join(tb_list).strip())
Ejemplo n.º 33
0
def _get_traceback(tb, highlight):
    template = '\n\n\t{title}\n\t{tb}'
    # Prune "check.py" from tb (hacky)
    tb = [record for record in tb if not record[0].endswith('check.py')]
    tb_range = tb[-5:-2]
    tb_list = [_format_traceback(p, l, fn, t, i, len(tb_range), highlight) for i, (p, l, fn, t) in enumerate(tb_range)]
    return template.format(title=color('Traceback:', 'blue', attrs=['bold']),
                           tb='\n'.join(tb_list).strip())
Ejemplo n.º 34
0
def get_datcol(strs, pstrs, noparse=False):
    dstrs = [x for x in pstrs if "Count" not in x]
    ext_col_strs = 'Select the data column(s):\n' + '\n'.join(dstrs)
    while True:
        try:
            ext_col_idx = parseNumList(input(ext_col_strs).rstrip())
        except ValueError:
            print(color("Input must be integer!\n", 'red'))
        else:
            if type(ext_col_idx) is list:
                print(color('You chose: ', 'green') + 'Multiple Columns')
            else:
                print(
                    color('You chose: ', 'green') + str(pstrs[ext_col_idx]) +
                    '\n')
            break
    return ext_col_idx
Ejemplo n.º 35
0
def hydra(service, accounts):
    login = []
    for i in accounts:
        cmd = ("hydra -l %s -e nsr %s" % (i, service)).split()
        p = Popen(cmd, stderr=PIPE, stdout=PIPE)
        output = p.communicate()[0].decode().rstrip().splitlines()
        for line in output:
            if "login" in line and "tries" not in line:
                print(color(line, "green"))
Ejemplo n.º 36
0
def play_game(text_list):
    remaining_guess = 4
    rand_text = choice(text_list)
    print(rand_text['author'])
    print("Here's the quote: ")
    guess = ''
    c = color(rand_text['text'], color="magenta")
    print(c)
    while guess.lower() != rand_text['author'] and remaining_guess > 0:
        guess = input(f"Guess The AUTHOR:{remaining_guess}")
        if guess.lower() == rand_text['author'].lower():
            print(f"YOU GODDAMN RIGHT")
            break
        remaining_guess -= 1
        if remaining_guess == 3:
            res = requests.get(f"{url}{rand_text['bio-link']}")
            soup = BeautifulSoup(res.text, "html.parser")
            born_date = soup.select_one(".author-born-date").get_text()
            born_location = soup.select_one(".author-born-location").get_text()
            colored_born = color(f"{born_date} {born_location}", color="blue")
            print(f"HINT: {colored_born}")
        elif remaining_guess == 2:
            first_char = color(
                f"First Name char: {rand_text['author'][0]}.",
                color="red")
            print(f"HINT: {first_char}")
        elif remaining_guess == 1:
            spl = rand_text["author"].split(" ")
            initials = color(
                f"Initials: {spl[0][0]}.{spl[1][0]}.",
                color="yellow")
            print(f"HINT: {initials}")
        elif remaining_guess == 0:
            print(f"You ran out of HINT :((")
            # if yes == "y"
        else:
            break

    again = input("Would You Like To Play Again:")
    str_again = ["yes", "y", "Yes"]
    if again.lower() in str_again:
        return play_game(text_list)
    else:
        print("OK BYEEEEE.........")
Ejemplo n.º 37
0
def get_volcol(strs, pstrs, noparse=False):
    vstrs = [x for x in pstrs if "Voxel:" in x]  # Not sure if centroid needed
    vol_col_strs = 'Select the \'volume\' column: \n' + '\n'.join(vstrs)
    if len(vstrs) > 1:
        while True:
            vol_col_idx = input(vol_col_strs).rstrip()
            try:
                vol_col_idx = int(vol_col_idx) - 1
            except ValueError:
                print(color("Input must be integer!\n", 'red'))
            else:
                break
    elif len(vstrs) == 1:
        vol_col_idx = vstrs[0]
    else:
        print(color('No volume columns identified: Exiting', 'red'))
        sys.exit()
    print(color('You chose: ', 'green') + strs[vol_col_idx] + '\n')
    return vol_col_idx
Ejemplo n.º 38
0
def print_winning_board(board,tuples,turn):
	for r in range(BOARD_HEIGHT + 1):
		row = '|'
		for c in range(BOARD_WIDTH):
			if [r,c] in tuples:
				if (turn == 0):
					row += (' '+color('X',X_COLOR)+' |')
				else:
					row += (' '+color('O',O_COLOR)+' |')
			elif (board[r][c] == 0):
				row += '   |'
			elif (board[r][c] == 3):
				row += ' 0 |'
				LAST_MOVE = [r,c]
			elif (board[r][c] == 2):
				row += ' X |'
				LAST_MOVE = [r,c]
			else:
				row += (' ' + BOTTOM_LABELS[c] + ' |')
		print color(row,'white')
Ejemplo n.º 39
0
def count_objects(args):
    """ Count the number of objects """
    global counter
    with counter.get_lock():
        counter.value += 1

    f, nfiles, band = args
    print_running(counter.value, nfiles, indent=4, step=1)

    fits = fitsio.FITS(f, 'r')
    num = fits[1].get_nrows()
    hpx = (fits[1].read_header().get('HPX') is not None)
    fits.close()

    # Ignore low numbers of objects in pixelized files
    if (not hpx) and (num < 5e3 if band == 'Y' else num < 1e4):
        msg = "Only %i objects in %s" % (num, f)
        print color(msg, 'yellow')

    return num
Ejemplo n.º 40
0
def get_file(nolists=False, noparse=False, infolder='../input/'):
    fn_prompt_strs = []
    os.chdir(infolder)
    files = glob.glob('*.csv')
    files.sort()
    for i in range(0, len(files)):  # creates prompt string: choice component
        fn_prompt_strs.append(str(i + 1) + ' - ' + files[i])
    if noparse == False:
        fn_strs = 'Select the file to analyze:\n' + '\n'.join(fn_prompt_strs)
    elif noparse == True:
        print('All files in input directory:\n' + '\n'.join(fn_prompt_strs))
        return
    while True:
        try:
            file_path_idx = parseNumList(input(fn_strs).rstrip())
            if (nolists == True) and (type(file_path_idx) is list):
                if len(file_path_idx) != 1:
                    print(
                        color(
                            'Lists are not permitted in this mode, defaulting to first list item',
                            'red'))
                file_path_idx = file_path_idx[0]

            break
        except ValueError:
            print(color("Input must be integer!\n", 'red'))
    if type(file_path_idx) is not int:
        print(color('You chose: ', 'green') + 'multiple files' + '\n')
        file_path = []
        file_name = []
        for i in file_path_idx:
            file_path.append(infolder + files[i])
            mfile_name = files[i]
            mfile_name = mfile_name[:-4]
            file_name.append(mfile_name)
    else:
        print(color('You chose: ', 'green') + files[file_path_idx] + '\n')
        file_path = infolder + files[file_path_idx]
        file_name_ = files[file_path_idx]
        file_name = file_name_[:-4]
    return file_path, file_name
Ejemplo n.º 41
0
    def writeout(self):

        binout = self.realbins[1:]
        ostr = [self.extstr, 'Counts', 'Volume']
        odat = np.column_stack([binout, self.counts, self.volbinsums])
        out = np.vstack([ostr, odat])
        with open('../output/' + self.current_file_name + '_output.csv',
                  'w') as csvout:
            outputwriter = csv.writer(csvout, delimiter=',')
            outputwriter.writerows(out)
            print(color("Plot saved as output.csv", 'green') + '\n')
        return
Ejemplo n.º 42
0
def main():
  '''Wrapper'''

  #
  # Setting up configuration: dev = development; prod = production.
  #
  p = LoadConfig('config/config.json')
  if p is not False:

    print('--------------------------------------------------')
    print('%s HDX Site: %s' % (I('bullet'), p['hdx_site']))

    #
    # Deleting all datasets from org.
    #
    if p['delete_datasets']:
      try:
        delete.DeleteAllDatasetsFromOrg(organization='un-operational-satellite-appplications-programme-unosat', hdx_site=p['hdx_site'], apikey=p['hdx_key'], verbose=p['verbose'])

      except Exception as e:
        print(e)
        return False

    try:
      #
      # Loading JSON data.
      #
      dataset_dict = load.LoadData(os.path.join(p['json_folder'], 'datasets.json'))
      resource_dict = load.LoadData(os.path.join(p['json_folder'], 'resources.json'))
      # gallery_dict = load.LoadData(os.path.join(p['json_folder'], 'gallery.json'))

      # Delete resources before running:
      if p['delete_resources']:
        delete.DeleteResources(dataset_dict=dataset_dict, hdx_site=p['hdx_site'], apikey=p['hdx_key'], verbose=p['verbose'])

      if p['update_all_datasets']:
        print('--------------------------------------------------')
        print(color(u" ATTENTION:", "blue", attrs=['bold']) + ' Updating ALL datasets.')
        print('--------------------------------------------------')

      #
      # Create datasets, resources, and gallery items.
      #
      create.CreateDatasets(dataset_dict=dataset_dict, hdx_site=p['hdx_site'], apikey=os.getenv('HDX_KEY'), verbose=p['verbose'], update_all_datasets=p['update_all_datasets'])
      create.CreateResources(resource_dict=resource_dict, hdx_site=p['hdx_site'], apikey=os.getenv('HDX_KEY'), verbose=p['verbose'], update_all_datasets=p['update_all_datasets'])
      # create.CreateGalleryItems(gallery_dict=gallery_dict, hdx_site=p['hdx_site'], apikey=os.getenv('HDX_KEY'), verbose=p['verbose'], update_all_datasets=p['update_all_datasets'])

    except Exception as e:
      print(e)
      return False
Ejemplo n.º 43
0
def downloader(url):
    """
    Takes --url as input and downloads the song from the url
    """
    if not Noodle.is_valid_url(url):
        if url == "":
            msg = termcolor.colored("Enter url with --url paramater :)", 'red')
            click.echo(msg)
        else:
            err_msg = termcolor.colored("Invalid URL format! -__- ", "red")
            click.echo(err_msg)
    else:
        #Strip the URL from any white spaces
        app = Noodle(url.strip())
        if not app.download_link:
            err = termcolor.colored("Sorry, it's copyrighted! :(", "blue")
            click.echo(err)
        else:
            msg = termcolor.color("Here's the link :) : \n", "yellow")
            click.echo(msg)
            click.echo(app.download_link)
            #Opens the download link in users browser
            webbrowser.open(app.download_link)
Ejemplo n.º 44
0
def item(i):
  '''Adding formatting elements to stdout.'''

  dictionary = {
    'bullet_red': color(" →", "red", attrs=['bold']),
    'bullet_green': color(" →", "green", attrs=['bold']),
    'prompt_error':  color(" ERROR:", "red", attrs=['bold']),
    'prompt_bullet': color(" →", "blue", attrs=['bold']),
    'prompt_success': color(" SUCCESS:", "green", attrs=['bold']),
    'prompt_warn': color(" WARN:", "yellow", attrs=['bold'])
  }

  #
  # Checking for the key.
  #
  if i not in dictionary.keys():
    print '>>> The item formatted you are looking for is not present.'
  else:
    return dictionary[i]
Ejemplo n.º 45
0
def rate():
    BASE_URL = "http://www.rottentomatoes.com/m/"
    MOVIES_DIR = "path_to_folder_containing_movies"

    # get the movie directory path via command line arguments
    args = len(sys.argv)
    if args > 1:
        if os.path.exists(sys.argv[1]):
            movies = os.listdir(sys.argv[1])
        else:
            sys.exit("Impossible to find the folder, check the path again")
    else:
        sys.exit("Usage: movie_rater.py [path to folder containing movies]")
        # movies = os.listdir(MOVIES_DIR)

    rank_file = open(str(sys.argv[1]) + "/" + "Rottent Tomatoes.txt", "a")
    csv_file = open(str(sys.argv[1]) + "/" + "Movies details.csv", "w", newline="")
    csv_w = csv.writer(csv_file, delimiter=",")
    t = [["Movies", "Rotten Tomatoes %", "Cast", "Critics"]]  # the title (optional)
    csv_w.writerows(t)

    # table like display
    print("\n" + "-" * 72)
    print(Fore.RED + " ROTTEN TOMATOES %" + Fore.WHITE + " |		 	MOVIES 				 				")
    print("-" * 72)
    print("		   |")

    for m in movies:
        m = m.replace(" ", "_").replace("'", "")  # replace spaces w/ _ and ' w/ nothing
        # this allow me to get only the name, not the extension
        name = m.split(".")

        req = r.get(BASE_URL + str(name[0]))
        cont = req.content
        html = bs(cont, "html.parser")
        elem = html.find("span", attrs={"itemprop": "ratingValue"})
        critic = html.find("p", attrs={"class": "critic_consensus"})
        cast = html.find("div", attrs={"class": "media-body"})

        # Make a nice command line display of the results
        colors = ["green", "yellow", "red"]

        try:
            # write in a csv file
            d = [[str(name[0]), str(elem.get_text()), str(cast.get_text()), str(critic.get_text())]]
            csv_w.writerows(d)

            # color the result in green, yellow or red according to its % and display it table like

            if int(elem.get_text()) > 70:
                print(" " + color(str(elem.get_text()), colors[0]) + "%		   |			" + str(name[0]))
                # print(str(critic.get_text())+"\n"+"-"*72)
            elif int(elem.get_text()) < 70 and int(elem.get_text()) > 40:
                print(" " + color(str(elem.get_text()), colors[1]) + "%		   |			" + str(name[0]))
                # print(str(critic.get_text())+"\n"+"-"*72)
            elif int(elem.get_text()) < 40:
                print(Style.BRIGHT + " " + color(str(elem.get_text()), colors[2]) + "%		   |			" + str(name[0]))
                # print(str(critic.get_text())+"\n"+"-"*72)

            rank_file.write(str(name[0]) + " [" + str(elem.get_text()) + "]\n")

        except:
            print(" " + color(":(", "grey", attrs=["bold"]) + "		   |			" + str(name[0]))
            err = str(name[0]) + " [not rated :/]"
            rank_file.write(err + "\n")

    rank_file.close()
Ejemplo n.º 46
0
def getDatasetListforTag(tag = None, l = None, verbose = False):

	if tag is None:
		print "Please provide tag."
		return

	if l is None:
		print "I need a CSV path, e.g. data/data.csv"
		return

	print "----------------------------------"

	u = "https://data.hdx.rwlabs.org/api/action/tag_show?id=" + tag
	d = r.get(u).json()

	if d["success"] is False:
		m = color("ERROR", "red", attrs=['bold'])
		print "%s : %s" % (m, d["error"]["message"])
		return

	if d["success"] is True:
		m = color("SUCCESS", "green", attrs=['bold'])
		n = color(len(d["result"]["packages"]), "blue", attrs=['dark'])
		print "%s : processing %s records." % (m, n)

        f = csv.writer(open(l, "wb+"))
        
        # Write headers.
        f.writerow(["title", "name", "owner_org", "maintainer", "revision_timestamp", "id", "num_resources", "num_tags", "num_extras"])
        
        # Write records.
        record_counter = 0
        for dataset in d["result"]["packages"]:
			record_counter += 1
			try:
                            row = [
			    	dataset["title"],
			    	dataset["name"],
			    	dataset["owner_org"],
			    	dataset["maintainer"],
			    	dataset["maintainer_email"],
			    	dataset["metadata_modified"],
			    	dataset["id"],
			    	dataset["num_resources"],
			    	dataset["num_tags"],
			    	len(dataset["extras"])
			    	]
                            row = [unicode(x).encode('utf-8') for x in row]
                            f.writerow(row)

			except Exception as e:
				err = color("ERROR", "red", attrs=['bold'])
				rec = color(record_counter, "yellow", attrs=['bold'])
				print "%s : record %s failed to write." % (err, rec)
				f.writerow([
			    	"NA",
			    	"NA",
			    	"NA",
			    	"NA",
			    	"NA",
			    	"NA",
			    	"NA",
			    	"NA",
			    	"NA",
			    	"NA"
			    	])

				# Printing more detailed error messages.
				if verbose is True:
					print e
                                raise

	print "----------------------------------"
	print "************* %s ***************" % (color("DONE", "blue", attrs=['blink','bold']))
	print "----------------------------------"
Ejemplo n.º 47
0
# #!/usr/bin/python
# # -*- coding: utf-8 -*-

import sys
import run_scheduler
from termcolor import colored as color

__version__ = "v.0.2.2"

#
# Run the scheduler.
#
if __name__ == '__main__':

  print '--------------------------'
  print '|    %s    |' % color("ROLLTIME COLLECT", "blue", attrs=['bold'])
  print '|       [ %s ]      |' % color(__version__, "yellow", attrs=['bold'])
  print '--------------------------'

  run_scheduler.RunScheduler()
Ejemplo n.º 48
0
from cap_man import abuse
from database import log,get_log
from myemailc import mail_send

BOLD = "\033[1m"   #use to bold the text
END = "\033[0m"    #use to close the bold text
CLIENT_ACCESS_TOKEN = '__key__'
ai = apiai.ApiAI(CLIENT_ACCESS_TOKEN)


try:
    r = sr.Recognizer()
#    r.energy_threshold = 3500
    with sr.Microphone() as source:
        call(['clear'])
        print(color(f'�� {BOLD}Hola!\n�� Ask me anything.{END}',"green"))
        while True:
            r.adjust_for_ambient_noise(source)
            audio = r.listen(source)

#	while True:	
            try:
                query = r.recognize_google(audio)
    			
                print(color(f'                                 {BOLD}{query}{END}\n','red'))
                if '*' in query:
                    abuse(query)
                
                log(query)
                request = ai.text_request()
                request.query = query  
Ejemplo n.º 49
0
def _format_user_error(text, i, highlight):
    template = '\n\t  {sp} {t}'
    spacing = '  '*i + color(' >>>', 'red')
    if highlight:
        text = text.replace(str(highlight), color(str(highlight), 'yellow'))
    return template.format(sp=spacing, t=text)