Exemple #1
0
def print_leaderbord(members, mode='star'):
    print ' '.ljust(28)+'  '.join(i for i in map(str, xrange(1, 10)))+' '+' '.join(i for i in map(str, xrange(10, 26))) + '  Total  Diff   G' + '\n'+'-'*120

    leaderboard_rank = sorted(members.itervalues(
    ), key=lambda y: y['local_score'], reverse=True)

    for j, member in enumerate(leaderboard_rank):
        if j == 0:
            top = member['local_score']
        if member['stars']:
            name = member['name'] if member['name'] else 'Anonymous'
            print str(j+1).ljust(2, ' ') + ' ' + name.ljust(24, ' '),
            for day in map(str, xrange(1, 26)):
                if day in member['completion_day_level']:
                    if mode == 'star':
                        if len(member['completion_day_level'][day].keys()) == 1:
                            print blue('~ ', bg='black'),
                        elif len(member['completion_day_level'][day].keys()) == 2:
                            print yellow('* ', bg='black'),
                    elif mode == 'pos':
                        pos = position_in_leaderboard(
                            leaderboard_rank, member['id'], day)
                        if pos:
                            if pos == '1':
                                print yellow(pos.ljust(2, ' ')),
                            elif pos in ['2', '3']:
                                print blue(pos.ljust(2, ' '), bg='black'),
                            else:
                                print pos.ljust(2, ' '),
                else:
                    print '  ',
            print str(member['local_score']).ljust(6, ' '),
            print str(top-member['local_score']).ljust(6, ' '),
            print member['global_score']
Exemple #2
0
def libs():
    verb = input("Type in a verb: ")
    word_list.append(verb)

    noun = input("Type in a noun: ")
    word_list.append(noun)

    pronoun = input("Type in a pronoun: ")
    word_list.append(pronoun)

    adjective = input("Type in an adjective: ")
    word_list.append(adjective)

    print(red('verb:red'))
    print(green('noun:green'))
    print(blue('pronoun:blue'))
    print(yellow('adjective:yellow'))

    print("I {} some {} then I've seen {}. I didn't realize it's {}".format(
        red(verb), green(noun), blue(pronoun), yellow(adjective)))

    inputs = input('Enter R to show results: ')

    if inputs == 'r' or inputs == 'R':
        for list_item in word_list:
            print(magenta(list_item))
Exemple #3
0
  def console_output(self, targets):
    buildfile_aliases = self.context.build_file_parser.registered_aliases()
    extracter = BuildDictionaryInfoExtracter(buildfile_aliases)

    alias = self.get_options().details
    if alias:
      target_types = buildfile_aliases.target_types_by_alias.get(alias)
      if target_types:
        tti = next(x for x in extracter.get_target_type_info() if x.build_file_alias == alias)
        yield blue('\n{}\n'.format(tti.description))
        yield blue('{}('.format(alias))

        for arg in extracter.get_target_args(list(target_types)[0]):
          default = green('(default: {})'.format(arg.default) if arg.has_default else '')
          yield '{:<30} {}'.format(
            cyan('  {} = ...,'.format(arg.name)),
            ' {}{}{}'.format(arg.description, ' ' if arg.description else '', default))

        yield blue(')')
      else:
        yield 'No such target type: {}'.format(alias)
    else:
      for tti in extracter.get_target_type_info():
        description = tti.description or '<Add description>'
        yield '{} {}'.format(cyan('{:>30}:'.format(tti.build_file_alias)), description)
Exemple #4
0
    def console_output(self, targets):
        buildfile_aliases = self.context.build_configuration.registered_aliases(
        )
        extracter = BuildDictionaryInfoExtracter(buildfile_aliases)

        alias = self.get_options().details
        if alias:
            tti = next(x for x in extracter.get_target_type_info()
                       if x.symbol == alias)
            yield blue("\n{}\n".format(tti.description))
            yield blue("{}(".format(alias))

            for arg in tti.args:
                default = green("(default: {})".format(arg.default) if arg.
                                has_default else "")
                yield "{:<30} {}".format(
                    cyan("  {} = ...,".format(arg.name)),
                    " {}{}{}".format(arg.description,
                                     " " if arg.description else "", default),
                )

            yield blue(")")
        else:
            for tti in extracter.get_target_type_info():
                yield "{} {}".format(cyan("{:>30}:".format(tti.symbol)),
                                     tti.description)
Exemple #5
0
def get_repos():
    """ Checks if $newrepo exists and bails out if it does, otherwise returns all the repos"""
    page = 1
    repos = []
    while (page != 0):
        param = {'page_size': 1000, 'page': page}
        try:
            r = requests.get(base_url + "/repositories/" + org + "/",
                             headers=token,
                             params=param)
            r.raise_for_status()
        except requests.exceptions.HTTPError as err:
            print red("Retrieving repos failed: {}").format(err)
            sys.exit(1)
        readable_json = r.json()
        next_page = str(r.json()['next'])
        for i in readable_json['results']:
            repos.append(str(i['name']))
        if (next_page != "None"):
            page += 1
        else:
            page = 0
    print "Found %s repositories" % (len(repos))
    if new_repo in repos:
        print green("Repository {0} already exists.").format(new_repo)
        sys.exit()
    else:
        print blue("Repo doesn't exist.")
    return repos
Exemple #6
0
def query_yes_no(question, default="yes"):
    """Ask a yes/no question via raw_input() and return their answer.

    "question" is a string that is presented to the user.
    "default" is the presumed answer if the user just hits <Enter>.
        It must be "yes" (the default), "no" or None (meaning
        an answer is required of the user).

    The "answer" return value is True for "yes" or False for "no".
    """
    valid = {"yes": True, "y": True, "ye": True, "no": False, "n": False}
    if default is None:
        prompt = " [" + blue("y") + "/" + red("n") + "] "
    elif default == "yes":
        prompt = " [" + blue("Y") + "/" + red("n") + "] "
    elif default == "no":
        prompt = " [" + blue("y") + "/" + red("N") + "] "
    else:
        raise ValueError("invalid default answer: '%s'" % default)

    while True:
        sys.stdout.write(question + prompt)
        choice = raw_input().lower()
        if default is not None and choice == '':
            return valid[default]
        elif choice in valid:
            return valid[choice]
        else:
            sys.stdout.write("Please respond with 'yes' or 'no' "
                             "(or 'y' or 'n').\n")
Exemple #7
0
    def console_output(self, targets):
        buildfile_aliases = self.context.build_configuration.registered_aliases(
        )
        extracter = BuildDictionaryInfoExtracter(buildfile_aliases)

        alias = self.get_options().details
        if alias:
            tti = next(x for x in extracter.get_target_type_info()
                       if x.symbol == alias)
            yield blue('\n{}\n'.format(tti.description))
            yield blue('{}('.format(alias))

            for arg in tti.args:
                default = green('(default: {})'.format(arg.default) if arg.
                                has_default else '')
                yield '{:<30} {}'.format(
                    cyan('  {} = ...,'.format(arg.name)),
                    ' {}{}{}'.format(arg.description,
                                     ' ' if arg.description else '', default))

            yield blue(')')
        else:
            for tti in extracter.get_target_type_info():
                yield '{} {}'.format(cyan('{:>30}:'.format(tti.symbol)),
                                     tti.description)
Exemple #8
0
    def console_output(self, targets):
        buildfile_aliases = self.context.build_file_parser.registered_aliases()
        extracter = BuildDictionaryInfoExtracter(buildfile_aliases)

        alias = self.get_options().details
        if alias:
            target_types = buildfile_aliases.target_types_by_alias.get(alias)
            if target_types:
                tti = next(x for x in extracter.get_target_type_info()
                           if x.build_file_alias == alias)
                yield blue('\n{}\n'.format(tti.description))
                yield blue('{}('.format(alias))

                for arg in extracter.get_target_args(list(target_types)[0]):
                    default = green('(default: {})'.format(arg.default) if arg.
                                    has_default else '')
                    yield '{:<30} {}'.format(
                        cyan('  {} = ...,'.format(arg.name)),
                        ' {}{}{}'.format(arg.description,
                                         ' ' if arg.description else '',
                                         default))

                yield blue(')')
            else:
                yield 'No such target type: {}'.format(alias)
        else:
            for tti in extracter.get_target_type_info():
                description = tti.description or '<Add description>'
                yield '{} {}'.format(
                    cyan('{:>30}:'.format(tti.build_file_alias)), description)
Exemple #9
0
def handleRosters(year, rosters):
    for roster in rosters:
        print blue("ROSTER: " + roster)
        r = requests.get(BASE_URL + roster)
        s = BeautifulSoup(r.text)
        teams = s.find_all("li")
        if teams:
            handleEntries(year, [li.contents[0] for li in teams])
Exemple #10
0
def directorios(req, target, verbose, archivo, lista, envio):
    #print envio
    dirs = [
        '/includes/', '/misc/', '/modules/', '/profiles/', '/scripts/',
        '/sites/', '/includes/', '/themes/', '/robots.txt', '/xmlrpc.php',
        '/CHANGELOG.txt', '/core/CHANGELOG.txt'
    ]
    i = 0
    print colors.green(
        '\n[***] ') + ' Directorios y archivos:\n' if verbose else '',
    lista.append("<strong>Directorios y archivos</strong></br>")
    lista.append("<ul>")
    for d in dirs:
        try:
            i += 1
            print colors.blue('[*] ') + "=> Respuesta(" + str(
                req.get(target + d).status_code) + ") para %s \n" % (
                    target + d) if verbose else '',
            lista.append(
                "<li><a href='%s'>%s </a><strong>Respuesta: %s</strong></li>" %
                (target + d, target + d, str(req.get(target + d).status_code)))
        except Exception as e:
            print e
            print colors.red(
                '[*] '
            ) + "=> Hubo un problema al intentar acceder a %s, posible redireccionamiento \n" % (
                target + d) if verbose else '',
    lista.append('</ul>')
    if i == 0:
        print colors.green(
            '\t[*] '
        ) + 'Wow! no tiene directorios comunes de drupal expuestos o incluso indicios de su existencia!'
        lista.append(
            "<p>Wow! no tiene directorios comunes de drupal expuestos o incluso indicios de su existencia!</p>"
        )

    lista.append('<strong>LOGIN: </strong><br/>')
    if req.get(target +
               '/user/login').status_code == 200 and 'password' in req.get(
                   target + '/user/login').text:
        print colors.green(
            '\n[**] '
        ) + "Pagina para ingreso de usuarios:\n\t %s/user/login\n" % target if verbose else '',
        lista.append('<p><a href="%s">%s</p>' %
                     (target + '/user/login', target + '/user/login'))
    elif req.get(target + '/?q=user/login'
                 ).status_code == 200 and 'password' in req.get(
                     target + '/?q=user/login').text:
        print colors.green(
            '\n[**] '
        ) + "Pagina para ingreso de usuarios:\n\t %s/?q=user/login\n" % target if verbose else '',
        lista.append('<p><a href="%s">%s</a></p>' %
                     (target + '/?q=user/login', target + '/?q=user/login'))

    reportes.listado(archivo, lista)
    if envio:
        reportes.vuln(archivo, envio)
Exemple #11
0
def program(sharefile, config):

	target_month = raw_input('[VHL ROBOT] Enter target month: ')

	team_leaders = [leader for leader in sharefile.list('Team Leaders/Monthly Paperwork')]
	if not team_leaders:
		print(red('[VHL ROBOT] Could not find team leader files. Quitting.'))
		return

	alphabet_segments = sharefile.list('Dependent E-Files')
	alphabet_segments = {key: value for key, value in alphabet_segments.iteritems() if len(key) == 3}

	for indexed_team_leader in enumerate(team_leaders):
		print('[VHL ROBOT] [%d] %s' % indexed_team_leader)

	input_recognized = False
	while not input_recognized:
		indices = raw_input('[VHL ROBOT] Enter team leaders (space separated), or Ctrl-C to quit: ')
		try:
			indices = [int(index) for index in indices.rstrip().split(' ')]
			input_recognized = True
		except:
			print(red('[VHL ROBOT] Could not parse input...'))

	for index in indices:
		target_folder = 'Team Leaders/Monthly Paperwork/%s/%s' % (team_leaders[index], target_month)
		print('[VHL ROBOT] Searching "%s"' % target_folder)

		month = sharefile.list(target_folder)
		for filename in month:

			if filename.find('VHL') == -1:
				print(blue('[VHL ROBOT] "%s" does not seem to be a VHL file' % filename))
				continue

			try:
				pieces = filename.split()
				if not (len(pieces) == 4):
					raise Error
				child_name = pieces[2]
				print('[VHL ROBOT] "%s" is a VHL file for child %s' % (filename, child_name))
			except:
				print(blue('[VHL ROBOT] "%s" might be a VHL file with a nonstandard name. Ignoring it.' % filename))
				continue

			found = False
			for segment in alphabet_segments:
				range_pair = segment.split('-')
				if child_name[0] >= range_pair[0] and child_name[0] <= range_pair[1]:
					found = True
					item = filename
					source = 'Team Leaders/Monthly Paperwork/%s/%s' % (team_leaders[index], target_month)
					destination = 'Dependent E-Files/%s/%s/CASA Internal Documents' % (segment, child_name[:-1] + ' ' + child_name[-1])
					sharefile.copy(item, source, destination, ' '.join(filename.split()[1:]))
			if not found:
				print(red('[VHL ROBOT] Could not alphabetize %s in %s', child_name, str(alphabet_segments)))
Exemple #12
0
def check_fuel():
    global player_pos
    global fuel
    if player_pos == blue("3"):
        fuel += 3
        player_pos = "O"
    if player_pos == blue("5"):
        fuel += 5
        player_pos = "O"
    if player_pos == blue("6"):
        fuel += 6
        player_pos = "O"
Exemple #13
0
def get_potion(amt):
	global potion
	if amt > 0:
		print blue("+++%s POTIONS+++" % amt)
		potion += amt
		for pots in range(amt):
			bp.append('potion')
	else:
		print "%s takes a " % name + bold(blue("POTION"))
		health(30)
		potion -= 1
		bp.remove('potion')
Exemple #14
0
def health(hit):
	global healthp
	if hit > 0:
		print blue("\nPLUS %d health!" % hit)
		healthp += hit
		print "HEALTH: %d\n" % healthp
	elif hit == 0:
		print "\nHEALTH: %d\n" % healthp
	else:
		time.sleep(1)
		print red("%s takes %d DAMAGE!\n") % (name, hit)
		healthp += hit
		if healthp <= 0:
			die('%s takes a mortal BLOW!' % name)
			sys.exit(0)
Exemple #15
0
def read_chat_history():

    read_for = select_a_friend()
    #chat history function will give a history of chat messages and the time.

    for chat in friends[read_for].chats:

        if chat.send_by_me:

            print '[%s] %s: %s' % (chat.time.strftime(
                blue('%d %Y %B')), red('you_said'), chat.message)

        else:
            print '[%s] %s: %s' % (chat.time.strftime(
                blue('%d %Y %B')), red(friends[read_for].name), chat.message)
Exemple #16
0
 def printBiomeMap(self):
     for y in range(0, self.height):
         print("")
         for x in range(0, self.width):
             if (self.tiles[x][y].settlement != None):
                 sys.stdout.write(
                     color(self.tiles[x][y].settlement.type,
                           self.tiles[x][y].colorX))
             elif (self.tiles[x][y].color == "cyan"):
                 sys.stdout.write(cyan(self.tiles[x][y].biome))
             elif (self.tiles[x][y].color == "white"):
                 sys.stdout.write(white(self.tiles[x][y].biome))
             elif (self.tiles[x][y].color == "green"):
                 sys.stdout.write(green(self.tiles[x][y].biome))
             elif (self.tiles[x][y].color == "yellow"):
                 sys.stdout.write(yellow(self.tiles[x][y].biome))
             elif (self.tiles[x][y].color == "blue"):
                 sys.stdout.write(blue(self.tiles[x][y].biome))
             elif (self.tiles[x][y].color == "magenta"):
                 sys.stdout.write(magenta(self.tiles[x][y].biome))
             elif (self.tiles[x][y].color == "red"):
                 sys.stdout.write(red(self.tiles[x][y].biome))
             elif (self.tiles[x][y].colorX != None):
                 sys.stdout.write(
                     color(self.tiles[x][y].biome, self.tiles[x][y].colorX))
             else:
                 sys.stdout.write(self.tiles[x][y].biome)
Exemple #17
0
 def check_config(self):
     if os.path.isfile("config.json"):
         print(green("> Config found!"))
     else:
         print(blue("> Config not found! Creating one.."))
         self.create_config()
         print(green("> Config created!"))
Exemple #18
0
def driveinit():
    creds = None
    SCOPES = [
        'https://www.googleapis.com/auth/drive.readonly',
        'https://www.googleapis.com/auth/userinfo.profile', 'openid',
        'https://www.googleapis.com/auth/userinfo.email'
    ]
    if os.path.exists('token.pickle'):
        with open('token.pickle', 'rb') as token:
            creds = pickle.load(token)
    # If there are no (valid) credentials available, let the user log in.
    if not creds or not creds.valid:
        if creds and creds.expired and creds.refresh_token:
            creds.refresh(Request())
        else:
            flow = InstalledAppFlow.from_client_secrets_file(
                'credentials.json', SCOPES)
            creds = flow.run_local_server(port=0)
        # Save the credentials for the next run
        with open('token.pickle', 'wb') as token:
            pickle.dump(creds, token)
    service = build('drive', 'v3', credentials=creds)

    user_service = build('oauth2', 'v2', credentials=creds)
    info = user_service.userinfo().get().execute()
    print("Accessing drive of user {} <{}>".format(blue(bold(info['name'])),
                                                   info['email']))

    return service
Exemple #19
0
    def status(self):
        for content in self.get_esxi_hosts():
            host = get_host_view(content)[0]
            for health in host.runtime.healthSystemRuntime.systemHealthInfo.numericSensorInfo:
                print_status_info(health)

            print_status_info(host.runtime.healthSystemRuntime.
                              hardwareStatusInfo.memoryStatusInfo[0])
            print_status_info(host.runtime.healthSystemRuntime.
                              hardwareStatusInfo.cpuStatusInfo[0])

            print "%s (%s)\n\t%s\n\tCPU: %s\n\tRAM: %s" % (
                blue(host.name), content.about.fullName, get_tags(host),
                get_cpu_info(host), get_mem_info(host))

            datastores = content.viewManager.CreateContainerView(
                content.rootFolder, [vim.Datastore], True).view
            for datastore in datastores:
                summary = datastore.summary
                ds_capacity = summary.capacity
                ds_freespace = summary.freeSpace
                ds_uncommitted = summary.uncommitted if summary.uncommitted else 0
                ds_provisioned = ds_capacity - ds_freespace + ds_uncommitted
                ds_used = ds_capacity - ds_freespace
                ds_overp = ds_provisioned - ds_capacity
                ds_overp_pct = (ds_overp * 100) / ds_capacity \
                    if ds_capacity else 0
                desc = "\t{}: used {} of {}".format(summary.name,
                                                    format_space(ds_used),
                                                    format_space(ds_capacity))
                desc += get_colored_percent(
                    float(ds_used) / float(ds_capacity) * 100)
                if ds_provisioned > ds_capacity:
                    desc += " %.0f%% over-provisioned" % ds_overp_pct
                print desc
Exemple #20
0
def get_chest():	
	global triangle
	global square
	global healthp
	global chest
	comb = ['2', '4', '1', '3']
	ans = []
	print "The chest is locked and has four colored switches on it:\n"
	print green("[1GREEN]"), yellow("[2YELLOW]"), red("[3RED]"), blue("[4BLUE]\n")
	for nums in comb:
		press = raw_input('Which switch should %s press? ' % name)
		ans.append(press)
	if ans == comb:
		pause('+++')
		print "The chest suddenly pops open! There is a hexagon key and a triangle key...\n"
		choo = raw_input('Which one should %s take? ' % name)
		if choo in ('t', 'triangle', 'the triangle'):
			pause('...')
			print "%s takes the triangle shaped key and the chest snaps shut!\n" % name
			triangle = True
			chest = False
		elif choo in ('h', 'hexagon', 'the hexagon'):
			pause('...')
			print "%s takes the hexagon shaped key and the chest snaps shut!\n" % name
			square = True
			chest = False
		else:
			pause('...')
			print "The chest snaps shut!\n"
			get_chest()
	else:
		print "\nThe chest shocks %s!" % name
		health(-10)
		room2()
Exemple #21
0
def main():
    print(
        colors.blue(
            ' ________________________\n|SK-WifiDeath ' + ver +
            '       |\n| Written By Skittles_  |\n|       ssssssss        |\n|    sss        sss     |\n| ss     sssss      ss  |\n|    ssss     ssss      |\n|         sss           |\n|          _            |\n|_________|S|___________|'
        ))
    print('')
    print('')
    selectionFromMenu = input(
        colors.white(
            'What would you like to do?\n'
            '1)Deauth a client\n2)Deauth an Access Point\nE)Exit WifiDeath\nSKWD>'
        ))

    if selectionFromMenu == '1':
        system('clear')
        print('OK, Client Deauth.')
        deauth.wifiDeauthClient()
        mainMenu()

    elif selectionFromMenu == '2':
        print('OK, AP Deauth.')
        deauth.wifiDeauthAP()
        mainMenu()
    elif selectionFromMenu == 'E':
        sys.exit()
    else:
        if name == 'nt':
            system('cls')
        else:
            system('clear')
        mainMenu()
def do_commands(lines):
    for line in lines:
        sys.stdout.write(colors.blue(prompt))
        type_it_out(line)
        time.sleep(0.5)
        print
        os.system(colors.strip_color(line))
Exemple #23
0
 def readSMS(self):
     self.configure()
     messages = []
     self.sendCmd(b'AT+CMGL="REC UNREAD"')
     smsData = self.normalizedRecv()
     logPrint("SMS data: " + colors.green(smsData))
     for l in smsData:
         if l.startswith(b'OK'):
             break
         if l.startswith(b'ERROR'):
             break
         if l.startswith(b'+CMGL: '):
             # +CMGL: 6,"REC UNREAD","002B003900370032003500300035003200330037003800300039",,"" 0054006500730074
             smsInfo = l[len(b'+CMGL: '):].split(b',')
             smsId = int(smsInfo[0])
             smsSender = smsInfo[2].replace(b'"', b'')
             smsSender = binascii.unhexlify(smsSender).decode('utf-16be')
             continue
         try:
             msg = binascii.unhexlify(l).decode('utf-16be')
         except:
             continue
         logPrint("%d: %s sent: %s (%s)" % (smsId, smsSender, l, msg))
         messages.append((smsSender, msg))
     # Delete all stored SMS
     self.sendCmd(b'AT+CMGDA="DEL ALL"')
     self.sendCmd(b'AT+CMGD=0,4')
     deleteResult = self.recv()
     if self.verbose:
         logPrint(colors.blue(deleteResult.decode('utf8')))
     return messages
Exemple #24
0
    def print_stat_bar(self):
        """Print the HP, MP, and XP bars, with some nice coloring."""
        current_hp = int(self.user['stats']['hp'])
        max_hp = int(self.user['stats']['maxHealth'])
        current_mp = int(self.user['stats']['mp'])
        max_mp = int(self.user['stats']['maxMP'])
        current_exp = int(self.user['stats']['exp'])
        level_exp = int(self.user['stats']['toNextLevel'])

        width = 60

        hp_percent = min(float(current_hp) / max_hp, 1.0)
        mp_percent = min(float(current_mp) / max_mp, 1.0)
        xp_percent = min(float(current_exp) / level_exp, 1.0)

        if hp_percent < 0.25:
            hp_color = colors.red
        elif hp_percent < 0.5:
            hp_color = colors.yellow
        else:
            hp_color = colors.green

        hp_bar = ("="*int(hp_percent*width)).ljust(width)
        mp_bar = ("="*int(mp_percent*width)).ljust(width)
        xp_bar = ("="*int(xp_percent*width)).ljust(width)

        print "HP: " + hp_color("[" + hp_bar + "]")
        print "MP: " + colors.blue("[" + mp_bar + "]")
        print "XP: [" + xp_bar + "]"
        if self.user['cached']:
            print "(Cached)"
Exemple #25
0
def readMessages(
    clientSocket
):  # Essa função funciona dentro de uma thread e permite que um usuário possa enviar mensagens ao servidor e receber as mensagens dele simultaneamente.
    while True:
        message = clientSocket.recv(1024).decode('utf-8')
        if message == "bye":  # Essa mensagem "bye" é uma mensagem de resposta de confirmação enviada pelo servidor para indicar que o usuário foi desconectado.
            clientSocket.close(
            )  # O clientSocket do usuário é encerrado e a execução da função é finalizada.
            break
        else:
            if message != "OK" and message != "NOT OK":
                if message[-1] == "1":  # Public Message
                    print(message[:-1])
                    publicPostalBox.append(message[:-1])
                elif message[-1] == "2":  # Private Message
                    print(blue(message[:-1]))
                    privatePostalBox.append(message[:-1])
                elif message[-1] == "3":  # List of Connected Users
                    print("")
                    print(green(message[:-1]))
                    print("")
                elif message[-1] == "4":  # Issue
                    print(red(message[:-1]))
        #print(message) ##################### TEM QUE PRINTAR A FUNÇÂO DE CORES DIFERENTES #########################
    return
Exemple #26
0
    def test_generate_ipex_ansicolors(self):
        self.create_python_requirement_library(
            "3rdparty/ipex", "ansicolors", requirements=["ansicolors"]
        )
        self.create_python_library(
            "src/ipex",
            "lib",
            {
                "main.py": dedent(
                    """\
        from colors import blue

        print(blue('i just lazy-loaded the ansicolors dependency!'))
        """
                )
            },
        )
        binary = self.create_python_binary(
            "src/ipex", "bin", "main", dependencies=["3rdparty/ipex:ansicolors", ":lib",]
        )

        self.set_options(generate_ipex=True)
        dist_dir = os.path.join(self.build_root, "dist")

        self._assert_pex(
            binary, expected_output=blue("i just lazy-loaded the ansicolors dependency!") + "\n"
        )

        dehydrated_ipex_file = os.path.join(dist_dir, "bin.ipex")
        assert os.path.isfile(dehydrated_ipex_file)
        hydrated_pex_output_file = os.path.join(dist_dir, "bin.pex")
        assert os.path.isfile(hydrated_pex_output_file)
def do_commands(lines):
    for line in lines:
        sys.stdout.write(colors.blue(prompt))
        type_it_out(line)
        time.sleep(0.5)
        print
        os.system(colors.strip_color(line))
Exemple #28
0
def create_symlink(origin, new_dir):
    """
    Creates symlink for a file or directory to the specified path
    src: where is the file/folder located
    dst: where should the symlink be (also known as the origin)
    """
    try:
        src = os.path.abspath(new_dir) + "/" + os.path.basename(origin)
        dst = origin

        print colors.blue("[NOTICE]") + \
            " creating symlink for: %s to %s" % (os.path.basename(origin), src)

        os.symlink(src, dst)
    except OSError:
        sys.exit(colors.yellow("[ERROR]") + " symlinking failed, file exists")
Exemple #29
0
def print_problem(n, members):
    time_str = r"%Y-%m-%dT%H:%M:%S"
    print 'Problem', n.ljust(19), blue('  1st Star', bg='black'), yellow('    2nd Star', bg='black') + '\n' + '-'*51
    start_time = dt.strptime(event+'-12-' + n.zfill(2) + 'T05:00:00', time_str)

    data = []
    for member in members.itervalues():
        if n in member['completion_day_level']:
            t1, t2 = timedelta(days=1000), timedelta(days=1000)
            if '1' in member['completion_day_level'][n]:
                t1 = dt.utcfromtimestamp(
                    int(member['completion_day_level'][n]['1']['get_star_ts'])) - start_time
            if '2' in member['completion_day_level'][n]:
                t2 = dt.utcfromtimestamp(
                    int(member['completion_day_level'][n]['2']['get_star_ts'])) - start_time
            data.append((member, t1, t2))

    for j, (member, t1, t2) in enumerate(sorted(data, key=lambda x: (x[2], x[1]))):
        name = member['name'] if member['name'] else 'Anonymous'
        print str(j+1).ljust(2, ' ') + ' ' + name.ljust(24, ' '),
        if t1 != timedelta(days=1000):
            print ' ', str(t1).ljust(10, ' '),
        if t2 != timedelta(days=1000):
            print ' ', t2,
        print
Exemple #30
0
    def fancy_format(self):
        from colors import red, green, blue

        for item in self.data:
            c1 = item['min'] - 1
            c2 = item['max'] - 1
            cs = item['pass']
            cc = item['char']
            output = ''

            if item['tob'] == 'good':
                output += green('good') + "  "
            else:
                output += red('FAIL') + "  "

            output += str(c1).zfill(2) + "-" + str(c2).zfill(
                2) + "|" + cc + "| "

            if c1 == 0:
                cleft = ''
            else:
                cleft = cs[0:c1]

            if cs[c1] == cc:
                cX = blue(cs[c1])
            else:
                cX = red(cs[c1])

            if c1 + 1 == c2 - 1:
                cmid = cs[c1 + 1]
            else:
                cmid = cs[c1 + 1:c2 - 1]

            if cs[c2] == cc:
                cY = blue(cs[c2])
            else:
                cY = red(cs[c2])

            if c2 == len(cs):
                cright = ''
            else:
                cright = cs[c2 + 1:]

            output += cleft + cX + cmid + cY + cright

            print(output)
Exemple #31
0
    def __str__(self):
        'Return the colorized name of this player.'

        try:
            name = self.extra_settings['recap']
        except: 
            name = blue(Character.__str__(self))
        return name
Exemple #32
0
def color_mark(mark: str) -> str:
    """Разукрашивает метки для вывода на доску"""
    if mark == 'x':
        return blue(mark)
    elif mark == 'o':
        return yellow(mark)
    else:
        return ' '
Exemple #33
0
def print_eq_sections(in_file, flag=True, section_name=""):
    if not in_file:
        print_msg(-1, "File is't exist")
        return

    sample = pefile.PE(in_file)
    for section in sample.sections:
        if (section.Misc_VirtualSize == section.SizeOfRawData) and (section_name in section.Name):
            sys.stdout.write(magenta("Name: %0s" % section.Name + "\tRawSize = 0x%08x" % section.SizeOfRawData))
            sys.stdout.write(magenta("\tVirtualSize = 0x%08x" % section.Misc_VirtualSize))
            sys.stdout.write(magenta("\tEntropy = %02d" % section.get_entropy() + "\n"))
        elif flag == False:
            print_msg(1, "No sections with equal RSize and VSize")
        elif flag == True:
            sys.stdout.write(blue("Name: %0s" % section.Name + "\tRawSize = 0x%08x" % section.SizeOfRawData))
            sys.stdout.write(blue("\tVirtualSize = 0x%08x" % section.Misc_VirtualSize))
            sys.stdout.write(blue("\tEntropy = %02d" % section.get_entropy() + "\n"))
Exemple #34
0
def set_dot_path(path):
    """
    Set the path of where the dotfiles are located. This will be the location
    of the files and backup folders.
    """
    data = get_dotconfig()

    try:
        data.update({'dot_path': path})
    except AttributeError:
        sys.exit(
            colors.yellow("[ERROR]") + " not able to update .dotconfig"
            "file. Check if the integrity of the file.")

    set_dotconfig(data)

    print colors.blue("[NOTICE]") + " set %s as path in .dotconfig" % path
Exemple #35
0
 def configure(self):
     logPrint(colors.blue("Reconfiguring SMS format"))
     self.sendCmd(b'AT+CSCS="UCS2"')
     data = self.recv()
     assert b"OK" in data, "Cant setup SMS to UCS2"
     self.sendCmd(b"AT+CMGF=1")
     data = self.recv()
     assert b"OK" in data, "Cant setup SMS to TEXT mode"
Exemple #36
0
def wifiDeauthClient():

    #getting the information from user, interface, client, and Access Point mac addresses
    interface = input(
        colors.blue(
            'What Monitor mode interface would you like to use to deauth?:\n????>'
        ))
    print(colors.red('OK, ' + interface))

    client = input(
        colors.blue('What is the client\'s BSSID (MAC Address)\nSKWD>'))
    print(colors.red('OK, ' + client))
    print('Press Ctrl+C when done.')
    scanForTarget()

    accessPoint = input(
        colors.blue('What is the Access Point\'s BSSID (MAC Address)\nSKWD>'))
    print(colors.red('OK, ' + accessPoint))
    #From here, we print out the info, to make sure the info is correct than we start with deauth, or exit SKWifiDeath

    print('__________________________________________________')
    print(
        'Just to be sure, here is are the current settings:\nMonitor Mode Interface:'
        + interface + '\nClient:' + client + '\nAccess Point:' + accessPoint)
    print('__________________________________________________')

    correct = input(colors.red('Is this correct? (yes/y no/n):\n????>'))

    def deauthClient():
        print('Building the packet.')
        #using scapy to craft anf send deauth packet, thanks Abdou Rockikz!
        dot11 = Dot11(addr1=client, addr2=accessPoint, addr3=accessPoint)
        # stack them up
        packet = RadioTap() / dot11 / Dot11Deauth(reason=7)
        print('Packet ready.')
        # send the packet
        print('Sending packets')
        sendp(packet, inter=0.1, count=200, iface=interface, verbose=1)

    if correct == 'y':
        print('Alright. Starting Deauth...')
        deauthClient()
    elif correct == 'n':
        print('Exiting...')
        sys.exit()
Exemple #37
0
 def print(self, nodes_per_row=5):
     import sys, colors
     sys.stderr.write(
         "======================================================\n")
     sys.stderr.write(colors.blue("world@t=%i\n" % (self.t)))
     string_representations = []
     max_incoming_agents = 0
     for idx, node in enumerate(self.nodes):
         num_incoming_agents = 0
         for link in node.incoming_links:
             num_incoming_agents += len(link)
         if num_incoming_agents > max_incoming_agents:
             max_incoming_agents = num_incoming_agents
     sys.stderr.write(
         colors.blue("max incoming=%i\n" % (max_incoming_agents)))
     for idx, node in enumerate(self.nodes):
         num_incoming_agents = 0
         for link in node.incoming_links:
             num_incoming_agents += len(link)
         total_jam_capacity = sum(l.jam_capacity
                                  for l in node.outgoing_links)
         total_freeflow_capacity = sum(l.free_flow_capacity
                                       for l in node.outgoing_links)
         color_component = 0
         if num_incoming_agents <= total_freeflow_capacity:
             color_component = int(
                 (num_incoming_agents / total_freeflow_capacity) * 5) + 28
         else:
             color_component = -int(
                 ((num_incoming_agents - total_freeflow_capacity) /
                  (total_jam_capacity - total_freeflow_capacity)) * 5) + 129
         string_representations.append(
             colors.color(
                 "(%s):%s" % (str(idx).zfill(len(str(len(
                     self.nodes)))), str(num_incoming_agents).zfill(
                         len(str(max_incoming_agents)))), color_component))
     rows = []
     for c in range(0, len(self.nodes), nodes_per_row):
         rows.append(string_representations[c:c + nodes_per_row])
     for r in rows:
         sys.stderr.write(", ".join(r))
         sys.stderr.write("\n")
     sys.stderr.write(
         "======================================================\n")
     sys.stderr.flush()
Exemple #38
0
 def basic_parse(self):
     print(bold(blue("[To]")), (":").rjust(11), self.eml["To"])
     print(bold(green("[From]")), (":").rjust(9), self.eml["From"])
     print(bold(yellow("[Sender]")), (":").rjust(7), self.eml["Sender"])
     print(bold(orange("[Delivered To]")), ":", self.eml["Delivered-To"])
     print(bold(red("[Subject]")), (":").rjust(6), self.eml["Subject"])
     print(bold(purple("[Date]")), (":").rjust(9), self.eml["Date"])
     print(bold(grey("[Content-Type]")), (":").rjust(1),
           self.eml["Content-Type"])
Exemple #39
0
    def get_optional_header(self):
        headers = [
            bold(blue("Fields")),
            bold(red("FileOffset")),
            bold(green("Offset")),
            bold(orange("Value"))
        ]
        table = []

        print("\n\t\t\t\t", bold(white("OPTIONAL HEADER")), "\n")
Exemple #40
0
def blink(count):
        while count > 0:
                set(colors.red())
                time.sleep(0.1)
                lightsOff()
                time.sleep(0.1)
                count = count - 1
        else:
                set(colors.blue())
                time.sleep(1)
Exemple #41
0
  def console_output(self, targets):
    buildfile_aliases = self.context.build_file_parser.registered_aliases()
    extracter = BuildDictionaryInfoExtracter(buildfile_aliases)

    alias = self.get_options().details
    if alias:
      tti = next(x for x in extracter.get_target_type_info() if x.symbol == alias)
      yield blue('\n{}\n'.format(tti.description))
      yield blue('{}('.format(alias))

      for arg in tti.args:
        default = green('(default: {})'.format(arg.default) if arg.has_default else '')
        yield '{:<30} {}'.format(
          cyan('  {} = ...,'.format(arg.name)),
          ' {}{}{}'.format(arg.description, ' ' if arg.description else '', default))

      yield blue(')')
    else:
      for tti in extracter.get_target_type_info():
        yield '{} {}'.format(cyan('{:>30}:'.format(tti.symbol)), tti.description)
def create_playlist(input_filename, output_filename, library):
    """The function that actually creates the playlist"""
    # start by reading the file
    with open(input_filename) as file_handle:
        content = file_handle.readlines()

    # now process the file
    output = process_content(content, library)

    # write the output to a file
    if output_filename is None:
        # two blank lines
        print ""
        print ""
        print blue("Output:")
        print output
        return 1

    with open(output_filename, 'w') as file_:
        file_.write(output)

    return 1
Exemple #43
0
def cmd_recap(s, r):
    '''recap <recapped-name>

    Define your character's "recapped name". For instance, if your 
    name is "Montainrat", you can define it to be seen as 
    "MontainRat". You cannot, however, use this command to change 
    your name.
    '''
    recapped = r['message']
    if s.player.name.lower() == recapped.lower():
        s.player.extra_settings['recap'] = blue(recapped)
        s.message('Your name will now be seen by everyone as ' + s.player.extra_settings['recap'])
    else:
        s.message('The recapped name still has to match your proper name.')
Exemple #44
0
def main(args):
    """Main method

    :param args: arguments
    :return: None
    """
    opts = parse_cmdline_params(args[1:])
    if opts.b is not None and opts.l is not None:
        nb = True
    else:
        nb = False
    sequences = cloning(opts.fastq, opts.n, nb, opts.b, opts.l)
    # sequences = create_fastq_dict('sampleFastq')
    total_error_num = 0
    total_errors = 0
    total_lengths = 0
    for key in sequences:
        error_seq_string = ''
        seq_name = key
        seq_string = sequences[key]

        position = 0
        error_num = 0
        for base in seq_string:
            if base not in 'AGCTN':
                raise ValueError("This base,", base, ", is not an A, G, C, T, or N!")
            position += 1
            error_prob = 0.001 * position
            if error_prob * 100 <= 0:
                raise ValueError("The error probability must be greater than 0!")
            # Checks if it needs to add an error
            if random.randint(1, 1000) < (error_prob) * 1000:
                error_seq_string = add_error(error_seq_string, base, True)
                error_num += 1
            else:
                error_seq_string = add_error(error_seq_string, base, False)
        total_errors += error_num
        total_error_num += 1
        error_perc = error_num / len(seq_string)
        total_lengths += len(seq_string)
        print_errors(blue(seq_name), seq_string, error_seq_string, green(str(error_num)))
        print 'The error percent for this sequence is:', yellow(str(error_perc * 100)), '%'
        print 'The new quality string is:            ', create_quality_scores(seq_string), '\n'
    print 'The average number of errors generated was:' \
          '', magenta(str(int(total_errors / total_error_num)))
    print 'The total error percentage is:', magenta(str(total_errors / total_lengths * 100)), '%'
def downloads_finished():

    global counter, fail_counter, errors, progress_bar

    progress_bar.finish()

    print(green("Obtained %i out of %i images, %i could not be retrieved"
          % (counter - fail_counter, counter, fail_counter)))

    for url, error in errors:
        print("Error", red(error.getErrorMessage()),
              "at url", blue(url))

    print(green("Obtained %i out of %i images, %i could not be retrieved"
          % (counter - fail_counter, counter, fail_counter)))

    return
Exemple #46
0
def print_headers():
    resp = requests.get(args.url, headers=headers)
    if resp.ok:
        headtable = PrettyTable(["header", "value"])
        headtable.header = False
        session_info = {}
        h = collections.OrderedDict(sorted(resp.headers.items()))
        for header in h:
            if header == 'x-akamai-session-info':
                aheadtable = PrettyTable(["header", "value"])
                aheadtable.header = False
                si = [x.strip() for x in h[header].split(',')]
                for s in si:
                    i = [x.strip() for x in s.split(';')]
                    session_info[i[0][5:]] = i[1][6:]
                    if len(i) > 2:
                        t = i[2].split('=')
                        session_info[t[0]] = t[1]
            elif header == 'x-check-cacheable':
                if h[header] == 'NO':
                    headtable.add_row([blue(header), red(h[header])])
                else:
                    headtable.add_row([blue(header), green(h[header])])
            elif header == 'x-cache':
                if 'TCP_MISS' in h[header]:
                    headtable.add_row([blue(header), red(h[header])])
                else:
                    headtable.add_row([blue(header), green(h[header])])
            else:
                headtable.add_row([blue(header), green(h[header])])
        headtable.align = "l"
        print bold(underline(blue("### Headers")))
        print headtable
        if session_info:
            if args.session:
                d = collections.OrderedDict(sorted(session_info.items()))
                for key in d:
                    aheadtable.add_row([blue(key), green(d[key])])
                aheadtable.align = "l"
                print bold(underline(blue("### Akamai Session Info")))
                print aheadtable
Exemple #47
0
 def readline(self):
     prompt = 'tiget[{}]% '.format(self.lineno)
     if settings.core.color:
         prompt = blue(prompt)
     readline.set_completer(self.complete)
     readline.set_completer_delims(whitespace)
     try:
         line = input(prompt).strip()
     except KeyboardInterrupt:
         print('^C')
         raise
     except EOFError:
         print('quit')
         raise
     finally:
         readline.set_completer()
     if not line:
         self.lineno -= 1
     return line
Exemple #48
0
    def report_results_to_stdout(self, result, exec_time):
        """pretty prints the results of a simulation"""

        print(blue('Execution time: {}s {}ms'.format(exec_time.seconds, exec_time.microseconds)))

        if self.starting_cards == '':
            self.starting_cards='any'

        result_record=[self.starting_cards, str(self.draws), self.target + ' low', '{:,}'.format(self.simulations), '{0:.4%}'.format(result)]
        headers = ['starting cards','nb draws','target hand','simulations','odds (%)']
        collist = tuple([i for i in range(headers.__len__() + 1)])
        # this sets the initial column width based on the width of the headers
        colwidth = dict(zip(collist,(len(x) for x in headers)))
        # if the width of our values is longer than the corresponding header's we update that column's width
        colwidth.update(( i, max(colwidth[i],len(el)) ) for i,el in enumerate(result_record))
        width_pattern = ' | '.join('%%-%ss' % colwidth[i] for i in range(0,5))

        # note the lists are converted into tuples in order to apply width_pattern onto them
        print('\n'.join((width_pattern % tuple(headers), '-|-'.join(colwidth[i] * '-' for i in range(5)),
                         ''.join(width_pattern % tuple(result_record)))))
Exemple #49
0
def get_job():
    jobs = sorted(
        client.get_my_jobs(),
        key=lambda j: (
            j.find('Client').find('Name').text.strip(),
            j.find('Name').text.strip(),
        )
    )

    print()

    for i, job in enumerate(jobs):
        print('{index}: {job} | {client}'.format(
            index=colors.bold('{:3}'.format(i+1)),
            client=colors.blue(job.find('Client').find('Name').text.strip()),
            job=colors.magenta(job.find('Name').text.strip()),
        ))

    return input_valid(
        '\npick a job (1-{}): '.format(len(jobs)),
        lambda i: jobs[int(i)-1],
    )
Exemple #50
0
def main(args):
    opts = parse_cmdline_params(args[1:])
    sequences = createFastqDict(opts.fastq)
    #sequences = createFastqDict('sampleFastq')
    total_error_num = 0
    total_errors = 0
    total_lengths = 0
    for key in sequences:
        error_seq_string = ''
        seq_name = key
        seq_string = sequences[key]
        position = 0
        error_num = 0
        quality_string = createQualityScores(seq_string)
        for base in seq_string:
            if base not in 'AGCT':
                raise ValueError("This base,", base ,",is not an A, G, C, or T!")
            position += 1
            error_prob = 0.001 * position
            if error_prob * 100 <= 0:
                raise ValueError("The error probability must be greater than 0!")
            #Checks if it needs to add an error
            if (random.randint(1,1000) < (error_prob)*1000):
                error_seq_string = addError(error_seq_string,base,True)
                error_num += 1
            else:
                error_seq_string = addError(error_seq_string,base,False)
        total_errors += error_num
        total_error_num += 1
        error_perc = error_num/len(seq_string)
        total_lengths += len(seq_string)
        printErrors(blue(seq_name),seq_string,error_seq_string,green(str(error_num)))
        print 'The error percent for this sequence is:',yellow(str(error_perc*100)),'%'
        print 'The new quality string is:            ',quality_string,'\n'
    print 'The average number of errors generated was:',magenta(str(int(total_errors/total_error_num)))
    print 'The total error percentage is:',magenta(str(total_errors/total_lengths*100)),'%'
Exemple #51
0
def fight(type, hit, min, max):
	global sword
	global healthp
	global potion
	global bp
	beast = hit
	pause('#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#_#')
	if sword == 3:
		minA = 10
		maxA = 40
		attword = 'slashes'
		print "\nWith sword in hand, %s stands ready for the %s!\n" % (name, type)
	else:
		minA = 5
		maxA = 12
		attword = "hits"
		print "\nNot enough time to untie the sword from the backpack! Should have equiped it!\n"

 	while beast >= 0:
		print "%s's HEALTH: " % name + blue("%d") % healthp
		print "%s HEALTH: " % type + bold("%d") % beast
		swordh = random.randint(minA, maxA)
		beasth = random.randint(min, max)
		fight = raw_input("1. Attack  2. Flash  3. Potion >>> ")
		
		if fight in('1', 'attack', 'Attack'):
			print'\n'
			pause(bold('++I====>'))
			print "%s %s the %s for" % (name, attword, type) + red(" %d DAMAGE!\n") % swordh
			beast -= swordh
			if beast > 0:
				beastatt(type, beasth)
			else:
				print "%s strikes the %s DOWN!" % (name, type)
				print blue("****VICTORY****")
				get_potion(3)
		elif fight in ('2', 'flash', 'Flash'):
			if min != max:
				print '\n'
				pause(bold(yellow('<(--)>')))
				print "%s shines the flashlight into the %ss eyes, weakening it..." % (name, type)
				max -= 1
				print "%s attack" % type + bold(" DOWN\n")
				beastatt(type, beasth)
			else:
				print'\n'
				pause('---')
				print "Can't weaken anymore.\n"
				beastatt(type, beasth)
		elif fight in ('3', 'potion', 'Potion'):
			if potion >= 1:
				print '\n'
				pause(bold(blue('-OTO-')))
				print "%s takes a " % name + bold(blue("POTION"))
				health(30)
				potion -= 1
				bp.remove('potion')
				beastatt(type, beasth)
			else:
				print '\n'
				pause('000')
				print "No potions!!!\n"
		else:
			print '\n'
			pause(bold('<==>'))
			print "The %s grabs at %s in a fit of rage." % (type, name)
			health(-2)
def debug(*msg):
    if DEBUG:
        msg = map(str, msg)
        print colors.bold(colors.blue('DEBUG')), ' '.join(msg)
Exemple #53
0
# if (flag2 != True):
#      print red("Error. Can't find children " + option.text)
# # endregion

# region ------ Add Event


class Add_Event(unittest.TestCase):

    print blue("Adding event... Click 'Event'")


driver.get("http://develop.ckids.web.drucode.com/centre/xyz-childrens-creche/events")
WebDriverWait(driver, 10)
driver.find_element_by_link_text("Add New Event").click()
print blue("Adding event...")
wait = WebDriverWait(driver, 10)
# date_event = driver.find_element_by_class_name("date-clear form-text hasDatepicker date-popup-init").clear()
wait.until(
    lambda driver: driver.find_element_by_xpath("//*[@id='edit-field-event-date-und-0-value-datepicker-popup-0']")
)
date_event = driver.find_element_by_xpath("//*[@id='edit-field-event-date-und-0-value-datepicker-popup-0']").clear()
WebDriverWait(driver, 10)
driver.find_element_by_id("edit-field-event-date-und-0-value-datepicker-popup-0").click()
driver.find_element_by_xpath("//*[@id='ui-datepicker-div']/table/tbody/tr[5]/td[1]/a").click()
driver.find_element_by_id("edit-title").send_keys("test")
driver.find_element_by_id("edit-body-und-0-value").send_keys("test description")
print green("Added event :) ")
# driver.find_element_by_id("edit-submit").click()
driver.find_element_by_class_name("cancel-button").click()
driver.get("http://develop.ckids.web.drucode.com/")
Exemple #54
0
def _build_report(job, build, build_number, failed):
    report = build['test_report']
    build = build['build']
    if build.get('building'):
        return 'Building is currently running'
    if report.get('status') == 'error':
        return 'No tests report has been generated for this build'
    failed_dir = work.failed_dir(job, build_number)
    passed_dir = work.passed_dir(job, build_number)
    for d in [passed_dir, failed_dir]:
        d.rmtree_p()
        d.mkdir()
    build_parameters = _extract_build_parameters(build)
    interesting_parameters = ['system_tests_branch', 'system_tests_descriptor']
    interesting_parameters = {k: v for k, v in build_parameters.items()
                              if k in interesting_parameters}
    cause = _extract_build_cause(build)
    timestamp = build['timestamp']
    print '{}: {} ({})'.format(colors.bold('Cause'),
                               cause,
                               _timestamp_to_datetime(timestamp))
    print
    print colors.bold('Parameters: ')
    print yaml.safe_dump(interesting_parameters, default_flow_style=False)
    colored_cause = colors.blue(' - CAUSE')
    for suite in report['suites']:
        suite_name = suite['name']
        cases = []
        has_passed = False
        has_failed = False
        for case in suite['cases']:
            test_status = case['status']
            if test_status in ['FAILED', 'REGRESSION']:
                test_status = 'FAILED'
                colored_status = colors.red(test_status)
                has_failed = True
            elif test_status in ['PASSED', 'FIXED']:
                test_status = 'PASSED'
                colored_status = colors.green(test_status)
                has_passed = True
            elif test_status == 'SKIPPED':
                colored_status = colors.yellow(test_status)
                has_failed = True
            else:
                colored_status = test_status
            name = case['name']
            class_name = (case['className'] or '').split('.')[-1].strip()
            if class_name:
                name = '{}.{}'.format(class_name, name)
            if not failed or test_status != 'PASSED':
                cases.append('{:<18}{}'.format(
                    colored_status,
                    name.split('@')[0].strip()))
            filename = '{}.log'.format(name.replace(' ', '-'))
            dirname = passed_dir if test_status == 'PASSED' else failed_dir
            with open(dirname / filename, 'w') as f:
                f.write('name: {}\n\n'.format(case['name']))
                f.write('status: {}\n\n'.format(case['status']))

                if has_failed:
                    handle_failure(cases, case, colored_cause, f)

                f.write('class: {}\n\n'.format(case['className']))
                f.write('duration: {}\n\n'.format(case['duration']))
                f.write('error details: {}\n\n'.format(case['errorDetails']))
                f.write('error stacktrace: {}\n\n'.format(
                    case['errorStackTrace']))
                f.write('stdout: \n{}\n\n'.format(
                    (case['stdout'] or '').encode('utf-8', errors='ignore')))
                f.write('stderr: \n{}\n\n'.format(
                    (case['stderr'] or '').encode('utf-8', errors='ignore')))
        if has_passed and has_failed:
            suite_name_color = colors.yellow
        elif has_passed:
            suite_name_color = colors.green
        elif has_failed:
            suite_name_color = colors.red
        else:
            suite_name_color = colors.white
        if cases:
            print suite_name_color(colors.bold(suite_name))
            print suite_name_color(colors.bold('-' * (len(suite_name))))
            print '\n'.join(cases)
            print
    print 'Report files written to {}'.format(work.build_dir(job,
                                                             build_number))
Exemple #55
0
def print_command(str):
	print colors.blue(">>"), str
Exemple #56
0
    tokens_list = parse_expr.parse_expr(expr)
    expression_type = EXPR_TYPES[INFIX]

    for tokens in tokens_list:
        current_count = current_count + 1
        rpn_expr = []
        solution = ""


        if tokens == ["quit"]:
            sys.exit(0)

        elif len(tokens) > 0 and tokens[0] == "infix":
            expression_type = EXPR_TYPES[0]
            tokens = tokens[1:]

        elif len(tokens) > 0 and tokens[0] == "rpn":
            expression_type = EXPR_TYPES[1]
            rpn_expr = tokens[1:]

        if tokens != [] and expression_type == EXPR_TYPES[0]:
            rpn_expr = compile_to_rpn.compile_to_rpn(tokens)

        if rpn_expr != [] or expression_type == EXPR_TYPES[1]:
            solution = solve_rpn.solve_rpn(rpn_expr)

        if solution != "":
            print colors.green("Result(") + colors.cyan(str(current_count)) + colors.green("): ") + colors.blue(str(solution))

    print ""
Exemple #57
0
    def __str__(self):
        'Return the colorized name of this player.'

        name = Character.__str__(self)
        return blue(name)
    "Space Pirate King/Queen",
    "Void Crystals",
    "Star Dreadnought",
    "Quantum Tunnel",
    "Ancient Space Ruin",
    "Alien Artifact",
)

which_will_list = (
    "Destroy a Solar System",
    "Reverse Time",
    "Enslave a Planet",
    "Start a War / Invasion",
    "Rip a Hole in Reality",
    "Fix Everything"
)

if __name__ == '__main__':
    nb = 1
    if len(sys.argv) > 1:
        nb = int(sys.argv[1])
    for i in range(nb, 0, -1):
        print "A threat...\n%s wants to %s the %s which will %s" % (
            blue(random.choice(threat_list)),
            blue(random.choice(wants_to_list)),
            blue(random.choice(the_list)),
            blue(random.choice(which_will_list))
            )
        if i > 1:
            print 80 * "-"
Exemple #59
0
 def show_commands(self):
     print blue("\nYou have the following commands available:")
     for command in self.commands:
         print blue("- " + command)
Exemple #60
0
 def default(self, token):
     return ansicolors.blue(token)