This CLI can take forms like:
 timers  1  3
 timers msec 300  3
 timers msec 750 msec 2500
765970
def timers_get
      hash = {}
      hash[:hello] = default_timers_hello
      hash[:mshello] = default_timers_hello_msec
      hash[:hold] = default_timers_hold
      hash[:mshold] = default_timers_hold_msec
      str = config_get('interface_hsrp_group', 'timers', @get_args)
      return hash if str.nil?
      regexp = Regexp.new('(?<msec1>msec)?'\
               ' *(?<he>\d+) *(?<msec2>msec)? *(?<ho>\d+)')
      params = regexp.match(str)
      hash[:mshello] = true if params[:msec1]
      hash[:mshold] = true if params[:msec2]
      hash[:hello] = params[:he].to_i
      hash[:hold] = params[:ho].to_i
      hash
    end
919662
def install_timers(config, context):
    """"""
    timers = []
    if config.get('capture_timeout_warnings'):
        timeout_threshold = config.get('timeout_warning_threshold')
        # Schedule the warning at the user specified threshold given in percent.
        # ie: 0.50 of 30000 ms = 15000ms
        # Schedule the error a few milliseconds before the actual timeout happens.
        time_remaining = context.get_remaining_time_in_millis() / 1000
        timers.append(Timer(time_remaining * timeout_threshold, timeout_warning, (config, context)))
        timers.append(Timer(max(time_remaining - .5, 0), timeout_error, [config]))

    if config.get('capture_memory_warnings'):
        # Schedule the memory watch dog interval. Warning will re-schedule itself if necessary.
        timers.append(Timer(.5, memory_warning, (config, context)))

    for t in timers:
        t.start()

    return timers
21447
def cli(ctx, collections, threads, debug):
    
    ctx.obj = {
        'collections': collections,
        'debug': debug,
        'threads': threads
    }
    if debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)
1156158
def can_replicate_commands(self):
        
        if not hasattr(self, '_can_replicate_commands'):
            info = self.redis.info('server')
            version_info = info['redis_version'].split('.')
            major, minor = int(version_info[0]), int(version_info[1])
            result = major > 3 or major == 3 and minor >= 2
            self._can_replicate_commands = result
        return self._can_replicate_commands
265570
def timer(fn, miniter=3, minwall=3.0):
    

    results = []
    count = 0

    # Ideally a monotonic clock, but doesn't matter too much.
    wall_begin = time.time()

    while True:
        wstart = time.time()
        start = os.times()
        fn()
        end = os.times()
        wend = time.time()
        count += 1

        user = end[0] - start[0]
        system = end[1] - start[1]
        cpu = user + system
        wall = wend - wstart

        results.append((cpu, user, system, wall))

        # Ensure we run at least ``miniter`` times.
        if count < miniter:
            continue

        # And for ``minwall`` seconds.
        elapsed = wend - wall_begin

        if elapsed < minwall:
            continue

        break

    return results
454539
def cli_progress(addr, offset, size):
    """"""
    width = 25
    done = offset * width // size
    print("\r0x{:08x} {:7d} [{}{}] {:3d}% "
          .format(addr, size, '=' * done, ' ' * (width - done),
                  offset * 100 // size), end="")
    try:
        sys.stdout.flush()
    except OSError:
        pass # Ignore Windows CLI "WinError 87" on Python 3.6
    if offset == size:
        print("")
662391
def _create_ide_controllers(ide_controllers):
    '''
    
    '''
    ide_ctrls = []
    keys = range(-200, -250, -1)
    if ide_controllers:
        devs = [ide['adapter'] for ide in ide_controllers]
        log.trace('Creating IDE controllers %s', devs)
        for ide, key in zip(ide_controllers, keys):
            ide_ctrls.append(_apply_ide_controller_config(
                ide['adapter'], 'add', key, abs(key + 200)))
    return ide_ctrls
1284493
def cli(env,
        format='table',
        config=None,
        verbose=0,
        proxy=None,
        really=False,
        demo=False,
        **kwargs):
    """"""

    # Populate environement with client and set it as the context object
    env.skip_confirmations = really
    env.config_file = config
    env.format = format
    env.ensure_client(config_file=config, is_demo=demo, proxy=proxy)
    env.vars['_start'] = time.time()
    logger = logging.getLogger()

    if demo is False:
        logger.addHandler(logging.StreamHandler())
    else:
        # This section is for running CLI tests.
        logging.getLogger("urllib3").setLevel(logging.WARNING)
        logger.addHandler(logging.NullHandler())

    logger.setLevel(DEBUG_LOGGING_MAP.get(verbose, logging.DEBUG))
    env.vars['_timings'] = SoftLayer.DebugTransport(env.client.transport)
    env.client.transport = env.vars['_timings']
1084118
def schedule_timers(timers)

      timers.each do |t|

        after, action = if t.is_a?(String)
          i = t.rindex(':')
          [ t[0..i - 1], t[i + 1..-1] ]
        else
          t
        end

        after = after.strip
        action = action.strip

        next if after == ''

        msg = case action

          when 'timeout', 'undo', 'pass'

            { 'action' => 'cancel',
              'fei' => h.fei,
              'flavour' => action == 'timeout' ? 'timeout' : nil }

          when 'redo', 'retry'

            { 'action' => 'cancel',
              'fei' => h.fei,
              're_apply' => true }

          when /^err(or)?( *.+)?$/

            message = if $~[2]
              $~[2].to_s.strip
            else
              "timer induced error (\"#{after}: #{action}\")"
            end

            { 'action' => 'cancel',
              'fei' => h.fei,
              're_apply' => { 'tree' => [ 'error', { message => nil }, [] ] } }

          when CommandExpression::REGEXP

            { 'action' => 'cancel',
              'fei' => h.fei,
              're_apply' => {
                'tree' => [
                  $~[1], { $~[2].split(' ').last.to_s => nil }, [] ] } }

          else

            { 'action' => 'apply',
              'wfid' => h.fei['wfid'],
              'expid' => h.fei['expid'],
              'parent_id' => h.fei,
              'flanking' => true,
              'tree' => [ action, {}, [] ],
              'workitem' => h.applied_workitem }
        end

        (h.timers ||= []) <<
          [ @context.storage.put_schedule('at', h.fei, after, msg), action ]
      end
    end
889896
def clusterflow_commands_table (self):
        

        # I wrote this when I was tired. Sorry if it's incomprehensible.

        desc = '''Every Cluster Flow run will have many different commands.
            MultiQC splits these by whitespace, collects by the tool name
            and shows the first command found. Any terms not found in <em>all</em> subsequent
            calls are replaced with <code>[variable]</code>
            <em>(typically input and ouput filenames)</em>. Each column is for one Cluster Flow run.'''

        # Loop through pipelines
        tool_cmds = OrderedDict()
        headers = dict()
        for pipeline_id, commands in self.clusterflow_commands.items():
            headers[pipeline_id] = {'scale': False}
            self.var_html = '<span style="background-color:#dedede; color:#999;">[variable]</span>'
            tool_cmd_parts = OrderedDict()
            for cmd in commands:
                s = cmd.split()
                tool = self._guess_cmd_name(s)
                if tool not in tool_cmd_parts.keys():
                    tool_cmd_parts[tool] = list()
                tool_cmd_parts[tool].append(s)


            for tool, cmds in tool_cmd_parts.items():
                cons_cmd = self._replace_variable_chunks(cmds)
                # Try again with first two blocks if all variable
                variable_count = cons_cmd.count(self.var_html)
                if variable_count == len(cmds[0]) - 1 and len(cmds[0]) > 2:
                    for subcmd in set([x[1] for x in cmds]):
                        sub_cons_cmd = self._replace_variable_chunks([cmd for cmd in cmds if cmd[1] == subcmd])
                        tool = "{} {}".format(tool, subcmd)
                        if tool not in tool_cmds:
                            tool_cmds[tool] = dict()
                        tool_cmds[tool][pipeline_id] = '<code style="white-space:nowrap;">{}</code>'.format(" ".join(sub_cons_cmd) )
                else:
                    if tool not in tool_cmds:
                        tool_cmds[tool] = dict()
                    tool_cmds[tool][pipeline_id] = '<code style="white-space:nowrap;">{}</code>'.format(" ".join(cons_cmd) )

        table_config = {
            'namespace': 'Cluster Flow',
            'id': 'clusterflow-commands-table',
            'table_title': 'Cluster Flow Commands',
            'col1_header': 'Tool',
            'sortRows': False,
            'no_beeswarm': True
        }
        self.add_section (
            name = 'Commands',
            anchor = 'clusterflow-commands',
            description = desc,
            plot = table.plot(tool_cmds, headers, table_config)
        )
142571
def cli(env, identifier, passwords=False, price=False):
    """"""

    vsi = SoftLayer.VSManager(env.client)
    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    vs_id = helpers.resolve_id(vsi.resolve_ids, identifier, 'VS')
    result = vsi.get_instance(vs_id)
    result = utils.NestedDict(result)

    table.add_row(['id', result['id']])
    table.add_row(['guid', result['globalIdentifier']])
    table.add_row(['hostname', result['hostname']])
    table.add_row(['domain', result['domain']])
    table.add_row(['fqdn', result['fullyQualifiedDomainName']])
    table.add_row(['status', formatting.FormattedItem(
        result['status']['keyName'] or formatting.blank(),
        result['status']['name'] or formatting.blank()
    )])
    table.add_row(['state', formatting.FormattedItem(
        utils.lookup(result, 'powerState', 'keyName'),
        utils.lookup(result, 'powerState', 'name'),
    )])
    table.add_row(['active_transaction', formatting.active_txn(result)])
    table.add_row(['datacenter',
                   result['datacenter']['name'] or formatting.blank()])
    _cli_helper_dedicated_host(env, result, table)
    operating_system = utils.lookup(result,
                                    'operatingSystem',
                                    'softwareLicense',
                                    'softwareDescription') or {}
    table.add_row(['os', operating_system.get('name') or formatting.blank()])
    table.add_row(['os_version',
                   operating_system.get('version') or formatting.blank()])
    table.add_row(['cores', result['maxCpu']])
    table.add_row(['memory', formatting.mb_to_gb(result['maxMemory'])])
    table.add_row(['public_ip',
                   result['primaryIpAddress'] or formatting.blank()])
    table.add_row(['private_ip',
                   result['primaryBackendIpAddress'] or formatting.blank()])
    table.add_row(['private_only', result['privateNetworkOnlyFlag']])
    table.add_row(['private_cpu', result['dedicatedAccountHostOnlyFlag']])
    table.add_row(['created', result['createDate']])
    table.add_row(['modified', result['modifyDate']])
    if utils.lookup(result, 'billingItem') != []:
        table.add_row(['owner', formatting.FormattedItem(
            utils.lookup(result, 'billingItem', 'orderItem',
                         'order', 'userRecord',
                         'username') or formatting.blank(),
        )])
    else:
        table.add_row(['owner', formatting.blank()])

    vlan_table = formatting.Table(['type', 'number', 'id'])
    for vlan in result['networkVlans']:
        vlan_table.add_row([
            vlan['networkSpace'], vlan['vlanNumber'], vlan['id']])
    table.add_row(['vlans', vlan_table])

    if result.get('networkComponents'):
        secgroup_table = formatting.Table(['interface', 'id', 'name'])
        has_secgroups = False
        for comp in result.get('networkComponents'):
            interface = 'PRIVATE' if comp['port'] == 0 else 'PUBLIC'
            for binding in comp['securityGroupBindings']:
                has_secgroups = True
                secgroup = binding['securityGroup']
                secgroup_table.add_row([
                    interface, secgroup['id'],
                    secgroup.get('name') or formatting.blank()])
        if has_secgroups:
            table.add_row(['security_groups', secgroup_table])

    if result.get('notes'):
        table.add_row(['notes', result['notes']])

    if price:
        total_price = utils.lookup(result,
                                   'billingItem',
                                   'nextInvoiceTotalRecurringAmount') or 0
        total_price += sum(p['nextInvoiceTotalRecurringAmount']
                           for p
                           in utils.lookup(result,
                                           'billingItem',
                                           'children') or [])
        table.add_row(['price_rate', total_price])

    if passwords:
        pass_table = formatting.Table(['software', 'username', 'password'])

        for component in result['softwareComponents']:
            for item in component['passwords']:
                pass_table.add_row([
                    utils.lookup(component,
                                 'softwareLicense',
                                 'softwareDescription',
                                 'name'),
                    item['username'],
                    item['password'],
                ])

        table.add_row(['users', pass_table])

    table.add_row(['tags', formatting.tags(result['tagReferences'])])

    # Test to see if this actually has a primary (public) ip address
    try:
        if not result['privateNetworkOnlyFlag']:
            ptr_domains = env.client.call(
                'Virtual_Guest', 'getReverseDomainRecords',
                id=vs_id,
            )

            for ptr_domain in ptr_domains:
                for ptr in ptr_domain['resourceRecords']:
                    table.add_row(['ptr', ptr['data']])
    except SoftLayer.SoftLayerAPIError:
        pass

    env.fout(table)
412798
def run(self, conn, tmp, module_name, module_args, inject):
        '''  '''
        hosts = ', '.join(self.runner.host_set)
        args = parse_kv(template(self.runner.basedir, module_args, inject))

        # Are 'minutes' or 'seconds' keys that exist in 'args'?
        if 'minutes' in args or 'seconds' in args:
            try:
                if 'minutes' in args:
                    self.pause_type = 'minutes'
                    # The time() command operates in seconds so we need to
                    # recalculate for minutes=X values.
                    self.seconds = int(args['minutes']) * 60
                else:
                    self.pause_type = 'seconds'
                    self.seconds = int(args['seconds'])
                    self.duration_unit = 'seconds'
            except ValueError, e:
                raise ae("non-integer value given for prompt duration:\n%s" % str(e))
        # Is 'prompt' a key in 'args'?
        elif 'prompt' in args:
            self.pause_type = 'prompt'
            self.prompt = "[%s]\n%s: " % (hosts, args['prompt'])
        # Is 'args' empty, then this is the default prompted pause
        elif len(args.keys()) == 0:
            self.pause_type = 'prompt'
            self.prompt = "[%s]\nPress enter to continue: " % hosts
        # I have no idea what you're trying to do. But it's so wrong.
        else:
            raise ae("invalid pause type given. must be one of: %s" % \
                         ", ".join(self.PAUSE_TYPES))

        vv("created 'pause' ActionModule: pause_type=%s, duration_unit=%s, calculated_seconds=%s, prompt=%s" % \
                (self.pause_type, self.duration_unit, self.seconds, self.prompt))

        ########################################################################
        # Begin the hard work!
        try:
            self._start()
            if not self.pause_type == 'prompt':
                print "[%s]\nPausing for %s seconds" % (hosts, self.seconds)
                time.sleep(self.seconds)
            else:
                # Clear out any unflushed buffered input which would
                # otherwise be consumed by raw_input() prematurely.
                tcflush(sys.stdin, TCIFLUSH)
                raw_input(self.prompt)
        except KeyboardInterrupt:
            while True:
                print '\nAction? (a)bort/(c)ontinue: '
                c = getch()
                if c == 'c':
                    # continue playbook evaluation
                    break
                elif c == 'a':
                    # abort further playbook evaluation
                    raise ae('user requested abort!')
        finally:
            self._stop()

        return ReturnData(conn=conn, result=self.result)
568716
def _cursor_timer_cb(self, timer):
        
        data = timer.data
        self.gui_do_oneshot('field-info', self._showxy,
                            data.viewer, data.data_x, data.data_y)
305822
def system(cmd_str, args=[], opts={})
      unless EventMachine.reactor_running?
        raise "has to prepare EventMachine context"
      end

      cmd = quote_args(cmd_str, args, (opts[:quote_char] || '\''))

      capture_io = opts[:io] || StringIO.new
      stdin_buf = opts[:stdin_input]
      
      evmsg = {:cmd => cmd}
      wait_q = ::Queue.new
      if opts[:timeout] && opts[:timeout].to_f > 0.0
        EventMachine.add_timer(opts[:timeout].to_f) {
          wait_q.enq(RuntimeError.new("timeout child process wait: #{opts[:timeout].to_f} sec(s)"))
        }
        evmsg[:timeout] = opts[:timeout].to_f        
      end
      popenobj = EventMachine.popen(cmd, EmSystemCb, capture_io, stdin_buf, proc { |exit_stat|
                                      wait_q.enq(exit_stat)
                                    })
      pid = EventMachine.get_subprocess_pid(popenobj.signature)
      evmsg[:pid] = pid
      if self.respond_to? :logger
        logger.debug("Exec command (pid=#{pid}): #{cmd}")
      end

      stat = wait_q.deq
      evmsg = {}
      
      case stat
      when Process::Status
        evmsg[:exit_code] = stat.exitstatus
        if stat.exited? && stat.exitstatus == 0
        else
          raise "Unexpected status from child: #{stat}"
        end
      when Exception
        raise stat
      else
        raise "Unknown signal from child: #{stat}"
      end
      
    end
577596
def cli():
    """"""
    objcli = WrHierCli(sys.argv[1:])
    fouts_txt = objcli.get_fouts()
    if fouts_txt:
        for fout_txt in fouts_txt:
            objcli.wrtxt_hier(fout_txt)
    else:
        objcli.prt_hier(sys.stdout)
1014359
def parse_timers(self):
        
        filenames = list(filter(os.path.exists, [task.output_file.path for task in self]))

        parser = AbinitTimerParser()
        parser.parse(filenames)

        return parser
1087884
def reset_bunch_counter(self):
        '''
        '''
        logging.info('')
        commands = []
        commands.extend(self.register.get_commands("RunMode"))
        commands.extend(self.register.get_commands("BCR"))
        self.send_commands(commands)
        time.sleep(0.1)
        commands = []
        commands.extend(self.register.get_commands("ConfMode"))
        self.send_commands(commands)