コード例 #1
0
    def info_3(self, *args: Any, **kwargs: Any) -> None:
        """Same as cli_ui.info_3(), except this is a no-op if the
        task is run in parallel with other tasks.

        """
        if not self.parallel:
            ui.info_3(*args, **kwargs)
コード例 #2
0
ファイル: remote_setter.py プロジェクト: FelipeCarlini/tsrc
 def add_remote(self, repo: tsrc.Repo, remote: tsrc.Remote) -> None:
     full_path = self.workspace_path / repo.dest
     # fmt: off
     ui.info_3(repo.dest + ":", "Add remote", ui.bold, remote.name,
               ui.reset, ui.brown, f"({remote.url})")
     # fmt: on
     tsrc.git.run(full_path, "remote", "add", remote.name, remote.url)
コード例 #3
0
 def set_remote(self, repo: tsrc.Repo, remote: tsrc.Remote) -> None:
     full_path = self.workspace_path / repo.src
     # fmt: off
     ui.info_3(repo.src + ":", "Update remote", ui.reset,
               ui.bold, remote.name, ui.reset,
               "to new url:", ui.bold, remote.url)
     # fmt: on
     tsrc.git.run(full_path, "remote", "set-url", remote.name, remote.url)
コード例 #4
0
ファイル: file_system.py プロジェクト: FelipeCarlini/tsrc
def safe_link(*, source: Path, target: Path) -> None:
    """ Safely create a link in 'source' pointing to 'target'. """
    # Not: we need to call both islink() and exist() to safely ensure
    # that the link exists:
    #
    #    islink()  exists()    Description
    #    ----------------------------------------------------------
    #    False     False       source doesn't currently exist : OK
    #    False     True        source corresponds to a file or dir : Error!
    #    True      False       broken symlink, need to remove
    #    True      True        symlink points to a valid target, check target
    #    ----------------------------------------------------------
    make_link = check_link(source=source, target=target)
    if make_link:
        ui.info_3("Creating link", source, "->", target)
        os.symlink(
            target.normpath(), source.normpath(), target_is_directory=target.isdir()
        )
コード例 #5
0
def dbconf():
    cli_ui.info_2("Database configuration")
    try:
        with open(".env") as dbconf:
            connstr = dbconf.readline().split("DB_URL=")[1]
            if (checker.checkMongoDBConnection(connstr)):
                cli_ui.info(cli_ui.check, "Database configuration is valid")
            else:
                cli_ui.error("Database configuration is invalid")
    except:
        cli_ui.info_3(
            "You need to configure Your MongoDB database. https://docs.atlas.mongodb.com/getting-started/"
        )
        while (1):
            connstr = cli_ui.ask_string(
                "Please enter Your MongoDB connection string.")
            if (checker.checkMongoDBConnection(connstr)):
                cli_ui.info(cli_ui.check, "Connected to the database")
                save.save("DB_URL=" + connstr, ".env")
                break
            else:
                cli_ui.error("Connection string is invalid")
コード例 #6
0
ファイル: file_system.py プロジェクト: tronje/tsrc
def check_link(*, source: Path, target: Path) -> bool:
    remove_link = False
    if source.exists() and not source.is_symlink():
        raise tsrc.Error("Specified symlink source exists but is not a link")
        return False
    if source.is_symlink():
        if source.exists():
            # symlink exists and points to some target
            current_target = Path(os.readlink(str(source)))
            if current_target.resolve() == target.resolve():
                ui.info_3("Leaving existing link")
                return False
            else:
                ui.info_3("Replacing existing link")
                remove_link = True
        else:
            # symlink exists, but points to a non-existent target
            ui.info_3("Replacing broken link")
            remove_link = True
    if remove_link:
        os.unlink(source)
    return True
コード例 #7
0
def verifyJS(url, dirname):
    count_items = 0
    global vt_count
    ssl._create_default_https_context = ssl._create_unverified_context
    r = requests.get(url)
    soup = BeautifulSoup(r.content, features="lxml")
    try:
        os.mkdir(sc_path_reports + "/" + str(dirname))
        cli_ui.info_3("Directory ", dirname, " Created ")
    except FileExistsError:
        cli_ui.info_3("Directory ", dirname, " already exists")

    lista = [i.get('src') for i in soup.find_all('script') if i.get('src')]

    for item in lista:
        item = clearJS(item)
        myfile = filename(item)
        newURL = clearURL(item)  ## elimina // en url inicial
        if newURL.startswith('/'):
            newURL = generateUrl(url) + newURL
        try:
            os.system("wget -q -U='" + vt_user_agent + "' -O '" +
                      sc_path_reports +
                      "/{0}' {1}".format(str(dirname) + "/" + myfile, newURL))
            pathfile = sc_path_reports + "/" + str(dirname) + "/" + str(myfile)
            sha256 = sha256sum(pathfile)
            result = (vTotalQuery(sha256))
            if (result != 'ERROR'):
                if (result['response_code'] == 1):
                    permalink = (result['permalink'])
                    total = (result['total'])
                    positives = (result['positives'])
                    if (positives > 0):
                        vt_count += 1
                        data = [[(cli_ui.blue, str(myfile)),
                                 (cli_ui.blue, str(sha256)),
                                 (cli_ui.blue,
                                  str(positives) + "/" + str(total)),
                                 (cli_ui.blue, str(permalink))]]

                        data_final.extend(data)
                else:
                    params = {"apikey": vt_apikey, "resource": str(sha256)}
                    headers = {
                        "Accept-Encoding": "identity, deflate, compress, gzip",
                        "User-Agent": vt_user_agent
                    }
                    files = {'file': (pathfile, open(pathfile, 'rb'))}
                    time.sleep(int(vt_sleep_post_file))
                    response = requests.post(vt_url_post_file,
                                             files=files,
                                             params=params)
                    json_response = response.json()
                    data = [[(cli_ui.blue, str(myfile)),
                             (cli_ui.blue, str(sha256)),
                             (cli_ui.blue, str(json_response['permalink']))]]

                    data_files_vt.extend(data)

            else:
                cli_ui.error("ERROR AL CONSULTAR, VALIDAR API")
            count_items += 1
            cli_ui.info_progress("Done", count_items, len(lista))
        except Exception as e:
            cli_ui.error(str(e))
コード例 #8
0
                    data_files_vt.extend(data)

            else:
                cli_ui.error("ERROR AL CONSULTAR, VALIDAR API")
            count_items += 1
            cli_ui.info_progress("Done", count_items, len(lista))
        except Exception as e:
            cli_ui.error(str(e))


if __name__ == "__main__":
    if (results.url):
        try:
            os.mkdir(sc_path_reports)
            cli_ui.info_3("Directory ", sc_path_reports, " Created ")
        except FileExistsError:
            cli_ui.info_3("Directory ", sc_path_reports, " already exists")

        ts = calendar.timegm(time.gmtime())
        verifyJS(results.url, ts)
        print('\n' * 2)
        cli_ui.info_section("RESULTADO")
        cli_ui.info_1("URL: " + str(results.url))
        cli_ui.info_1("ARCHIVOS ENCONTRADOS EN VIRUS TOTAL: " + str(vt_count))

        if (vt_count > 0):
            print('\n' * 2)
            cli_ui.info_section("DETALLE")
            cli_ui.info_table(data_final, headers=headers)
コード例 #9
0

cls()

#### SCALES LIST

if (args.list_scales):

    cli_ui.info_section("All the scales")

    with open("cleanScales.txt") as fp:
        for i, line in enumerate(fp):
            print(f"{i}) {line}", end='')

    print()
    cli_ui.info_3("You can specify a scale with --scale %d")
    print()
    exit(0)

#### SIGNATURE CREATION
cli_ui.info_section("Music Signature Generator")

alphabet = [
    'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O',
    'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z'
]

nom = inquirer.prompt([inquirer.Text('nom', message="What's your name")
                       ])['nom'].upper()
signature = []
コード例 #10
0
def run(file: str) -> None:
    """
    Calculates the current CBBI confidence value alongside all the required metrics.
    Everything gets pretty printed to the current stdout and a clean copy
    is written to a JSON file specified by the path in the ``file`` argument.

    Args:
        file: File path where the output is stored in the JSON format.

    Returns:
        None
    """

    # fetch online data
    df_bitcoin = fetch_bitcoin_data(365 * 4)

    col_google_trends, df_bitcoin = add_google_trends_index(df_bitcoin)
    col_rupl, df_bitcoin = add_rupl_index(df_bitcoin)

    # parse and analyse the data
    col_golden_ratio = add_golden_ratio_index(df_bitcoin)
    col_stock_to_flow = add_stock_to_flow_index(df_bitcoin)
    col_pi_cycle = add_pi_cycle_index(df_bitcoin)
    col_2yma = add_2yma_index(df_bitcoin)
    col_trolololo = add_trolololo_index(df_bitcoin)
    col_puell = add_puell_index(df_bitcoin)
    col_confidence = 'Confidence'

    cols_metric = [
        col_google_trends,
        col_rupl,
        col_golden_ratio,
        col_stock_to_flow,
        col_pi_cycle,
        col_2yma,
        col_trolololo,
        col_puell,
    ]

    df_result = pd.DataFrame(df_bitcoin[['Date', 'Price'] + cols_metric])

    df_result.dropna(inplace=True)
    df_result.set_index('Date', inplace=True)
    df_result[col_confidence] = df_result[cols_metric].mean(axis=1)
    df_result.to_json(
        file,
        double_precision=4,
        date_unit='s',
        indent=2,
    )

    df_result_latest = df_result.tail(1)

    details_stdout = {
        'The Golden 51%-49% Ratio':
        df_result_latest[col_golden_ratio][0],
        '"Bitcoin" search term (Google Trends)':
        df_result_latest[col_google_trends][0],
        'Stock-to-Flow Chart':
        df_result_latest[col_stock_to_flow][0],
        'Pi Cycle Top Indicator':
        df_result_latest[col_pi_cycle][0],
        '2 Year Moving Average':
        df_result_latest[col_2yma][0],
        'Bitcoin Trolololo Trend Line':
        df_result_latest[col_trolololo][0],
        'RUPL/NUPL Chart':
        df_result_latest[col_rupl][0],
        'Puell Multiple':
        df_result_latest[col_puell][0],
    }

    print('\n')
    cli_ui.info_3('Confidence we are at the peak:')
    cprint(figlet_format(format_percentage(df_result_latest[col_confidence][0],
                                           ''),
                         font='univers'),
           'cyan',
           attrs=['bold'],
           end='')

    for k, v in details_stdout.items():
        cprint(format_percentage(v) + ' ',
               color=get_color(v),
               attrs=['reverse'],
               end='')
        print(f' - {k}')

    print()
    cli_ui.info_3('Source code: https://github.com/Zaczero/CBBI', end='\n\n')