コード例 #1
0
ファイル: main.py プロジェクト: palikar/code_manager
def list_cache(args, core):
    logging.debug('Dumping cache file %s', core.cache_file)

    cache = core.get_cache_content()
    header = ['Name', 'Fetched', 'Built', 'Installed', 'Root']
    rows = list(map(lambda x: list(x.values()), cache))

    if args.packages:
        rows = list(filter(lambda x: x[0] in args.packages, rows))

    if args.plain:
        for values in rows:
            line = ','.join(str(val) for val in values)
            print(line)
    else:
        string = termtables.to_string(
            rows,
            header=header,
            style=termtables.styles.ascii_thin_double,
            padding=(0, 1),
            alignment='lcccc',
        )
        if len(string.split('\n')) > 10 and not args.no_pager:
            less(bytes(string, 'utf-8'))
        else:
            print(string)
コード例 #2
0
def _get_report_card(df, func, report_each_source=True, decs=2):
    """
    Gets a report card for a DataFrame using a specific function.
    """
    labels, data = func(df, decs=decs)

    data.insert(0, 'OVERALL')
    data = [data]

    if report_each_source:
        for name in np.unique(df['source']):
            _df = df[df['source'] == name]
            _, _data = func(_df, decs=decs)
            _data.insert(0, name.upper())
            data.append(_data)

    # transposing data so each column has the source and its metrics
    data = list(map(list, zip(*data)))
    header = data.pop(0)
    header.insert(0, 'METRIC')
    for i in range(1, len(header)):
        header[i] = _format_title(header[i], 16)
    for l, d in zip(labels, data):
        d.insert(0, l)

    alignment = ["c" for _ in header]
    alignment[0] = "l"
    alignment = ''.join(alignment)

    report_card = termtables.to_string(data,
                                       header=header,
                                       padding=(0, 1),
                                       alignment=alignment)

    return report_card
コード例 #3
0
ファイル: waiting_rental.py プロジェクト: EricB2A/BDR_RBNB
def displayRental():
    g = Gui()

    # a ajouter avant where
    query = "SELECT * FROM location_personne INNER JOIN search_biens ON bien_immobilier_id = search_biens.bien_id WHERE location_personne.date_arrivee > NOW() AND location_personne.estConfirme IS NULL AND personne_id = {}".format(
        g.user.id)
    logging.debug(query)
    locations = getQueryRes(query)
    headerBiens = [
        "Cap. person.", "Taille (m²)", "type_bien", "Description", "Rue",
        "Commune", "Etat", "date arrivee", "date depart"
    ]

    biens = []
    for location in locations:
        biens.append([
            location["capacite"], location["taille"], location["type_bien"],
            location["description"], location["rue"], location["commune"],
            location["etat"], location["date_arrivee"], location["date_depart"]
        ])

    if biens:
        print(
            tt.to_string(
                data=biens,
                header=headerBiens,
                style=tt.styles.ascii_thin_double,
            ))
    input("Appuyez sur une touche")
    return True
コード例 #4
0
    def initial_guess(self) -> None:
        """ Find an inital guess for normalization parameters

        Uses guess of normalizer_nld and corresponding normalization of gsf

        Returns:
           The arguments used for chi^2 minimization and the
           minimizer.
        """
        normalizer_nld = self.normalizer_nld
        normalizer_gsf = self.normalizer_gsf

        args_nld, guess = normalizer_nld.initial_guess()
        [A, alpha, T, Eshift] = [guess["A"], guess["alpha"],
                                 guess["T"], guess["Eshift"]]

        nld = normalizer_nld.nld.transform(A, alpha, inplace=False)
        nld_model = lambda E: normalizer_nld.model(E, T=T, Eshift=Eshift)  # noqa

        normalizer_gsf.normalize(nld=nld, nld_model=nld_model, alpha=alpha)
        guess["B"] = normalizer_gsf.res.pars["B"][0]

        guess_print = copy.deepcopy(guess)
        self.LOG.info("DE results/initial guess:\n%s",
                      tt.to_string([list(guess_print.values())],
                                   header=['A', 'α [MeV⁻¹]', 'T [MeV]',
                                           'Eshift [MeV]', 'B']))

        return args_nld, guess
コード例 #5
0
ファイル: db_operations.py プロジェクト: SAMORA2/kharjban
def show_payment(id):
    row = ''
    conn = sqlite3.connect(os.path.join('src/db/', 'db.wallet.db'))
    c = conn.cursor()
    temp = c.execute(
        "select category,amount,datetime from asset where user_fk =?", [id])
    zero = []

    for row in temp:
        zero.append(row)

    if type(row) == str:
        print("\nNothing Found ! (NO PAYMENT)\n")
        conn.commit()
        conn.close()
        return False
    else:

        for i in range(len(zero)):
            zero[i] = (i + 1, ) + zero[i]

        tbl_info = tt.to_string(
            zero,
            header=["No.", "Category", "Cost", "Date"],
            style=tt.styles.ascii_thin_double,
        )
        print(tbl_info, '\n')

        conn.commit()
        conn.close()
コード例 #6
0
def print_most_frequent_words(frequent_words):
    header = ['words', 'frequency']
    string = tt.to_string(frequent_words,
                          header=header,
                          style=tt.styles.thin_thick,
                          alignment='c')
    print(string)
コード例 #7
0
def test_escape_sequences():
    data = [["key", "\033[31mred\033[0m"]]

    string = tt.to_string(data)
    print(string)

    assert string == "\n".join(
        ["┌─────┬─────┐", "│ key │ \033[31mred\033[0m │", "└─────┴─────┘"])
コード例 #8
0
ファイル: utils.py プロジェクト: Egnod/adonai-cli
def get_table(dict_list: Union[List[Dict], Dict], header: List[str]):
    rows = []

    if isinstance(dict_list, dict):
        dict_list = [dict_list]

    for obj in dict_list:
        rows.append(list(obj.values()))

    return termtables.to_string(rows, header=header)
コード例 #9
0
ファイル: eval.py プロジェクト: Vastlab/SSFiOWL
def fixed_probability_score(results_for_all_batches, unknowness_threshold=0.5):
    UDA = []
    OCA = []
    CCA = []
    table_data = []
    threshold_scores = []
    logger.critical(
        f"Evaluation at fixed probability score of {unknowness_threshold}")
    for batch_no in sorted(results_for_all_batches.keys())[:-1]:
        unknown_classes = (
            set(results_for_all_batches[batch_no].keys()) -
            set(results_for_all_batches[batch_no]['classes_order']) -
            {'classes_order'})
        unknown_classes = np.array(list(unknown_classes))
        current_batch_scores = []
        current_batch_gt = []
        current_batch_prediction = []
        scores_order = np.array(
            results_for_all_batches[batch_no]['classes_order'])
        for test_cls in list(
                set(results_for_all_batches[batch_no].keys()) -
            {'classes_order'}):
            max_scores = torch.max(results_for_all_batches[batch_no][test_cls],
                                   dim=1)
            current_batch_scores.extend(max_scores.values.tolist())
            current_batch_prediction.extend(
                scores_order[max_scores.indices].tolist())
            current_batch_gt.extend([test_cls] * max_scores.values.shape[0])
        current_batch_scores, CCA_correct, UDA_correct, OCA_correct = eval_data_prep(
            current_batch_scores, current_batch_prediction, current_batch_gt,
            unknown_classes)
        UDA.append(
            UDA_correct[current_batch_scores >= unknowness_threshold][-1] *
            100.)
        OCA.append(
            OCA_correct[current_batch_scores >= unknowness_threshold][-1] *
            100.)
        CCA.append(
            CCA_correct[current_batch_scores >= unknowness_threshold][-1] *
            100.)
        threshold_scores.append(current_batch_scores[
            current_batch_scores >= unknowness_threshold][-1])
        table_data.append(
            (batch_no, f"{threshold_scores[-1]:.3f}", f"{UDA[-1]:.2f}",
             f"{OCA[-1]:.2f}", f"{CCA[-1]:.2f}"))
    table_data.append(("Average", "", f"{np.mean(UDA):.2f}",
                       f"{np.mean(OCA):.2f}", f"{np.mean(CCA):.2f}"))
    table_data_str = tt.to_string(
        table_data,
        header=["Batch No", "Score", "UDA", "OCA", "CCA"],
        style=tt.styles.rounded_thick,
        alignment="ccccc",
        padding=(0, 1))
    logger.warning("\n" + table_data_str)
    return UDA, OCA, CCA
コード例 #10
0
    def initial_guess(
        self,
        limit_low: Optional[Tuple[float, float]] = None,
        limit_high: Optional[Tuple[float, float]] = None
    ) -> Tuple[Tuple[float, float, float, float], Dict[str, float]]:
        """ Find an inital guess for the constant, α, T and D₀

        Uses differential evolution to perform the guessing.

        Args:
            limit_low: The limits (start, stop) where to normalize
               to discrete levels.
            limit_high: The limits (start, stop) where to normalize to
                a theoretical model and neutron separation energy at high
                energies.

        Returns:
           The arguments used for chi^2 minimization and the
           minimizer.
        """
        limit_low = self.self_if_none(limit_low)
        limit_high = self.self_if_none(limit_high)

        bounds = list(self.bounds.values())
        spinParsstring = json.dumps(self.norm_pars.spincutPars,
                                    indent=4,
                                    sort_keys=True)

        self.LOG.debug("Using bounds %s", bounds)
        self.LOG.debug("Using spincutModel %s", self.norm_pars.spincutModel)
        self.LOG.debug("Using spincutPars %s", spinParsstring)

        nld_low = self.nld.cut(*limit_low, inplace=False)
        discrete = self.discrete.cut(*limit_low, inplace=False)
        nld_high = self.nld.cut(*limit_high, inplace=False)

        nldSn = self.nldSn_from_D0(**self.norm_pars.asdict())[1]
        rel_uncertainty = self.norm_pars.D0[1] / self.norm_pars.D0[0]
        nldSn = np.array([nldSn, nldSn * rel_uncertainty])

        def neglnlike(*args, **kwargs):
            return -self.lnlike(*args, **kwargs)

        args = (nld_low, nld_high, discrete, self.model, self.norm_pars.Sn[0],
                nldSn)
        res = differential_evolution(neglnlike, bounds=bounds, args=args)

        self.LOG.info(
            "DE results:\n%s",
            tt.to_string([res.x.tolist()],
                         header=['A', 'α [MeV⁻¹]', 'T [MeV]', 'Eshift [MeV]']))

        p0 = dict(zip(["A", "alpha", "T", "Eshift"], (res.x).T))

        return args, p0
コード例 #11
0
def rentals_before():
    Page.clear()

    g = Gui()
    current_user = g.user
    logging.debug("Current user id %s", current_user.id)
    #Print my buildings
    cursor = db.cursor(dictionary=True)
    query = "SELECT *, location.id location_id, location.date_arrivee, DATE_ADD(location.date_arrivee, INTERVAL location.duree DAY) as date_depart FROM location_prioprietaire INNER JOIN location on location.bien_immobilier_id = location_prioprietaire.bien_id WHERE proprietaire_id = {} AND estConfirme = 1 AND location.date_arrivee < DATE(NOW())".format(
        current_user.id)
    logging.debug("QUERY: %s", query)
    cursor.execute(query)
    my_rentals = cursor.fetchall()
    db.commit()
    logging.debug("LOCATION EN ATTENTE : %s", my_rentals)
    headers = [
        "id", "Type de bien", "description", "addresse", "date arrivée",
        "date départ"
    ]

    def build_addresse(ad):
        if ad is None:
            return ""
        return "" + ad["rue"] + " " + ad["numero"] + " " + ad[
            "etat"] + "(" + ad["commune"] + ")"

    data = list(
        map(
            lambda x: (x["bien_id"], x["type_bien"], x["description"][:20],
                       build_addresse(x), x["date_arrivee"], x["date_depart"]),
            my_rentals))
    if len(data) <= 0:
        data = [["" for i in range(len(headers))]]
    string = tt.to_string(
        data,
        header=headers,
        style=tt.styles.ascii_thin_double,
    )
    print(string)

    #Actions on buildings
    mapping_actions = {"Retour": "return"}
    actions = [
        inquirer.List("action",
                      message="Que voulez vous faire?",
                      choices=["Retour"])
    ]
    action = inquirer.prompt(actions)
    logging.debug("CHOOSING TO DO %s ON BUILDING", action)
    if action is None or "action" not in action.keys():
        return False

    action = mapping_actions[action["action"]]
    if action == "return":
        return False
コード例 #12
0
ファイル: covid.py プロジェクト: gon2410/covid-terminal
def print_table(arr):
    table = tt.to_string(arr,
                         header=[
                             'Pos', 'Country',
                             colored('Infected', 'yellow'),
                             colored('Deaths', 'red'),
                             colored('Recovered', 'green')
                         ],
                         style=tt.styles.ascii_thin_double,
                         alignment="c")
    print(table)
コード例 #13
0
def tabelaCores():
    titulo = ["", "CORES"]
    cores = []

    for i, cor in enumerate(dados.coresFixas):
        cores.append([i + 1, cor])

    listaCores = tt.to_string(cores,
                              header=titulo,
                              style=tt.styles.ascii_thin_double)
    print("\n" + listaCores + "\n")
コード例 #14
0
def tabelaModelos():
    titulo = ["", "MODELOS"]
    modelos = []

    for i, modelo in enumerate(dados.modelosFixos):
        modelos.append([i + 1, modelo])

    menuModelos = tt.to_string(modelos,
                               header=titulo,
                               style=tt.styles.ascii_thin_double)
    print(Fore.GREEN + "\n" + menuModelos + "\n")
コード例 #15
0
    def ShowTable(self):
        ## Reference the data count
        dataCount = len(self.Data)

        ## Check if there is any data to show
        if dataCount < 1:
            Display.Print("There isn't any data to show")
            return

        ## Calculate the page amount
        pageCount = max(dataCount / self.showAmount, 1)

        idx = 0  ## Initial index
        startIdx = self.showAmount * self.page  ## Starting index
        startIdx = startIdx if startIdx < dataCount else 0  ## Starting index
        endIdx = startIdx + self.showAmount  ## Ending index
        endIdx = endIdx if dataCount > endIdx else dataCount  ## Ending index

        localSelectedIndex = ((self.selectedIndex - 1) % self.showAmount) + 1

        ## Create the data table item list
        dataTableItemList = []

        for i in range(int(startIdx), int(endIdx)):
            ## Reference the data item by index
            dataItem = self.Data[i]

            ## Create the data item list
            dataItemList = []

            ## Increase the local index
            idx += 1

            ## Append the index selection status
            dataItemList.append("x" if idx == localSelectedIndex else "")

            ## Append the data items for the selection and fill the data list
            for item in dataItem:
                dataItemList.append(item)

            dataTableItemList.append(dataItemList)

        ## Generate the data table by list
        self.table = table = termtables.to_string(
            dataTableItemList,
            header=self.Header,
            style=termtables.styles.ascii_thin_double,
        )

        ## Print the accounts data table
        Display.Print(table)

        ## Show the table details
        self.ShowNavigationLabel(self.page, self.selectedIndex)
コード例 #16
0
def tabelaMenu():
    menu = ["", "MENU"]
    itens = [["0", "Sair"], ["1", "Cadastrar Tenis"], ["2", "Relatório Geral"],
             ["3", "Realizar Venda"], ["4", "Atualizar preços"],
             ["5", "Cadastrar cores"], ["6", "Exportar os dados"],
             ["7", "Importar os dados"]]

    menuGeral = tt.to_string(itens,
                             header=menu,
                             style=tt.styles.ascii_thin_double)
    print(Fore.RED + "\n" + menuGeral + "\n")
コード例 #17
0
def tabelaVenda(modelo, numeracao, cor, quantidade):
    topo = ["MODELO", "NUMERAÇÃO", "COR", "QUANTIDADE"]
    linha = []

    calculos.calculaEstoqueModelo()
    linha.append([modelo, numeracao, cor, quantidade])

    tabelaVenda = tt.to_string(linha,
                               header=topo,
                               style=tt.styles.ascii_thin_double)
    print("\n" + tabelaVenda)
コード例 #18
0
def tabelaNovasCores():
    titulo = ["", "ATUALIZA"]
    cores = []

    for i, cor in enumerate(dados.novaCor):
        cores.append([i + 1, cor])

    listaCores = tt.to_string(cores,
                              header=titulo,
                              style=tt.styles.ascii_thin_double)
    print("\n" + listaCores + "\n")
コード例 #19
0
def tabelaOpcoes():
    titulo = ["", "ATUALIZAR"]
    op = []
    opcoes = ["Por modelo", "Específico"]

    for i, j in enumerate(opcoes):
        op.append([i + 1, j])

    listaOp = tt.to_string(op,
                           header=titulo,
                           style=tt.styles.ascii_thin_double)
    print("\n" + listaOp)
コード例 #20
0
ファイル: unfolder.py プロジェクト: minrk/ompy
    def apply(self, raw: Matrix, response: Optional[Matrix] = None) -> Matrix:
        """Run unfolding

        TODO: Use better criteria for terminating
        """
        if response is not None:
            self.R = response
        self.raw = copy(raw)
        # Set up the arrays
        self.update_values()
        unfolded_cube = np.zeros((self.num_iter, *self.r.shape))
        chisquare = np.zeros((self.num_iter, self.r.shape[0]))
        fluctuations = np.zeros((self.num_iter, self.r.shape[0]))
        folded = np.zeros_like(self.r)

        # Use u⁰ = r as initial guess
        unfolded = self.r
        for i in range(self.num_iter):
            unfolded, folded = self.step(unfolded, folded, i)
            unfolded_cube[i, :, :] = unfolded
            chisquare[i, :] = self.chi_square(folded)
            fluctuations[i, :] = self.fluctuations(unfolded)

            if LOG.level >= logging.DEBUG:
                chisq = np.mean(chisquare[i, :])
                LOG.debug(f"Iteration {i}: Avg χ²/ν {chisq}")

        # Score the solutions based on χ² value for each Ex bin
        # and select the best one.
        fluctuations /= self.fluctuations(self.r)
        iscores = self.score(chisquare, fluctuations)
        unfolded = np.zeros_like(self.r)
        for iEx in range(self.r.shape[0]):
            unfolded[iEx, :] = unfolded_cube[iscores[iEx], iEx, :]
        if LOG.level >= logging.DEBUG:
            print_array = np.column_stack((np.arange(len(self.raw.Ex)),
                                           self.raw.Ex.astype(int), iscores))
            LOG.debug(
                "Selecting following iterations: \n%s",
                tt.to_string(print_array, header=('i', 'Ex', 'iteration')))

        if self.use_compton_subtraction:
            unfolded = self.compton_subtraction(unfolded)

        unfolded = Matrix(unfolded, Eg=self.raw.Eg, Ex=self.raw.Ex)
        unfolded.state = "unfolded"

        # These two lines feel out of place
        # TODO: What they do and where they should be run is very unclear.
        #     Fix later.
        unfolded.fill_negative(window_size=10)
        unfolded.remove_negative()
        return unfolded
コード例 #21
0
ファイル: player.py プロジェクト: aleksandernovikov/otus-3
 def show_card(self) -> None:
     """
     Вывод карты в консоль
     :return:
     """
     print(f'Карта игрока {self.name}')
     print(tt.to_string(
         data=self.card.preview(),
         header=[],
         alignment='c',
         style=tt.styles.rounded_double
     ))
コード例 #22
0
def test_noborder():
    numpy.random.seed(0)
    data = [
        [["a", "bb", "ccc"]],
        [[1, 2, 3], [613.23236243236, 613.23236243236, 613.23236243236]],
    ]

    string = tt.to_string(data, style=None, padding=0)

    assert (string == """a              bb             ccc
1              2              3
613.23236243236613.23236243236613.23236243236""")
    return
コード例 #23
0
def printMetricsTable(arr):
    """
    Print a nice table of the evaluation metrics
    """
    import termtables as tt
    strategy, precision, recall, F1Score = arr
    precision, recall, F1Score = round(precision,
                                       2), round(recall, 2), round(F1Score, 2)
    string = tt.to_string(
        [[strategy, precision, recall, F1Score]],
        header=["Strategy", "Precision", "Recall", "F1Score"],
        style=tt.styles.ascii_thin_double)
    print(string)
コード例 #24
0
def test_table_alignment():
    numpy.random.seed(0)
    data = [[1, 2, 3], [613.23236243236, 613.23236243236, 613.23236243236]]

    string = tt.to_string(data, style=tt.styles.ascii_thin, alignment="lcr")

    assert (
        string == """+-----------------+-----------------+-----------------+
| 1               |        2        |               3 |
+-----------------+-----------------+-----------------+
| 613.23236243236 | 613.23236243236 | 613.23236243236 |
+-----------------+-----------------+-----------------+""")
    return
コード例 #25
0
def test_padding_0():
    numpy.random.seed(0)
    data = [[1, 2, 3], [613.23236243236, 613.23236243236, 613.23236243236]]

    string = tt.to_string(data,
                          style=tt.styles.ascii_thin_double,
                          padding=0,
                          alignment="lcr")

    ref = """+---------------+---------------+---------------+
|1              |       2       |              3|
+---------------+---------------+---------------+
|613.23236243236|613.23236243236|613.23236243236|
+---------------+---------------+---------------+"""

    assert string == ref

    string = tt.to_string(data,
                          style=tt.styles.ascii_thin_double,
                          padding=(0, ),
                          alignment="lcr")
    assert string == ref
    return
コード例 #26
0
ファイル: cinemas.py プロジェクト: Safintim/13_cinemas
def output_movies_to_console(movies):
    header = ['title', 'votes', 'rating']
    movies_for_table = []
    for movie in sorted(movies,
                        key=lambda movie: movie['rating'],
                        reverse=True):
        movies_for_table.append(
            [movie['title'], movie['votes'], movie['rating']])

    string = tt.to_string(movies_for_table,
                          header=header,
                          style=tt.styles.thin_thick,
                          alignment='c')
    print(string)
コード例 #27
0
def test_table_mixed():
    numpy.random.seed(0)
    data = [[0, 0.123], [1, 2.13], [2, 613.2323]]

    string = tt.to_string(data, style=tt.styles.ascii_thin)

    assert (string == """+---+----------+
| 0 | 0.123    |
+---+----------+
| 1 | 2.13     |
+---+----------+
| 2 | 613.2323 |
+---+----------+""")
    return
コード例 #28
0
def lista():
    topo = ["MODELO", "NUMERAÇÃO", "QUANTIDADE", "COR", "VALOR UNIDADE", "VALOR ESTOQUE"] 
    listas = []  # lista criada pra gerar a tabela conforme doc da lib 
    calculos.calculaEstoqueModelo()
    for i in range(len(dados.lstModelo)):
        listas.append([dados.lstModelo[i], dados.lstNumeracao[i], dados.lstQtd[i], 
        dados.lstCor[i], dados.lstValorUnit[i], dados.lstValorEstoque[i]]) 

    tabelaRelatorio = tt.to_string(
        listas,
        header=topo,
        style=tt.styles.ascii_thin_double
    )
    print("\n" + tabelaRelatorio)
コード例 #29
0
def print_fold_info(args, index, optimizing, x_test, x_train_fold, x_val, y_test, y_train_fold, y_val):
    # print some information
    if optimizing is False and args.verbose:
        print("Split %d..." % index)
        print(tt.to_string([
            [
                "%d items, 0: %d, 1: %d" % (len(x_train_fold),
                                            len(y_train_fold) - np.count_nonzero(y_train_fold),
                                            np.count_nonzero(y_train_fold)),
                "%d data points, 0: %d, 1: %d" % (len(x_val), len(y_val) - np.count_nonzero(y_val),
                                                  np.count_nonzero(y_val)),
                "%d items, 0: %d, 1: %d" % (len(x_test), len(y_test) - np.count_nonzero(y_test),
                                            np.count_nonzero(y_test))
            ]
        ], ["Train", "Validation", "Test"], alignment="lll"))
コード例 #30
0
def test_header():
    header = ["a", "bb", "ccc"]
    data = [[1, 2, 3], [613.23236243236, 613.23236243236, 613.23236243236]]

    string = tt.to_string(data, header, alignment="lcr")

    assert (
        string == """┌─────────────────┬─────────────────┬─────────────────┐
│ a               │       bb        │             ccc │
╞═════════════════╪═════════════════╪═════════════════╡
│ 1               │        2        │               3 │
├─────────────────┼─────────────────┼─────────────────┤
│ 613.23236243236 │ 613.23236243236 │ 613.23236243236 │
└─────────────────┴─────────────────┴─────────────────┘""")
    return