Пример #1
0
    def list(self):
        """List the Drbd volumes and statuses"""
        # Set permissions as having been checked, as listing VMs
        # does not require permissions
        self._get_registered_object('auth').set_permission_asserted()

        # Create table and add headers
        table = Texttable()
        table.set_deco(Texttable.HEADER | Texttable.VLINES)
        table.header(('Name', 'Type', 'Location', 'Nodes', 'Shared', 'Free Space', 'ID'))

        # Set column alignment and widths
        table.set_cols_width((15, 5, 30, 70, 6, 15, 50))
        table.set_cols_align(('l', 'l', 'l', 'l', 'l', 'l', 'l'))

        for storage_backend in self.get_all():
            table.add_row((
                storage_backend.name,
                storage_backend.storage_type,
                storage_backend.get_location(),
                ', '.join(storage_backend.nodes),
                str(storage_backend.shared),
                SizeConverter(storage_backend.get_free_space()).to_string(),
                storage_backend.id_
            ))
        return table.draw()
Пример #2
0
    def get_aggregation_summary_text(self, matches):
        text = ''
        if 'aggregation' in self.rule and 'summary_table_fields' in self.rule:
            summary_table_fields = self.rule['summary_table_fields']
            if not isinstance(summary_table_fields, list):
                summary_table_fields = [summary_table_fields]
            # Include a count aggregation so that we can see at a glance how many of each aggregation_key were encountered
            summary_table_fields_with_count = summary_table_fields + ['count']
            text += "Aggregation resulted in the following data for summary_table_fields ==> {0}:\n\n".format(summary_table_fields_with_count)
            text_table = Texttable()
            text_table.header(summary_table_fields_with_count)
            match_aggregation = {}

            # Maintain an aggregate count for each unique key encountered in the aggregation period
            for match in matches:
                key_tuple = tuple([unicode(lookup_es_key(match, key)) for key in summary_table_fields])
                if key_tuple not in match_aggregation:
                    match_aggregation[key_tuple] = 1
                else:
                    match_aggregation[key_tuple] = match_aggregation[key_tuple] + 1
            for keys, count in match_aggregation.iteritems():
                text_table.add_row([key for key in keys] + [count])
            text += text_table.draw() + '\n\n'

        return unicode(text)
Пример #3
0
    def do_delete(self, args):
        try:
            #add arguments
            doParser = self.arg_delete()
            doArgs = doParser.parse_args(shlex.split(args))

            #if the help command is called, parse_args returns None object
            if not doArgs:
                return 2

            #call UForge API
            printer.out("Searching bundle with id ["+doArgs.id+"] ...")
            myBundle = self.api.Users(self.login).Mysoftware(doArgs.id).Get()
            if myBundle is None or type(myBundle) is not MySoftware:
                printer.out("Bundle not found", printer.WARNING)
            else:
                table = Texttable(800)
                table.set_cols_dtype(["t","t","t", "t","t", "t"])
                table.header(["Id", "Name", "Version", "Description", "Size", "Imported"])
                table.add_row([myBundle.dbId, myBundle.name, myBundle.version, myBundle.description, size(myBundle.size), "X" if myBundle.imported else ""])
                print table.draw() + "\n"
                if generics_utils.query_yes_no("Do you really want to delete bundle with id "+str(myBundle.dbId)):
                    self.api.Users(self.login).Mysoftware(myBundle.dbId).Delete()
                    printer.out("Bundle deleted", printer.OK)


        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: "+str(e), printer.ERROR)
            self.help_delete()
        except Exception as e:
            return handle_uforge_exception(e)
Пример #4
0
def top(db):
    count_query = '''
    SELECT count(*)
    FROM commands
    WHERE
        timestamp > ?
    '''
    percentage = 100 / float(execute_scalar(db, count_query, TIMESTAMP))

    query = '''
    SELECT count(*) AS counts, command
    FROM commands
    WHERE timestamp > ?
    GROUP BY command
    ORDER BY counts DESC
    LIMIT 20
    '''

    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_cols_align(('r', 'r', 'l'))
    table.header(('count', '%', 'command'))
    for row in db.execute(query, (TIMESTAMP,)):
        table.add_row((row[0], int(row[0]) * percentage, row[1]))
    print table.draw()
Пример #5
0
 def __repr__(self):
   t = Texttable()
   
   for rowId in range(0,self.size[0]):
     rowDetails = []
     for cellId in range(0,self.size[1]):
       cell = self.cellAtLocation(cellId,rowId)
       
       color = {
         "free":   bcolors.WHITE,
         "mine":   bcolors.PURPLE,
         "theirs": bcolors.RED
       }[cell.getState()]
       
       rowDetails.append(
         get_color_string(color, cell)
       )
     
     t.add_row(rowDetails)
   
   return "\n".join([
     t.draw(),
     self.board,
     self.state
   ])
Пример #6
0
    def list(self):
        """List the Drbd volumes and statuses"""
        # Create table and add headers
        table = Texttable()
        table.set_deco(Texttable.HEADER | Texttable.VLINES)
        table.header(('Volume Name', 'VM', 'Minor', 'Port', 'Role', 'Connection State',
                      'Disk State', 'Sync Status'))

        # Set column alignment and widths
        table.set_cols_width((30, 20, 5, 5, 20, 20, 20, 13))
        table.set_cols_align(('l', 'l', 'c', 'c', 'l', 'c', 'l', 'c'))

        # Iterate over Drbd objects, adding to the table
        for drbd_object in self.get_all_drbd_hard_drive_object(True):
            table.add_row((drbd_object.resource_name,
                           drbd_object.vm_object.get_name(),
                           drbd_object.drbd_minor,
                           drbd_object.drbd_port,
                           'Local: %s, Remote: %s' % (drbd_object._drbdGetRole()[0].name,
                                                      drbd_object._drbdGetRole()[1].name),
                           drbd_object._drbdGetConnectionState().name,
                           'Local: %s, Remote: %s' % (drbd_object._drbdGetDiskState()[0].name,
                                                      drbd_object._drbdGetDiskState()[1].name),
                           'In Sync' if drbd_object._isInSync() else 'Out of Sync'))
        return table.draw()
Пример #7
0
 def do_list(self, args):
         try:                        
                 #call UForge API
                 printer.out("Getting scans for ["+self.login+"] ...")
                 myScannedInstances = self.api.Users(self.login).Scannedinstances.Get(None, Includescans="true")
                 if myScannedInstances is None or not hasattr(myScannedInstances, 'get_scannedInstance'):
                         printer.out("No scans available")
                         return
                 else:
                         table = Texttable(800)
                         table.set_cols_dtype(["t","t","t","t"])
                         table.header(["Id", "Name", "Status", "Distribution"])
                         myScannedInstances = generics_utils.oder_list_object_by(myScannedInstances.get_scannedInstance(), "name")
                         for myScannedInstance in myScannedInstances:
                                     table.add_row([myScannedInstance.dbId, myScannedInstance.name, "", myScannedInstance.distribution.name + " "+ myScannedInstance.distribution.version + " " + myScannedInstance.distribution.arch])
                                     scans = generics_utils.oder_list_object_by(myScannedInstance.get_scans().get_scan(), "name")
                                     for scan in scans:
                                                 if (scan.status.complete and not scan.status.error and not scan.status.cancelled):
                                                         status = "Done"
                                                 elif(not scan.status.complete and not scan.status.error and not scan.status.cancelled):
                                                         status = str(scan.status.percentage)+"%"
                                                 else:
                                                         status = "Error"
                                                 table.add_row([scan.dbId, "\t"+scan.name, status, "" ])
                                                 
                         print table.draw() + "\n"
                         printer.out("Found "+str(len(myScannedInstances))+" scans")
         except ArgumentParserError as e:
                 printer.out("ERROR: In Arguments: "+str(e), printer.ERROR)
                 self.help_list()
         except Exception as e:        
                 return generics_utils.handle_uforge_exception(e)
Пример #8
0
    def do_search(self, args):
        try:
            #add arguments
            doParser = self.arg_search()
            doArgs = doParser.parse_args(shlex.split(args))

            #if the help command is called, parse_args returns None object
            if not doArgs:
                    return 2

            #call UForge API
            printer.out("Search package '"+doArgs.pkg+"' ...")
            distribution = self.api.Distributions(doArgs.id).Get()
            printer.out("for OS '"+distribution.name+"', version "+distribution.version)
            pkgs = self.api.Distributions(distribution.dbId).Pkgs.Getall(Query="name=="+doArgs.pkg)
            pkgs = pkgs.pkgs.pkg
            if pkgs is None or len(pkgs) == 0:
                printer.out("No package found")
            else:
                table = Texttable(800)
                table.set_cols_dtype(["t","t","t","t","t","t","t"])
                table.header(["Name", "Version", "Arch", "Release", "Build date", "Size", "FullName"])
                pkgs = generics_utils.order_list_object_by(pkgs, "name")
                for pkg in pkgs:
                    table.add_row([pkg.name, pkg.version, pkg.arch, pkg.release, pkg.pkgBuildDate.strftime("%Y-%m-%d %H:%M:%S"), size(pkg.size), pkg.fullName])
                print table.draw() + "\n"
                printer.out("Found "+str(len(pkgs))+" packages")
        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: "+str(e), printer.ERROR)
            self.help_search()
        except Exception as e:
            return handle_uforge_exception(e)
Пример #9
0
    def schedule(self, label="default", *argvs, **kwargs):
        simulate = kwargs.get("simulate")
        reserver = kwargs.get("reserve")
        fullInfo = kwargs.get("fullInfo")

        if kwargs.get("list"):
            tp = TaskPeriod.objects.all()
            table = Texttable()
            table.set_deco(Texttable.HEADER)
            table.header(["Id", "Title", "Label", "Schedule"])
            for it in tp:
                table.add_row([it.id, it.title, it.label, it.cron])
            print(table.draw())

        if kwargs.get("template_id"):
            template_ids = kwargs.get("template_id")
            logger.debug("Schedule template id %s" % template_ids)

            filter = {"id__in": template_ids}
            self.scheduleByJobTemplates(
                filter, label, fullInfo, simulate, reserver)

        if kwargs.get("schedule_label"):
            period_label = kwargs.get("schedule_label")
            filter = {"schedule__label__in": period_label, "is_enable": True}
            if not label:
                label = period_label
            self.scheduleByJobTemplates(
                filter, "".join(label), fullInfo, simulate, reserver)
Пример #10
0
def print_table(prefix, items):
    table = Texttable(max_width=160)
    table.set_deco(Texttable.HEADER)
    table.header(['%s_id' % prefix, '%s_updated' % prefix, '%s_fk' % prefix])
    for key, values in items.iteritems():
        table.add_row([key, values.get('updated'), values.get('opposite_id')])
    print table.draw() + "\n"
Пример #11
0
        def do_list(self, args):
                try:
                        doParser = self.arg_list()
                        doArgs = doParser.parse_args(shlex.split(args))

                        printer.out("Getting roles and their entitlements for user [" + doArgs.account + "]:\n")
                        roles = self.api.Users(doArgs.account).Roles.Getall()

                        table = Texttable(200)
                        table.set_cols_align(["l", "l"])
                        table.header(["Name", "Description"])
                        table.set_cols_width([30,60])
                        for role in roles.roles.role:
                                table.add_row([role.name.upper(), role.description])
                                for entitlement in role.entitlements.entitlement:
                                        table.add_row(["===> " + entitlement.name, entitlement.description])

                        printer.out("Role entitlements are represented with \"===>\".", printer.INFO)
                        print table.draw() + "\n"
                        return 0

                except ArgumentParserError as e:
                        printer.out("In Arguments: "+str(e), printer.ERROR)
                        self.help_list()
                except Exception as e:
                        return handle_uforge_exception(e)
Пример #12
0
 def do_list(self, args):
     try:
         #call UForge API
         printer.out("Getting distributions for ["+self.login+"] ...")
         distributions = self.api.Users(self.login).Distros.Getall()
         distributions = distributions.distributions
         if distributions is None or not hasattr(distributions, "distribution"):
             printer.out("No distributions available")
         else:
             table = Texttable(800)
             table.set_cols_dtype(["t","t","t","t","t", "t"])
             table.header(["Id", "Name", "Version", "Architecture", "Release Date", "Profiles"])
             distributions = generics_utils.order_list_object_by(distributions.distribution, "name")
             for distribution in distributions:
                 profiles = self.api.Distributions(distribution.dbId).Profiles.Getall()
                 profiles = profiles.distribProfiles.distribProfile
                 if len(profiles) > 0:
                     profile_text=""
                     for profile in profiles:
                         profile_text+=profile.name+"\n"
                     table.add_row([distribution.dbId, distribution.name, distribution.version, distribution.arch, distribution.releaseDate.strftime("%Y-%m-%d %H:%M:%S") if distribution.releaseDate is not None else "", profile_text])
                 else:
                     table.add_row([distribution.dbId, distribution.name, distribution.version, distribution.arch, distribution.releaseDate.strftime("%Y-%m-%d %H:%M:%S") if distribution.releaseDate is not None else "", "-"])
             print table.draw() + "\n"
             printer.out("Found "+str(len(distributions))+" distributions")
         return 0
     except ArgumentParserError as e:
         printer.out("ERROR: In Arguments: "+str(e), printer.ERROR)
         self.help_list()
     except Exception as e:
         return handle_uforge_exception(e)
Пример #13
0
    def do_delete(self, args):
        try:
            #add arguments
            doParser = self.arg_delete()
            try:
                doArgs = doParser.parse_args(args.split())
            except SystemExit as e:
                return
            #call UForge API
            printer.out("Searching template with id ["+doArgs.id+"] ...")
            myAppliance = self.api.Users(self.login).Appliances(doArgs.id).Get()
            if myAppliance is None or type(myAppliance) is not Appliance:
                printer.out("Template not found")
            else:
                table = Texttable(800)
                table.set_cols_dtype(["t","t","t","t","t","t","t","t","t","t"])
                table.header(["Id", "Name", "Version", "OS", "Created", "Last modified", "# Imgs", "Updates", "Imp", "Shared"])
                table.add_row([myAppliance.dbId, myAppliance.name, str(myAppliance.version), myAppliance.distributionName+" "+myAppliance.archName,
                               myAppliance.created.strftime("%Y-%m-%d %H:%M:%S"), myAppliance.lastModified.strftime("%Y-%m-%d %H:%M:%S"), len(myAppliance.imageUris.uri),myAppliance.nbUpdates, "X" if myAppliance.imported else "", "X" if myAppliance.shared else ""])
                print table.draw() + "\n"

                if doArgs.no_confirm:
                    self.api.Users(self.login).Appliances(myAppliance.dbId).Delete()
                    printer.out("Template deleted", printer.OK)
                elif generics_utils.query_yes_no("Do you really want to delete template with id "+str(myAppliance.dbId)):
                    self.api.Users(self.login).Appliances(myAppliance.dbId).Delete()
                    printer.out("Template deleted", printer.OK)
            return 0
        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: "+str(e), printer.ERROR)
            self.help_delete()
        except Exception as e:
            return handle_uforge_exception(e)
Пример #14
0
def print_mapping(prefix, key, items):
    table = Texttable(max_width=160)
    table.set_deco(Texttable.HEADER)
    table.header(['%s_%s' % (prefix, key),  '%s_fk' % prefix])
    for key, value in items.iteritems():
        table.add_row([key, value])
    print table.draw() + "\n"
Пример #15
0
    def do_list(self, args):
        try:
            #call UForge API
            printer.out("Getting generation formats for ["+self.login+"] ...")
            targetFormatsUser = self.api.Users(self.login).Targetformats.Getall()
            if targetFormatsUser is None or len(targetFormatsUser.targetFormats.targetFormat) == 0:
                printer.out("No generation formats available")
                return 0
            else:
                targetFormatsUser = generics_utils.order_list_object_by(targetFormatsUser.targetFormats.targetFormat,"name")
                table = Texttable(200)
                table.set_cols_align(["l", "l", "l", "l", "l", "c"])
                table.header(["Name", "Format", "Category", "Type", "CredAccountType", "Access"])
                for item in targetFormatsUser:
                    if item.access:
                        access = "X"
                    else:
                        access = ""
                    if item.credAccountType is None:
                        credAccountType = ""
                    else:
                        credAccountType = item.credAccountType
                    table.add_row(
                        [item.name, item.format.name, item.category.name, item.type, credAccountType,
                         access])
                print table.draw() + "\n"
            return 0

        except ArgumentParserError as e:
            printer.out("In Arguments: " + str(e), printer.ERROR)
            self.help_list()
        except Exception as e:
            return handle_uforge_exception(e)
Пример #16
0
    def do_promote(self, args):
        try:
            doParser = self.arg_promote()
            doArgs = doParser.parse_args(shlex.split(args))
            orgSpecified = org_utils.org_get(api=self.api, name=doArgs.org)

            adminUser = self.api.Users(doArgs.account).Get()

            if adminUser == None:
                printer.out("User [" + doArgs.account + "] doesn't exist.", printer.ERROR)
            else:
                self.api.Orgs(orgSpecified.dbId).Members(adminUser.loginName).Change(Admin=True, body=adminUser)
                printer.out("User [" + doArgs.account + "] has been promoted in [" + orgSpecified.name + "] :",
                            printer.OK)

            if adminUser.active == True:
                active = "X"
            else:
                active = ""

            printer.out("Informations about [" + adminUser.loginName + "] :")
            table = Texttable(200)
            table.set_cols_align(["c", "l", "c", "c", "c", "c", "c", "c"])
            table.header(
                ["Login", "Email", "Lastname", "Firstname", "Created", "Active", "Promo Code", "Creation Code"])
            table.add_row([adminUser.loginName, adminUser.email, adminUser.surname, adminUser.firstName,
                           adminUser.created.strftime("%Y-%m-%d %H:%M:%S"), active, adminUser.promoCode,
                           adminUser.creationCode])
            print table.draw() + "\n"
            return 0
        except ArgumentParserError as e:
            printer.out("In Arguments: " + str(e), printer.ERROR)
            self.help_promote()
        except Exception as e:
            return marketplace_utils.handle_uforge_exception(e)
Пример #17
0
    def do_info_draw_publication(self, info_image):
        printer.out("Information about publications:")
        pimages = self.api.Users(self.login).Pimages.Getall()
        table = Texttable(0)
        table.set_cols_align(["l", "l"])

        has_pimage = False
        for pimage in pimages.publishImages.publishImage:
            if pimage.imageUri == info_image.uri:
                has_pimage = True
                cloud_id = None
                publish_status = image_utils.get_message_from_status(pimage.status)
                if not publish_status:
                    publish_status = "Publishing"

                if publish_status == "Done":
                    cloud_id = pimage.cloudId
                    format_name = info_image.targetFormat.format.name
                    if format_name == "docker" or format_name == "openshift":
                        cloud_id = pimage.namespace + "/" + pimage.repositoryName + ":" + pimage.tagName

                table.add_row([publish_status, cloud_id])

        if has_pimage:
            table.header(["Status", "Cloud Id"])
            print table.draw() + "\n"
        else:
            printer.out("No publication")
Пример #18
0
def find_commands(db, *filters):
    user_filter = '\s+'.join(filters)
    user_re = re.compile(user_filter)
    RE_CACHE[user_filter] = user_re

    query = '''
    SELECT hostname, timestamp, duration, user_string
    FROM commands
    WHERE timestamp > ? AND user_string REGEXP ?
    ORDER BY timestamp
    '''

    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_cols_align(('l', 'r', 'r', 'l'))
    table.header(('host', 'date', 'duration', 'command'))

    host_width = 6
    max_command_width = 9
    now = time.time()
    for row in db.execute(query, (TIMESTAMP, user_filter)):
        host_width = max(host_width, len(row[0]))
        max_command_width = max(max_command_width, len(row[3]))
        table.add_row((
            row[0],
            format_time(row[1], now),
            format_duration(row[2]) if row[2] > 0 else '',
            highlight(row[3], user_re)))

    table.set_cols_width((host_width, 30, 10, max_command_width + 2))

    print table.draw()
Пример #19
0
 def do_list(self, args):
     try:
         #call UForge API
         printer.out("Getting templates for ["+self.login+"] ...")
         appliances = self.api.Users(self.login).Appliances().Getall()
         appliances = appliances.appliances
         if appliances is None or not hasattr(appliances, 'appliance'):
             printer.out("No template")
         else:
             images = self.api.Users(self.login).Images.Get()
             images = images.images
             table = Texttable(800)
             table.set_cols_dtype(["t","t","t","t","t","t","t","t","t","t"])
             table.header(["Id", "Name", "Version", "OS", "Created", "Last modified", "# Imgs", "Updates", "Imp", "Shared"])
             appliances = generics_utils.order_list_object_by(appliances.appliance, "name")
             for appliance in appliances:
                 nbImage=0
                 if images is not None and hasattr(images, 'image'):
                     for image in images.image:
                         if hasattr(image, 'applianceUri') and image.applianceUri == appliance.uri:
                             nbImage+=1
                 table.add_row([appliance.dbId, appliance.name, str(appliance.version), appliance.distributionName+" "+appliance.archName,
                                appliance.created.strftime("%Y-%m-%d %H:%M:%S"), appliance.lastModified.strftime("%Y-%m-%d %H:%M:%S"), nbImage, appliance.nbUpdates, "X" if appliance.imported else "", "X" if appliance.shared else ""])
             print table.draw() + "\n"
             printer.out("Found "+str(len(appliances))+" templates")
         return 0
     except ArgumentParserError as e:
         printer.out("ERROR: In Arguments: "+str(e), printer.ERROR)
         self.help_list()
     except Exception as e:
         return handle_uforge_exception(e)
Пример #20
0
    def do_disable(self, args):
        try:
            doParser = self.arg_disable()
            doArgs = doParser.parse_args(shlex.split(args))

            printer.out("Disabling user [" + doArgs.account + "] ...")
            user = self.api.Users(doArgs.account).Get()
            if user is None:
                printer.out("user " + doArgs.account + "does not exist", printer.ERROR)
            else:
                if user.active == False:
                    printer.out("User [" + doArgs.account + "] is already disabled", printer.ERROR)
                else:
                    user.active = False
                    self.api.Users(doArgs.account).Update(body=user)
                    printer.out("User [" + doArgs.account + "] is now disabled", printer.OK)
                if user.active == True:
                    actived = "X"
                else:
                    actived = ""
                printer.out("Informations about [" + doArgs.account + "] :")
                table = Texttable(200)
                table.set_cols_align(["c", "l", "c", "c", "c", "c", "c", "c"])
                table.header(
                    ["Login", "Email", "Lastname", "Firstname", "Created", "Active", "Promo Code", "Creation Code"])
                table.add_row([user.loginName, user.email, user.surname, user.firstName,
                               user.created.strftime("%Y-%m-%d %H:%M:%S"), actived, user.promoCode, user.creationCode])
                print table.draw() + "\n"
            return 0
        except ArgumentParserError as e:
            printer.out("In Arguments: " + str(e), printer.ERROR)
            self.help_disable()
        except Exception as e:
            return marketplace_utils.handle_uforge_exception(e)
Пример #21
0
        def do_info(self, args):
                try:
                        doParser = self.arg_info()
                        doArgs = doParser.parse_args(shlex.split(args))
                        
                        printer.out("Getting user ["+doArgs.account+"] ...")
                        user = self.api.Users(doArgs.account).Get()
                        if user is None:
                                printer.out("user "+ doArgs.account +" does not exist", printer.ERROR)
                        else:
                                if user.active:
                                        active = "X"
                                else:
                                        active = ""

                                printer.out("Informations about " + doArgs.account + ":",)
                                table = Texttable(200)
                                table.set_cols_align(["c", "l", "c", "c", "c", "c", "c", "c"])
                                table.header(["Login", "Email", "Lastname",  "Firstname",  "Created", "Active", "Promo Code", "Creation Code"])
                                table.add_row([user.loginName, user.email, user.surname , user.firstName, user.created.strftime("%Y-%m-%d %H:%M:%S"), active, user.promoCode, user.creationCode])
                                print table.draw() + "\n"
                        return 0

                except ArgumentParserError as e:
                        printer.out("In Arguments: "+str(e), printer.ERROR)
                        self.help_info()
                except Exception as e:
                        return handle_uforge_exception(e)
Пример #22
0
def render_datasets_as_table(datasets, display_heading=True):
    """
    Returns ASCII table view of datasets.

    :param datasets: The datasets to be rendered.
    :type datasets: :class:`mytardisclient.models.resultset.ResultSet`
    :param render_format: The format to display the data in ('table' or
        'json').
    :param display_heading: Setting `display_heading` to True ensures
        that the meta information returned by the query is summarized
        in a 'heading' before displaying the table.  This meta
        information can be used to determine whether the query results
        have been truncated due to pagination.
    """
    heading = "\n" \
        "Model: Dataset\n" \
        "Query: %s\n" \
        "Total Count: %s\n" \
        "Limit: %s\n" \
        "Offset: %s\n\n" \
        % (datasets.url, datasets.total_count,
           datasets.limit, datasets.offset) if display_heading else ""

    table = Texttable(max_width=0)
    table.set_cols_align(["r", 'l', 'l', 'l'])
    table.set_cols_valign(['m', 'm', 'm', 'm'])
    table.header(["Dataset ID", "Experiment(s)", "Description", "Instrument"])
    for dataset in datasets:
        table.add_row([dataset.id, "\n".join(dataset.experiments),
                       dataset.description, dataset.instrument])
    return heading + table.draw() + "\n"
Пример #23
0
def sub(db, command, *filters):
    counts = collections.defaultdict(int)
    user_filter = ' '.join(itertools.chain([command], filters))
    total = 0

    query = '''
    SELECT user_string
    FROM commands
    WHERE
        timestamp > ?
        AND command = ?
    '''

    for row in db.execute(query, (TIMESTAMP, command)):
        command = normalize_user_string(row[0])
        if command.startswith(user_filter):
            counts[command] += 1
            total += 1
    percentage = 100 / float(total)

    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_cols_align(('r', 'r', 'l'))
    table.set_cols_width((5, 6, 75))
    table.header(('count', '%', 'command'))
    for key, value in sorted(counts.iteritems(), key=lambda (k, v): (v, k), reverse=True)[:20]:
        table.add_row((value, value * percentage, key))
    print table.draw()
Пример #24
0
def render_schemas_as_table(schemas, display_heading=True):
    """
    Returns ASCII table view of schemas.

    :param schemas: The schemas to be rendered.
    :type schemas: :class:`mytardisclient.models.resultset.ResultSet`
    :param render_format: The format to display the data in ('table' or
        'json').
    :param display_heading: Setting `display_heading` to True ensures
        that the meta information returned by the query is summarized
        in a 'heading' before displaying the table.  This meta
        information can be used to determine whether the query results
        have been truncated due to pagination.
    """
    heading = "\n" \
        "Model: Schema\n" \
        "Query: %s\n" \
        "Total Count: %s\n" \
        "Limit: %s\n" \
        "Offset: %s\n\n" \
        % (schemas.url, schemas.total_count,
           schemas.limit, schemas.offset) if display_heading else ""

    table = Texttable(max_width=0)
    table.set_cols_align(["r", 'l', 'l', 'l', 'l', 'l', 'l'])
    table.set_cols_valign(['m', 'm', 'm', 'm', 'm', 'm', 'm'])
    table.header(["ID", "Name", "Namespace", "Type", "Subtype", "Immutable",
                  "Hidden"])
    for schema in schemas:
        table.add_row([schema.id, schema.name, schema.namespace,
                       schema.type, schema.subtype or '',
                       str(bool(schema.immutable)), str(bool(schema.hidden))])
    return heading + table.draw() + "\n"
Пример #25
0
def render_instruments_as_table(instruments, display_heading=True):
    """
    Returns ASCII table view of instruments.

    :param instruments: The instruments to be rendered.
    :type instruments: :class:`mytardisclient.models.resultset.ResultSet`
    :param render_format: The format to display the data in ('table' or
        'json').
    :param display_heading: Setting `display_heading` to True ensures
        that the meta information returned by the query is summarized
        in a 'heading' before displaying the table.  This meta
        information can be used to determine whether the query results
        have been truncated due to pagination.
    """
    heading = "\n" \
        "Model: Instrument\n" \
        "Query: %s\n" \
        "Total Count: %s\n" \
        "Limit: %s\n" \
        "Offset: %s\n\n" \
        % (instruments.url, instruments.total_count,
           instruments.limit, instruments.offset) if display_heading else ""

    table = Texttable(max_width=0)
    table.set_cols_align(["r", 'l', 'l'])
    table.set_cols_valign(['m', 'm', 'm'])
    table.header(["ID", "Name", "Facility"])
    for instrument in instruments:
        table.add_row([instrument.id, instrument.name, instrument.facility])
    return heading + table.draw() + "\n"
Пример #26
0
def make_ssh_fingerprints_table(output):
    ('Generate a table of SSH fingerprints in reStructuredText for the EOS Lab'
     'machines.')
    # Enable skip_bad_hosts -- we will list down hosts as such in the table.
    #
    # skip_bad_hosts and parallel are, unfortunately, mutually exclusive. Don't
    # see why they have to be, but that's the way it is.
    env.skip_bad_hosts = True

    # Generate table.
    results_dict = execute(_get_fingerprint)

    table = Texttable()
    # The default decoration produces the correct table.
    table.header(['Host', 'Fingerprint'])

    for host, command_output in sorted(six.iteritems(results_dict)):
        # Use the short host name.
        short_hostname = host.split('.')[0]

        fingerprint_text = (
            # Indicate that the host is down in the table.
            'down for maintenance' if
            # Fabric returns the exception if the task failed.
            isinstance(command_output, Exception)
            # Use a fixed-width font for the fingerprint itself.
            else '``{0}``'.format(command_output))
        table.add_row((short_hostname, fingerprint_text))

    with open(output, 'w') as output_file:
        six.print_(table.draw(), file=output_file)
Пример #27
0
        def do_list(self, args):
                try:
                        doParser = self.arg_list()
                        doArgs = doParser.parse_args(shlex.split(args))

                        printer.out("Getting entitlements list of the UForge :")
                        entList = self.api.Entitlements.Getall()
                        if entList is None:
                                printer.out("No entitlements found.", printer.OK)
                        else:
                                entList=generics_utils.order_list_object_by(entList.entitlements.entitlement, "name")
                                printer.out("Entitlement list for the UForge :")
                                table = Texttable(200)
                                table.set_cols_align(["l", "l"])
                                table.header(["Name", "Description"])
                                table.set_cols_width([30,60])
                                for item in entList:
                                        table.add_row([item.name, item.description])
                                print table.draw() + "\n"
                        return 0

                except ArgumentParserError as e:
                        printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
                        self.help_list()
                except Exception as e:
                        return handle_uforge_exception(e)
Пример #28
0
    def do_delete(self, args):
        try:
            # add arguments
            doParser = self.arg_delete()
            doArgs = doParser.parse_args(shlex.split(args))

            #if the help command is called, parse_args returns None object
            if not doArgs:
                    return 2

            # call UForge API
            printer.out("Searching account with id [" + doArgs.id + "] ...")
            account = self.api.Users(self.login).Accounts(doArgs.id).Get()
            if account is None:
                printer.out("No Account available", printer.WARNING)
            else:
                table = Texttable(800)
                table.set_cols_dtype(["t", "t", "t", "t"])
                table.header(["Id", "Name", "Type", "Created"])
                table.add_row(
                    [account.dbId, account.name, account.targetPlatform.name, account.created.strftime("%Y-%m-%d %H:%M:%S")])
                print table.draw() + "\n"
                if doArgs.no_confirm:
                    self.api.Users(self.login).Accounts(doArgs.id).Delete()
                    printer.out("Account deleted", printer.OK)
                elif generics_utils.query_yes_no("Do you really want to delete account with id " + str(account.dbId)):
                    self.api.Users(self.login).Accounts(doArgs.id).Delete()
                    printer.out("Account deleted", printer.OK)
            return 0

        except ArgumentParserError as e:
            printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
            self.help_delete()
        except Exception as e:
            return handle_uforge_exception(e)
Пример #29
0
 def do_search(self, args):
         try:
                 #add arguments
                 doParser = self.arg_search()
                 try:
                         doArgs = doParser.parse_args(args.split())
                 except SystemExit as e:
                         return
                 #call UForge API
                 printer.out("Search package '"+doArgs.pkg+"' ...")
                 distribution = self.api.Distributions(doArgs.id).Get()
                 printer.out("for OS '"+distribution.name+"', version "+distribution.version)
                 pkgs = self.api.Distributions(distribution.dbId).Pkgs.Getall(Search=doArgs.pkg, Version=distribution.version)
                 
                 if pkgs is None or not hasattr(pkgs, 'pkgs'):
                         printer.out("No package found")
                 else:
                     table = Texttable(800)
                     table.set_cols_dtype(["t","t","t","t","t","t"])
                     table.header(["Name", "Version", "Arch", "Release", "Build date", "Size"])
                     pkgs = generics_utils.oder_list_object_by(pkgs.get_pkgs().get_pkg(), "name")
                     for pkg in pkgs:
                             table.add_row([pkg.name, pkg.version, pkg.arch, pkg.release, pkg.pkgBuildDate.strftime("%Y-%m-%d %H:%M:%S"), size(pkg.size)])
                     print table.draw() + "\n"
                     printer.out("Found "+str(len(pkgs))+" packages")
         except ArgumentParserError as e:
                 printer.out("ERROR: In Arguments: "+str(e), printer.ERROR)
                 self.help_search()
         except Exception as e:        
                 generics_utils.print_uforge_exception(e)
Пример #30
0
    def get_hard_drive_list_table(self):
        """Return a table of hard drives"""
        # Manually set permissions asserted, as this function can
        # run high privilege calls, but doesn't not require
        # permission checking
        self._get_registered_object('auth').set_permission_asserted()

        # Create table and set headings
        table = Texttable()
        table.set_deco(Texttable.HEADER | Texttable.VLINES)
        table.header(('ID', 'Size', 'Type', 'Storage Backend', 'Virtual Machine'))
        table.set_cols_width((50, 15, 15, 50, 20))

        # Obtain hard ives and add to table
        for hard_drive_obj in self.get_all():
            vm_object = hard_drive_obj.get_virtual_machine()
            hdd_type = ''
            storage_backend_id = 'Storage backend does not exist'
            try:
                storage_backend_id = hard_drive_obj.storage_backend.id_
                hdd_type = hard_drive_obj.get_type()
                hdd_size = SizeConverter(hard_drive_obj.get_size()).to_string()
            except (VolumeDoesNotExistError,
                    HardDriveDoesNotExistException,
                    StorageBackendDoesNotExist), exc:
                hdd_size = str(exc)

            table.add_row((hard_drive_obj.id_, hdd_size,
                           hdd_type, storage_backend_id,
                           vm_object.get_name() if vm_object else 'Not attached'))
Пример #31
0
def list_modules(driver, extension, pattern):
    drvcls = loadmodules(driver, extension)
    from texttable import Texttable
    table = Texttable()
    table.set_cols_align(["l", "l"])
    # table.set_deco(Texttable.HEADER)
    table.header(["Module", "Description"])
    mods = drvcls.listmodule()
    for k in sorted(mods.keys()):
        if pattern is not None and k.find(pattern) == -1:
            continue
        table.add_row([k, mods[k]])
    print(table.draw())
Пример #32
0
 def make_new():
     table = Texttable(max_width=80)
     table.set_deco(Texttable.HEADER)
     table.set_cols_width(
         [
             max([chrsize_len(str(c)) for c in gs["timed_role"].keys()]),
             max([chrsize_len(str(to_lts(c))) for c in gs["timed_role"].values()]),
         ]
     )
     table.set_cols_dtype(["t", "t"])
     table.set_cols_align(["l", "l"])
     table.add_row(get_txt(ctx.guild.id, "tr_list_row"))
     return table
Пример #33
0
def stacks(args):
    client = AWS.current_session().client('cloudformation')
    stacks = client.describe_stacks()
    table = Texttable(max_width=150)
    table.add_rows([STACK_HEADERS])

    for stack in stacks['Stacks']:
        table.add_row([
            stack['StackName'], stack['CreationTime'],
            stack.get('LastUpdatedTime', ''), stack['StackStatus']
        ])

    logger.info("Current Stacks:\n" + table.draw() + "\n")
Пример #34
0
    def showBoard(self, player, board):
        table = Texttable()
        table.set_deco(GameController.textTableDecorator)
        board = self.boardRepository.getBoard(player, board)
        table.add_row([""] + Board.columns)
        for rowNumber in range(Board.dimension):
            rowString = str(rowNumber)
            line = [rowString]
            for column in Board.columns:
                line.append(board.getMark(column + rowString))
            table.add_row(line)

        return table.draw()
Пример #35
0
def migration_table(migrations):
    table = Texttable(800)
    table.set_cols_dtype(["t", "t", "t"])
    table.set_cols_align(["c", "l", "c"])
    table.header(["Id", "Name", "Status"])

    for migration in migrations:
        status = migration.status.message + " (" + str(migration.status.percentage) + "%)"
        if migration.status.complete or migration.status.error or migration.status.cancelled:
            status = migration.status.message
        table.add_row([migration.dbId, migration.name, status])

    return table
Пример #36
0
    def __str__(self):
        table = Texttable()

        for particle in self.__particles:
            for individual in particle.position:
                row = []
                for column in range(len(individual)):
                    row.append(
                        str(individual.first[column]) + ", " +
                        str(individual.second[column]))
                table.add_row(row)

        return table.draw()
Пример #37
0
def retrieve_channels():
    table = Texttable()
    table = table.header(['ID', 'Channel title', 'Username'])
    table = table.set_cols_width([12, 32, 33])
    table = table.set_cols_dtype(['t', 't', 't'])
    print('Retrieving dialogs...')
    for dialog in client.iter_dialogs():
        if dialog.is_channel:
            _id = str(dialog.entity.id)
            title = dialog.title
            username = '******' + dialog.entity.username
            table.add_row([_id, title, username])
    print(table.draw())
Пример #38
0
    def __str__(self):
        #Debug purposes
        t = Texttable()
        for i in range(self._h):
            t.add_row(self._data[i])
        print(t.draw())

        #until here
        t = Texttable()
        for i in range(self._h):
            t.add_row(self._reveal[i])

        return t.draw()
Пример #39
0
 def table_mutation_types(self, genedr):
     table = Texttable(LINE_WIDTH)
     for muttype in genedr['mutation_types']:
         # len(cols) == 2
         row = [muttype['label']]
         muts = [
             mut['text'].replace('*', '\*').replace('_', '\_')
             for mut in genedr['mutations']
             if mut['type'] == muttype['name']
         ]
         row.append(', '.join(muts) or 'None')
         table.add_row(row)
     return table.draw()
Пример #40
0
def lsshare(lsDir):
    try:
        session = connect()
        output = session.get_shares(path=lsDir, subfiles=True)
        t = Texttable()
        t.header(["Path", "Token", "Date Created"])
        for i in output:
            t.add_row([i.get_path(), i.get_token(), i.get_share_time()])
        t.set_deco(t.VLINES | t.HEADER)
        print(t.draw())
    except Exception as e:
        print("ERR: " + str(e) + "\n\nStack Trace:\n")
        print(traceback.format_exc())
Пример #41
0
 def print_onnx_graph(self):
     t = Texttable(max_width=180)
     t.add_row(['lay_num', 'input_node', 'output_node', 'node_type'])
     dims = self.get_conv_dims()
     lay_num = 0
     for layer in self.parsed_graph:
         t.add_row([lay_num,
                    layer['input_node'],
                    layer['output_node'],
                    layer['node_type']])
         lay_num += 1
     print("Onnx Model Graph:")
     print(t.draw())
Пример #42
0
    def output_object(items):
        table = Texttable(max_width=get_terminal_size()[1])
        table.set_deco(Texttable.BORDER | Texttable.VLINES)
        for i in items:
            if len(i) == 3:
                name, _, value = i
                table.add_row([name, TableOutputFormatter.format_value(value, ValueType.STRING)])

            if len(i) == 4:
                name, _, value, vt = i
                table.add_row([name, TableOutputFormatter.format_value(value, vt)])

        print table.draw()
Пример #43
0
    def __str__(self):
        table = Texttable()

        header = [""]
        header.extend(range(self.__n))
        table.header(header)

        for noOfRow in range(self.__n):
            row = [str(noOfRow) + ")"]
            row.extend(self.getRow(noOfRow))
            table.add_row(row)

        return table.draw()
Пример #44
0
def cmd_list(nexus_client):
    """Performs ``nexus3 repository list``"""
    repositories = nexus_client.repositories.raw_list()

    table = Texttable(max_width=util.TTY_MAX_WIDTH)
    table.add_row(['Name', 'Format', 'Type', 'URL'])
    table.set_deco(Texttable.HEADER)
    for repo in repositories:
        table.add_row(
            [repo['name'], repo['format'], repo['type'], repo['url']])

    print(table.draw())
    return exception.CliReturnCode.SUCCESS.value
Пример #45
0
def display_similarities(comparisons):
    """
    Method that display the matches in the comparisons

    :param comparisons: a list of triples (device1, device2, sign)
    """
    table = Texttable()
    table.set_cols_width([30, 30, 30])
    table.header(['Device 1', 'Device 2', 'Signature'])
    for triple in comparisons:
        table.add_row([triple[0], triple[2], triple[1]])
    print(bcolors.HEADER + 'Similarities: ' + bcolors.ENDC)
    print(table.draw())
Пример #46
0
 def __print_table(self, header, rows):
     if self.__clean_print:
         print(", ".join(header))
         for r in rows:
             print(", ".join(r))
     else:
         #Pretty Print
         table = TextTable(max_width=shutil.get_terminal_size((80,
                                                               20)).columns)
         table.header(header)
         for r in rows:
             table.add_row(r)
         print(table.draw())
Пример #47
0
def display_nets(muxes, netname):
    table = Texttable()
    table.set_deco(Texttable.HEADER)
    table.set_cols_dtype(['t', 't', 't'])
    table.set_cols_align(['l', 'r', 'r'])
    table.add_row(['name', 'type', 'channel'])
    for mux in muxes:
        for mapping in mux['mappings']:
            if netname is None or netname == mapping['net']:
                channel = channel_num(mux, mapping)
                table.add_row([mapping['net'], mux['role'], channel])

    click.echo(table.draw())
Пример #48
0
def read_JSON(pokemon):

    # Open and load json file for reading.
    file = open(('DATA/' + pokemon.upper() + "/" + pokemon.upper()))
    data = json.load(file)

    # Extract Pokemon name and Pokedex Id from API data.
    id = data['id']
    name = data['name']

    # Extract the type(s). Pokemon could either have 1-2 types.
    type1 = data['types'][0]['type']['name']
    type2 = data['types'][1]['type']['name'] if len(data['types']) == 2 else 0
    types = [type1, type2] if len(data['types']) == 2 else [type1]

    # Extract the relevant stats for this pokemon.
    stats = data['stats']
    speed = stats[0]['base_stat']
    spDefence = stats[1]['base_stat']
    spAttack = stats[2]['base_stat']
    defence = stats[3]['base_stat']
    attack = stats[4]['base_stat']
    hp = stats[5]['base_stat']
    totalStats = speed + spDefence + spAttack + defence + attack + hp

    # Height and Weight for Pokemon; Convert API data to lbs and metres.
    weight = data['weight'] * 0.220462
    height = data['height'] * 0.1

    # Link to the image for this pokemon.
    image = data['sprites']['front_default']

    # Create and display table containing information relating to that particular pokemon.
    table = Texttable()
    table.add_row(['ID', 'NAME', 'TYPE(S)', 'HP', 'ATK', 'DEF', 'SP. ATK', 'SP. DEF', 'SPD',
                   'HEIGHT \n(m)', 'WEIGHT \n(lbs)', 'TOTAL'])
    table.add_row([id, name.upper(), str(types)[1:-1].upper().replace("'", ''), hp, attack, defence, spAttack, spDefence, speed,
                   height, weight, totalStats])
    table.set_cols_width([4, 15, 20, 4, 4, 4, 4, 4, 4, 6, 8, 6])
    print(table.draw())

    # Format height and weights decimal points (limit to 2 decimal places).
    weight_Format = "%.2f" % weight
    height_Format = "%.2f" % height

    values = {'id': id, 'name': name.upper(), 'type': types, 'hp': hp, 'attack': attack, 'defence': defence, 'spAttack': spAttack,
              'spDefence': spDefence, 'speed': speed, 'height': height_Format,
              'weight': weight_Format, 'totalStats': totalStats, 'imageUrl': image}

    # Return dictionary containing all relevant information of interest from json.
    return values
Пример #49
0
 def do_list(self, args):
     try:
         #call UForge API
         printer.out("Getting distributions for [" + self.login + "] ...")
         distributions = self.api.Users(self.login).Distros.Getall()
         distributions = distributions.distributions
         if distributions is None or not hasattr(distributions,
                                                 "distribution"):
             printer.out("No distributions available")
         else:
             table = Texttable(800)
             table.set_cols_dtype(["t", "t", "t", "t", "t", "t"])
             table.header([
                 "Id", "Name", "Version", "Architecture", "Release Date",
                 "Profiles"
             ])
             distributions = generics_utils.order_list_object_by(
                 distributions.distribution, "name")
             for distribution in distributions:
                 profiles = self.api.Distributions(
                     distribution.dbId).Profiles.Getall()
                 profiles = profiles.distribProfiles.distribProfile
                 if len(profiles) > 0:
                     profile_text = ""
                     for profile in profiles:
                         profile_text += profile.name + "\n"
                     table.add_row([
                         distribution.dbId, distribution.name,
                         distribution.version, distribution.arch,
                         distribution.releaseDate.strftime(
                             "%Y-%m-%d %H:%M:%S")
                         if distribution.releaseDate is not None else "",
                         profile_text
                     ])
                 else:
                     table.add_row([
                         distribution.dbId, distribution.name,
                         distribution.version, distribution.arch,
                         distribution.releaseDate.strftime(
                             "%Y-%m-%d %H:%M:%S") if
                         distribution.releaseDate is not None else "", "-"
                     ])
             print table.draw() + "\n"
             printer.out("Found " + str(len(distributions)) +
                         " distributions")
         return 0
     except ArgumentParserError as e:
         printer.out("ERROR: In Arguments: " + str(e), printer.ERROR)
         self.help_list()
     except Exception as e:
         return handle_uforge_exception(e)
def print_docs_that_contain_word(dataset: StructuredDataset,
                                 word: str,
                                 num_chars_preview=70):
    """
    Prints a table with the following properties of all documents in the dataset that contain the given word:
        - Category name
        - Index inside the document list of that category (in the dataset.files_dict)
        - Number of words of that document
        - Number of occurrences of the word in that document
        - Document name in the dataset
        - Preview of the document content

    :param dataset: Dataset.
    :param word: Word contained in the printed documents.
    :param num_chars_preview: Number of characters to show in the preview column.
    """
    # Create table for better printing
    table = Texttable()
    table.set_cols_width([30, 15, 10, 15, 10, num_chars_preview])
    table.set_cols_align(['c', 'c', 'c', 'c', 'c', 'l'])

    # Specify header
    table.set_header_align(['c', 'c', 'c', 'c', 'c', 'c'])
    table.header([
        'Category name', 'Doc index inside category list of docs', 'Num words',
        'Num occurrences of given word', 'Document name', 'Content preview'
    ])

    num_docs_contain_word = 0
    for category_name, category_docs in dataset.files_dict.items():
        doc_index_in_category = 0
        for doc in category_docs:
            doc_words = doc.content.split()
            if word in doc_words:
                num_docs_contain_word += 1
                num_words_in_doc = len(doc_words)
                num_word_occurences_in_doc = doc_words.count(word)
                # Add row for each doc that contain the given word
                table.add_row([
                    category_name,
                    doc_index_in_category,
                    num_words_in_doc,
                    num_word_occurences_in_doc,
                    doc.name,
                    # TODO: Instead of showing the first k characters, it would be better to show text around the word
                    doc.content[:num_chars_preview]
                ])
            doc_index_in_category += 1

    print(table.draw())
    print(" Num docs with the word " + word + ":", num_docs_contain_word)
Пример #51
0
def delContact(cur, con):
    try:
        name = input(
            "Search for the customer name whose contact you want to delete(Simply press enter if you want to see the whole list) : "
        )
        SearchCust(name, cur, con)
        cust_id = int(
            input("Enter the customer ID whose contact you want to delete : "))
        cur.execute("SELECT * FROM CONTACT WHERE cust_id=%s", (cust_id))
        cust = []
        todelete = []
        table = Texttable()
        table.header(["S.No.", "Phone"])
        table.set_cols_dtype(["i", "t"])
        for i, row in enumerate(cur):
            cust.append(row)
            table.add_row([i + 1, row['phone']])
        if len(cust) == 0:
            raise Exception("This customer has no contacts stored!")
        print(table.draw())
        while (len(todelete) <= len(cust)):
            sno = input(
                "Enter the Sno of the Phone no. you want to delete, leave blank to quit(proceed) :"
            )
            if sno and int(sno) > 0:
                sno = int(sno)
                todel = cust[sno - 1]
                if (todel in todelete):
                    print("Number already selected for deletion!")
                    continue
                else:
                    todelete.append(todel)
                    cur.execute(
                        "DELETE FROM CONTACT WHERE cust_id=%s AND phone=%s",
                        (cust_id, todel['phone']))
                    continue
            else:
                break
        if (len(todelete) > 0):
            ch = input(
                "Are you sure you want to delete the selected numbers? (y/N)")
            if (ch.lower() == 'y'):
                con.commit()
                print("Contacts deleted!")
            else:
                con.rollback()
                print("Contacts were not deleted.")
    except Exception as e:
        con.rollback()
        print("Failed to delete contacts from database")
        print(">>>>>>>>>>>>>", e)
Пример #52
0
    def main(self):
        from texttable import Texttable
        from egtlib.utils import format_duration, format_td
        import shutil
        termsize = shutil.get_terminal_size((80, 25))
        table = Texttable(max_width=termsize.columns)
        table.set_deco(Texttable.HEADER)
        table.set_cols_align(("l", "l", "r", "c", "r"))
        table.add_row(("Name", "Tags", "Logs", "Hrs", "Last entry"))
        e = self.make_egt(self.args.projects)
        projs = e.projects

        blanks = []
        worked = []
        for p in projs:
            if p.last_updated is None:
                blanks.append(p)
            else:
                worked.append(p)

        blanks.sort(key=lambda p: p.name)
        worked.sort(key=lambda p: p.last_updated)

        now = datetime.datetime.now()

        def add_summary(p):
            table.add_row((
                p.name,
                " ".join(sorted(p.tags)),
                len(list(p.log.entries)),
                format_duration(p.elapsed, tabular=True)
                if p.last_updated else "--",
                "%s ago" % format_td(now - p.last_updated, tabular=True)
                if p.last_updated else "--",
            ))


#        res["mins"] = self.elapsed
#        res["last"] = self.last_updated
#        res["tags"] = self.tags
#        res["entries"] = len(self.log)
#        #"%s" % format_duration(mins),
#        #format_td(datetime.datetime.now() - self.last_updated)),
#        print "%s\t%s" % (self.name, ", ".join(stats))

        for p in blanks:
            add_summary(p)
        for p in worked:
            add_summary(p)

        print(table.draw())
Пример #53
0
def _setup_table():
    table = Texttable(max_width=CELL_WIDTH)
    table.add_row([
        NAME_LABEL,
        Stat.PLAYED.value,
        Stat.WON.value,
        Stat.DRAW.value,
        Stat.LOST.value,
        Stat.GOALS_FOR.value,
        Stat.GOALS_AGAINST.value,
        Stat.POINTS.value,
        Stat.POINTS_ADJUSTED.value,
    ])
    return table
Пример #54
0
 def __repr__(self):
     t = Texttable()
     l = []
     d = {-1: 'Y', 0: ' ', 1: 'B'}
     for i in range(0, 42, 7):
         row = self._data[i:i + 7]
         for j in range(7):
             row[j] = d[row[j]]
         l.append(row)
     s = len(l) - 1
     while s > -1:
         t.add_row(l[s])
         s -= 1
     return t.draw()
Пример #55
0
 def __str__(self):
     from ..formatters import to_format
     table = Texttable(max_width=0)
     table.set_chars(self.__border__())
     data = self.to_array()
     for sub_array in data:
         new_array = []
         for item in sub_array:
             if item == "":
                 new_array.append(" ")
             else:
                 new_array.append(to_format(str, item))
         table.add_row(new_array)
     return table.draw()
Пример #56
0
def search_tweet():
    api = TwitterClient()
    t = Texttable()
    print('\n1) Search by keyword\n2) Search by username')
    choice = int(input('Enter choice: '))
    if (choice == 1):
        q = str(input('Enter a Name to Search: '))
        nu = int(input('\nEnter the number of tweets to fetch: '))
        tweets = api.get_tweets(query=q, count=100)

        i = 1
        t.add_row(['', 'Tweets'])
        for tweet in tweets[:nu]:
            t.add_row([i, tweet['text']])
            i += 1
        print t.draw()
    elif (choice == 2):
        extractor = twitter_setup()
        q = str(input('Enter a Name to Search: '))
        nu = int(input('\nEnter the number of tweets to fetch: '))
        try:
            tweets = extractor.user_timeline(screen_name=q, count=100)
            t.add_row(['', 'Tweets'])
            i = 1
            for tweet in tweets[:nu]:
                t.add_row([i, tweet.text])
                i += 1
            print t.draw()
        except:
            print('User not found')
    sys.stdin.read(1)
Пример #57
0
def analyze_tweets():
    api = TwitterClient()
    q = input('Enter a Name to Search: ')
    tweets = api.get_tweets(query=q, count=1000)
    ptweets = [tweet for tweet in tweets if tweet['sentiment'] == 'positive']
    print("\n\nGood tweets percentage: {} %".format(100 * len(ptweets) /
                                                    len(tweets)))
    ntweets = [tweet for tweet in tweets if tweet['sentiment'] == 'negative']
    print("\n\nBad tweets percentage: {} %".format(100 * len(ntweets) /
                                                   len(tweets)))
    print("\n\nUnbiased tweets percentage: {} %".format(
        100 * (len(tweets) - len(ntweets) - len(ptweets)) / len(tweets)))
    t1 = Texttable()
    t2 = Texttable()
    print "\n\n"
    t1.add_row(['Good Tweets'])
    for tweet in ptweets[:10]:
        t1.add_row([tweet['text']])
    print t1.draw()
    print "\n\n"
    t2.add_row(['Bad Tweets'])
    for tweet in ntweets[:10]:
        t2.add_row([tweet['text']])
    print t2.draw()
    sys.stdin.read(1)
Пример #58
0
    def stack_bash():

        t = Texttable()
        t.add_row(["Menu"])
        t.add_row(["1: Search For Answer for a Question"])
        t.add_row(["2: Search For Questions Similar to the Question"])
        t.add_row(["3: Exit"])
        print(t.draw())
        while True:
            g = input("Enter your Choice : ")
            if re.search('[^0-9]', g) != None or not g:
                print("Enter Valid Option")
                continue
            g = int(g, 10)
            if g == 3:
                break
            else:
                if g == 1:
                    ques = input(
                        "Enter The Question that you want to Search : ")
                    print(get_answers(str(ques)) + "\n")
        #             print ques
                elif g == 2:
                    ques = input(
                        "Enter The Question that you want to Search : ")
                    #             print ques
                    print(similar_questions_search(str(ques)) + "\n")
                else:
                    print("Enter Valid Option")
Пример #59
0
 def __str__(self):
     t = Texttable()
     d = {
         0: " ",
         1: "s",
         2: "X",
         3: "o"
     }  #x apare unde a lovit calculatorul barca si nu a nimerit
     for i in range(0, 8):
         list = self.tabla[i][:]
         for j in range(0, 8):
             list[j] = d[list[j]]
         t.add_row(list)
     return t.draw()
Пример #60
0
 def afisareTablaComputer(self):
     t = Texttable()
     d = {
         0: " ",
         1: "h",
         2: "X",
         3: "o"
     }  #o apare unde a lovit player-ul pe tabla computerului si a nimerit
     for i in range(0, 8):
         list = self.tabla[i][:]
         for j in range(0, 8):
             list[j] = d[list[j]]
         t.add_row(list)
     return t.draw()