Exemplo n.º 1
0
def main():
    jsonInputs = iter(argv)
    next(jsonInputs)
    INPUTS = [] # list which contains 
    for input in jsonInputs: # reads argv json files
        print("Reading " + input + " ...")
        assert ".json" in input, "Must input json files!"
        data = jsonLoad(open(input))
        INPUTS.extend(data)

        print("Found " + str(len(data)) + " inputs.")

    print("\n" + str(len(INPUTS)) + " total inputs found")

    # REDIRECTIONS = [x for x in INPUTS if any(y for y in REDIRECTION_TYPES if y in x)]
    INPUTS = [BaseCommand(x) for x in INPUTS if x]
    
    while len(argv) > 1: # unittest.main() gets mad if you pass in argv, so I pop all them off
        argv.pop()


    COMBINATIONS = getCombinations(INPUTS)
    print(str(len(INPUTS)) + " of the inputs generated " + str(len(COMBINATIONS)) + " combinations.")

    INPUTS = [] # free dat ram

    for x in COMBINATIONS: #Actually dynamically creates the unit tests
        generated = dynamicTestingGenerator(x)
        addCommand(generated)

    unittest.main()
Exemplo n.º 2
0
    def __init__(self):
        if ".py" in argv[0]:
            self.name = f"python {argv[0]}"
        else:
            self.name = argv[0]

        self.french = 0
        if "-mfr" in argv:
            argv.pop(argv.index("-mfr"))
            self.french = 1

        if len(argv) == 2 and "adv" in argv:
            self.exam_type = "adv"
        elif len(argv) == 2 and "basic" in argv:
            self.exam_type = "basic"
        else:
            print(f"\nUsage:  {self.name}  'basic'  or  'adv'")
            print("Mode Français:  Ajouter  '-mfr'  au fin\n")
            exit(1)

        if self.exam_type == "adv":
            self.question_total = 50
        else:
            self.question_total = 100

        self.pwd = os.path.dirname(__file__)
        self.file_name = f"amat_{self.exam_type}_quest"
        self.file_path = os.path.join(self.pwd, self.file_name)
        self.log_path = os.path.join(self.pwd, self.file_name[:-6] + "_EXAM")
        self.url = f"https://apc-cap.ic.gc.ca/datafiles/{self.file_name}.zip"

        self.score = 0
Exemplo n.º 3
0
    def _construct(self):
        """
        Construct the argument parser.
        
        lense-devtools build {package} (optional) # Defaults to build all
        """
        self.parser = ArgumentParser(description=self._desc(),
                                     formatter_class=RawTextHelpFormatter)

        # Main argument
        self.parser.add_argument('command', help=self._command_help())

        # Argument flags
        self.parser.add_argument(
            '-p',
            '--projects',
            help='A single project or comma seperated list of projects',
            action='append')
        self.parser.add_argument('-a',
                                 '--auto',
                                 help='Run in automated mode (avoid prompts)',
                                 action='store_true')

        # Parse arguments
        argv.pop(0)
        self.storage = vars(self.parser.parse_args(argv))
Exemplo n.º 4
0
def decode():
    _test_ready()
    try:
        _argv.pop(0)
        target = _argv.pop(0)
        if len(_argv) > 0:
            raise IndexError()
    except IndexError:
        print('"unembedmath <filename>" requires exactly one filename.',
              file=_stderr)
        exit(1)
    target = _path.join(_path.curdir, target)
    if not _path.exists(target):
        print('{} file not found'.format(repr(target)), file=_stderr)
        exit(1)
    with _TD() as cd:
        dest = _path.join(cd, 'temp.md')
        _run([
            'pandoc', target, '-f', 'markdown', '-t', 'markdown', '-s', '-o',
            dest, '--filter', '_embedmath_decoding_filter'
        ],
             timeout=30,
             text=True)
        with open(dest, 'rt') as fp:
            print(fp.read())
    exit(0)
Exemplo n.º 5
0
def get_input_number():
    if len(argv) <= 2:
        print_help()

    argv.pop(0)

    return map(lambda a: float(a), argv)
Exemplo n.º 6
0
def main(argv):
    split = True
    if argv[1] == '-w':
        split = False
        argv.pop(1)
    if len(argv) > 1:
        expr = ' '.join(argv[1:])
    else:
        expr = "$"

    if '$' in expr:
        lines = []
        for line in stdin:
            lines.append(line)
        var = ''.join(lines).strip()
        if split:
            var = var.split()[0]
        expr = expr.replace('$', str(var))
    words = re.findall(r"[a-zA-Z]{2,}", expr)
    bad_words = list(filter(lambda w: w not in globals(), words))
    no_bad_words = expr
    for bad_word in bad_words:
        no_bad_words = no_bad_words.replace(bad_word, '')
    arrays = r"(\[[\[\]\(\)\d\w, ]*\])"
    np_arrays = re.sub(arrays, r"array(\1)", no_bad_words)
    try:
        result = eval(np_arrays)
        print(result)
        pass
    except SyntaxError as e:
        print("SyntaxError:", e.msg)
        pass
Exemplo n.º 7
0
def getargs(shortcuts):
    argv.pop(0)
    commands = ['help', 'add', 'update', 'rm', 'ls']
    short = argv[0] if len(argv) > 0 else None
    if short in commands[1:2] and len(argv) is 3:
        key = goto_add(shortcuts, argv[1], argv[2])
        print(format_shortcuts(shortcuts), file=stderr)
    elif short == commands[3] and len(argv) is 2:
        key = goto_rm(shortcuts, argv[1])
        print("Deleted {red}{key}{clear}".format(red=RED, clear=CLEAR,
                                                 key=key),
              file=stderr)
    elif short == commands[4]:
        try:
            print(goto_ls(shortcuts, argv[1]), file=stderr)
        except:
            print(goto_ls(shortcuts), file=stderr)
    elif short not in commands and len(argv) is 1:
        if short in shortcuts.keys():
            print(shortcuts[short])
        else:
            print("{red}{alias} Not Found{clear}".format(red=RED,
                                                         alias=short,
                                                         clear=CLEAR),
                  file=stderr)
    else:
        get_help(shortcuts)
Exemplo n.º 8
0
def hfst_specific_option(option):
    if option in argv:
        index = argv.index(option)
        argv.pop(index)
        return True
    else:
        return False
Exemplo n.º 9
0
def run():
    # Defaults
    argv.pop(0)
    defaults = {'day': '1', 'part': '1', 'input': '__default__'}
    cli_args = dict(zip(defaults.keys(), argv))
    args = ChainMap(cli_args, defaults)
    day, part, puzzle_input = args.values()
    input_is_file = True

    # Handle puzzle input
    if '__default__' == puzzle_input:
        puzzle_input = Path(f'./resources/day{day.zfill(2)}.txt')
    else:
        input_is_file = Path(puzzle_input).is_file()

    try:
        solution = import_module(f"aoc.solution.day{day.zfill(2)}")
        puzzle_part = getattr(solution, f"part{part}")

        if input_is_file:
            with open(puzzle_input, 'r') as file:
                print(puzzle_part(FileReader(file)))
        else:
            print(puzzle_part(FileReader(StringIO(puzzle_input))))
        exit(0)
    except FileNotFoundError:
        print(f"Input file {puzzle_input} not found.")
    except AttributeError:
        print(f"Part {part} not found.")
        exit(1)
    except ModuleNotFoundError:
        print(f"Day {day} not found.")
        exit(1)
Exemplo n.º 10
0
def main():
    if len(argv) < 2:
        print("type 'hackthebox.py usage' for usage")
        exit()

    argv.reverse()
    argv.pop()

    t = argv.pop()
    if t == "list":
        ls(argv)
    elif t == "get":
        get(argv)
    elif t == "switch":
        switch_vpn(argv)
    elif t == "usage":
        print_usage()
        exit()
    elif t == "submit":
        submit_flag(argv)
    elif t == "reset":
        reset_machine(argv)
    else:
        print("I don't understand")
        exit()
Exemplo n.º 11
0
 def test_with_incorrect_word(self, capsys, test_input, expected):
     argv.pop()  # Remove --help
     argv.append(test_input)
     with pytest.raises(SystemExit) as e:
         main()
     captured = capsys.readouterr()
     assert captured.out == suggestion
     assert e.value.code == expected
Exemplo n.º 12
0
Arquivo: eisp.py Projeto: cceh/eisp
 def __init__(self) -> None:
     '''
     todo: docs
     '''
     argv.pop(0)
     basicConfig(
         datefmt='%Y-%m-%d %H:%M:%S',
         format='%(asctime)s [%(levelname)s] <%(name)s> %(message)s')
     getLogger('elasticsearch').disabled = True
Exemplo n.º 13
0
	def test_main_with_gui_argument(self):
		argv.append("-g")
		pacsudoku = main()
		with open(self.default_config_file) as rawfile:
			actual_xml_content = rawfile.readlines()
		self.assertEqual([], actual_xml_content)
		argv.pop()
		pacsudoku.config_file.file.close()
		remove(self.default_config_file)
Exemplo n.º 14
0
Arquivo: hfbrw.py Projeto: ekevoo/hfbr
 def _targets_from_argv(self):
     argv.pop(0)  # remove script name
     if not len(argv):
         log.fatal("Nothing to do! Check the documentation and make sure to have a settings file.")
         exit(1)
         return []
     target = {"target_path": argv.pop(0)}
     if len(argv):
         target["backup_dir"] = argv.pop(0)
     yield target
Exemplo n.º 15
0
	def test_main_with_valid_config_file(self):
		argv.append("-c")
		argv.append(self.my_config_file)
		pacsudoku = main()
		with open(self.my_config_file) as rawfile:
			actual_xml_content = rawfile.readlines()
		self.assertEqual(self.expected_xml_content, actual_xml_content)
		argv.pop()
		argv.pop()
		pacsudoku.config_file_handler.file.close()
Exemplo n.º 16
0
	def startup(self):
		argv.pop()
		
		p = Process(target=self.startWorker)
		p.start()

		p = Process(target=self.startRESTAPI)
		p.start()
		
		p = Process(target=self.startElasticsearch)
		p.start()
Exemplo n.º 17
0
def handle_args(argv):
    
    # Default settings:
    settings = {'root':False, 'port':'22', 'password':'', 'idfile':''}

    argv = argv[1:] # Discard the name of the program.
    for index, arg in enumerate(argv):
        #print(index, arg)
        if arg == '-r':
            settings['root'] = True
        elif arg == '-h':
            try:
                settings['hostname'] = argv.pop(index + 1)
            except IndexError:
                raise InputError('-h takes a positional argument.')
        elif arg == '-i':
            try:
                settings['idfile'] = argv.pop(index + 1)
            except IndexError:
                raise InputError('-i takes a positional argument.')
        elif arg == '-p':
            settings['password'] = True
        elif arg == '--install':
            install() # Not a setting that gets passed along.
            exit() # Also, it's the only thing we'll be doing, in that case.
        elif arg.startswith('-'):
            raise InputError('Unkown option ' + arg)
        # First positional is host.
        elif not 'host' in settings:
            # Check for the presence of a user.
            target = arg.split('@')
            if len(target) == 1:
                target = target[0]
            elif len(target) == 2:
                settings['user'] = target[0]
                target = target[1]
            else:
                raise InputError('Multiple @ symbols in connection string.')
            target = target.split(':')
            settings['host'] = target[0]
            if len(target) == 2:
                settings['port'] = target[1]
            elif len(target) > 2:
                raise InputError('Multiple : symbols in connection string.')
        # Second positional is bastion. or an intermediate host.
        elif not 'bastion' in settings:
            settings['bastion'] = arg
        else:
            raise InputError('Too many arguments')
    if settings['password']:
        settings['password'] = getpass(prompt='Please enter password: '******'hostname' in settings:
        settings['hostname'] = settings['host']
    return settings
Exemplo n.º 18
0
def setup():
    # determine whether "-y" was provided on the command line
    try:
        argv.pop(argv.index('-y'))
        skip_confirmation = True
    except ValueError:
        skip_confirmation = False

    # basic sanity check
    if len(argv) != 2:
        print(DOCUMENTATION)
        print("you provided %s argument(s)" % len(argv))
        print()
        exit(1)
    else:
        try:
            with open(argv[1], 'r') as file:
                file_json = json.load(file)
        except ValueError as e:
            print(
                "woops, looks like there is a syntax issue in your JSON, the following error was encountered:"
            )
            print(e)
            print()
            exit(1)

    # sort deletees by date.
    sorted_data = sorted(file_json.items(), key=lambda x: x[1])

    # test thata all the participants exist, exit if they don't
    all_patients_exist = True
    for patient_id, _ in sorted_data:
        if not Participant.objects.filter(patient_id=patient_id).exists():
            all_patients_exist = False
            print("Participant '%s' does not exist." % patient_id)
    if not all_patients_exist:
        exit(1)

    # print out info for confirmation
    for participant_name, date in sorted_data:
        print(participant_name, "--", humanize_date(date))

    # force user to confirm
    if not skip_confirmation:
        print()
        msg = input(
            "I hereby confirm that I want to irreparably delete all data for the above users starting on the day listed. (y/n)\n"
        )
        if not msg.lower() == "y":
            print("Exiting...")
            print()
            exit(0)

    return sorted_data
Exemplo n.º 19
0
def handle_args(argv):

    # Default settings:
    settings = {'root': False, 'port': '22', 'password': '', 'idfile': ''}

    argv = argv[1:]  # Discard the name of the program.
    for index, arg in enumerate(argv):
        #print(index, arg)
        if arg == '-r':
            settings['root'] = True
        elif arg == '-h':
            try:
                settings['hostname'] = argv.pop(index + 1)
            except IndexError:
                raise InputError('-h takes a positional argument.')
        elif arg == '-i':
            try:
                settings['idfile'] = argv.pop(index + 1)
            except IndexError:
                raise InputError('-i takes a positional argument.')
        elif arg == '-p':
            settings['password'] = True
        elif arg == '--install':
            install()  # Not a setting that gets passed along.
            exit()  # Also, it's the only thing we'll be doing, in that case.
        elif arg.startswith('-'):
            raise InputError('Unkown option ' + arg)
        # First positional is host.
        elif not 'host' in settings:
            # Check for the presence of a user.
            target = arg.split('@')
            if len(target) == 1:
                target = target[0]
            elif len(target) == 2:
                settings['user'] = target[0]
                target = target[1]
            else:
                raise InputError('Multiple @ symbols in connection string.')
            target = target.split(':')
            settings['host'] = target[0]
            if len(target) == 2:
                settings['port'] = target[1]
            elif len(target) > 2:
                raise InputError('Multiple : symbols in connection string.')
        # Second positional is bastion. or an intermediate host.
        elif not 'bastion' in settings:
            settings['bastion'] = arg
        else:
            raise InputError('Too many arguments')
    if settings['password']:
        settings['password'] = getpass(prompt='Please enter password: '******'hostname' in settings:
        settings['hostname'] = settings['host']
    return settings
Exemplo n.º 20
0
 def __init__(self) -> None:
     '''
 todo: docs
 '''
     argv.pop(0)
     basicConfig(
         datefmt='%Y-%m-%d %H:%M:%S',
         format='%(asctime)s [%(levelname)s] <%(name)s> %(message)s')
     environ['WERKZEUG_RUN_MAIN'] = 'true'
     getLogger('elasticsearch').disabled = True
     getLogger('werkzeug').disabled = True
Exemplo n.º 21
0
def process_batch_command(argv):
    if len(argv) > 0:
        command = str(argv[0]);
    else:
        command = "help"

    if len(argv) > 0:
        argv.pop(0)
        args = argv
    else:
        args = []

    return process_command(command, args)
Exemplo n.º 22
0
def main(argv):
    argv.pop(0)
    entry = Entrypoint(args=argv)
    try:
        if not entry.is_handled and not entry.should_config:
            entry.log.warning("Running command without config")
            entry.launch()
        entry.log.debug("Starting config")
        entry.run_pre_conf_cmds()
        entry.apply_conf()
        entry.run_post_conf_cmds()
        entry.launch()
    except Exception as e:
        entry.log.error(str(e))
Exemplo n.º 23
0
 def sum(self):
     if self.len < 4:
         self.prnt('sum')
     else:
         argv.pop(0)
         argv.pop(0)
         total = 0
         for arg in argv:
             try:
                 arg = int(arg)
                 total += arg
             except ValueError:
                 print("\n\tError! Arguments for 'sum' must be integers\n")
                 return
         print('\n\t', total, '\n')
Exemplo n.º 24
0
def initiate_pipeline():
    """
    Main function initiate build and execution of the data pipeline.
    :return: NoneType
    """

    # Removing the execution script name from the argument list.
    args.pop(0)
    try:
        # Getting the task list by analyzing the arguments.
        task_list = build_pipeline(args)
        if task_list:
            execute_pipeline(task_list)
    except Exception as exception:
        notify(exception)
Exemplo n.º 25
0
def main_():
    addaudithook(_audit_hook)

    if len(argv) >= 2:
        cmd = argv.pop(1)
    else:
        cmd = ""
    argv[0] += ' ' + cmd

    if cmd == 'qt':
        from .qt.__main__ import main
        return main()
    if cmd == 'manifolds':
        from .scripts.manifolds import main
        return main()
    if cmd == 'thumbs':
        from .scripts.thumbs import main
        return main()
    if cmd == 'load_coco':
        from .scripts.load_coco import main
        return main()
    if cmd == 'build_procrustes':
        from .scripts.build_procrustes import main
        return main()
    if cmd == 'load_dir':
        from .scripts.load_dir import main
        return main()

    print("Unrecognized command.")
    print("Please choose one from " + ", ".join(commands) + ".")
    return 1
Exemplo n.º 26
0
def parse_argv() -> ("relative_path", "gvim_flags", int):
    """ converts argv into a more usable format
    :returns: a tuple of the relative path name and the flags for gvim and the number of rotations to encode
    """
    _ = argv.pop(0)
    relative_paths = []
    gvim_flags = ""
    next_arg_is_n = False
    n = 0
    for arg in argv:
        if arg == '--rotn':
            next_arg_is_n = True
        elif arg.startswith('-'):
            gvim_flags += arg + " "
        elif next_arg_is_n:
            n = int(arg)
            next_arg_is_n = False
        else:
            if '.' not in arg:
                arg += ".txt"
            relative_paths.append(arg)
    length = len(relative_paths)
    if length < 1:
        raise (Exception("Too few arguments"))
    return relative_paths, gvim_flags, n
Exemplo n.º 27
0
def print_machines(argv):
    global htb

    if len(argv) == 0:
        argv.append("all")

    machines = htb.get_machines()
    t = PrettyTable(['ID', 'Name', 'OS', 'Points', 'Maker'])

    fltr = argv.pop()
    for machine in machines:
        if fltr == "retired" and (machine.get("retired_date") != None):
            t.add_row([
                machine["id"], machine["name"], machine["os"],
                machine["points"], machine["maker"]["name"]
            ])
        elif fltr == "active" and (machine.get("retired_date") == None):
            t.add_row([
                machine["id"], machine["name"], machine["os"],
                machine["points"], machine["maker"]["name"]
            ])
        elif fltr == "all":
            t.add_row([
                machine["id"], machine["name"], machine["os"],
                machine["points"], machine["maker"]["name"]
            ])

    print(t)
Exemplo n.º 28
0
def main(*args, **kwargs):
    """
    Upload a file to a Twitter account
    """
    argv.pop(0)
    status = str()
    if argv:
        status = argv.pop()
    unuploaded = True
    while unuploaded:
        try:
            api = create_api(read_keys())
            api.update_with_media("output.png", status)
            unuploaded = False
            print("Successfully uploaded!")
        except Exception as e:
            print("Error: {}".format(e))
Exemplo n.º 29
0
def main(argv):
    argv.pop(0)
    entry = Entrypoint(args=argv)
    try:
        entry.exit_if_disabled()
        if not entry.is_handled and not entry.should_config:
            entry.log.warning("Running command without config")
            entry.launch()
        entry.config.set_to_env()
        entry.log.debug("Starting config")
        entry.run_pre_conf_cmds()
        entry.apply_conf()
        entry.run_post_conf_cmds()
        entry.launch()
    except Exception as e:
        entry.log.error(str(e))
        exit(1)
Exemplo n.º 30
0
def main(*args, **kwargs):
    """
    Upload a file to a Twitter account
    """
    argv.pop(0)
    status = str()
    if argv:
        status = argv.pop()
    unuploaded = True
    while unuploaded:
        try:
            api = create_api(read_keys())
            api.update_with_media("output.png", status)
            unuploaded = False
            print("Successfully uploaded!")
        except Exception as e:
            print("Error: {}".format(e))
Exemplo n.º 31
0
def get_input_number(mode=MODE_COMPARING_SORT):
    if mode == MODE_COMPARING_SORT:
        if len(argv) <= 1:
            print_help(mode)

        argv.pop(0)
        return map(lambda a: int(a), argv)
    elif mode == MODE_BUCKET_SORT:
        if len(argv) <= 1:
            print_help(mode)

        argv.pop(0)
        lst = map(lambda a: float(a), argv)
        for x in lst:
            if x < 0 or x >= 1.0:
                print 'number %g is invalid' % x
                exit(0)
        return lst
    elif mode == MODE_LINEAR_TIME_SORT:
        if len(argv) <= 2:
            print_help(mode)

        argv.pop(0)
        k = int(argv.pop(0))
        lst = map(lambda a: int(a), argv)
        for x in lst:
            if x < 0 or x > k:
                print 'number %d is invalid' % x
                exit(0)
        return k, lst
    else:
        return None
Exemplo n.º 32
0
def main(argv):
    argv.pop(0)
    entry = Entrypoint(args=argv)
    try:
        entry.exit_if_disabled()
        if not entry.is_handled and not entry.should_config:
            entry.log.warning("Running command without config")
            entry.launch()
        entry.config.set_to_env()
        entry.log.debug("Starting config")
        entry.run_set_enviroment()
        entry.run_pre_conf_cmds()
        entry.apply_conf()
        entry.run_post_conf_cmds()
        entry.launch()
    except Exception as e:
        entry.log.error(str(e))
        exit(1)
Exemplo n.º 33
0
def ls(argv):
    global htb
    t = argv.pop()
    if t == "machines":
        print_machines(argv)
    elif t == "vpns":
        print("eufree, usfree, euvip, usvip")
    else:
        print(t + ": I can't list that")
Exemplo n.º 34
0
 def _construct(self):
     """
     Construct the argument parser.
     
     lense-devtools build {package} (optional) # Defaults to build all
     """
     self.parser = ArgumentParser(description=self._desc(), formatter_class=RawTextHelpFormatter)
     
     # Main argument
     self.parser.add_argument('command', help=self._command_help())
     
     # Argument flags
     self.parser.add_argument('-p', '--projects', help='A single project or comma seperated list of projects', action='append')
     self.parser.add_argument('-a', '--auto', help='Run in automated mode (avoid prompts)', action='store_true')
     
     # Parse arguments
     argv.pop(0)
     self.storage = vars(self.parser.parse_args(argv))
Exemplo n.º 35
0
def main():
    if len(argv) == 1:
        unittest.main()
    elif len(argv) == 4:
        _ = argv.pop(0)
        rgb = [int(val) for val in argv]
        print("rgb(" + ", ".join(argv) + ") = #" + rgb_to_hex(tuple(rgb)))
    else:
        print("Incorrect Usage.")
Exemplo n.º 36
0
def name_workspaces():
    """
    Entry point function for `pyx-space` command, to automatically relabel all
    workspaces (desktops) according to their windows.
    """
    print("Renaming workspaces")
    rets = main(prog=argv.pop(0))
    # ff_session, x_session, wm_territory, tmux_server, wm_remap = rets
    relabel_workspaces(*rets)
Exemplo n.º 37
0
def main():

   if len(argv) == 1 or len(argv) > 3:
      print 'Usage: [-s] file_name'
      exit()
   elif len(argv) == 3 and '-s' not in argv:
      print 'Usage: [-s] file_name'
      exit()
   else:
      if len(argv) == 2:
         file_name = argv[1]
      else:
         argv.pop(argv.index('-s'))
         file_name = argv[1]
         argv.append('-s')
      try:
         inFile = open(file_name, 'r')
      except IOError as e:
         print e
         exit()

   total = 0
   ints = floats = other = 0
   for line in inFile:
      the_line = line.split()
      for elem in the_line:
         try:
            temp = int(elem)
            ints += 1
            total += temp
         except:
            try:
               temp = float(elem)
               floats += 1
               total += temp
            except:
               other += 1

   inFile.close()
   print 'Ints: %d' % ints
   print 'Floats: %d' % floats
   print 'Other: %d' % other
   if len(argv) == 3:
      print 'Sum: %.2f' % total
Exemplo n.º 38
0
def main():
    prog = "mr_repo"
    if (len(argv) > 0):
        prog = argv.pop(0)
        # If prog does not look something like Mr. Repo then change it
        if None == re.search('mr(\.|)([-_ ]{0,2})repo', prog,
                flags=re.IGNORECASE):
            prog = "mr_repo"
    #Create an instance of MrRepo
    Repossesser(prog=prog, args=argv, execute=True, one_use=True)
Exemplo n.º 39
0
def main_func():

    # Check the number of inputs
    numofinputs = len(sys.argv)

    # Conditional expressions
    if numofinputs > 5 :
        print ("Invalid arguments \nGood BYE")
    else :
        # Get the input arguments
        filename = argv.pop(1) # EXE name, File Name, Module Name
        operation = argv.pop(1) # DEBUG, INFO, WARN, ERROR, CRITICAL, EXCEPTION
        message = argv.pop(1) # Message to be printed
        logFile = argv.pop(1) # Log file

        # setup `logging` module
        logger = logging.getLogger(filename)
        fileHandler = logging.FileHandler('Logger.log')
        logger.setLevel(logging.INFO)
        formatter = logging.Formatter("[%(asctime)s] [%(name)s] : %(message)s")

        # setup `RainbowLoggingHandler`
        handler = RainbowLoggingHandler(sys.stderr, color_name=('grey', None , True),color_asctime=('green', None  , True))
        handler.setFormatter(formatter)
        fileHandler.setFormatter(formatter)
        logger.addHandler(fileHandler)
        logger.addHandler(handler)

        if operation == 'DEBUG' :
            logger.debug(message)
        if operation == 'INFO' :
            logger.info(message)
        if operation == 'WARN' :
            logger.warn(message)
        if operation == 'ERROR' :
            logger.error(message)
        if operation == 'CRITICAL' :
            logger.critical(message)
        if operation == 'EXCEPTION' :
            raise RuntimeError("InstallException!")
            logger.exception(message)
            logger.exception(e)
Exemplo n.º 40
0
def main():
  success = True
  argv.pop(0)

  if not argv:
    help()
    success = False

  while (argv):
    init_dir()
    command = argv.pop(0)

    if not command in commands:
      help();
      success = False
      break
    returncode = commands[command][0]()
    success = success and not bool(returncode)

  sys.exit(not success)
Exemplo n.º 41
0
    def run(self):
        """
        Parse the command-line arguments and call the method corresponding to
        the situation.
        """
        # We're using a custom parser here to handle subcommands.
        argv = self.argv
        argc = len(argv)
        if argc == 0:
            return self.print_help()
        action = argv.pop(0)
        argc -= 1
        if action in HELP_FLAGS:
            self.print_version()
            return self.print_help()
        if action in ('-v', '-version', '--version'):
            return self.print_version()

        # Subcommands are defined as below:
        #   def action_some_keyword(self, ...)
        # defines an action 'some:keyword'. We might need to use classes for
        # subcommands like Thor (Ruby gem), but it'd be too much overhead for
        # now.
        name = 'action_%s' % action.replace(':', '_')
        if not hasattr(self, name):
            print("Unrecognized action '%s'" % action)
            return self.print_help()

        fun = getattr(self, name)

        # dynamically check if enough arguments were given on the command line
        spec = inspect.getargspec(fun)
        # skip 'self'
        spec_args = (spec.args or ())[1:]
        spec_defaults = spec.defaults or ()
        defaults_len = len(spec_defaults)
        required_len = len(spec_args) - defaults_len

        if argc < required_len or (argc > 0 and argv[0] in HELP_FLAGS):
            defaults = list(reversed(spec_args))[:defaults_len]
            args = []
            for arg in spec_args:
                fmt = '<%s>'
                if arg in defaults:
                    fmt = '[%s]' % fmt
                args.append(fmt % arg)

            if spec.varargs:
                args.append('[<%s...>]' % spec.varargs)

            print("Usage:\n\t%s %s %s" % (self.exe, action, ' '.join(args)))
            return False

        return fun(*argv)
Exemplo n.º 42
0
    def run(self):
        """
        Parse the command-line arguments and call the method corresponding to
        the situation.
        """
        # We're using a custom parser here to handle subcommands.
        argv = self.argv
        argc = len(argv)
        if argc == 0:
            return self.print_help()
        action = argv.pop(0)
        argc -= 1
        if action in HELP_FLAGS:
            self.print_version()
            return self.print_help()
        if action in ('-v', '-version', '--version'):
            return self.print_version()

        # Subcommands are defined as below:
        #   def action_some_keyword(self, ...)
        # defines an action 'some:keyword'. We might need to use classes for
        # subcommands like Thor (Ruby gem), but it'd be too much overhead for
        # now.
        name = 'action_%s' % action.replace(':', '_')
        if not hasattr(self, name):
            print("Unrecognized action '%s'" % action)
            return self.print_help()

        fun = getattr(self, name)

        # dynamically check if enough arguments were given on the command line
        spec = inspect.getargspec(fun)
        # skip 'self'
        spec_args = (spec.args or ())[1:]
        spec_defaults = spec.defaults or ()
        defaults_len = len(spec_defaults)
        required_len = len(spec_args) - defaults_len

        if argc < required_len or (argc > 0 and argv[0] in HELP_FLAGS):
            defaults = list(reversed(spec_args))[:defaults_len]
            args = []
            for arg in spec_args:
                fmt = '<%s>'
                if arg in defaults:
                    fmt = '[%s]' % fmt
                args.append(fmt % arg)

            if spec.varargs:
                args.append('[<%s...>]' % spec.varargs)

            print("Usage:\n\t%s %s %s" % (self.exe, action, ' '.join(args)))
            return False

        return fun(*argv)
Exemplo n.º 43
0
def main():
    prog = "mr_repo"
    if (len(argv) > 0):
        prog = argv.pop(0)
        # If prog does not look something like Mr. Repo then change it
        if None == re.search('mr(\.|)([-_ ]{0,2})repo',
                             prog,
                             flags=re.IGNORECASE):
            prog = "mr_repo"
    #Create an instance of MrRepo
    Repossesser(prog=prog, args=argv, execute=True, one_use=True)
Exemplo n.º 44
0
def main():
  success = True
  argv.pop(0)

  if not argv:
    help()
    success = False

  while (argv):
    # Make sure that we're always rooted in the dart root folder.
    os.chdir(dart_dir)
    command = argv.pop(0)

    if not command in commands:
      help();
      success = False
      break
    returncode = commands[command][0]()
    success = success and not bool(returncode)

  sys.exit(not success)
Exemplo n.º 45
0
def main(argv):
    status, result = None, None
    arg = argv.pop(0).lower()
    if arg == "keygen":
        status, result = createPrimaryKey(argv)
    elif arg == "encrypt":
        status, result = encrytData(argv)
    elif arg == "decrypt":
        status, result = decryptData(argv)
    elif arg == "crack":
        status, result = crackEncryptedData(argv)
    else:
        status, result = False, "Invalid argument: {0}".format(arg)
    print("{0}".format(result))
    return status
Exemplo n.º 46
0
def test_dart2js(browser, argv):
  cmd = [
    os.path.join('tools', 'test.py'),
    '-c', 'dart2js',
    '-r', browser,
    '--mode=release',
    '--checked',
    '--arch=ia32',
    '-v',
  ]
  if argv:
    cmd.append(argv.pop(0))
  else:
    print(
        'Test commands should be followed by tests to run. Defaulting to html')
    cmd.append('html')
  return call(cmd)
Exemplo n.º 47
0
	def test_sudoku_argument_parser_class_with_arguments(self):
		expected_config_metavar = "other.xml"
		argv.append("-g")
		argv.append("-c")
		argv.append(expected_config_metavar)
		parser = SudokuArgumentParser()
		actual_arguments = parser.parse_args()
		argv.pop()
		argv.pop()
		argv.pop()
		self.assertEqual(expected_config_metavar, actual_arguments.config)
		self.assertTrue(actual_arguments.gui)
Exemplo n.º 48
0
def test_dart2js(browser, argv):
    cmd = [
        os.path.join("tools", "test.py"),
        "-c",
        "dart2js",
        "-r",
        browser,
        "--mode=release",
        "--checked",
        "--arch=ia32",
        "-v",
    ]
    if argv:
        cmd.append(argv.pop(0))
    else:
        print ("Test commands should be followed by tests to run. Defaulting to html")
        cmd.append("html")
    return call(cmd)
Exemplo n.º 49
0
	for ind, comp in enumerate(scratch):
		components[comp].append((p[ind], ind))

	res = [ 0 ] * len(p)
	for c in components:
		if c == []:
			continue
		(v, k) = [ list(x) for x in zip(*c) ]
		v.sort()
		k.sort()
		for ind, val in enumerate(v):
			res[k[ind]] = val

	if verbose:
		print ' '.join([ str(x) for x in res ])
	return res

def test():
	assert(solve([ '7', '5 2 4 3 6 7 1', '0001001', '0000000', '0000010', '1000001', '0000000', '0010000', '1001000' ], verbose=True) == [ 1, 2, 4, 3, 6, 7, 5 ])
	assert(solve([ '5', '4 2 1 5 3', '00100', '00011', '10010', '01101', '01010' ], verbose=True) == [ 1, 2, 3, 4, 5 ])


if __name__ == '__main__':
	from sys import argv
	if argv.pop() == 'test':
		test_utilities()
		test()
	else:
		dbug = False
		solve(list(fileinput.input()), verbose=True)
Exemplo n.º 50
0

def upload(directory):
    _create_tarball(directory)
    print("Uploading {} tarball to S3... ({})".format(cache_name, _tarball_size(directory)))
    with timer():
        key.set_contents_from_filename(_tarball_filename_for(directory))
    print("{} cache successfully updated.".format(cache_name))
    mark_uploaded(cache_name)


if __name__ == '__main__':
    # Uses environment variables:
    #   AWS_ACCESS_KEY_ID -- AWS Access Key ID
    #   AWS_SECRET_ACCESS_KEY -- AWS Secret Access Key
    argv.pop(0)
    if len(argv) != 2:
        raise SystemExit("USAGE: s3_cache.py <download | upload> <cache name>")
    mode, cache_name = argv
    script_dir = dirname(realpath(__file__))
    chdir(script_dir)
    try:
        with open(CONFIG_FILE, 'rt') as config_file:
            config = load(config_file)
    except (IOError, OSError, ValueError) as config_err:
        print(config_err)
        raise SystemExit("Error when trying to load config from JSON file!")

    try:
        cache_info = config[cache_name]
        key_file = expandvars(cache_info["key"])
Exemplo n.º 51
0
from jinja2 import (
	Environment,
	FileSystemLoader,
)


include_base      = 'include/lair'
src_base          = 'src'

tmpl_dir          = 'tmpl'
header_tmpl_file  = 'source.h'
source_tmpl_file  = 'source.cpp'
cmake_tmpl_file   = 'CMakeLists.txt'

program_name      = argv.pop(0)
module            = None
class_camel       = None
overwrite         = False
create_module     = False


def usage(*, file=stdout):
	print("Usage: {} [-f] [-h] [-m] MODULE CLASS_NAME".format(program_name), file=file)


def error(msg, *, print_usage=False):
	print('Error:', msg, file=stderr)
	if print_usage:
		usage(file=stderr)
	exit(1)
Exemplo n.º 52
0
          return RET_OK

#############################################
##            MAIN starts here             ##
#############################################
sql=0
migrate=0

t=datetime.datetime.now()
CTIME=time.mktime(t.timetuple())

argc=len(argv) - 1
if argc < 1:
   usage()

basename = argv.pop(1)

# First check specified arguments
if "/dev/" in basename:
   usage()

if argc >= 2:
   sqls=argv.pop(1)
   if "-sql" in sqls:
      sql=1
   else:
      usage()

if argc == 3:
   migs=argv.pop(1)
   if "-migrate" in migs:
Exemplo n.º 53
0
def dart2js():
  compile_dart2js(argv.pop(0), True)
Exemplo n.º 54
0
    'PyStemmer',
    'python-dateutil',
    'SOAPpy',
    'SQLAlchemy>=0.5,<0.6a', # Works with >=0.4.6 except on OS X
    'Twisted',
    'wokkel>=0.6.3',
]

if version_info[0] == 2 and version_info[1] < 6:
    install_requires.append('simplejson')
if version_info[0] == 2 and version_info[1] < 5:
    install_requires.append('cElementTree')
    install_requires.append('pysqlite')

if argv[1:] == ['install', '--no-dependencies']:
    argv.pop()
    install_requires = None

setup(
    name='Ibid',
    version='0.2.0dev',
    description='Multi-protocol general purpose chat bot',
    url='http://ibid.omnia.za.net/',
    keywords='chat bot irc jabber twisted messaging',
    author='Ibid Developers',
    author_email='*****@*****.**',
    license='MIT',
    py_modules=['ibid'],
    install_requires=install_requires,
    extras_require = {
        'imdb': ['imdbpy'],
Exemplo n.º 55
0
def usage():
    print "Usage : %s sdtierX [-sql] [-migrate]" % argv.pop(0)
    print "Please note : -migrate requires -sql"
    exit()
Exemplo n.º 56
0
        if mass >= minmass and mass <= maxmass and run>1:
            if run<minrun:
                minrun=run
            if run>maxrun:
                maxrun=run
            ## cat = cat % 4
            ### if pt < 40:
            ###     cat = cat + 4
            lst[ (run, ls, ev) ] = ( vtx, cat, mass, pt )
    return lst

ROOT.gROOT.SetStyle("Plain")
ROOT.gStyle.SetPalette(1)
ROOT.gStyle.SetOptStat(111111)

fn1 = argv.pop(1)
fn2 = argv.pop(1)
        
file1 = open(fn1)
file2 = open(fn2)

## list1 = getlist( file1.read(),100,180 )
list1 = getlist( file1.read() )
## print list1

## list2 = getlist( file2.read(),100,180 )
list2 = getlist( file2.read() )
## print list2

def cmp(x,y):
    if x[0] < y[0] : return True
Exemplo n.º 57
0
#!/usr/bin/python

import png
from sys import argv
from io import open
from array import array

inpng_names = []
outbin_names = []

while len(argv) > 1:
    nextarg = argv.pop(1)
    if nextarg == '-o':
        break
    inpng_names.append(nextarg)

while len(argv) > 1:
    nextarg = argv.pop(1)
    outbin_names.append(nextarg)

if len(inpng_names) != len(outbin_names):
    print "%d inputs and %d outputs, should be equal" % (len(inpng_names), len(outbin_names))


for (inpng_name, outbin_name) in zip(inpng_names, outbin_names):

    inpng = png.Reader(inpng_name)

    (width, height, pixels, metadata) = inpng.read()

    if metadata['bitdepth'] != 1 or width != 8 or height != 8:
Exemplo n.º 58
0
import shlex, subprocess

# print help
def printhelp():
    print(
'''usage:  python compiletest.py EXEC_FILE [COMPILER]
  reads trees in a GBRT ensemble from stdin, writes a C++
  program to EXEC_FILE.cpp, and compiles an executable to
  EXEC_FILE.  Optionally a COMPILER may be supplied; default
  compiler string is "g++ -O3".
    ''')

# set compiler
compiler = 'g++ -O3'
if len(argv) == 3:
    compiler = argv.pop(0)
    
# check args
if len(argv) != 2:
    print('Illegal usage. (If supplying a compiler command, wrap in quotes.)')
    printhelp();
    exit();

# open cpp file
binfile = argv[1]
cppfile = binfile + '.cpp'
f = open(cppfile, 'w')

# print header
f.write("""
#include <iostream>
Exemplo n.º 59
0
#!/usr/bin/env python

from sys import argv

#accept user input of one argument. Expect it to be a valid IP address. Assign that argument to variable ip_dec
if len(argv) == 2 and len(argv[1].split(".")) == 4:
    ip_addr = argv[-1]
    ip_str = argv.pop().split(".")
else:
    print "Please enter just one valid address"

ip_dec = range(len(ip_str))

#convert list from strings to integers for easier use later when converting to binary
for string in range(len(ip_str)):
    ip_dec[string] = int(ip_str[string])

#create binary representations of the octets
ip_bin = range(len(ip_dec))
for number in ip_bin:
    ip_bin[number] = bin(ip_dec[number])

#trim off the 0b designator and left-fill with 0s to 8 places
for number in range(len(ip_bin)):
    ip_bin[number] = ip_bin[number][2:].zfill(8)

ip_bin = ".".join(ip_bin)

#print out the headings 'IP address' and 'Binary' left alligned 20 spaces
print "\n%-20s %-40s" % ("IP address", "Binary")