Esempio n. 1
0
def activate_env():
    """ Activates the virtual environment for this project."""

    error_msg = None

    try:
        virtualenv_dir = Path(os.environ['WORKON_HOME'])
    except KeyError:
        error_msg = "Error: 'WORKON_HOME' is not set."

    if error_msg:
        color_init()
        sys.stderr.write(Fore.RED + Style.BRIGHT + error_msg + "\n")
        sys.exit(1)

    filepath = Path(__file__).absolute()
    site_dir = filepath.ancestor(4).components()[-1]
    repo_dir = filepath.ancestor(3).components()[-1]

    # Add the app's directory to the PYTHONPATH
    sys.path.append(filepath.ancestor(2))
    sys.path.append(filepath.ancestor(1))

    # Set manually in environment
    #os.environ['DJANGO_SETTINGS_MODULE'] = 'settings.production'

    if os.environ['DJANGO_SETTINGS_MODULE'] == 'settings.production':
        bin_parent = site_dir
    else:
        bin_parent = repo_dir

    # Activate the virtual env
    activate_env = virtualenv_dir.child(bin_parent, "bin", "activate_this.py")
    execfile(activate_env, dict(__file__=activate_env))
Esempio n. 2
0
        def wrapper(*api_args):
            """The function that we actually call.

            Args:
                api_args (tuple|list):
                    CLI arguments as specified via Python rather than
                    sys.argv directly.
                    If specified these will be passed to the option parser.

            """
            use_color = False
            wrapped_args, wrapped_kwargs = tuple(), {}
            # should we use colour?
            if parser_function:
                parser = parser_function()
                opts, args = parser_function().parse_args(
                    list(api_args), **parser_kwargs)
                # Ensure runN args are replaced with actual run number.
                endings = (WorkflowFiles.RUN_N, f'{WorkflowFiles.RUN_N}/')
                args = [
                    parse_reg(cli_arg)
                    if cli_arg.endswith(endings) else cli_arg
                    for cli_arg in args
                ]
                use_color = (hasattr(opts, 'color')
                             and (opts.color == 'always' or
                                  (opts.color == 'auto' and supports_color())))
                wrapped_args = (parser, opts, *args)
            if 'color' in inspect.signature(wrapped_function).parameters:
                wrapped_kwargs['color'] = use_color

            # configure Cylc to use colour
            color_init(autoreset=True, strip=not use_color)
            if use_color:
                ansi_log()

            try:
                # run the command
                wrapped_function(*wrapped_args, **wrapped_kwargs)
            except (CylcError, ParsecError) as exc:
                if cylc.flow.flags.verbosity < 2:
                    # catch "known" CylcErrors which should have sensible short
                    # summations of the issue, full traceback not necessary
                    print(EXC_EXIT.format(name=exc.__class__.__name__,
                                          exc=exc),
                          file=sys.stderr)
                    sys.exit(1)
                else:
                    # if command is running non-interactively just raise the
                    # full traceback
                    raise
            except SystemExit as exc:
                if exc.args and isinstance(exc.args[0], str):
                    # catch and reformat sys.exit(<str>)
                    # NOTE: sys.exit(a) is equivalent to:
                    #       print(a, file=sys.stderr); sys.exit(1)
                    print(EXC_EXIT.format(name='ERROR', exc=exc.args[0]),
                          file=sys.stderr)
                    sys.exit(1)
                raise
Esempio n. 3
0
def get_env_variable(name, console=False):
    """Get the specified environment variable.

    :param name: The name of the variable.
    :type name: str
    :param console: Whether or not this is run via the console or from within django.
    :type console: bool
    :returns: The value of the specified variable.
    :raises: **ImproperlyConfigured** when the specified variable does not exist.

    """
    try:
        return os.environ[name]
    except KeyError:
        error_msg = "The {variable_name} environment variable is not set!\n".format(
            variable_name=name)

        if console:
            color_init()
            sys.stderr.write(
                colored(text="ImproperlyConfigured: " + error_msg, color='red', attrs=['bold']))
            sys.exit(1)
        else:
            from django.core.exceptions import ImproperlyConfigured
            raise ImproperlyConfigured(error_msg)
Esempio n. 4
0
def check(domain):
    color_init()
    spoofable = False
    if domain is None:
        output_error('ERROR')
    else:
        spf_record_strength = is_spf_record_strong(domain)

        dmarc_record_strength = is_dmarc_record_strong(domain)
        if spf_record_strength is False:
            output_good('No SPF records found! GOATSY! ')
            _spoofable = True
        else:
            output_bad('Warning: %s has sfp ...' % domain)
            _spoofable = False

        if dmarc_record_strength is False:
            spoofable = True
        else:
            spoofable = False

        if spoofable:
            output_good("Spoofing possible for " + domain + "!")
            return True
        else:
            output_bad("Spoofing not possible for " + domain)
            return False
Esempio n. 5
0
def activate_env():
    """ Activates the virtual environment for this project."""

    error_msg = None

    try:
        virtualenv_dir = Path(os.environ['WORKON_HOME'])
    except KeyError:
        error_msg = "Error: 'WORKON_HOME' is not set."

    if error_msg:
        color_init()
        sys.stderr.write(Fore.RED + Style.BRIGHT + error_msg + "\n")
        sys.exit(1)

    filepath = Path(__file__).absolute()
    site_dir = filepath.ancestor(4).components()[-1]
    repo_dir = filepath.ancestor(3).components()[-1]

    # Add the app's directory to the PYTHONPATH
    sys.path.append(filepath.ancestor(2))
    sys.path.append(filepath.ancestor(1))

    # Set manually in environment
    #os.environ['DJANGO_SETTINGS_MODULE'] = 'settings.production'

    if os.environ['DJANGO_SETTINGS_MODULE'] == 'settings.production':
        bin_parent = site_dir
    else:
        bin_parent = repo_dir

    # Activate the virtual env
    activate_env = virtualenv_dir.child(bin_parent, "bin", "activate_this.py")
    execfile(activate_env, dict(__file__=activate_env))
Esempio n. 6
0
    def __init__(self):
        color_init()
        zf = ZmqFactory()
        e = ZmqEndpoint(ZmqEndpointType.connect, ENDPOINT)
        self._conn = ZmqREQConnection(zf, e)

        self.data = []
        if self.service:
            self.data = [self.service]
Esempio n. 7
0
def initColoredLogging():
    if os_name == 'nt':
        color_init(autoreset=True)
    stream = logging.StreamHandler()
    stream.setFormatter(
        ColorFormatter(dedent(f"""\
            %(levelname)s {Style.RESET_ALL+Style.DIM}\
            %(name)s @ %(asctime)s{Style.RESET_ALL} >> %(message)s\
        """),
                       datefmt='%H:%M.%S'))
    return stream
Esempio n. 8
0
def start():
    os.system('cls')
    color_init()
    print(f'Версия: {__version__}')
    description = 'Программа не для продажи...\n\n' \
                  'NativeClient предназначен для быстрой установки и удаления чита NativeTrainer, для использования\n' \
                  'переместите файлы чита в папку "native_client\\bin", а также укажите путь до папки игры в файле\n' \
                  '"native_client\\settings.json", вместо "none". Путь должен быть в формате\n' \
                  '"D:\\\\Steam\\\\steamapps\\\\common\\\\Grand Theft Auto V"\n'
    print(colored(description, 'yellow'))
    main()
Esempio n. 9
0
    def __init__(self, cfg, print_json=False):
        self.cfg = cfg

        color_init()
        zf = ZmqFactory()
        e = ZmqEndpoint(ZmqEndpointType.connect, ENDPOINT)
        self._conn = ZmqREQConnection(zf, e)

        self.data = []
        if self.service:
            self.data = [self.service]
        self.print_json = print_json
Esempio n. 10
0
def main():
    color_init(autoreset=True)

    if not URL:
        print(ERROR + 'You need to specify gitlab url.')
        exit(1)

    if not POSTFIX:
        print(ERROR + 'You need to specify gitlab url postfix.')
        exit(1)

    if not PRIVATE_TOKEN:
        print(
            ERROR +
            'You need to specify your gitlab user\'s PRIVATE_TOKEN in the config file.'
        )
        exit(1)

    parser = argparse.ArgumentParser(
        description="Clone GitLab repositories at once.")

    parser.add_argument('group',
                        nargs='?',
                        default=False,
                        help='Provide project group key.')
    parser.add_argument('-u',
                        '--update',
                        action='store_true',
                        default=False,
                        help='Update the existing repositories.')

    args = parser.parse_args()

    if not args.group:
        print(ERROR + 'Please provide group key.')
        exit(1)
    else:
        print(LINE)
        print(BOLD + ' Group name is: ' + GREEN + args.group)
        print(BOLD + ' Update: ' + 'True' if args.update is True else 'False')
        print(LINE)
        print('')

    projects = _getProjectsOfGroup(args.group)

    if not projects:
        exit(1)

    currentFolder = _getCurrentFolder()
    print('')

    _cloneRepos(args.group, projects, currentFolder, update=args.update)
Esempio n. 11
0
        def wrapper(*api_args: str) -> None:
            """The function that we actually call.

            Args:
                api_args (tuple|list):
                    CLI arguments as specified via Python rather than
                    sys.argv directly.
                    If specified these will be passed to the option parser.

            """
            use_color = False
            wrapped_args, wrapped_kwargs = [], {}
            if parser_function:
                parser = parser_function()
                opts, args = parser_function().parse_args(
                    list(api_args), **parser_kwargs)
                if hasattr(opts, 'color'):
                    use_color = (opts.color == 'always' or
                                 (opts.color == 'auto' and supports_color()))
                wrapped_args = [parser, opts, *args]
            if 'color' in inspect.signature(wrapped_function).parameters:
                wrapped_kwargs['color'] = use_color

            # configure Cylc to use colour
            color_init(autoreset=True, strip=not use_color)
            if use_color:
                ansi_log()

            try:
                # run the command
                wrapped_function(*wrapped_args, **wrapped_kwargs)
            except (CylcError, ParsecError) as exc:
                if cylc.flow.flags.verbosity > 1:
                    # raise the full traceback
                    raise
                # else catch "known" CylcErrors which should have sensible
                # short summations of the issue, full traceback not necessary
                print(EXC_EXIT.format(name=exc.__class__.__name__, exc=exc),
                      file=sys.stderr)
                sys.exit(1)

            except SystemExit as exc:
                if exc.args and isinstance(exc.args[0], str):
                    # catch and reformat sys.exit(<str>)
                    # NOTE: sys.exit(a) is equivalent to:
                    #       print(a, file=sys.stderr); sys.exit(1)
                    print(EXC_EXIT.format(name='ERROR', exc=exc.args[0]),
                          file=sys.stderr)
                    sys.exit(1)
                raise
Esempio n. 12
0
        def wrapper():
            use_color = False
            wrapped_args, wrapped_kwargs = tuple(), {}
            # should we use colour?
            if parser_function:
                parser = parser_function()
                opts, args = parser_function().parse_args(**parser_kwargs)
                use_color = (
                    hasattr(opts, 'color')
                    and (
                        opts.color == 'always'
                        or (opts.color == 'auto' and supports_color())
                    )
                )
                wrapped_args = (parser, opts, *args)
            if 'color' in inspect.signature(wrapped_function).parameters:
                wrapped_kwargs['color'] = use_color

            # configure Cylc to use colour
            color_init(autoreset=True, strip=not use_color)
            if use_color:
                ansi_log()

            try:
                # run the command
                wrapped_function(*wrapped_args, **wrapped_kwargs)
            except (CylcError, ParsecError) as exc:
                if is_terminal() or not cylc.flow.flags.debug:
                    # catch "known" CylcErrors which should have sensible short
                    # summations of the issue, full traceback not necessary
                    sys.exit(EXC_EXIT.format(
                        name=exc.__class__.__name__,
                        exc=exc
                    ))
                else:
                    # if command is running non-interactively just raise the
                    # full traceback
                    raise
            except SystemExit as exc:
                if exc.args and isinstance(exc.args[0], str):
                    # catch and reformat sys.exit(<str>)
                    # NOTE: sys.exit(a) is equivalent to:
                    #       print(a, file=sys.stderr); sys.exit(1)
                    sys.exit(EXC_EXIT.format(
                        name='ERROR',
                        exc=exc.args[0]
                    ))
                raise
Esempio n. 13
0
def single_domain(domain):
    color_init()
    spoofable = False

    spf_record_strength = is_spf_record_strong(domain)

    dmarc_record_strength = is_dmarc_record_strong(domain)
    if dmarc_record_strength is False:
        spoofable = True
    else:
        spoofable = False

    if spoofable:
        output_good("Spoofing possible for " + domain + "!")
    else:
        output_bad("Spoofing not possible for " + domain)
Esempio n. 14
0
def get_env_variable(name):
    """ Gets the specified environment variable.

    :param name: The name of the variable.
    :type name: str
    :returns: The value of the specified variable.
    :raises: **ImproperlyConfigured** when the specified variable does not exist.

    """

    try:
        return os.environ[name]
    except KeyError:
        error_msg = "Error: The %s environment variable is not set!" % name
        color_init()
        sys.stderr.write(Fore.RED + Style.BRIGHT + error_msg + "\n")
        sys.exit(1)
Esempio n. 15
0
def get_env_variable(name):
    """ Gets the specified environment variable.

    :param name: The name of the variable.
    :type name: str
    :returns: The value of the specified variable.
    :raises: **ImproperlyConfigured** when the specified variable does not exist.

    """

    try:
        return os.environ[name]
    except KeyError:
        error_msg = "Error: The {variable_name} environment variable is not set!\n".format(variable_name=name)
        color_init()
        sys.stderr.write(colored(text=error_msg, color='red', attrs=['bold']))
        sys.exit(1)
Esempio n. 16
0
def cli_help():
    """Display the main Cylc help page."""
    # add a splash of colour
    # we need to do this explicitly as this command is not behind cli_function
    # (assume the cylc help is only ever requested interactively in a
    # modern terminal)
    color_init(autoreset=True, strip=False)
    print(USAGE)
    print('Selected Sub-Commands:')
    print_command_list(
        # print a short list of the main cylc commands
        commands=[
            'hold', 'install', 'kill', 'pause', 'play', 'release', 'scan',
            'stop', 'trigger', 'tui', 'validate'
        ],
        indent=2)
    print('\nTo see all commands run: cylc help all')
    sys.exit(0)
Esempio n. 17
0
def main():

    color_init(autoreset=True)

    if not URL:
        print(ERROR + 'You need to specify gitlab url.')
        exit(1)

    if not POSTFIX:
        print(ERROR + 'You need to specify gitlab url postfix.')
        exit(1)

    if not PRIVATE_TOKEN:
        print(ERROR + 'You need to specify your gitlab user\'s PRIVATE_TOKEN in the config file.')
        exit(1)

    parser = argparse.ArgumentParser(
         description="Clone GitLab repositories at once.")

    parser.add_argument('group', nargs='?', default=False, help='Provide project group key.')
    parser.add_argument('-u', '--update', action='store_true', default=False, help='Update the existing repositories.')

    args = parser.parse_args()

    if not args.group:
        print (ERROR + 'Please provide group key.')
        exit(1)
    else:
        print(LINE)
        print(BOLD + ' Group name is: ' + GREEN + args.group)
        print(BOLD + ' Update: ' + 'True' if args.update is True else 'False')
        print(LINE)
        print('')


    projects = _getProjectsOfGroup(args.group)

    if not projects:
        exit(1)

    currentFolder = _getCurrentFolder()
    print('')

    _cloneRepos(args.group, projects, currentFolder, update=args.update)
Esempio n. 18
0
def main():
    """Parse arguments and then call the appropriate function(s)."""
    parser = _build_parser()
    color_init(autoreset=True)
    args = parser.parse_args()

    print(Style.BRIGHT + "gitup" + Style.RESET_ALL + ": the git-repo-updater")
    print()

    if args.selftest:
        _selftest()
        return

    if args.bookmark_file:
        args.bookmark_file = os.path.expanduser(args.bookmark_file)

    acted = False
    if args.bookmarks_to_add:
        add_bookmarks(args.bookmarks_to_add, args.bookmark_file)
        acted = True
    if args.bookmarks_to_del:
        delete_bookmarks(args.bookmarks_to_del, args.bookmark_file)
        acted = True
    if args.list_bookmarks:
        list_bookmarks(args.bookmark_file)
        acted = True
    if args.clean_bookmarks:
        clean_bookmarks(args.bookmark_file)
        acted = True

    if args.command:
        if args.directories_to_update:
            run_command(args.directories_to_update, args)
        if args.update or not args.directories_to_update:
            run_command(get_bookmarks(args.bookmark_file), args)
    else:
        if args.directories_to_update:
            update_directories(args.directories_to_update, args)
            acted = True
        if args.update or not acted:
            update_bookmarks(get_bookmarks(args.bookmark_file), args)
Esempio n. 19
0
    def __init__(self):
        color_init()
        self.prepare = False
        self.compose = False
        self.send = False
        self.month_int = 0
        self.year = 0
        self.month_str = ''
        self.duplicates_found = False
        self.google_path = get_google_drive_path()
        self.config_fname = self.google_path + 'settings.ini'
        if not isfile(self.config_fname):
            self.create_config_file()
        self.config = self.load_config()
        self.rtp_log_level = self.config['rtp']['log_level']
        self.bill_tenant_0 = str2bool(self.config['rtp']['bill_tenant_0'])
        self.sql_log_level = self.config['sql']['log_level']
        self.sql_db_fname = self.google_path + self.config['sql']['db_file_name']
        self.pdf_log_level = self.config['pdf']['log_level']
        self.pdf_docx_template = self.google_path + self.config['pdf']['docx_template']

        self.mail_log_level = self.config['email']['log_level']
        self.mail_user = self.config['email']['user']
        self.mail_pswd = self.config['email']['pswd']
        self.mail_server = self.config['email']['server']
        self.mail_port = self.config['email']['port']
        self.mail_msg = self.config['email']['msg_body']

        self.logger_fname = self.google_path + 'rtp_log.txt'
        self.logger = create_logger(self.logger_fname, self.rtp_log_level, "rtp_log")
        if not isfile(self.sql_db_fname):
            self.critical_stop("Something has gone very wrong! db file doesn't exist!")
        self.logger.debug("Run Time Properties are initialized")

        self.utilityBillList: List[UtilityBill] = []
        self.tenantList: List[Tenant] = []
        self.recurringChargeList: List[RecurringCharges] = []
        self.tenantBillList = TenantBillList()
Esempio n. 20
0
def is_domain_spoofable(from_address):
    color_init()
    spoofable = False

    try:
        domain = args.from_address.split('@')[1]

        spf_record_strength = is_spf_record_strong(domain)

        dmarc_record_strength = is_dmarc_record_strong(domain)
        if dmarc_record_strength is False:
            spoofable = True
        else:
            spoofable = False

        if spoofable:
            output_good("Spoofing possible for " + domain + "!")
        else:
            output_bad("Spoofing not possible for " + domain)

    except IndexError:
        output_error("Wrong domain name!")

    return spoofable
Esempio n. 21
0
class Workers:
    """Returns number of matches found."""
    def __init__(self, count=None):
        self.count = count

    filepath = Path(__file__).parent
    results = filepath / "results"
    iocs = filepath / "iocs"
    hostname = socket.gethostname().upper()

    # Initialize colorama
    color_init()

    # Unicode Symbols and colors -  ref: http://www.fileformat.info/info/unicode/char/a.htm
    processing = f"{Fore.CYAN}>{Fore.RESET}"
    found = f"{Fore.GREEN}\u2714{Fore.RESET}"
    notfound = f"{Fore.YELLOW}\u00D8{Fore.RESET}"
    error = f"{Fore.RED}\u2718{Fore.RESET}"

    def iocs_file(self):
        return self.iocs / "known_iocs.txt"

    def save_iocs_csv(self):
        if not self.results.exists():
            self.results.mkdir(parents=True)
        timestr = time.strftime("%Y%m%d-%H%M%S")
        return self.results / f"{worker.hostname}_{timestr}.csv"

    @staticmethod
    def sha256(fname):
        hash_sha256 = hashlib.sha256()
        with open(fname, "rb") as _file:
            for chunk in iter(lambda: _file.read(4096), b""):
                hash_sha256.update(chunk)
        return hash_sha256.hexdigest()

    def read_file(self):
        with open(self.iocs_file(), "r") as _file:
            # skip file header starting with '#'
            try:
                next(_file)
                data = [data.strip() for data in _file.readlines()]
            except StopIteration:
                pass
            else:
                return data
            return None
Esempio n. 22
0
def main():
    color_init()
    cli = BitmaskCLI()
    reactor.callWhenRunning(reactor.callLater, 0, send_command, cli)
    reactor.run()
Esempio n. 23
0
def main(parser, options):
    """Implement "cylc scan"."""
    if options.full:
        options.describe = options.state_totals = options.publisher = True
    if options.format in ['raw', 'json']:
        options.color = False

    # color settings
    if options.color in ['auto', 'always'] and terminal.supports_color():
        options.color = True
    else:
        options.color = False
    color_init(autoreset=True, strip=not options.color)

    # name and owner patterns
    if options.patterns_name:
        patterns_name = options.patterns_name
    else:
        patterns_name = ['.*']  # Any suite name.
    patterns_owner = None
    if options.patterns_owner:
        patterns_owner = options.patterns_owner
    try:  # Compile and check "name" and "owner" regular expressions
        cre_owner, cre_name = re_compile_filters(patterns_owner, patterns_name)
    except ValueError as exc:
        parser.error(str(exc))

    # list of endpoints to call
    methods = ['identify']
    if options.describe:
        methods.append('describe')
    if options.state_totals:
        methods.append('state_totals')

    # suite generator
    suites = scan_many(
        get_scan_items_from_fs(cre_owner, cre_name),
        timeout=options.comms_timeout,
        methods=methods,
        ordered=options.ordered
    )

    # determine output format
    if options.format == 'json':
        print(json.dumps(list(suites), indent=4))
    elif options.format == 'raw':
        formatter = format_raw
    elif options.format == 'plain':
        formatter = format_plain
    else:
        raise UserInputError('Unknown format: %s' % options.format)

    # output state legend if necessary
    state_legend = ""
    if options.color and options.state_totals:
        n_states = len(TASK_STATUSES_ORDERED)
        for index, state in enumerate(TASK_STATUSES_ORDERED):
            state_legend += get_status_prop(state, 'ascii_ctrl')
            if index == n_states / 2:
                state_legend += "\n"
        print(state_legend.rstrip() + "\n")

    # work through scan results one by one
    for reg, host, port, pub_port, api, info in suites:
        if isinstance(info, str):
            print(ERROR_STYLE + ' '.join([reg, host, port, info]))
        elif info is None:
            print(ERROR_STYLE +
                  ' '.join([reg, host, port, 'Error Connecting']))
        elif info[KEY_NAME] != reg:
            # TODO - should we do anything here, is this likely?
            print(ERROR_STYLE + 'Warning: suite has changed name %s => %s' % (
                reg, info[KEY_NAME]))
        else:
            formatter(reg, host, port, pub_port, api, info, options)
Esempio n. 24
0
def app(db_name='imd_city_db'):
    run('clear')
    print(
        '[+]City Weather ::\n\n***Choose 1 from below list for first time use***\n'
    )
    ch = __get_menu__()
    if (ch == -1):
        return
    if (ch == 1):
        resp = fetch_city()
        if (not resp.get('error')):
            print('[+]Status after storing record : {}'.format(
                store_city_name_id(resp, db_name=db_name)))
            print('\n')
            for i, j in resp.items():
                print('\t{}\n'.format(i))
                for k in j:
                    for l, m in k.items():
                        print('\t\t\'{}\'  |  {}'.format(l, m))
                print('\n')
        else:
            print('[!]{} -> {}\n'.format('Error', resp.get('error', ':/')))
            resp = fetch_city_name_id(db_name=db_name)
            for i, j in resp.items():
                print('\t\t{}\t---\t{}'.format(i, j))
    elif (ch == 2):
        resp = __fetch_a_certain_city__(db_name)
        print('\n')
        for i, j in resp.items():
            print('\t{}\t---\t{}'.format(i, j))
        print('\n')
    else:
        resp = __fetch_a_certain_city__(db_name)
        print('\n')
        if (resp.get('error')):
            print('{}\n'.format(resp))
        else:
            if (len(resp.keys()) > 1):
                print('[+]Possible Matches found ...\n')
                for i, j in enumerate(resp.keys()):
                    print('\t{} -> {}'.format(i + 1, resp.get(j)))
                tmp = input('\n[?]Choose one from above >> ')
                try:
                    tmp = int(tmp)
                except ValueError as e:
                    print('[!]Error : {}'.format(str(e)))
                    return
                if (tmp not in range(1, len(resp.keys()) + 1)):
                    print('[!]Bad input')
                    return
                resp = {
                    list(resp.keys())[tmp - 1]:
                    resp.get(list(resp.keys())[tmp - 1])
                }
            else:
                print('[+]Match found :\n\t{}\n'.format(resp))
            print('[+]Fetching data ...\n')
            city_id = list(resp.keys())[0]
            weather = fetch_weather(city_id, db_name=db_name)
            if (weather.get('error')):
                print('{}\n'.format(weather))
                return
            print('[+]Weather Data :\n')
            pref_it = 'http://city.imd.gov.in/citywx/'
            color_init()
            for i, j in weather.get(city_id).items():
                if (i == 'past_24_hours_weather'):
                    print('\t{}{}{} :\n'.format(
                        Fore.GREEN,
                        ' '.join([x.capitalize() for x in i.split('_')]),
                        Fore.RESET))
                    for k, l in j.items():
                        if (k.startswith('Departure from Normal(oC)')):
                            k = 'Departure from Normal(oC)'
                        print('\t\t{:<90} ---  {}{}{}'.format(
                            k, Fore.RED, l, Fore.RESET))
                    print('\n')
                elif (i == '7_days_forecast'):
                    print('\t{}{}{} :\n'.format(
                        Fore.GREEN,
                        ' '.join([x.capitalize() for x in i.split('_')]),
                        Fore.RESET))
                    for k in j:
                        k[3] = Fore.MAGENTA + pref_it + k[3] + Fore.RESET
                        print('\t\t{} | {} | {} | {}'.format(*k))
                    print('\n')
                else:
                    print('\t{}{}{}\t---\t{}\n'.format(
                        Fore.GREEN,
                        ' '.join([x.capitalize() for x in i.split('_')]),
                        Fore.RESET, Fore.MAGENTA + pref_it + j + Fore.RESET))
            reset_all()
            print('[+]End\n')
    return
Esempio n. 25
0
def main():
    """Parse arguments and then call the appropriate function(s)."""
    parser = argparse.ArgumentParser(
        description="""Easily update multiple git repositories at once.""",
        epilog="""
            Both relative and absolute paths are accepted by all arguments.
            Questions? Comments? Email the author at {0}.""".format(__email__),
        add_help=False)

    group_u = parser.add_argument_group("updating repositories")
    group_b = parser.add_argument_group("bookmarking")
    group_m = parser.add_argument_group("miscellaneous")
    rebase_or_merge = group_u.add_mutually_exclusive_group()

    group_u.add_argument(
        'directories_to_update',
        nargs="*",
        metavar="path",
        help="""update all repositories in this directory (or the directory
                itself, if it is a repo)""")
    group_u.add_argument('-u',
                         '--update',
                         action="store_true",
                         help="""update all bookmarks
        (default behavior when called without arguments)""")
    group_u.add_argument('-c',
                         '--current-only',
                         action="store_true",
                         help="""only fetch the
        remote tracked by the current branch instead of all remotes""")
    rebase_or_merge.add_argument('-r',
                                 '--rebase',
                                 action="store_true",
                                 help="""always rebase upstream
        branches instead of following `pull.rebase` and `branch.<name>.rebase`
        in git config (like `git pull --rebase=preserve`)""")
    rebase_or_merge.add_argument('-m',
                                 '--merge',
                                 action="store_true",
                                 help="""like --rebase, but merge
        instead""")

    group_b.add_argument('-a',
                         '--add',
                         dest="bookmarks_to_add",
                         nargs="+",
                         metavar="path",
                         help="add directory(s) as bookmarks")
    group_b.add_argument(
        '-d',
        '--delete',
        dest="bookmarks_to_del",
        nargs="+",
        metavar="path",
        help="delete bookmark(s) (leaves actual directories alone)")
    group_b.add_argument('-l',
                         '--list',
                         dest="list_bookmarks",
                         action="store_true",
                         help="list current bookmarks")
    group_m.add_argument('-h',
                         '--help',
                         action="help",
                         help="show this help message and exit")
    group_m.add_argument('-v',
                         '--version',
                         action="version",
                         version="gitup version " + __version__)

    color_init(autoreset=True)
    args = parser.parse_args()
    update_args = args.current_only, args.rebase, args.merge

    print(Style.BRIGHT + "gitup" + Style.RESET_ALL + ": the git-repo-updater")
    print()

    acted = False
    if args.bookmarks_to_add:
        add_bookmarks(args.bookmarks_to_add)
        acted = True
    if args.bookmarks_to_del:
        delete_bookmarks(args.bookmarks_to_del)
        acted = True
    if args.list_bookmarks:
        list_bookmarks()
        acted = True
    if args.directories_to_update:
        update_directories(args.directories_to_update, update_args)
        acted = True
    if args.update or not acted:
        update_bookmarks(get_bookmarks(), update_args)
Esempio n. 26
0
                            repeat(user),
                            input_handle,
                        ),
                        1,
            )

        ''' terminate all other workers on exception '''
        except Exception, e:
            pool.close()
            pool.terminate()
            success_msg = str(e)
            print ' '*3, success_msg
            send_notification(
                success_msg.replace(
                    '[32m', '').replace(
                        '37m', '').replace(
                            '34m', '').replace(
                                '39m', ''))
        ''' otherwise wait for workers to join parent process '''
        else:
            pool.close()
            pool.join()
    
        ''' leave '''
        print '    %s[%s*%s]%s Exiting.%s' %\
            (Fore.GREEN, Fore.YELLOW, Fore.GREEN, Fore.WHITE, Fore.RESET)
    
if __name__ == '__main__':
    color_init()
    main()
Esempio n. 27
0
def main():
    """Parse arguments and then call the appropriate function(s)."""
    parser = argparse.ArgumentParser(
        description="Easily update multiple git repositories at once.",
        epilog="""
            Both relative and absolute paths are accepted by all arguments.
            Direct bug reports and feature requests to:
            https://github.com/earwig/git-repo-updater.""",
        add_help=False)

    group_u = parser.add_argument_group("updating repositories")
    group_b = parser.add_argument_group("bookmarking")
    group_m = parser.add_argument_group("miscellaneous")

    group_u.add_argument(
        'directories_to_update', nargs="*", metavar="path",
        help="""update all repositories in this directory (or the directory
                itself, if it is a repo)""")
    group_u.add_argument(
        '-u', '--update', action="store_true", help="""update all bookmarks
        (default behavior when called without arguments)""")
    group_u.add_argument(
        '-c', '--current-only', action="store_true", help="""only fetch the
        remote tracked by the current branch instead of all remotes""")
    group_u.add_argument(
        '-f', '--fetch-only', action="store_true",
        help="only fetch remotes, don't try to fast-forward any branches")

    group_b.add_argument(
        '-a', '--add', dest="bookmarks_to_add", nargs="+", metavar="path",
        help="add directory(s) as bookmarks")
    group_b.add_argument(
        '-d', '--delete', dest="bookmarks_to_del", nargs="+", metavar="path",
        help="delete bookmark(s) (leaves actual directories alone)")
    group_b.add_argument(
        '-l', '--list', dest="list_bookmarks", action="store_true",
        help="list current bookmarks")

    group_m.add_argument(
        '-h', '--help', action="help", help="show this help message and exit")
    group_m.add_argument(
        '-v', '--version', action="version",
        version="gitup " + __version__)

    # TODO: deprecated arguments, for removal in v1.0:
    parser.add_argument(
        '-m', '--merge', action="store_true", help=argparse.SUPPRESS)
    parser.add_argument(
        '-r', '--rebase', action="store_true", help=argparse.SUPPRESS)

    color_init(autoreset=True)
    args = parser.parse_args()
    update_args = args.current_only, args.fetch_only

    print(Style.BRIGHT + "gitup" + Style.RESET_ALL + ": the git-repo-updater")
    print()

    # TODO: remove in v1.0
    if args.merge or args.rebase:
        print(Style.BRIGHT + Fore.YELLOW + "Warning:", "--merge and --rebase "
              "are deprecated. Branches are only updated if they\ntrack an "
              "upstream branch and can be safely fast-forwarded. Use "
              "--fetch-only to\navoid updating any branches.\n")

    acted = False
    if args.bookmarks_to_add:
        add_bookmarks(args.bookmarks_to_add)
        acted = True
    if args.bookmarks_to_del:
        delete_bookmarks(args.bookmarks_to_del)
        acted = True
    if args.list_bookmarks:
        list_bookmarks()
        acted = True
    if args.directories_to_update:
        update_directories(args.directories_to_update, update_args)
        acted = True
    if args.update or not acted:
        update_bookmarks(get_bookmarks(), update_args)
Esempio n. 28
0
def main(args):
    global folder
    global sources

    color_init(autoreset=True)
    message("Welcome to the Honeybadger Program Checker")

    folder = Path(args["FOLDER"] or ".").resolve()
    message("The folder `%s` will be examinated." % str(folder))

    users = auteur_users(folder) + args["--user"]
    if len(users) > 1:
        message("The authors of this project are: %s." % ", ".join(users))
    elif users:
        message("The author of this project is: %s." % users[0])
    else:
        warning("No usernames availables, headers cannot be checked properly.")

    sources = sorted((s for s in folder.glob("**/*.[ch]") if s.is_file()),
                     key=lambda p: p.stat().st_size,
                     reverse=True)
    amount_sources = len(sources)
    if 0 < amount_sources < 32:
        joined = ", ".join(map(lambda p: str(p.relative_to(folder)), sources))
        message("Found %d source files: %s." % (amount_sources, joined))
        pool_size = amount_sources
    elif sources:
        message("Found %d source files." % amount_sources)
        pool_size = 32
    else:
        error("No source files were found.")
    pool = Pool(pool_size)  # TODO: Make it faster :(
    results = pool.map(check_source, sources)
    pool.close()
    pool.join()
    for result in results:
        if result["header"]:
            message("File %s: (%s | %s | %s)" % (
                result["path"].relative_to(folder),
                result["header"]["author"],
                result["header"]["created_by"],
                result["header"]["updated_by"],
                ))
            if (result["header"]["filename"] != result["path"].name):
                error(" -- The header's filename differs in the header")
            if users and (result["header"]["author"] not in users
                          or result["header"]["created_by"] not in users
                          or result["header"]["updated_by"] not in users):
                error(" -- Login in header differs from allowed authors")
        else:
            message("File %s:" % result["path"].relative_to(folder))
        for error_message in result["errors"]:
            error(" --  " + error_message)
    message("End of script, calling make")
    if folder == Path(".").resolve():
        make_args = ["make"]
    else:
        make_args = ["make", "-C", str(folder.relative_to(Path().resolve()))]
    make = Popen(make_args)
    while make.poll() is None:
        sleep(0.1)
    exit(0)
Esempio n. 29
0
def main():
    """Parse arguments and then call the appropriate function(s)."""
    parser = argparse.ArgumentParser(
        description="Easily update multiple git repositories at once.",
        epilog="""
            Both relative and absolute paths are accepted by all arguments.
            Direct bug reports and feature requests to
            https://github.com/earwig/git-repo-updater.""",
        add_help=False)

    group_u = parser.add_argument_group("updating repositories")
    group_b = parser.add_argument_group("bookmarking")
    group_a = parser.add_argument_group("advanced")
    group_m = parser.add_argument_group("miscellaneous")

    group_u.add_argument(
        'directories_to_update', nargs="*", metavar="path", type=_decode,
        help="""update all repositories in this directory (or the directory
                itself, if it is a repo)""")
    group_u.add_argument(
        '-u', '--update', action="store_true", help="""update all bookmarks
        (default behavior when called without arguments)""")
    group_u.add_argument(
        '-c', '--current-only', action="store_true", help="""only fetch the
        remote tracked by the current branch instead of all remotes""")
    group_u.add_argument(
        '-f', '--fetch-only', action="store_true",
        help="only fetch remotes, don't try to fast-forward any branches")
    group_u.add_argument(
        '-p', '--prune', action="store_true", help="""after fetching, delete
        remote-tracking branches that no longer exist on their remote""")

    group_b.add_argument(
        '-a', '--add', dest="bookmarks_to_add", nargs="+", metavar="path",
        type=_decode, help="add directory(s) as bookmarks")
    group_b.add_argument(
        '-d', '--delete', dest="bookmarks_to_del", nargs="+", metavar="path",
        type=_decode,
        help="delete bookmark(s) (leaves actual directories alone)")
    group_b.add_argument(
        '-l', '--list', dest="list_bookmarks", action="store_true",
        help="list current bookmarks")
    group_b.add_argument(
        '-n', '--clean', '--cleanup', dest="clean_bookmarks",
        action="store_true", help="delete any bookmarks that don't exist")
    group_b.add_argument(
        '-b', '--bookmark-file', nargs="?", metavar="path", type=_decode,
        help="use a specific bookmark config file (default: {0})".format(
            get_default_config_path()))

    group_a.add_argument(
        '-e', '--exec', '--batch', dest="command", metavar="command",
        help="run a shell command on all repos")

    group_m.add_argument(
        '-h', '--help', action="help", help="show this help message and exit")
    group_m.add_argument(
        '-v', '--version', action="version",
        version="gitup " + __version__)

    # TODO: deprecated arguments, for removal in v1.0:
    parser.add_argument(
        '-m', '--merge', action="store_true", help=argparse.SUPPRESS)
    parser.add_argument(
        '-r', '--rebase', action="store_true", help=argparse.SUPPRESS)

    color_init(autoreset=True)
    args = parser.parse_args()
    update_args = args.current_only, args.fetch_only, args.prune

    print(Style.BRIGHT + "gitup" + Style.RESET_ALL + ": the git-repo-updater")
    print()

    # TODO: remove in v1.0
    if args.merge or args.rebase:
        print(Style.BRIGHT + Fore.YELLOW + "Warning:", "--merge and --rebase "
              "are deprecated. Branches are only updated if they\ntrack an "
              "upstream branch and can be safely fast-forwarded. Use "
              "--fetch-only to\navoid updating any branches.\n")

    if args.bookmark_file:
        args.bookmark_file = os.path.expanduser(args.bookmark_file)

    acted = False
    if args.bookmarks_to_add:
        add_bookmarks(args.bookmarks_to_add, args.bookmark_file)
        acted = True
    if args.bookmarks_to_del:
        delete_bookmarks(args.bookmarks_to_del, args.bookmark_file)
        acted = True
    if args.list_bookmarks:
        list_bookmarks(args.bookmark_file)
        acted = True
    if args.clean_bookmarks:
        clean_bookmarks(args.bookmark_file)
        acted = True

    if args.command:
        if args.directories_to_update:
            run_command(args.directories_to_update, args.command)
        if args.update or not args.directories_to_update:
            run_command(get_bookmarks(args.bookmark_file), args.command)
    else:
        if args.directories_to_update:
            update_directories(args.directories_to_update, update_args)
            acted = True
        if args.update or not acted:
            update_bookmarks(get_bookmarks(args.bookmark_file), update_args)
Esempio n. 30
0
def main():
    color_init()
    cli = BitmaskCLI()
    reactor.callWhenRunning(reactor.callLater, 0, send_command, cli)
    reactor.run()
Esempio n. 31
0
def main():
    with open("test.txt", 'r', encoding="utf-8") as f:
        text = f.read()

    if (False):
        sentences = array(split_into_sentences(text, True))
        if (not len(sentences)):
            print("Nothing found")
            exit(-1)

        tags = pos_tag_sents(map(word_tokenize, sentences))

        lemmatized = lemmatize_sents(
            deepcopy(tags))  #Only for aesthetics reasons

        chunker = RegexpParser("AC: {(<CD>?<TO|IN>?<CD>)+}\n "
                               "AN: {(<NPP>+<DT|NPP|JJ>*)+}\n "
                               "}<DT>+{\n "
                               "PH: {<[B-Z]+>+}\n "
                               "}<DT|CC|PRP|EX|WDT>+{")
        chunked = list(chunker.parse_sents(lemmatized))

        droped = setup_search_structure(chunked, tuple)

        if (True):
            num_print = input("Full data of:[None] ")
            if (num_print):
                num_print = int(num_print)
                print()

                for num_print in range(num_print, num_print + 10):
                    print(sentences[num_print])
                    print()
                    print(tags[num_print])
                    print()
                    print(lemmatized[num_print])
                    print()
                    #chunks = ne_chunk_sents(tags)
                    #iob = [tree2conlltags(chunk) for chunk in chunks]
                    #iob = tree2conlltags(chunks)
                    #print(iob[num_print])
                    #print()
                    #tree = [conlltags2tree(i) for i in iob]
                    #print(tree[num_print])
                    #print()
                    #"NP: {<IN|TO>?((<IN>?<DT>?<JJ.?>*<CD>?<NN.*>+<POS>?)+<CD>?<FW>?)+}\n "
                    #"VP: {((<WP>?<PRP>?<MD>?<VB.?>?<JJ>*<TO>?<VB.?>+<RB>*(<JJ>*<TO>?)*)+<CC>?)+}\n "

                    print(chunked[num_print])
                    print("\n###\n")

                    print(droped[0][num_print])
                    print()

                    if (input(f"({num_print}) ?> ")): break

    ### Search params
    to_search = input("Search: ") or "work"
    tag = {
        '1': 'n',
        '2': 'v',
        '3': 'a',
        '4': 'r'
    }.get(
        input(f"\nWhat '{to_search}'?\n"
              "[1]: Noun\n"
              "[2]: Verb\n"
              "[3]: Adjective\n"
              "[4]: Adverb\n\n"
              "> "), None)
    syn = 'y' in input("\nFind related words too? ").lower()
    exact = 'y' in input("\nFind exact word? ").lower()
    print()

    _, ph_num_ls, sentences = analize_text(text, exact_words=exact)
    num = 1000000
    num2 = 10

    if (to_search):
        if (syn):
            w_rel = words_related(to_search, tag)
        else:
            w_rel = to_search

        ph_nums = find(w_rel, ph_num_ls)

    print()

    if (not len(ph_nums)):
        print(f"{to_search} not in text.")
        exit(0)

    if (False):
        print(f"Looking for \"{to_search}\" {num} times...\n")

        print(timeit.timeit("find(w_rel, ph_num_ls)",
                            number=num,
                            globals={
                                **globals(),
                                **locals()
                            }),
              end=' seconds\n\n')

    if (False):
        print(f"{num2} times text setup...\n")
        print(timeit.timeit("analize_text(text)",
                            number=num2,
                            globals={
                                **globals(),
                                **locals()
                            }),
              end=' seconds \n')

    if ("y" in input("Show found instances?[No] ")):
        from colorama import init as color_init
        color_init()

        print()
        if (not ph_nums is None):  # Unnecessary, but clean
            for ph in ph_nums:
                print(_color_sent(sentences[ph], w_rel))
                print()
        else:
            print("You did not specify any search param")
Esempio n. 32
0
from srim.srim import TRIM
from srim.output import Results
import srim
import yaml
from srim.core import elementdb, element

import typing as t
from typing import Union, List, cast
from .mytypes import floatArray, precisionLitType

if sys.version_info < (3, 8):
    from typing_extensions import Final
else:
    from typing import Final

color_init(autoreset=True)

dbpath = os.path.join(srim.__path__[0], 'data',
                      'elements.yaml')  # type: ignore
yaml.load(open(dbpath, "r"), Loader=yaml.FullLoader)

# this via instance?
element_database = elementdb.ElementDB()
sulphur: element.Element = element_database.lookup('S')
print(sulphur)
# orthis bacause classmethod?
sulphur = elementdb.ElementDB.lookup('S')
print(sulphur)

srim_executable_directory: Final = Path(R'C:\srim')
Esempio n. 33
0
def main():
    """Parse arguments and then call the appropriate function(s)."""
    parser = argparse.ArgumentParser(
        description="""Easily update multiple git repositories at once.""",
        epilog="""
            Both relative and absolute paths are accepted by all arguments.
            Questions? Comments? Email the author at {0}.""".format(__email__),
        add_help=False)

    group_u = parser.add_argument_group("updating repositories")
    group_b = parser.add_argument_group("bookmarking")
    group_m = parser.add_argument_group("miscellaneous")
    rebase_or_merge = group_u.add_mutually_exclusive_group()

    group_u.add_argument(
        'directories_to_update', nargs="*", metavar="path",
        help="""update all repositories in this directory (or the directory
                itself, if it is a repo)""")
    group_u.add_argument(
        '-u', '--update', action="store_true", help="""update all bookmarks
        (default behavior when called without arguments)""")
    group_u.add_argument(
        '-c', '--current-only', action="store_true", help="""only fetch the
        remote tracked by the current branch instead of all remotes""")
    rebase_or_merge.add_argument(
        '-r', '--rebase', action="store_true", help="""always rebase upstream
        branches instead of following `pull.rebase` and `branch.<name>.rebase`
        in git config (like `git pull --rebase=preserve`)""")
    rebase_or_merge.add_argument(
        '-m', '--merge', action="store_true", help="""like --rebase, but merge
        instead""")

    group_b.add_argument(
        '-a', '--add', dest="bookmarks_to_add", nargs="+", metavar="path",
        help="add directory(s) as bookmarks")
    group_b.add_argument(
        '-d', '--delete', dest="bookmarks_to_del", nargs="+", metavar="path",
        help="delete bookmark(s) (leaves actual directories alone)")
    group_b.add_argument(
        '-l', '--list', dest="list_bookmarks", action="store_true",
        help="list current bookmarks")
    group_m.add_argument(
        '-h', '--help', action="help", help="show this help message and exit")
    group_m.add_argument(
        '-v', '--version', action="version",
        version="gitup version " + __version__)

    color_init(autoreset=True)
    args = parser.parse_args()
    update_args = args.current_only, args.rebase, args.merge

    print(Style.BRIGHT + "gitup" + Style.RESET_ALL + ": the git-repo-updater")
    print()

    acted = False
    if args.bookmarks_to_add:
        add_bookmarks(args.bookmarks_to_add)
        acted = True
    if args.bookmarks_to_del:
        delete_bookmarks(args.bookmarks_to_del)
        acted = True
    if args.list_bookmarks:
        list_bookmarks()
        acted = True
    if args.directories_to_update:
        update_directories(args.directories_to_update, update_args)
        acted = True
    if args.update or not acted:
        update_bookmarks(get_bookmarks(), update_args)
Esempio n. 34
0
#!/usr/bin/env python
# -*- coding:utf-8 -*-

import subprocess
import argparse
import os
import time
import ftplib
import requests
import sys
from ftplib import FTP
from colorama import init as color_init, Fore

color_init()
"""
adb shell dumpsys window windows | grep -E 'mCurrentFocus'

yy: mCurrentFocus=Window{dea78f7 u0 com.duowan.mobile/com.yy.mobile.ui.home.MainActivity}
hy: mCurrentFocus=Window{6cbb508 u0 com.duowan.kiwi/com.duowan.kiwi.homepage.Homepage}
mo: mCurrentFocus=Window{f8e53db u0 com.immomo.momo/com.immomo.momo.maintab.MaintabActivity}
yk; mCurrentFocus=Window{ad5b889 u0 com.meelive.ingkee/com.meelive.ingkee.business.main.ui.MainActivity}
xm: mCurrentFocus=Window{823925b u0 com.wali.live/com.wali.live.main.LiveMainActivity}
bg: mCurrentFocus=Window{e75cc48 u0 sg.bigo.live/com.yy.iheima.FragmentTabs}
lm: mCurrentFocus=Window{5f80c36 u0 com.cmcm.live/com.cmcm.cmlive.activity.VideoListActivity}
dy: mCurrentFocus=Window{2ee0c143 u0 air.tv.douyu.android/tv.douyu.view.activity.MainActivity}
pd: mCurrentFocus=Window{3cdd7ff6 u0 com.panda.videoliveplatform/com.panda.videoliveplatform.activity.MainFragmentActivity}
cs: mCurrentFocus=Window{19bf2724 u0 com.android.settings/com.android.settings.Settings$DevelopmentSettingsActivity}
"""

# print '\033[1;31;40m' + str + '\033[0m'
Esempio n. 35
0
		return True
	else:
		return False


""" 
-----------------------------------------------------------------------------------------------------------------------
- Application entry point for sync.py
-----------------------------------------------------------------------------------------------------------------------
"""
seperator = Fore.GREEN + Style.DIM + '-------------------------------------------------------------------------------' + Fore.WHITE + Style.BRIGHT

if __name__ == "__main__":

	# init colorama module
	color_init(autoreset=False)

	# Initialize python's logging facilities
	logging.basicConfig(format=' %(asctime)s %(levelname)s %(message)s')
	sync_logger = logging.getLogger(__name__)
	sync_logger.setLevel(logging.ERROR)

	# log SSH errors to file
	#paramiko.util.log_to_file('paramiko.log')
	#paramiko.util.logging.basicConfig(level=logging.ERROR)

	print seperator
	print Fore.WHITE + Style.BRIGHT + 'Welcome to ' + Fore.GREEN + Style.BRIGHT + 'sync.py' + Fore.WHITE + Style.BRIGHT

	# load external .config
	if local_file_exists('./sync.config'):
Esempio n. 36
0
#!/usr/bin/env python
from sys import argv as args
from colorama import init as color_init
from src.wikirider import WikiRider
######### IMPORTS ########
color_init()  # Initialize colors
WikiRider.printBanner()  # Print the cool ASCII art

if __name__ == "__main__":
    if len(args) != 3:
        WikiRider.printHelp()
    else:
        rider = WikiRider(args[1], args[2])
Esempio n. 37
0
def main():

    color_init(autoreset=True)

    if not URL:
        print(ERROR + 'You need to specify gitlab url.')
        exit(1)

    if not POSTFIX:
        print(ERROR + 'You need to specify gitlab url postfix.')
        exit(1)

    if not PRIVATE_TOKEN:
        print(
            ERROR +
            'You need to specify your gitlab user\'s PRIVATE_TOKEN in the config file.'
        )
        exit(1)

    password = getpass.getpass("Enter " + os.environ['USERNAME'] +
                               " password: "******"Clone GitLab repositories at once.")

    parser.add_argument('group',
                        nargs='?',
                        default=False,
                        help='Provide project group key.')
    parser.add_argument('-u',
                        '--update',
                        action='store_true',
                        default=False,
                        help='Update the existing repositories.')

    args = parser.parse_args()

    if not args.group:
        print('Cloning all projects.')

        pages = _getAllProjectsPages()

        for x in range(0, int(pages)):

            projects = _getAllProjects(x + 1)

            if not projects:
                exit(1)

            currentFolder = _getCurrentFolder()
            print('')

            _cloneRepos(projects, password, currentFolder, update=args.update)

    else:
        print(LINE)
        print(BOLD + ' Group name is: ' + GREEN + args.group)
        print(BOLD + ' Update: ' + 'True' if args.update is True else 'False')
        print(LINE)
        print('')
        projects = _getProjectsOfGroup(args.group)

        if not projects:
            exit(1)

        currentFolder = _getCurrentFolder()
        print('')

        _cloneGroupRepos(args.group,
                         projects,
                         password,
                         currentFolder,
                         update=args.update)