split statement and task by last directive
332115
def finalize(self) -> None:
        '''  '''
        self.wrap_script()
        if not self.statements:
            self.task = ''
            return
        # handle tasks
        input_directive = [
            idx for idx, statement in enumerate(self.statements)
            if statement[0] == ':' and statement[1] == 'input'
        ]
        task_directive = [
            idx for idx, statement in enumerate(self.statements)
            if statement[0] == ':' and statement[1] == 'task'
        ]
        if len(task_directive) > 1:
            raise ValueError('Only one task statement is allowed in a step')
        # handle parameter
        for idx, statement in enumerate(self.statements):
            if statement[0] == ':' and statement[1] == 'parameter':
                if task_directive and task_directive[0] < idx:
                    raise ValueError(
                        'Parameter statement is not allowed in tasks.')
                if '=' not in statement[2]:
                    if ':' in statement[2]:
                        if not is_type_hint(statement[2]):
                            raise ValueError(
                                f'Invalid type trait in parameter specification {statement[2]}'
                            )
                        name, value = statement[2].split(':')
                    else:
                        name = statement[2]
                        value = 'str'
                else:
                    name, value = statement[2].split('=', 1)
                    # ignore type trait if a default value is specified
                    name = name.split(':')[0]
                name = name.strip()
                if name.startswith('_'):
                    raise ValueError(
                        f'Invalid parameter name {name}: names with leading underscore is not allowed.'
                    )
                if not value.strip():
                    raise ValueError(
                        f'{self.step_name()}: Invalid parameter definition: {statement[2]}'
                    )
                # there is a possibility that value contains # so  sos_handle_parameter(name, val # aaa) will fail
                self.statements[idx] = [
                    '!',
                    f'#begin_parameter {name}\n{name} = sos_handle_parameter_({name.strip()!r}, {value}\n) #end_parameter {name}\n',
                    statement[2].strip()
                ]
                self.parameters[name] = (value, statement[3])
                if input_directive and input_directive[0] < idx:
                    self.substep_parameters.add(name)
        # handle tasks
        if not task_directive:
            self.task = ''
        else:
            start_task = task_directive[0] + 1
            # convert statement to task
            self.task = ''
            for statement in self.statements[start_task:]:
                if statement[0] == ':':
                    if statement[1] in ('input', 'output', 'depends'):
                        raise ValueError(
                            f'{self.step_name()}: Step task should be defined as the last item in a SoS step'
                        )
                    elif statement[1] == 'task':
                        raise ValueError(
                            f'{self.step_name()}: Only one task is allowed for a step'
                        )
                    elif statement[1] == 'parameter':
                        raise ValueError(
                            f'{self.step_name()}: Parameters should be defined before step task'
                        )
                    # ignore ...
                    self.task += '\n'
                else:
                    self.task += statement[1]
            self.task_params = self.statements[task_directive[0]][2]
            self.statements = self.statements[:task_directive[0]]
        # merge multiple statments at the end
        if len(self.statements) > 1 and self.statements[-1][0] == '!':
            starting = len(self.statements) - 1
            for idx in range(starting - 1, -1, -1):
                if self.statements[idx][0] == '!':
                    starting = idx
                else:
                    break
            # merge
            for idx in range(starting + 1, len(self.statements)):
                self.statements[starting][1] += self.statements[idx][1]
            # remove the rest of the statements
            self.statements = self.statements[:starting + 1]
        #
        # auto provides #859
        if not any(opt in self.options for opt in ('provides', 'shared')) and \
                len([x for x in self.statements if x[0] == ':' and x[1] == 'output']) == 1:
            output_stmt = [
                x for x in self.statements if x[0] == ':' and x[1] == 'output'
            ][0][2]
            output_names = get_names_of_kwargs(output_stmt)
            self.options['namedprovides'] = repr(output_names)
1331982
private void readLeafTasks(Task parent, Integer id)
   {
      Integer currentID = id;
      Table table = getTable("A1TAB");
      while (currentID.intValue() != 0)
      {
         if (m_projectFile.getTaskByUniqueID(currentID) == null)
         {
            readTask(parent, currentID);
         }
         currentID = table.find(currentID).getInteger("NEXT_TASK_ID");
      }
   }
1158245
def chain_tasks(tasks):
    
    # If given tasks list is not empty
    if tasks:
        # Previous task
        previous_task = None

        # For given tasks list's each task
        for task in tasks:
            # If the task is not None.
            # Task can be None to allow code like ``task if _PY2 else None``.
            if task is not None:
                # If previous task is not None
                if previous_task is not None:
                    # Set the task to run after the previous task
                    task.set_run_after(previous_task)

                # Set the task as previous task for the next task
                previous_task = task

    # Return given tasks list.
    return tasks
859636
def run_tidy(args, tmpdir, build_path, queue, lock, failed_files):
  """"""
  while True:
    name = queue.get()
    invocation = get_tidy_invocation(name, args.clang_tidy_binary, args.checks,
                                     tmpdir, build_path, args.header_filter,
                                     args.extra_arg, args.extra_arg_before,
                                     args.quiet, args.config)

    proc = subprocess.Popen(invocation, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    output, err = proc.communicate()
    if proc.returncode != 0:
      failed_files.append(name)
    with lock:
      if len(output) > 0:
        sys.stdout.write(output.decode('utf-8') + '\n')
      if len(err) > 0:
        sys.stderr.write(err.decode('utf-8') + '\n')
    queue.task_done()
765653
function main () {
  var taskList = _(arguments).toArray().flatten(true).value()
  gulp.task('default', taskList)
  return this
}
111932
function(task, recurse) {
  // get time since last context swap (ms), if enough time has passed set
  // swap to true to indicate that doNext was performed asynchronously
  // also, if recurse is too high do asynchronously
  var swap =
    (recurse > sMaxRecursions) ||
    (+new Date() - task.swapTime) > sTimeSlice;

  var doNext = function(recurse) {
    recurse++;
    if(task.state === RUNNING) {
      if(swap) {
        // update swap time
        task.swapTime = +new Date();
      }

      if(task.subtasks.length > 0) {
        // run next subtask
        var subtask = task.subtasks.shift();
        subtask.error = task.error;
        subtask.swapTime = task.swapTime;
        subtask.userData = task.userData;
        subtask.run(subtask);
        if(!subtask.error)
        {
           runNext(subtask, recurse);
        }
      } else {
        finish(task);

        if(!task.error) {
          // chain back up and run parent
          if(task.parent !== null) {
            // propagate task info
            task.parent.error = task.error;
            task.parent.swapTime = task.swapTime;
            task.parent.userData = task.userData;

            // no subtasks left, call run next subtask on parent
            runNext(task.parent, recurse);
          }
        }
      }
    }
  };

  if(swap) {
    // we're swapping, so run asynchronously
    setTimeout(doNext, 0);
  } else {
    // not swapping, so run synchronously
    doNext(recurse);
  }
}
476067
def do_summary(self, args):
        ''''''
        assert args.json or args.text or (args.text is None)
        do_text = args.text

        xd = {}
        for ws in self.task_master.iter_work_specs():
            name = ws['name']
            status = self.task_master.status(name)
            xd[name] = status
        xd['_NOW'] = time.time()

        if args.json:
            self.stdout.write(json.dumps(xd) + '\n')
        else:
            if do_text is None:
                do_text = True

        if do_text:
            self.stdout.write('Work spec               Avail  Pending  Blocked'
                              '   Failed Finished    Total\n')
            self.stdout.write('==================== ======== ======== ========'
                              ' ======== ======== ========\n')
            for name in sorted(xd.keys()):
                if name == '_NOW':
                    continue
                status = xd[name]
                self.stdout.write('{0:20s} {1[num_available]:8d} '
                                  '{1[num_pending]:8d} {1[num_blocked]:8d} '
                                  '{1[num_failed]:8d} {1[num_finished]:8d} '
                                  '{1[num_tasks]:8d}\n'.format(name, status))
467446
function taskFontmin() {
    // prase options
    let opts    = this.options()
    let data    = this.data
    let destdir = opts.dest    || './'
    let basedir = opts.basedir || './'
    let src     = grunt.file.expand(data.src)
    let fonts   = grunt.file.expand(join(basedir, this.target))
    let getText = opts.getText!==undefined ? opts.getText : (content)=>html2text.fromString(content)
    let type='woff', typeOpts=true

    // check if more than one output option is specified
    if ( !atMostDefined(data, 1, 'woff', 'css') )
        throw new Error('Multiple output type defined!')

    // set type, typeOpts
    if (data.woff!==undefined) { type='woff' }
    if (data.css!==undefined)  { type='css'; typeOpts=data.css }

    // string of unique characters(glyphs) to be included in minimized font
    let uniqGlyphs =
        src.map( path => grunt.file.read(path) )
           .map( getText )
           .join()
           .split('')
           .sort().reduce( nodup(), [] )   // remove duplicate characters
           .join('')


    fonts.forEach( path => {
        // create output ArrayBuffer
        let ttf = readToTTF(path)
        let stripped = glyphStrip(ttf, uniqGlyphs)
        let output = ttfToOutput(stripped, type, typeOpts)

        // solve dest path, write output
        let destPath = join(destdir, getOutputFilename(path,type))
        grunt.file.write(destPath, toBuffer(output))

        // output information
        grunt.log.writeln(basename(path)+' => '+type+' '
            +chalk.green(stripped.glyf.length)+' glyphs, '
            +chalk.green(output.byteLength)+' bytes')
    } )

}
46847
def _get_command_templates(command_tokens, files=[], paths=[], job_options=[],
    count=1):
    
    if not command_tokens:
        return []

    comment_tokens, command_token = command_tokens.pop()
    parts = []

    parts += job_options + _get_comments(comment_tokens)
    for part in command_token[0]:
        # Check for file
        try:
            parts.append(_get_file_by_alias(part, files))
            continue
        except (AttributeError, ValueError):
            pass

        # Check for path/string
        for cut in part.split():
            try:
                parts.append(_get_path_by_name(cut, paths))
                continue
            except ValueError:
                pass

            parts.append(cut)

    command_template = CommandTemplate(alias=str(count), parts=parts)
    [setattr(p, 'alias', command_template.alias)
        for p in command_template.output_parts]
    return [command_template] + _get_command_templates(command_tokens,
        files, paths, job_options, count+1)
912686
def split_commands(cmd_line)
      return [""] if cmd_line.empty?

      cmd_line.split(/;/).each_with_object([]) do |v, m|
        if m.empty? || m.last[-1] != '\\'
          m << v.strip
          next
        end

        m.last[-1, 1] = ""
        m.last << ";" << v
      end
    end
318882
def _help():
	''''''
	for task in sorted(TASKS, key=lambda x: (x.ns or '000') + x.name):
		tags = ''
		if task is DEFAULT:
			tags += '*'
		if task is SETUP:
			tags += '+'
		if task is TEARDOWN:
			tags += '-'

		print LOCALE['help_command'].format(task, tags, task.help)

		if task.aliases:
			print LOCALE['help_aliases'].format(task.aliasstr())
		if task.reqs:
			print LOCALE['help_reqs'].format(task.reqstr())
		if task.gens:
			print LOCALE['help_gens'].format(task.gens)
		if task.args or task.defaults:
			print LOCALE['help_args'].format(task.ns + task.name, task.kwargstr(), task.argstr())
301148
def parseArgs():
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument("name", help="the file you want to split")
    parser.add_argument("out1", help="the name of the first file you want to output")
    parser.add_argument("out2", help="the name of the second file you want to output")
    return parser.parse_args()
846369
private static void listHierarchy(Task task, String indent)
   {
      for (Task child : task.getChildTasks())
      {
         System.out.println(indent + "Task: " + child.getName() + "\t" + child.getStart() + "\t" + child.getFinish());
         listHierarchy(child, indent + " ");
      }
   }
452276
def savvyize(self, input_string, recursive=False, stemma=False):
        '''
        
        '''
        input_string = os.path.abspath(input_string)
        tasks = []

        restricted = [ symbol for symbol in self.settings['skip_if_path'] ] if self.settings['skip_if_path'] else []

        # given folder
        if os.path.isdir(input_string):
            if recursive:
                for root, dirs, files in os.walk(input_string): # beware of broken links on unix! (NB find ~ -type l -exec rm -f {} \;)
                    # skip_if_path directive
                    to_filter = []
                    for dir in dirs:
                        dir = u(dir)
                        for rs in restricted:
                            if dir.startswith(rs) or dir.endswith(rs):
                                to_filter.append(dir)
                                break
                    dirs[:] = [x for x in dirs if x not in to_filter]
                    for filename in files:
                        # skip_if_path directive
                        filename = u(filename)
                        if restricted:
                            for rs in restricted:
                                if filename.startswith(rs) or filename.endswith(rs):
                                    break
                            else:
                                tasks.append(root + os.sep + filename)
                        else:
                            tasks.append(root + os.sep + filename)
            else:
                for filename in os.listdir(input_string):
                    filename = u(filename)
                    if os.path.isfile(input_string + os.sep + filename):
                        # skip_if_path directive
                        if restricted:
                            for rs in restricted:
                                if filename.startswith(rs) or filename.endswith(rs):
                                    break
                            else:
                                tasks.append(input_string + os.sep + filename)
                        else:
                            tasks.append(input_string + os.sep + filename)

        # given full filename
        elif os.path.isfile(input_string):
            tasks.append(input_string) # skip_if_path directive is not applicable here

        # given filename stemma
        else:
            if stemma:
                parent = os.path.dirname(input_string)
                for filename in os.listdir(parent):
                    filename = u(filename)
                    if input_string in parent + os.sep + filename and not os.path.isdir(parent + os.sep + filename):
                        # skip_if_path directive
                        if restricted:
                            for rs in restricted:
                                if filename.startswith(rs) or filename.endswith(rs):
                                    break
                            else:
                                tasks.append(parent + os.sep + filename)
                        else:
                            tasks.append(parent + os.sep + filename)
        return tasks
1330097
def handle_scoping_input(self, continue_flag, cmd, text):
        
        default_split = text.partition(SELECT_SYMBOL['scope'])[2].split()
        cmd = cmd.replace(SELECT_SYMBOL['scope'], '')

        continue_flag = True

        if not default_split:
            self.default_command = ""
            print('unscoping all', file=self.output)

            return continue_flag, cmd

        while default_split:
            if not text:
                value = ''
            else:
                value = default_split[0]

            tree_path = self.default_command.split()
            tree_path.append(value)

            if self.completer.command_tree.in_tree(tree_path):
                self.set_scope(value)
                print("defaulting: " + value, file=self.output)
                cmd = cmd.replace(SELECT_SYMBOL['scope'], '')
            elif SELECT_SYMBOL['unscope'] == default_split[0] and self.default_command.split():

                value = self.default_command.split()[-1]
                self.default_command = ' ' + ' '.join(self.default_command.split()[:-1])

                if not self.default_command.strip():
                    self.default_command = self.default_command.strip()
                print('unscoping: ' + value, file=self.output)

            elif SELECT_SYMBOL['unscope'] not in text:
                print("Scope must be a valid command", file=self.output)

            default_split = default_split[1:]
        return continue_flag, cmd
932751
function(file, tasks, options) {
              /** skip if no tasks or checking Gruntfile */
              if (!tasks.length || file && file === 'Gruntfile.js') {
                return '';
              }

              var result = '* ' + file + ' (' + tasks.length + ')\n\n';

              /** iterate over tasks, add data */
              tasks.forEach(function(task) {
                result += '    [' + task.lineNumber + ' - ' +
                  task.priority + '] ' + task.line.trim() + '\n';

                result += '\n';
              });

              return result;
            }
347737
function preprocessor_branch(if_directive,
                                 elif_directives,
                                 else_directive) {
      var elseList = elif_directives;
      if (else_directive) {
        elseList = elseList.concat([else_directive]);
      }
      var result = if_directive[0];
      result.guarded_statements = if_directive[1].statements;
      var current_branch = result;
      for (var i = 0; i < elseList.length; i++) {
        current_branch.elseBody = elseList[i][0];
        current_branch.elseBody.guarded_statements =
          elseList[i][1].statements;
        current_branch = current_branch.elseBody;
      }
      return result;
    }