Ejemplo n.º 1
0
    def seleccionar_ciudades_validas(self, term, tipo_ciudad):
        """En base a un ingreso valida el nombre de la ciudad"""
        ciudades_posibles = self.motor.obtener_ciudades_posibles(term)

        posicion = -1
        table_data = [["Opcion", "Ciudades"]]
        for id, ciudad in sorted(ciudades_posibles.items()):
            table_data.append([id, ciudad])

        table = DoubleTable(table_data, "Seleccion de ciudades disponibles")
        table.justify_columns = {0: 'center', 1: 'left'}
        print(table.table, "\n")
        while posicion == -1:
            try:
                print(
                    'Confirme la opción de la ciudad ingresada. Oprima 0 (Cero) para ingresarla nuevamente.'
                )
                numero = int(input("Número de opción correcta: "))
                if numero == 0:
                    return self.obtener_nombre_de_ciudad(tipo_ciudad)
                elif len(ciudades_posibles) >= numero >= 1:
                    posicion = numero
                else:
                    print("Debe ingresar un numero entre 1 y " +
                          str(len(ciudades_posibles)))
            except ValueError:
                print("Debe ingresar un numero entre 1 y " +
                      str(len(ciudades_posibles)))

        return ciudades_posibles[posicion]
Ejemplo n.º 2
0
    def get_lab_info(self, lab_hash=None, machine_name=None, all_users=False):
        user_name = utils.get_current_user_name() if not all_users else None

        machine_streams = self.docker_machine.get_machines_info(
            lab_hash, machine_filter=machine_name, user=user_name)

        table_header = [
            "LAB HASH", "USER", "DEVICE NAME", "STATUS", "CPU %",
            "MEM USAGE / LIMIT", "MEM %", "NET I/O"
        ]
        stats_table = DoubleTable([])
        stats_table.inner_row_border = True

        while True:
            machines_data = [table_header]

            try:
                result = next(machine_streams)
            except StopIteration:
                return

            if not result:
                return

            for machine_stats in result:
                machines_data.append([
                    machine_stats['real_lab_hash'], machine_stats['user'],
                    machine_stats['name'], machine_stats['status'],
                    machine_stats['cpu_usage'], machine_stats['mem_usage'],
                    machine_stats['mem_percent'], machine_stats['net_usage']
                ])

            stats_table.table_data = machines_data

            yield "TIMESTAMP: %s" % datetime.now() + "\n\n" + stats_table.table
Ejemplo n.º 3
0
    def get_lab_info(self, recursive, lab_hash=None, machine_name=None, all_users=False):
        user_name = utils.get_current_user_name() if not all_users else None
        if not recursive:
            machines = self.docker_machine.get_machines_by_filters(lab_hash=lab_hash,
                                                                   machine_name=machine_name,
                                                                   user=user_name
                                                                   )
        else:
            machines = self.docker_machine.get_machines_by_filters_rec(lab_hash=lab_hash,
                                                                       machine_name=machine_name,
                                                                       user=user_name
                                                                       )
        if not machines:
            if not lab_hash:
                raise Exception("No machines running.")
            else:
                raise Exception("Lab is not started.")

        machines = sorted(machines, key=lambda x: x.name)

        machine_streams = {}

        for machine in machines:
            machine_streams[machine] = machine.stats(stream=True, decode=True)

        table_header = ["LAB HASH", "USER", "MACHINE NAME", "STATUS", "CPU %", "MEM USAGE / LIMIT", "MEM %", "NET I/O"]
        stats_table = DoubleTable([])
        stats_table.inner_row_border = True

        while True:
            machines_data = [
                table_header
            ]

            for (machine, machine_stats) in machine_streams.items():
                real_name = machine.labels['name']
                if recursive:
                    path = machine.exec_run('hostname')[1].decode('utf-8')
                    real_name_split = path.split('.')
                    real_name = ('.'.join(real_name_split[:-1]))
                try:
                    result = next(machine_stats)
                except StopIteration:
                    continue

                stats = self._get_aggregate_machine_info(result)

                machines_data.append([machine.labels['lab_hash'],
                                      machine.labels['user'],
                                      real_name,
                                      machine.status,
                                      stats["cpu_usage"],
                                      stats["mem_usage"],
                                      stats["mem_percent"],
                                      stats["net_usage"]
                                      ])

            stats_table.table_data = machines_data

            yield "TIMESTAMP: %s" % datetime.now() + "\n\n" + stats_table.table
Ejemplo n.º 4
0
  def print_vulnerability(cls, vulnerability: Vulnerabilities):
    """
    print_vulnerability takes a vulnerability, and well, it prints it
    """
    cvss_score = vulnerability.get_cvss_score()
    table_data = [
        ["ID", vulnerability.get_id()],
        ["Title", vulnerability.get_title()],
        ["Description", '\n'.join(wrap(vulnerability.get_description(), 100))],
        ["CVSS Score", f"{vulnerability.get_cvss_score()} - {cls.get_cvss_severity(cvss_score)}"],
        ]
    if vulnerability.get_cvss_vector():
      table_data.append(
          ["CVSS Vector", vulnerability.get_cvss_vector()]
          )

    table_data.extend(
        [
            ["CVE", vulnerability.get_cve()],
            ["Reference", vulnerability.get_reference()]
        ]
        )
    table_instance = DoubleTable(table_data)
    table_instance.inner_heading_row_border = False
    table_instance.inner_row_border = True
    cls.do_print(table_instance.table, cvss_score)

    print("----------------------------------------------------")
Ejemplo n.º 5
0
def test_single_line():
    """Test single-lined cells."""
    table_data = [
        ["Name", "Color", "Type"],
        ["Avocado", "green", "nut"],
        ["Tomato", "red", "fruit"],
        ["Lettuce", "green", "vegetable"],
        ["Watermelon", "green"],
        [],
    ]
    table = DoubleTable(table_data, "Example")
    table.inner_footing_row_border = True
    table.justify_columns[0] = "left"
    table.justify_columns[1] = "center"
    table.justify_columns[2] = "right"
    actual = table.table

    expected = (
        u"\u2554Example\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n"
        u"\u2551 Name       \u2551 Color \u2551      Type \u2551\n"
        u"\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n"
        u"\u2551 Avocado    \u2551 green \u2551       nut \u2551\n"
        u"\u2551 Tomato     \u2551  red  \u2551     fruit \u2551\n"
        u"\u2551 Lettuce    \u2551 green \u2551 vegetable \u2551\n"
        u"\u2551 Watermelon \u2551 green \u2551           \u2551\n"
        u"\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n"
        u"\u2551            \u2551       \u2551           \u2551\n"
        u"\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d"
    )
    assert actual == expected
Ejemplo n.º 6
0
def _print_scores(live_feeds, args):
    if len(live_feeds) == 0:
        print('No live matches at this time')
        return

    if args.refresh > 0:
        os.system('clear')
    for feed in live_feeds:
        live_scores = []
        # Add the team scores to the display object
        live_scores.append(['Current time', "{} ({})".format(datetime.now().strftime('%H:%M:%S'), datetime.utcnow().strftime('%H:%M:%S'))])
        live_scores.append(['Match', "{}, {} v {} at {}, {}".format(feed.series[0]['series_name'], feed.details['team1_name'],
                                                                    feed.details['team2_name'], feed.details['ground_name'], feed.details['start_date'])])
        # if feed.details['present_datetime_gmt'] <= feed.details['start_datetime_gmt']:
        #     live_scores.append(
        #         [
        #             'Start',
        #             "{} in {}".format(
        #                 feed.details['start_time_gmt'],
        #                 (
        #                     datetime.strptime(feed.details['start_datetime_gmt'], "%Y-%m-%d %H:%M:%S") - datetime.utcnow()
        #                 )
        #             )
        #         ]
        #     )

        live_scores.append(['Status', feed.status()])
        if feed.details['present_datetime_gmt'] >= feed.details['start_datetime_gmt']:
            live_scores.append(['Summary', feed.summary()])

        table = DoubleTable(live_scores)
        table.inner_row_border = True
        table.justify_columns = {0: 'center', 1: 'center', 2: 'center'}
        print(table.table)
Ejemplo n.º 7
0
def echo_table(table, **kwargs):
    t = DoubleTable([[safe_str(cell) for cell in row] for row in table],
                    **kwargs)

    t.inner_row_border = True

    click.echo(t.table)
Ejemplo n.º 8
0
    def archs(self):
        filtered = []
        table    = []
        
        archs = sorted(list(self.executor.get_archs()))

        cur     = [archs[0]]
        loc_max = MN_INF
        for pos in range(1, len(archs)):
            if self.__is_similar(archs[pos], archs[pos-1]):
                cur.append(archs[pos])
            else:
                loc_max = max(loc_max, len(cur))
                filtered.append(['<cyan>{}</>'.format(x) for x in cur])
                cur = [archs[pos]]
        filtered.append(['<cyan>{}</>'.format(x) for x in cur])
        loc_max = max(loc_max, len(cur))
        
        table.append(['\r'] * len(filtered))
        for i in range(loc_max):
            cur_row = []
            for j in range(len(filtered)):
                cur_row.append('' if i >= len(filtered[j]) else make_colors(filtered[j][i]))
            table.append(cur_row)
        rtable = DoubleTable(table)
        rtable.inner_heading_row_border = False
        return rtable.table
Ejemplo n.º 9
0
    def allMode(self, inputt):
        TABLE_DATA = [['All Alice intents']]
        table_instance = DoubleTable(TABLE_DATA)
        self.write('\n' + table_instance.table + '\n', 'yellow')

        TABLE_DATA = [['Intent', 'D', 'Description', 'Example']]
        table_instance = DoubleTable(TABLE_DATA)
        table_instance.justify_columns[1] = 'center'

        for dtIntentName in self._intentNameSkillMatching:
            tDesc = self._intentsModulesValues[dtIntentName][
                '__otherattributes__']['description']
            tEnabledByDefault = self._intentsModulesValues[dtIntentName][
                '__otherattributes__']['enabledByDefault']

            tUtterance = random.choice(
                list(self._intentsModulesValues[dtIntentName]['utterances']))

            if not inputt.getOption('full'):
                tDesc = (tDesc[:self.DESCRIPTION_MAX] +
                         '..') if len(tDesc) > self.DESCRIPTION_MAX else tDesc
                tUtterance = (
                    tUtterance[:self.DESCRIPTION_MAX] + '..'
                ) if len(tUtterance) > self.DESCRIPTION_MAX else tUtterance

            TABLE_DATA.append([
                dtIntentName, 'X' if tEnabledByDefault else '',
                '-' if not tDesc else tDesc,
                '-' if not tUtterance else tUtterance
            ])

        self.write(table_instance.table)
Ejemplo n.º 10
0
    def archs(self):
        filtered = []
        table    = []
        
        archs = sorted(list(self.executor.get_archs()))

        cur     = [archs[0]]
        loc_max = MN_INF
        for pos in range(1, len(archs)):
            if self.__is_similar(archs[pos], archs[pos-1]):
                cur.append(archs[pos])
            else:
                loc_max = max(loc_max, len(cur))
                filtered.append(['<cyan>{}</>'.format(x) for x in cur])
                cur = [archs[pos]]
        filtered.append(['<cyan>{}</>'.format(x) for x in cur])
        loc_max = max(loc_max, len(cur))
        
        table.append(['\r'] * len(filtered))
        for i in range(loc_max):
            cur_row = []
            for j in range(len(filtered)):
                cur_row.append('' if i >= len(filtered[j]) else make_colors(filtered[j][i]))
            table.append(cur_row)
        rtable = DoubleTable(table)
        rtable.inner_heading_row_border = False
        return rtable.table
Ejemplo n.º 11
0
    def get_lab_info(self, lab_hash=None, machine_name=None, all_users=False):
        if all_users:
            raise NotSupportedError("Cannot use `--all` flag.")

        if lab_hash:
            lab_hash = lab_hash.lower()

        table_header = ["LAB HASH", "DEVICE NAME", "STATUS", "ASSIGNED NODE"]
        stats_table = DoubleTable([])
        stats_table.inner_row_border = True

        while True:
            machines_stats = self.k8s_machine.get_machines_info(lab_hash=lab_hash, machine_filter=machine_name)

            machines_data = [
                table_header
            ]
            for machine_stats in machines_stats:
                machines_data.append([machine_stats["real_lab_hash"],
                                      machine_stats["name"],
                                      machine_stats["status"],
                                      machine_stats["assigned_node"]
                                      ])

            stats_table.table_data = machines_data

            yield "TIMESTAMP: %s" % datetime.now() + "\n\n" + stats_table.table
Ejemplo n.º 12
0
def print_table(title, data):
    header = ('Язык программирования', 'Вакансий найдено', 'Вакансий обработано', 'Средняя зарплата')
    data.insert(0, header)
    table_instance = DoubleTable(data, title)
    table_instance.justify_columns[2] = 'right'
    print(table_instance.table)
    print()
Ejemplo n.º 13
0
    def execute(self, inputt):
        TABLE_DATA = [['Authors List']]
        table_instance = DoubleTable(TABLE_DATA)
        self.write('\n' + table_instance.table + '\n', 'magenta')

        TABLE_DATA = [['Name']]
        table_instance = DoubleTable(TABLE_DATA)

        try:
            req = requests.get('https://api.github.com/' +
                               ModuleManager.GITHUB_API_BASE_URL)

            if req.status_code == 403:
                self.write(
                    '<bg:red> Github API quota limitations reached<bg:reset>\n'
                )
                return

            result = req.content
            authors = json.loads(result.decode())

            for author in authors:
                TABLE_DATA.append([
                    author['name'],
                ])

        except Exception:
            self.write('Error listing authors', 'red')
            raise

        self.write(table_instance.table)
Ejemplo n.º 14
0
 def table(self):
     table_list = [[white("ID"), white("Name"), white("Path")]]
     for p in self.data:
         table_list.append(p.to_row)
     
     table = DoubleTable(table_list, title=white('Projects', True))
     table.inner_row_border = True
     return table
Ejemplo n.º 15
0
def table(items, title):
    """
    生成表格
    """

    table_instance = DoubleTable(items, "SM.MS - {}".format(title))
    table_instance.inner_row_border = True
    return table_instance.table
Ejemplo n.º 16
0
def gh_table(items):
    """
    生成表格
    """

    table_instance = DoubleTable(items, "GitHub - 上传文件")
    table_instance.inner_row_border = True
    return table_instance.table
Ejemplo n.º 17
0
	def interact(self, input):
		TABLE_DATA = [['Alice Module Generator']]
		table_instance = DoubleTable(TABLE_DATA)
		table_instance.justify_columns[2] = 'right'
		self.write('\n' + table_instance.table + '\n', 'yellow')

		self.write("""Welcome in this basic module generator tool. All modules shared by the official Project Alice repository must have english!
You can now start creating your module. Remember to edit the dialogTemplate/en.json and remove dummy data!""")

		fields = []
		fieldTypeAvailable = ['en', 'fr', 'de', 'it', 'es', 'ru', 'jp', 'kr']
		_loop = True

		while _loop:
			entity = self.ask('\nEntity name : ', fgColor='yellow')

			if entity == 'exit' or entity == 'quit' or entity == '!q':
				_loop = False
				sys.exit(0)
			_loop = False


		fieldList = ''

		for fieldItem in fieldTypeAvailable:
			fieldList += fieldItem + ', '

		fieldList = fieldList[0:len(fieldList)- 1]

		TABLE_DATA = [['Available languages']]
		table_instance = AsciiTable(TABLE_DATA)
		table_instance.justify_columns[2] = 'right'
		self.write('\n' + table_instance.table + '\n', 'yellow')

		self.write(fieldList)

		while True:
			field = self.ask('\nNew language name (press <return> to stop adding fields): ', fgColor='yellow')

			reg = re.compile(r'^([a-zA-Z0-9_]+)$')
			match = reg.match(field)

			if len(field) == 0:
				break
			elif match.group(0) == None or len(match.group(0)) <= 0:
				self.write('  The language name contains invalid characters.')
				continue
			else:
				while True:
					type = self.askCombo('Dummy type <fg:reset>[en]<fg:yellow>: ', 'en', fieldTypeAvailable, fgColor='yellow')
					fields.append({"name": field, "type": type})
					break


		print(fields)

		return 0
Ejemplo n.º 18
0
def display_table(headers, data):
    bolded_headers = [bold(header) for header in headers]
    table_data = [bolded_headers] + data

    # Issue with less displaying SingleTable so double is needed, appears NOT to be a unicode issue
    # TODO sort this ^
    table = DoubleTable(table_data)
    table.inner_row_border = True
    click.echo_via_pager(table.table)
Ejemplo n.º 19
0
 def print_neighbors(self):
     TABLE_DATA = [['#','name','cost','port','ip']]
     count = 0
     for neighbor in self.neighbors:
         count = count + 1
         TABLE_DATA.append([count,neighbor['name'],neighbor['cost'],neighbor['port'],neighbor['ip'] ])
     table_instance = DoubleTable(TABLE_DATA, 'neighbors')
     table_instance.justify_columns[2] = 'right'
     print(table_instance.table)
     print()    
Ejemplo n.º 20
0
def choice(choices, default):
    """ Asks the user which string he wants from a list of strings.
    Returns the selected string.

    :param choices: List of choices (one choice is a string)
    :type choices: list
    :param default: One element from the choices list.
    :type default: str
    :return: The choice selected by the user.
    :rtype: str
    """
    idx = 0
    data = list()
    colorama.init()
    default_idx = 0
    for choice in choices:
        if choice == default:
            data.append([
                '{}-> {}{}'.format(Fore.GREEN, idx, Style.RESET_ALL),
                '{}{}{}'.format(Fore.GREEN, choice, Style.RESET_ALL)
            ])
            default_idx = idx
        else:
            data.append([idx, choice])
        idx = idx + 1

    table = DoubleTable(data, title='Choices')
    table.inner_heading_row_border = False
    print(table.table)

    while True:
        input_msg = '{}[Choice or Enter for {} -> default ({}){}]> {}'.format(
            Fore.LIGHTBLUE_EX, Fore.GREEN, default_idx, Fore.LIGHTBLUE_EX,
            Style.RESET_ALL)
        print(input_msg, end='')
        last_in = input()

        if len(last_in) == 0:
            return choices[default_idx]

        choice, *args = shlex.split(last_in)
        if len(args) > 0:
            print('What did you mean?')
            continue

        try:
            choice = int(choice)
        except ValueError:
            print('Illegal choice "' + str(choice) + '", choose again')
            continue

        if choice >= 0 and choice < idx:
            return choices[choice]

        print('Illegal choice "' + str(choice) + '", choose again')
Ejemplo n.º 21
0
	def execute(self, inputt):
		TABLE_DATA = [['Modules created by ' + inputt.getArgument('authorName')]]
		table_instance = DoubleTable(TABLE_DATA)
		self.write('\n' + table_instance.table + '\n', 'yellow')

		TABLE_DATA = [['Name', 'Version', 'Langs', 'Description']]
		table_instance = DoubleTable(TABLE_DATA)

		try:
			req = requests.get('https://api.github.com/' + ModuleManager.GITHUB_API_BASE_URL + '/' + inputt.getArgument('authorName'))

			if req.status_code == 403:
				self.write('<bg:red> Github API quota limitations reached<bg:reset>\n')
				return
			elif req.status_code // 100 == 4:
				self.write('> Unknown author <fg:red>' + inputt.getArgument('authorName') + '<fg:reset>')
				self.write('- You can use <fg:yellow>author:list<fg:reset> to list all authors\n')
				return

			result = req.content
			modules = json.loads(result.decode())

			for module in modules:
				moduleInstallFile = module['html_url'] \
										.replace('github.com', 'raw.githubusercontent.com') \
										.replace('/blob', '') \
										.replace('/tree', '') \
									+ '/' + module['name'] + '.install'

				try:
					req = requests.get(moduleInstallFile)
					result = req.content
					moduleDetails = json.loads(result.decode())
					tLangs = '|'.join(moduleDetails['conditions']['lang']) if 'lang' in moduleDetails['conditions'] else '-'
					tDesc = moduleDetails['desc']

					if not inputt.getOption('full'):
						tDesc = (tDesc[:self.DESCRIPTION_MAX] + '..') if len(tDesc) > self.DESCRIPTION_MAX else tDesc

					TABLE_DATA.append([
						moduleDetails['name'],
						moduleDetails['version'],
						tLangs,
						tDesc
					])

				except Exception:
					self.write('Error get module {}'.format(module['name']), 'red')
					raise

		except Exception:
			self.write('Error listing modules', 'red')
			raise

		self.write(table_instance.table)
Ejemplo n.º 22
0
    def _feature_score_table(self):
        sortedFeatureScore = np.array(self._sorted_features())
        table_data = [['Feature', 'Subset', 'Internal_rank']]
        for featurItem in sortedFeatureScore:
            table_data.append(featurItem.tolist())

        table = DoubleTable(table_data,
                            title='{}'.format(
                                str.upper(self.featureScore['method'])))
        table.justify_columns[2] = 'center'
        return table
Ejemplo n.º 23
0
def draw_table(results, title):
    results_for_table = prepare_results_for_table(results)
    columns = [
        'Язык программирования', 'Вакансий найдено', 'Вакансий обработано',
        'Средняя зарплата'
    ]
    results_for_table.insert(0, columns)
    table_instance = DoubleTable(results_for_table, title)
    table_instance.justify_columns[2] = 'right'
    table_with_results = table_instance.table
    return table_with_results
Ejemplo n.º 24
0
def print_terminal_table(table_data, method_used):
    """
    Prints a table with the results in the terminal.
    :param table_data: the data of the table
    :param method_used: the method used, to print as the table title
    :return: None
    """
    table = DoubleTable(table_data)
    table.title = method_used
    table.inner_heading_row_border = False
    table.inner_row_border = True
    print(table.table)
Ejemplo n.º 25
0
    def listar_trayectos(self):
        """Lista los nombres de los trayectos"""
        table_data = [["Nro", "Nombre del Trayecto"]]
        index = 1
        for valor in sorted(self.motor.trayectos.keys()):
            row = [index, valor]
            table_data.append(row)
            index += 1

        table = DoubleTable(table_data, "Trayectos almacenados ")
        table.justify_columns = {0: 'center', 1: 'left'}
        print(table.table)
Ejemplo n.º 26
0
    def print_scan_status(self, scan_status_list):
        status = []
        status.append([ '#', 'Scanner', 'Status'])
        count = 0
        
        for scan_status in scan_status_list:
            count += 1
            status.append([ count, scan_status['scanner'], scan_status['status'] ])

        status_table = DoubleTable(status)
        status_table.title = 'Scan Status'
        print(status_table.table)
    def get_report(self) -> str:
        """
        Get report
        :return:
        """
        simulation_list = [[key] + value
                           for key, value in self.columns.items()]
        report_table = DoubleTable(simulation_list)

        for i in range(1, self.size + 1):
            report_table.justify_columns[i] = "right"

        return report_table.table
Ejemplo n.º 28
0
def table(title, rows=[]):
    print(Style.RESET_ALL)

    if len(rows) > 0 and type(rows[0]) != tuple:
        rows = [[
            row,
        ] for row in rows]

    table_instance = DoubleTable(rows, Fore.YELLOW + title + Fore.RESET)
    table_instance.outer_border = True
    table_instance.inner_heading_row_border = False
    table_instance.inner_column_border = True

    print(table_instance.table)
Ejemplo n.º 29
0
 def listar_rutas(self, nombre_trayecto):
     trayecto = self.trayectos[nombre_trayecto]
     for i in range(0, len(trayecto) - 1):
         table_data = [[trayecto[i] + "\n" + trayecto[i + 1]]]
         ruta = self.unir_origen_destino(trayecto[i], trayecto[i + 1])
         table_data.append([
             "Distancia: " + self.formatear_distancia(self.rutas[ruta][1])
         ])
         table_data.append(
             ["Duracion: " + self.formatear_tiempo(self.rutas[ruta][0])])
         table = DoubleTable(table_data, "Ruta numero " + str(i + 1))
         table.justify_columns = {0: 'left'}
         print(table.table)
     print()
Ejemplo n.º 30
0
def analyze_bucket(bucket):
    client = boto3.client('s3')
    bucket_acl = client.get_bucket_acl(Bucket=bucket)
    permission = []

    for grants in bucket_acl['Grants']:
        if ('URI' in grants['Grantee']) and ('AllUser'
                                             in grants['Grantee']['URI']):
            permission.append(grants['Permission'])

    globalListAccess = 'NO'
    globalWriteAccess = 'NO'
    points = 0
    if len(permission) >= 1:
        if len(permission) == 1:
            if permission[0] == 'READ':
                globalListAccess = 'YES'
                points += 1
            if permission[0] == 'WRITE':
                globalWriteAccess = 'YES'
                points += 1
        if len(permission) > 1:
            if permission[0] == 'READ':
                globalListAccess = 'YES'
                points += 1
            if permission[0] == 'WRITE':
                globalWriteAccess = 'YES'
                points += 1
            if permission[1] == 'READ':
                globalListAccess = 'YES'
                points += 1
            if permission[1] == 'WRITE':
                globalWriteAccess = 'YES'
                points += 1

        if globalListAccess == 'YES' or globalWriteAccess == 'YES':
            table_data = [
                ['BucketName', 'GlobalListAccess', 'GlobalWriteAccess'],
                [bucket, globalListAccess, globalWriteAccess],
            ]
            table = DoubleTable(table_data)
            table.inner_row_border = True
            print(table.table)

    api.Metric.send(
        metric="bucket.exposed",
        host="aws.s3.bucket." + bucket,
        points=points,  #0=ok, 1=read exposed, 2=write exposed
        tags=["aws", "s3", "s3permissions"])
def make_table(team1,team2=''):
	data=scrape()
	table_data=[['Match','Series','Date','Month','Time']]

	for i in data[:]:
		row=[]
		if team1.strip(' ') in i.get('desc') and team2.strip(' ') in i.get('desc') :
			row.extend((Color('{autoyellow}'+i.get('desc')+'{/autoyellow}'),Color('{autocyan}'+i.get('srs')[5:]+'{/autocyan}'),Color('{autored}'+i.get('ddt')+'{/autored}'),Color('{autogreen}'+i.get('mnth_yr')+'{/autogreen}'),Color('{autoyellow}'+i.get('tm')+'{/autoyellow}')))
			table_data.append(row)

	table_instance = DoubleTable(table_data)
	table_instance.inner_row_border = True

	print(table_instance.table)
	print()
Ejemplo n.º 32
0
    def get_report(self) -> str:
        """
        Get report
        :return:
        """

        rows = [list(self.data.keys())]
        for i in range(len(self.data["month"])):
            rows.append([self.data[k][i] for k in rows[0]])
        report_table = DoubleTable(rows)

        for i in range(1, len(rows)):
            report_table.justify_columns[i] = "right"

        return report_table.table
def make_table(result):
    table_data = [['S.No', 'Name', 'Rating']]

    for s_no,res in enumerate(result,1):
        row = []
        row.extend((Color('{autoyellow}' + str(s_no) + '.' + '{/autoyellow}'),
                        Color('{autogreen}' + res[0] + '{/autogreen}'),
                        Color('{autoyellow}' + res[1] + '{/autoyellow}')))
        table_data.append(row)

    table_instance = DoubleTable(table_data)
    table_instance.inner_row_border = True

    print(table_instance.table)
    print()
Ejemplo n.º 34
0
    def get_table(self, arch, pattern, colored=False, verbose=False):
        '''
        This function is used in sys command (when user want to find a specific syscall)

        :param Architecture for syscall table;
        :param Searching pattern;
        :param Flag for verbose output
        :return Return a printable table of matched syscalls
        '''

        if pattern != None and pattern != '':
            rawtable = self.search(arch, pattern)
        else:
            rawtable = self.tables[arch]

        if len(rawtable) == 0:
            return None

        used_hd = self.__fetch_used_headers(rawtable, verbose)
        table = [
            self.__make_colored_row(used_hd, 'yellow,bold', upper=True)
            if colored else used_hd
        ]

        for command in rawtable:
            cur_tb_field = []
            for hd in used_hd:
                value = command[hd]
                cur_tb_field.append(
                    self.__make_colored_field(value, hd, verbose=verbose))
            table.append(cur_tb_field)
        return DoubleTable(table)
Ejemplo n.º 35
0
def test_single_line():
    """Test single-lined cells."""
    table_data = [
        ['Name', 'Color', 'Type'],
        ['Avocado', 'green', 'nut'],
        ['Tomato', 'red', 'fruit'],
        ['Lettuce', 'green', 'vegetable'],
        ['Watermelon', 'green'],
        [],
    ]
    table = DoubleTable(table_data, 'Example')
    table.inner_footing_row_border = True
    table.justify_columns[0] = 'left'
    table.justify_columns[1] = 'center'
    table.justify_columns[2] = 'right'
    actual = table.table

    expected = (
        u'\u2554Example\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n'

        u'\u2551 Name       \u2551 Color \u2551      Type \u2551\n'

        u'\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n'

        u'\u2551 Avocado    \u2551 green \u2551       nut \u2551\n'

        u'\u2551 Tomato     \u2551  red  \u2551     fruit \u2551\n'

        u'\u2551 Lettuce    \u2551 green \u2551 vegetable \u2551\n'

        u'\u2551 Watermelon \u2551 green \u2551           \u2551\n'

        u'\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n'

        u'\u2551            \u2551       \u2551           \u2551\n'

        u'\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d'
    )
    assert actual == expected
def analyze_bucket(bucket):
    bucket_location = client.get_bucket_location(Bucket=bucket)['LocationConstraint']
    new_client = boto3.client('s3', region_name=bucket_location)
    bucket_acl = new_client.get_bucket_acl(Bucket=bucket)
    permission = []

    for grants in bucket_acl['Grants']:

        if ('URI' in grants['Grantee']) and ('AllUser' in grants['Grantee']['URI']):
            permission.append(grants['Permission'])

    if len(permission) == 1:

        if permission[0] == 'READ':
            globalListAccess = 'YES'
            globalWriteAccess = 'NO'

        table_data = [
            ['BucketName', 'Region', 'GlobalListAccess', 'GlobalWriteAccess'],
            [bucket, bucket_location, globalListAccess, globalWriteAccess],
        ]
        table = DoubleTable(table_data)
        table.inner_row_border = True
        print(table.table)

    elif len(permission) > 1:

        if permission[0] == 'READ':
            globalListAccess = 'YES'
        if permission[1] == 'WRITE':
            globalWriteAccess = 'YES'
        else:
            globalWriteAccess = 'NO'

        table_data = [
            ['BucketName', 'Region', 'GlobalListAccess', 'GlobalWriteAccess'],
            [bucket, bucket_location, globalListAccess, globalWriteAccess],

        ]
        table = DoubleTable(table_data)
        table.inner_row_border = True
        print(table.table)
print('--- Fetching hackathons--- \n')
driver = webdriver.PhantomJS()
driver.get('https://www.hackerearth.com/challenges/')
res = driver.page_source
soup = BeautifulSoup(res, 'lxml')
upcoming = soup.find('div',{'class':'upcoming challenge-list'})
all_hackathons = upcoming.find_all('div',{'class':'challenge-content'})

table_data = [['S.No', 'Name', 'Type', 'Timings']]

for s_no,hackathon in enumerate(all_hackathons,1):
    row = []
    challenge_type = hackathon.find('div',{'class':'challenge-type'}).text.replace("\n"," ").strip()
    challenge_name = hackathon.find('div',{'class':'challenge-name'}).text.replace("\n"," ").strip()
    date_time = hackathon.find('div',{'class':'challenge-list-meta challenge-card-wrapper'}).text.replace("\n"," ").strip()
    row.extend((Color('{autoyellow}' + str(s_no) + '.' + '{/autoyellow}'),
                    Color('{autocyan}' + challenge_name + '{/autogreen}'),
                    Color('{autogreen}' + challenge_type + '{/autoyellow}'),
                    Color('{autoyellow}' + date_time + '{/autoyellow}')))
    table_data.append(row)


table_instance = DoubleTable(table_data)
table_instance.inner_row_border = True

print(table_instance.table)
print()

    
Ejemplo n.º 38
0
def test_multi_line():
    """Test multi-lined cells."""
    table_data = [
        ["Show", "Characters"],
        ["Rugrats", "Tommy Pickles, Chuckie Finster, Phillip DeVille, Lillian DeVille, Angelica Pickles,\nDil Pickles"],
        ["South Park", "Stan Marsh, Kyle Broflovski, Eric Cartman, Kenny McCormick"],
    ]
    table = DoubleTable(table_data)

    # Test defaults.
    actual = table.table
    expected = (
        u"\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n"
        u"\u2551 Show       \u2551 Characters                                                                          "
        u"\u2551\n"
        u"\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n"
        u"\u2551 Rugrats    \u2551 Tommy Pickles, Chuckie Finster, Phillip DeVille, Lillian DeVille, Angelica Pickles, "
        u"\u2551\n"
        u"\u2551            \u2551 Dil Pickles                                                                         "
        u"\u2551\n"
        u"\u2551 South Park \u2551 Stan Marsh, Kyle Broflovski, Eric Cartman, Kenny McCormick                          "
        u"\u2551\n"
        u"\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d"
    )
    assert actual == expected

    # Test inner row border.
    table.inner_row_border = True
    actual = table.table
    expected = (
        u"\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n"
        u"\u2551 Show       \u2551 Characters                                                                          "
        u"\u2551\n"
        u"\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n"
        u"\u2551 Rugrats    \u2551 Tommy Pickles, Chuckie Finster, Phillip DeVille, Lillian DeVille, Angelica Pickles, "
        u"\u2551\n"
        u"\u2551            \u2551 Dil Pickles                                                                         "
        u"\u2551\n"
        u"\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n"
        u"\u2551 South Park \u2551 Stan Marsh, Kyle Broflovski, Eric Cartman, Kenny McCormick                          "
        u"\u2551\n"
        u"\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d"
    )
    assert actual == expected

    # Justify right.
    table.justify_columns = {1: "right"}
    actual = table.table
    expected = (
        u"\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n"
        u"\u2551 Show       \u2551                                                                          Characters "
        u"\u2551\n"
        u"\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n"
        u"\u2551 Rugrats    \u2551 Tommy Pickles, Chuckie Finster, Phillip DeVille, Lillian DeVille, Angelica Pickles, "
        u"\u2551\n"
        u"\u2551            \u2551                                                                         Dil Pickles "
        u"\u2551\n"
        u"\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n"
        u"\u2551 South Park \u2551                          Stan Marsh, Kyle Broflovski, Eric Cartman, Kenny McCormick "
        u"\u2551\n"
        u"\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550"
        u"\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d"
    )
    assert actual == expected
Ejemplo n.º 39
0
def test_multi_line():
    """Test multi-lined cells."""
    table_data = [
        ['Show', 'Characters'],
        ['Rugrats', 'Tommy Pickles, Chuckie Finster, Phillip DeVille, Lillian DeVille, Angelica Pickles,\nDil Pickles'],
        ['South Park', 'Stan Marsh, Kyle Broflovski, Eric Cartman, Kenny McCormick']
    ]
    table = DoubleTable(table_data)

    # Test defaults.
    actual = table.table
    expected = (
        u'\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n'

        u'\u2551 Show       \u2551 Characters                                                                          '
        u'\u2551\n'

        u'\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n'

        u'\u2551 Rugrats    \u2551 Tommy Pickles, Chuckie Finster, Phillip DeVille, Lillian DeVille, Angelica Pickles, '
        u'\u2551\n'

        u'\u2551            \u2551 Dil Pickles                                                                         '
        u'\u2551\n'

        u'\u2551 South Park \u2551 Stan Marsh, Kyle Broflovski, Eric Cartman, Kenny McCormick                          '
        u'\u2551\n'

        u'\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d'
    )
    assert actual == expected

    # Test inner row border.
    table.inner_row_border = True
    actual = table.table
    expected = (
        u'\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n'

        u'\u2551 Show       \u2551 Characters                                                                          '
        u'\u2551\n'

        u'\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n'

        u'\u2551 Rugrats    \u2551 Tommy Pickles, Chuckie Finster, Phillip DeVille, Lillian DeVille, Angelica Pickles, '
        u'\u2551\n'

        u'\u2551            \u2551 Dil Pickles                                                                         '
        u'\u2551\n'

        u'\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n'

        u'\u2551 South Park \u2551 Stan Marsh, Kyle Broflovski, Eric Cartman, Kenny McCormick                          '
        u'\u2551\n'

        u'\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d'
    )
    assert actual == expected

    # Justify right.
    table.justify_columns = {1: 'right'}
    actual = table.table
    expected = (
        u'\u2554\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2566\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2557\n'

        u'\u2551 Show       \u2551                                                                          Characters '
        u'\u2551\n'

        u'\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n'

        u'\u2551 Rugrats    \u2551 Tommy Pickles, Chuckie Finster, Phillip DeVille, Lillian DeVille, Angelica Pickles, '
        u'\u2551\n'

        u'\u2551            \u2551                                                                         Dil Pickles '
        u'\u2551\n'

        u'\u2560\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u256c\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2563\n'

        u'\u2551 South Park \u2551                          Stan Marsh, Kyle Broflovski, Eric Cartman, Kenny McCormick '
        u'\u2551\n'

        u'\u255a\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2569\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550'
        u'\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u2550\u255d'
    )
    assert actual == expected
Ejemplo n.º 40
0
def printTasks(board_id,board_name):
	query = "SELECT task_ids FROM boards WHERE board_id = {0}".format(board_id)
	cursor.execute(query)
	taskList = []
	for task in cursor:
		taskList.append(task)
	print taskList

	tasks = []
	for task in taskList:
		query2 = "SELECT task_description,task_state FROM tasks WHERE task_id = {0}".format(task)
		currentTask = cursor.execute(query2)
		tasks.append(currentTask)

	print tasks

	bl = 0
	ip = 0
	done = 0
	blList = []
	ipList = []
	doneList = []
	i = 0
	(width, height) = console.getTerminalSize()
	for task in tasks:
		for char in task[0]:
			if i == width/3-4:
				task[0] = insert(task[0],'\n',i) 
	    	i+=1
		if task[1] == 0:
			bl += 1
			blList.append(task[0])
		if task[1] == 1:
			ip+= 1
			ipList.append(task[0])
		if task[1] == 2:
			done += 1
			doneList.append(task[0])
	backLogWithSpacing = "Backlog" + " " * (width/3-4-len("Backlog"))
	inProgressWithSpacing = "In Progress" + " " * (width/3-4-len("In Progress"))
	doneWithSpacing = "Done" + " " * (width/3-4-len("Done"))
	allTasks = [[backLogWithSpacing,inProgressWithSpacing,doneWithSpacing]]
	for i in range (0,max(bl,ip,done)):
		currentList = []
		if i < bl:
			currentList.append(blList[i])
		else:
			currentList.append('')
		if i < ip:
			currentList.append[ipList[i]]
		else:
			currentList.append('')
		if i < done:
			currentList.append(doneList[i])
		else:
			currentList.append('')
		allTasks.append(currentList)

	table = DoubleTable(allTasks, board_name)
	table.inner_row_border = True
	print(table.table)
Ejemplo n.º 41
0
        else:
            in_data = 'login'
            

    if in_data == 'boards':
        listBoards =  models.database.getBoards(user.getID())
        printBoards = []
        temp = []
        #print listBoards
        for i in range (1,len(listBoards)+1):
            temp.append(listBoards[i-1])
            if i % 1 == 0:
                printBoards.append(temp)
                #print printBoards
                temp = []
        table = DoubleTable(printBoards, 'Boards')
        table.inner_row_border = True
        print(table.table)
        
        in_data = prompt.query('Pick board(0 to create):')

        if in_data == '0':
        	boardName = prompt.query('Enter board name:')
        	boardUsers = prompt.query('Enter users(separate by comma):')
        	#print boardUsers 
        	boardUsers = boardUsers.split(',')
        	#print boardUsers
        	currentBoard = user.makeBoard(boardName,user,boardUsers)
        else:
	    	(boardid,leaderid, memberid,taskids) = models.database.pickBoard(in_data)
	    	currentBoard = Board(boardid,in_data,taskids,leaderid,memberid)
Ejemplo n.º 42
0
def getSerialData():
    
    table_data = []
    
    
    try:
        line = ser.readline()
        data = line.rstrip('\r')
        data = data.rstrip('\n')
        data = data.split(' ');
        if data != ' ':
           if (len(data) == 6 ):
               table_data = [
               ['Device','dest','type','seq','bat', 'temp'],
               [data[0],data[1],data[2],data[3],data[4],data[5]]
               ]
               table = DoubleTable(table_data, 'Shiva Home Control')
               table.inner_row_border = True
               table.justify_columns[2] = 'right'
               print(table.table)
               if('4' == data[0]):
                   with open("test.txt", "a") as myfile:
                       now_utc = datetime.now(timezone('CET'))
                       t = now_utc.strftime("%Y-%m-%d %H:%M:%S")
                       s = "{}: {} {} {} {} {} {}\n".format(t, data[0],data[1],data[2],data[3],data[4],data[5])
                       myfile.write(s)
                   myfile.close()
                   
               if('1' == data[0]):
                   with open("test_solar.txt", "a") as myfile:
                       now_utc = datetime.now(timezone('CET'))
                       t = now_utc.strftime("%Y-%m-%d %H:%M:%S")
                       s = "{}: {} {} {} {} {} {}\n".format(t, data[0],data[1],data[2],data[3],data[4],data[5])
                       myfile.write(s)
                   myfile.close()
              
               if('2' == data[0]):
                   with open("test_solar_2.txt", "a") as myfile:
                       now_utc = datetime.now(timezone('CET'))
                       t = now_utc.strftime("%Y-%m-%d %H:%M:%S")
                       s = "{}: {} {} {} {} {} {}\n".format(t, data[0],data[1],data[2],data[3],data[4],data[5])
                       myfile.write(s)
                   myfile.close()
                   
               if('3' == data[0]):
                   with open("test_solar_3.txt", "a") as myfile:
                       now_utc = datetime.now(timezone('CET'))
                       t = now_utc.strftime("%Y-%m-%d %H:%M:%S")
                       s = "{}: {} {} {} {} {} {}\n".format(t, data[0],data[1],data[2],data[3],data[4],data[5])
                       myfile.write(s)
                   myfile.close()
                   
                   
               if('5' == data[0]):
                   with open("test_solar_5.txt", "a") as myfile:
                       now_utc = datetime.now(timezone('CET'))
                       t = now_utc.strftime("%Y-%m-%d %H:%M:%S")
                       s = "{}: {} {} {} {} {} {}\n".format(t, data[0],data[1],data[2],data[3],data[4],data[5])
                       myfile.write(s)
                   myfile.close()     
                   
              #sys.stdout.write('%s %s %s %s\r' % (data[0], data[2], data[3], data[4]))
               #sys.stdout.flush()
               if('1'==data[0]):
                   loc = "Living Room"
               elif('2'==data[0]):
                   loc = "out"
               elif('3'==data[0]):
                   loc = "out"
               elif('4'==data[0]):
                   loc = "out"
               elif('5'==data[0]):
                   loc = "out" 
               elif('6'==data[0]):
                   loc = "out"     
               else:
                   loc = "undefined error"
                   return 0
                   
                   
               now_utc = datetime.now(timezone('CET'));
               t = now_utc.strftime("%Y-%m-%d %H:%M:%S");  
               
               qry = """UPDATE temperature SET  seq=%s, temp=%s, bat=%s WHERE id='%s'""" % (data[3],data[5],data[4],data[0])
               sendMySQLQry(qry)
    
               if('6' == data[2]):
                   #  0     1      2     3     4      5     6
                   # ID | DEST | TYPE | SEQ | BAT | TEMP | HUM
                   qry = """INSERT INTO tempMeas (id, room, seq, bat, temp, hum, time) VALUES ('%s', '%s', '%s','%s', '%s', '%s', '%s')""" % (data[0], loc, data[3], data[4],data[5], data[5] ,t);
                   sendMySQLQry(qry)
                   
           else:
               print "invalid data"
               print data

    except (KeyboardInterrupt, SystemExit):
            ser.close()
            closeMySQL()
Ejemplo n.º 43
0
def printTasks(board_id, board_name):
    query = "SELECT task_ids FROM boards WHERE board_id = {0}".format(board_id)
    cursor.execute(query)
    taskList = []
    for task in cursor:
        taskList.append(task)
        # print taskList

    tasks = []
    if str(taskList[0]) != "(u'',)":
        for task in str(taskList[0]).split(","):
            # print task
            if task != "'" and task != ")":
                # print task.strip('()').replace("u'","")
                query2 = "SELECT task_description,task_state FROM tasks WHERE task_id = {0}".format(
                    task.strip("()").replace("u'", "")
                )
                cursor.execute(query2)
                for i in cursor:
                    # print i
                    tasks.append(i)

                # print tasks

    bl = 0
    ip = 0
    done = 0
    blList = []
    ipList = []
    doneList = []
    i = 0
    (width, height) = console.getTerminalSize()
    for task in tasks:
        for char in task[0]:
            if i == width / 3 - 4:
                task[0] = insert(task[0], "\n", i)
        i += 1
        if task[1] == "0":
            bl += 1
            appender = "{0}".format(i) + ":" + task[0]
            # appender = '{0}'.format(i)+ ' '+task[0]
            update_query = "UPDATE tasks SET task_description= '{0}' WHERE task_description='{1}'".format(
                appender, task[0]
            )
            cursor.execute(update_query)
            conn.commit()

            blList.append(appender)
        if task[1] == "1":
            update_query = "UPDATE tasks SET task_description= '{0}' WHERE task_description='{1}'".format(
                appender, task[0]
            )
            cursor.execute(update_query)
            conn.commit()
            ip += 1
            ipList.append(task[0])
        if task[1] == "2":
            done += 1
            update_query = "UPDATE tasks SET task_description= '{0}' WHERE task_description='{1}'".format(
                appender, task[0]
            )
            cursor.execute(update_query)
            conn.commit()
            doneList.append(task[0])

    backLogWithSpacing = "Backlog" + " " * (width / 3 - 4 - len("Backlog"))
    inProgressWithSpacing = "In Progress" + " " * (width / 3 - 4 - len("In Progress"))
    doneWithSpacing = "Done" + " " * (width / 3 - 4 - len("Done"))
    allTasks = [[backLogWithSpacing, inProgressWithSpacing, doneWithSpacing]]
    # print bl
    # print ip
    # print done
    for i in range(0, max(bl, ip, done)):
        currentList = []
        if i < bl:
            currentList.append(blList[i])
        else:
            currentList.append("")
        if i < ip:
            currentList.append[ipList[i]]
        else:
            currentList.append("")
        if i < done:
            currentList.append(doneList[i])
        else:
            currentList.append("")
        allTasks.append(currentList)

    table = DoubleTable(allTasks, board_name)
    table.inner_row_border = True
    print(table.table)