示例#1
0
文件: ec2.py 项目: kalaiser/acli
def output_ami_list(output_media='console', amis=None):
    """
    @type output_media: unicode
    @type amis: list
    """
    amis = sorted(amis, key=lambda k: k.get('CreationDate'), reverse=True)
    if output_media == 'console':
        td = list()
        table_header = [
            Color('{autoblue}image id{/autoblue}'),
            Color('{autoblue}name{/autoblue}'),
            Color('{autoblue}created (UTC){/autoblue}')
        ]
        for ami in amis:
            td.append([
                ami.get('ImageId'),
                dash_if_none(ami.get('Name')),
                dash_if_none(trim_creation_date(ami.get('CreationDate')))
            ])
        output_ascii_table_list(
            table_title=Color('{autowhite}AMIs{/autowhite}'),
            table_header=table_header,
            inner_heading_row_border=True,
            table_data=td)
    exit(0)
示例#2
0
def viewSentiments(number):
    twits = getFile()
    table_data = [[
        Color('{cyan}TWEET{/cyan}'),
        Color('{autored}SENTIMENTS{/autored}')
    ]]
    for twit in tqdm(twits.items(),
                     total=number,
                     desc="Analysing sentiments..."):
        sentiment = twit[1]['sentiments']
        sentString = ''
        for item in sentiment:
            sentString += item + '\n'
        sentString = sentString.strip()
        text = '\n'.join(wrap(twit[1]['tweet'], 80))
        table_data.append([
            Color('{cyan}' + text + '{/cyan}'),
            Color('{red}' + sentString + '{/red}')
        ])
    table_instance = SingleTable(table_data,
                                 Color('{green}Sentiment Analysis{/green}'))
    table_instance.inner_heading_row_border = True
    table_instance.inner_row_border = True
    table_instance.justify_columns = {0: 'left', 1: 'left'}
    return table_instance.table
示例#3
0
def viewRanks(number):
    twits = getFile()
    stopWords = getStopwords()
    words = []
    for twit in tqdm(twits.items(), total=number, desc="Ranking words..."):
        words.extend(word_tokenize(twit[1]['tweet']))
    words = [
        word for word in words
        if word.lower() not in stopWords and re.match(r'\w', word)
    ]
    wordsDict = Counter(words)
    sortedList = sorted(wordsDict.items(), key=lambda x: x[1], reverse=True)
    table_data = [[
        Color('{cyan}WORDS{/cyan}'),
        Color('{autored}RANKS{/autored}')
    ]]
    for word in sortedList:
        table_data.append(
            [Color(word[0]),
             Color('{autored}' + str(word[1]) + '{/autored}')])
    table_instance = SingleTable(table_data,
                                 Color('{green}Word Frequency{/green}'))
    table_instance.inner_heading_row_border = True
    table_instance.inner_row_border = True
    table_instance.justify_columns = {0: 'center', 1: 'center'}
    return table_instance.table
示例#4
0
def colored_status(status, text):
    if status == u'passed':
        return Color('{autogreen}%s{/autogreen}' % text)
    elif status == u'skipped':
        return Color('{autocyan}%s{/autocyan}' % text)
    else:
        return Color('{autored}%s{/autored}' % text)
示例#5
0
    def get_notifications_table(self):
        def _get_span_value_by_id(elem_id):
            return parsed_html.body.find('span', attrs={'id': elem_id}).text

        def _get_headers_color(header):
            return 'autored' if header else 'autocyan'

        def _get_notifs_count():
            return int(_get_span_value_by_id('requestsCountValue')),\
                   int(_get_span_value_by_id('mercurymessagesCountValue')),\
                   int(_get_span_value_by_id('notificationsCountValue'))

        cookies = self.browser.get_cookies()

        response = self.session.get(self.URL, cookies=cookies)
        parsed_html = BeautifulSoup(response.content, 'html.parser')
        friend_requests_count, messages_count, notifications_count = _get_notifs_count(
        )

        table_data = [[
            Color('{{{0}}}Friend Requests{{/{0}}}'.format(
                _get_headers_color(friend_requests_count))),
            Color('{{{0}}}Messages{{/{0}}}'.format(
                _get_headers_color(messages_count))),
            Color('{{{0}}}Notifications{{/{0}}}'.format(
                _get_headers_color(notifications_count)))
        ], [friend_requests_count, messages_count, notifications_count]]

        return AsciiTable(table_data).table
示例#6
0
def print_header():

    print ''
    print Color('  {autocyan}EasyConnect{/autocyan}')
    print Color('  {autocyan}-----------{/autocyan}')
    print Color('  {autoyellow}Select ssh configuration to launch{/autoyellow}')
    print ''
示例#7
0
def signal_power(signal):
    if signal <= -70:
        return Color("{autored}" + str(signal) + "{/autored}")
    elif signal > -70 and signal < -55:
        return Color("{autoyellow}" + str(signal) + "{/autoyellow}")
    else:
        return Color("{autogreen}" + str(signal) + "{/autogreen}")
示例#8
0
def drawTableForSwitches(switches):
    switchData = []
    switchData.append([Color('{autocyan}Switch(s){/autocyan}'), Color('{autoyellow}Termination Point(s){/autoyellow}')])
    for switch in switches:
        switchData.append([switch["node-id"], len(switch["termination-point"])])    
    table = SingleTable(switchData)
    print(table.table)
示例#9
0
def drawTableForHosts(hosts):
    hostData = []
    hostData.append([Color('{autogreen}MAC{/autogreen}'), Color('{autoblue}IP{/autoblue}')])
    for host in hosts:
        hostData.append([host["host-tracker-service:addresses"][0]["mac"], host["host-tracker-service:addresses"][0]["ip"]])    
    table = SingleTable(hostData)
    print(table.table)
示例#10
0
文件: asg.py 项目: kalaiser/acli
def output_lc_list(lc_list=None):
    """
    @type lc_list: list
    """
    if isinstance(lc_list, list):
        td = list()
        table_header = [
            Color('{autoblue}name{/autoblue}'),
            Color('{autoblue}image id{/autoblue}'),
            Color('{autoblue}instance type{/autoblue}'),
            Color('{autoblue}created{/autoblue}')
        ]
        for lc in lc_list:
            td.append([
                dash_if_none(lc.get('LaunchConfigurationName')),
                dash_if_none(lc.get('ImageId')),
                dash_if_none(lc.get('InstanceType')),
                dash_if_none(
                    lc.get('CreatedTime').replace(tzinfo=None, microsecond=0))
            ])
        output_ascii_table_list(
            table_title=Color('{autowhite}launch configurations{/autowhite}'),
            table_header=table_header,
            table_data=td,
            inner_heading_row_border=True)
    exit(0)
示例#11
0
def output_elbs(elbs=None):
    """
    @type elbs: list
    """
    if elbs:
        elbs.sort(key=lambda k: k.get('DNSName'))
        td = list()
        table_header = [
            Color('{autoblue}name{/autoblue}'),
            Color('{autoblue}instances{/autoblue}'),
            Color('{autoblue}dns name{/autoblue}')
        ]
        for elb in elbs:
            td.append([
                elb.get('LoadBalancerName'),
                str(len(elb.get('Instances'))),
                elb.get('DNSName')
            ])
        output_ascii_table_list(
            table_title=Color('{autowhite}ELBs{/autowhite}'),
            table_data=td,
            table_header=table_header,
            inner_heading_row_border=True)
    else:
        print("No ELBs found.")
    exit(0)
示例#12
0
def menu_flyto_stations():
    table_top = status_table()
    table_mid = My_Table(
        playership.currentsystem.create_structurelist(),
        Color('{yellow}[{}]{/yellow}').format(playership.name))
    table_bot = My_Table(
        [['Select station number to fly to it, input z to go back']],
        Color('{yellow}[{}]{/yellow}').format(playership.name))
    refresh(table_top, 1, table_mid, 1, table_bot, 1)
    action = input('Awaiting orders commander: ')
    if action == 'z':
        menu_main()
    else:
        try:
            playership.fly(playership.currentsystem.structurelist[int(action) -
                                                                  1])
            table_mid = My_Table(
                playership.createflylog(
                    playership.currentsystem.structurelist[int(action) - 1]),
                'FLIGHT LOG OF {} SHIP'.format(playership.name))
            refresh(None, 0, table_mid, 1, None, 0)
            input('press any key to confirm')
            menu_flyto_stations()
        except ValueError:
            input('Incorrect Value, press any key to try again')
            menu_flyto_stations()
        except IndexError:
            input('Incorrect Value, press any key to try again')
            menu_flyto_stations()
示例#13
0
def wait_key():

    result = None
    print Color('  {autowhite}>{/autowhite}'),

    if os.name == 'nt':
        import msvcrt
        result = msvcrt.getch()
    else:
        import termios
        fd = sys.stdin.fileno()

        old_term = termios.tcgetattr(fd)
        new_attr = termios.tcgetattr(fd)
        new_attr[3] = new_attr[3] & ~termios.ICANON & ~termios.ECHO
        termios.tcsetattr(fd, termios.TCSANOW, new_attr)

        try:
            result = sys.stdin.read(1)
        except IOError:
            pass
        finally:
            termios.tcsetattr(fd, termios.TCSAFLUSH, old_term)
            print Color('{autoyellow}' + result + '{/autoyellow}\n')

    return result
示例#14
0
    def on_epoch_end(self, batch, logs={}):
        self.epoch += 1

        # отберем немного сэмлов для визуализации текущего состояния модели
        samples2 = sorted(filter(lambda s: len(s.left_str) < 72, test_samples),
                          key=lambda z: random.random())[:10]
        X, y = vectorize_samples(samples2, self.computed_params)
        y_pred = model.predict(x=X, verbose=0)
        y_pred = np.argmax(y_pred, axis=-1)

        table = ['context true_output predicted_output'.split()]
        for sample, y_pred_sample in zip(samples2, y_pred):
            # Декодируем список индексов предсказанных токенов
            tokens = [self.index2token[itok] for itok in y_pred_sample]
            pred_right = ''.join(tokens).replace('▁', ' ').strip()
            if sample.right_str == pred_right:
                # выдача сетки полностью верная
                output2 = Color('{autogreen}' + pred_right + '{/autogreen}')
            elif jaccard(sample.right_str.split(), pred_right.split()) > 0.5:
                # выдача сетки частично совпала с требуемой строкой
                output2 = Color('{autoyellow}' + pred_right + '{/autoyellow}')
            else:
                # неправильная выдача сетки
                output2 = Color('{autored}' + pred_right + '{/autored}')

            table.append((sample.left_str, sample.right_str, output2))

        table = terminaltables.AsciiTable(table)
        print(table.table)
示例#15
0
def output_iam_user_list(users=None, mfa_devices=None):
    """
    @type users: list
    @type mfa_devices: list
    """
    td = list()
    table_header = [
        Color('{autoblue}user name{/autoblue}'),
        Color('{autoblue}created{/autoblue}'),
        Color('{autoblue}password last used{/autoblue}'),
        Color('{autoblue}mfa enabled{/autoblue}')
    ]
    for user in users:
        td.append([
            dash_if_none(user.get('UserName')),
            dash_if_none(user.get('CreateDate')),
            dash_if_none(user.get('PasswordLastUsed')),
            user_has_mfa_assigned(
                username=user.get('UserName'),
                password_last_used=user.get('PasswordLastUsed'),
                mfa_devices=mfa_devices)
        ])
    output_ascii_table_list(
        table_title=Color('{autowhite}user list{/autowhite}'),
        table_data=td,
        table_header=table_header,
        inner_heading_row_border=True)
    exit(0)
示例#16
0
def main():
    rows = []
    num_authors = 0

    for line in stdin_lines():
        match = COMMIT_REGEX.match(line)
        commit = match.group().strip() if match else 'None'

        match = AUTHOR_REGEX.search(line)
        author = match.group().strip() if match else 'None'

        match = AUTHOR_REGEX.match(line)
        code = line[match.end():].rstrip() if match else 'None'

        if commit not in commit_dict:
            commit_dict[commit] = COLOR_TAGS[num_authors % len(COLOR_TAGS)]
            num_authors += 1

        tag = commit_dict[commit]

        wrapped_author = u'{%s}%s{/%s}' % (tag, author.decode(
            'utf-8') if isinstance(author, str) else author, tag)
        wrapped_code = u'{%s}%s{/%s}' % (tag, code.decode('utf-8') if
                                         isinstance(code, str) else code, tag)

        rows.append([
            Color(wrapped_author),
            Color(wrapped_code),
        ])

    table = BorderlessTable(rows)
    table.inner_heading_row_border = False
    print(table.unicode_table('utf-8'))
示例#17
0
    def terminal(self, level, target, command, message=""):
        if level == 0 and not self.verbose:
            return

        formatting = {
            0: Color('{autoblue}[VERBOSE]{/autoblue}'),
            1: Color('{autogreen}[THREAD]{/autogreen}'),
            3: Color('{autobgyellow}{autored}[ERROR]{/autored}{/autobgyellow}')
        }

        leader = formatting.get(level, '[#]')

        format_args = {
            'time': strftime("%H:%M:%S", localtime()),
            'target': target,
            'command': command,
            'message': message,
            'leader': leader
        }

        if not self.silent:
            if level == 1:
                template = '[{time}] {leader} [{target}] {command} {message}'
            else:
                template = '[{time}] {leader} [{target}] {command} {message}'

            print(template.format(**format_args))
示例#18
0
def colour_staus(status=None):
    if not status:
        return Color('{autoblack}-{/autoblack}')
    elif status == 'Active':
        return Color('{autogreen}' + status + '{/autogreen}')
    elif status == 'Inactive':
        return Color('{autored}' + status + '{/autored}')
示例#19
0
    def minimize(self):
        """
        Minimizes the circuit and returns the list of terms for minimized circuit

        Returns:
            A list containing all possible solutions to the minimization problem
        """

        #actual process of minimization

        #find the prime implicants
        pis = self.pis()

        #essential prime implicant portion of the solution
        essential_pi_sol = ""

        primary_epis = self.primary_epis()

        for pi in primary_epis:
            #if the user specified variables e.g a,b,c,d then make the solution
            #in terms of this
            ch = self.to_char(pi, self.chars) if self.chars else pi

            #don't add a + to the end if this is the las pi in the list
            #e.g [ab,cd,dg] don't add a + to the end of dg as in ab + cd +dg +
            if pi == primary_epis[-1]:
                essential_pi_sol += ch
            else:
                essential_pi_sol += ch + ' + '

        #compute the part of the solution that should come from the secondary essential prime
        #implicants
        secondary_epi_sols = self.secondary_epis()
        possible_solutions = []

        if secondary_epi_sols:
            for spi in secondary_epi_sols:
                if essential_pi_sol:
                    #combine each possible solution due to secondary essential
                    #prime implicants with that from primary essential prime
                    #implicants
                    possible_solutions.append(essential_pi_sol + ' + ' + spi)
                else:
                    possible_solutions.append(spi)
        else:
            possible_solutions.append(essential_pi_sol)

        self.procedure += Color(
            '\n\n{autoblue}========\nSolution \n========\n{/autoblue}\n')
        self.procedure += possible_solutions[0] + '\n'

        if len(possible_solutions) > 1:
            self.procedure += Color(
                '\n\n{autoblue}========================\nOther Possible Solutions \n========================\n{/autoblue}\n'
            )

            for i in range(1, len(possible_solutions)):
                self.procedure += possible_solutions[i] + '\n'

        return possible_solutions
示例#20
0
    def calculate_path(self, matrix, line, column):
        i = 0
        j = 0
        end = matrix[-1][-1]

        while matrix[i][j] != end:
            if matrix[i][j] == matrix[-1][-1]:
                break
            if i == 0 and j == 0:
                self.x.append(matrix[i][j])
            if i >= line - 1:
                self.x.append(matrix[i][j + 1])
                matrix[i][j + 1] = Color('{green}⮞{/green}')
                j += 1
                continue
            if j >= column - 1:
                self.x.append(matrix[i + 1][j])
                matrix[i + 1][j] = Color('{green}⮟{/green}')
                i += 1
                continue
            if matrix[i + 1][j] > matrix[i][j + 1]:
                self.x.append(matrix[i + 1][j])
                matrix[i + 1][j] = Color('{green}⮟{/green}')
                i += 1
            elif matrix[i][j + 1] > matrix[i + 1][j]:
                self.x.append(matrix[i][j + 1])
                matrix[i][j + 1] = Color('{green}⮞{/green}')
                j += 1
示例#21
0
def print_task_diff(ecs_service_name, diffs, color):
    image_diff = next(x for x in diffs if x.field == 'image')
    if image_diff.old_value != image_diff.value:
        log_with_color(ecs_service_name + " New image getting deployed", color)
        log_with_color(ecs_service_name + " " + str(image_diff), color)
    else:
        log_with_color(ecs_service_name + " No change in image version", color)
    env_diff = next(x for x in diffs if x.field == 'environment')
    old_env, current_env = env_diff.old_value, env_diff.value
    env_vars = sorted(
        set(env_diff.old_value.keys()).union(env_diff.value.keys()))
    table_data = []
    table_data.append([
        Color('{autoyellow}Env. var.{/autoyellow}'),
        Color('{autoyellow}Old value{/autoyellow}'),
        Color('{autoyellow}Current value{/autoyellow}')
    ])
    for env_var in env_vars:
        old_val = old_env.get(env_var, '-')
        current_val = current_env.get(env_var, '-')
        if old_val != current_val:
            env_var_diff_color = 'autored'
            table_data.append([
                Color('{' + env_var_diff_color + '}' + env_var + '{/' +
                      env_var_diff_color + '}'), old_val, current_val
            ])
    if len(table_data) > 1:
        log_with_color(ecs_service_name + " Environment changes", color)
        print(SingleTable(table_data).table)
    else:
        log_with_color(
            ecs_service_name + " No change in environment variables", color)
示例#22
0
 def estadosEnCaja(self, nombrecaja):
     '''Muestra la cantidad de estados diferentes en una caja'''
     pipeline = [{
         '$match': {
             'caja': nombrecaja
         }
     }, {
         '$group': {
             '_id': '$estado',
             'cantidad': {
                 '$sum': 1
             }
         }
     }]
     estados = list(db.aggregate(pipeline))
     #Crea tabla
     table_data = [[
         Color('{autocyan}Estado{/cyan}'),
         Color('{autocyan}Cantidad{/cyan}')
     ]]
     total = 0
     for estado in estados:
         table_data.append([estado['_id'], estado['cantidad']])
         total += estado['cantidad']
     table_data.append([
         Color('{autocyan}Total:{/cyan}'),
         Color('{autocyan}' + str(total) + '{/cyan}')
     ])
     table = SingleTable(table_data)
     table.title = nombrecaja
     table.justify_columns = {0: 'right'}
     print(table.table)
示例#23
0
    def on_epoch_end(self, batch, logs={}):
        self.epoch += 1
        print('Epoch {} validation...'.format(self.epoch))

        # Оценка текущего качества
        score = score_model(self.model, self.test_samples, self.Xs_test,
                            self.y, self.computed_params)
        if score > self.best_score:
            print('NEW BEST SCORE={}'.format(score))
            self.best_score = score
            self.best_epoch = self.epoch
            self.wait = 0
            self.model.save_weights(self.weights_path, overwrite=True)

            # отберем немного сэмлов для визуализации текущего состояния модели
            # 16-06-2020 не будем показывать сэмплы с длиной левой части больше 71, чтобы не разваливались
            # ascii-таблицы.
            samples2 = sorted(filter(lambda s: len(s.left_str) < 72,
                                     test_samples),
                              key=lambda z: random.random())[:10]
            Xs, y = vectorize_samples(samples2, self.model_params,
                                      self.computed_params)
            y_pred = model.predict(Xs, verbose=0)
            y_pred = np.argmax(y_pred, axis=-1)

            table = ['context true_output predicted_output'.split()]
            for sample, y_pred_sample in zip(samples2, y_pred):
                # Декодируем список индексов предсказанных токенов
                tokens = [self.index2token[itok] for itok in y_pred_sample]
                pred_right = ''.join(tokens).replace('▁', ' ').strip()

                true2 = undress_output_line(sample.right_str)
                pred2 = undress_output_line(pred_right)

                if pred2 == true2:
                    # выдача сетки полностью верная
                    output2 = Color('{autogreen}' + pred_right +
                                    '{/autogreen}')
                elif jaccard(pred2.split(), true2.split()) > 0.5:
                    # выдача сетки частично совпала с требуемой строкой
                    output2 = Color('{autoyellow}' + pred_right +
                                    '{/autoyellow}')
                else:
                    # неправильная выдача сетки
                    output2 = Color('{autored}' + pred_right + '{/autored}')

                table.append((sample.left_str, sample.right_str, output2))

            table = terminaltables.AsciiTable(table)
            print(table.table)
        else:
            print(
                'val score={}; no improvement over best score={} at epoch={}'.
                format(score, self.best_score, self.best_epoch))
            self.wait += 1
            if self.wait > self.patience:
                print('Early stopping at epoch={} with best score={}'.format(
                    self.epoch, self.best_score))
                self.model.stop_training = True
示例#24
0
def _colorize_status(status):
    if status in ('finished'):
        return Color('{green}' + status + '{/green}')
    if status in ('started'):
        return Color('{yellow}' + status + '{/yellow}')
    if status in ('scheduled', 'notification'):
        return status
    return Color('{red}' + status + '{/red}')
示例#25
0
    def show_status(self, services=None):
        services = self.check_service(services, msg='In SHOW STATUS:')

        table_data = []
        table_data.append([
            'Service', 'Host', 'Service-Status', 'Image-Status', 'Depends-On',
            'Ports', 'Network-Mode', 'Stats'
        ])

        try:
            default_network = self.stream['networks']['default']['driver']
        except:
            default_network = 'bridge'

        for service in services:
            container = self.get_container_instance_by_service_name(service)
            host = self.get_host_instance_by_container_id(service)
            image_status = ''

            host_color = "{autobgwhite}{%s}%s{/%s}{/autobgwhite}" % (
                host.color, container.hostip, host.color)
            container_color = "{autobgwhite}{%s}%s{/%s}{/autobgwhite}" % (
                container.color, container.status, container.color)
            if container._image_status == 'changed':
                image_status = container._image_status
            depends = ''
            for depend in container.s_depends_on:
                depend_container = self.get_container_instance_by_service_name(
                    depend)
                depend_container_color = "- {autobgwhite}{%s}%s{/%s}{/autobgwhite}\n" % (
                    depend_container.color, depend, depend_container.color)
                depends += (Color(depend_container_color))
            depends = depends.strip('\n')

            ports = ''
            for port in container.ports:
                ports += "- %s\n" % port
            ports = ports.strip('\n')

            nm = default_network if container.network_mode == '' else container.network_mode
            stats = ''
            for s in [
                    'cpu:' + str(container.cpu_utilization) + '%' + '\n',
                    'mem:' + str(container.mem_usage) + 'm' + '\n',
                    'check:' + str(container.exec_time) + 'ms'
            ]:
                stats += s
            table_data.append([
                container.id,
                Color(host_color),
                Color(container_color), image_status, depends, ports, nm, stats
            ])

        table_instance = AsciiTable(table_data)

        table_instance.inner_heading_row_border = False
        table_instance.inner_row_border = True
        print table_instance.table
示例#26
0
def color_data(value):
    if float(value) > 0:
        number = Color('{autogreen}'+str(value)+'{/autogreen}')
    elif float(value) < 0:
        number = Color('{autored}'+str(value)+'{/autored}')
    else:
        number = str(value)

    return number
示例#27
0
def cours_btc_negatif():

    table_data = [['1 BTC --> Euro', 'BTC %'],
                  [
                      Color('{autored}' + str(cours_btc) + '{/autored}'),
                      Color('{autogreen}' + str(btc_percent) + '{/autogreen}')
                  ]]
    table = AsciiTable(table_data)
    print table.table
示例#28
0
def colour_state(state=None):
    if not state:
        return Color('{autoblack}-{/autoblack}')
    elif state == 'running':
        return Color('{autogreen}' + state + '{/autogreen}')
    elif state in ('stopped', 'stopping', 'shutting-down', 'terminated'):
        return Color('{autored}' + state + '{/autored}')
    elif state in ('rebooting', 'pending'):
        return Color('{autoyellow}' + state + '{/autoyellow}')
示例#29
0
文件: efs.py 项目: kalaiser/acli
def colour_state(state=None):
    if not state:
        return Color('{autoblack}-{/autoblack}')
    elif state == 'available':
        return Color('{autogreen}' + state + '{/autogreen}')
    elif state in ('deleting', 'deleted'):
        return Color('{autored}' + state + '{/autored}')
    elif state == 'creating':
        return Color('{autoyellow}' + state + '{/autoyellow}')
示例#30
0
 def guarda(self):
     '''Guarda Icc a base de datos, se requiere de Id, Agencia, Caja\n
   Si no existe, se crea nuevo registro\n
   Exito: True'''
     if self.agencia != '' or self.caja != '' or verify(self.id) == False:
         self.modificado = hoy
         existeRegistro = db.find_one({'_id': self.id})
         #Si existe registro
         if existeRegistro:
             #Revisa portacione y revisiones
             if 'revisiones' in existeRegistro:
                 self.revisiones = existeRegistro['revisiones']
             if 'portaciones' in existeRegistro:
                 self.portaciones = existeRegistro['portaciones']
             db.update_one({'_id': self.id}, {
                 '$set': {
                     'agencia': self.agencia,
                     'modificado': self.modificado,
                     'estado': self.estado,
                     'caja': self.caja,
                 }
             })
             print(
                 Color('{autobgblack}{hiyellow}' + 'GUARDADO'.center(80) +
                       '{/yellow}{/bgblack}'))
             self.cantEnCaja = str(self.cantidadEnCaja(self.caja))
             self.muestraDatos()
         else:
             #Si no existe registro, pone datos por default
             if self.estado == '':
                 self.estado = 'DESCONOCIDO'
             if self.creado == '':
                 self.creado = hoy
             db.insert_one({
                 "_id": self.id,
                 "agencia": self.agencia,
                 "creado": self.creado,
                 "modificado": self.modificado,
                 "estado": self.estado,
                 "caja": self.caja
             })
             print(
                 Color('{hibgyellow}{hiblack}' +
                       'REGISTRO CREADO'.center(80) +
                       '{/black}{/bgyellow}'))
             self.cantEnCaja = str(self.cantidadEnCaja(self.caja))
             self.muestraDatos()
         return True
     else:
         print(
             Color('{bgred}{hiwhite}' + 'NO SE PUDO GUARDAR'.center(50) +
                   '{/white}{/bgred}'))
         print(
             Color('{bgred}{hiwhite}' + 'DATOS INCOMPLETOS'.center(50) +
                   '{/white}{/bgred}'))
         return False