Execute a multi-level task
432578
def _execute_multi_level_task(self):
        
        self.log(u"Executing multi level task...")

        self.log(u"Saving rconf...")
        # save original rconf
        orig_rconf = self.rconf.clone()
        # clone rconfs and set granularity
        # TODO the following code assumes 3 levels: generalize this
        level_rconfs = [None, self.rconf.clone(), self.rconf.clone(), self.rconf.clone()]
        level_mfccs = [None, None, None, None]
        force_aba_autos = [None, False, False, True]
        for i in range(1, len(level_rconfs)):
            level_rconfs[i].set_granularity(i)
            self.log([u"Level %d mmn: %s", i, level_rconfs[i].mmn])
            self.log([u"Level %d mwl: %.3f", i, level_rconfs[i].mwl])
            self.log([u"Level %d mws: %.3f", i, level_rconfs[i].mws])
            level_rconfs[i].set_tts(i)
            self.log([u"Level %d tts: %s", i, level_rconfs[i].tts])
            self.log([u"Level %d tts_path: %s", i, level_rconfs[i].tts_path])
        self.log(u"Saving rconf... done")
        try:
            self.log(u"Creating AudioFile object...")
            audio_file = self._load_audio_file()
            self.log(u"Creating AudioFile object... done")

            # extract MFCC for each level
            for i in range(1, len(level_rconfs)):
                self._step_begin(u"extract MFCC real wave level %d" % i)
                if (i == 1) or (level_rconfs[i].mws != level_rconfs[i - 1].mws) or (level_rconfs[i].mwl != level_rconfs[i - 1].mwl):
                    self.rconf = level_rconfs[i]
                    level_mfccs[i] = self._extract_mfcc(audio_file=audio_file)
                else:
                    self.log(u"Keeping MFCC real wave from previous level")
                    level_mfccs[i] = level_mfccs[i - 1]
                self._step_end()

            self.log(u"Clearing AudioFile object...")
            self.rconf = level_rconfs[1]
            self._clear_audio_file(audio_file)
            self.log(u"Clearing AudioFile object... done")

            # compute head tail for the entire real wave (level 1)
            self._step_begin(u"compute head tail")
            (head_length, process_length, tail_length) = self._compute_head_process_tail(level_mfccs[1])
            level_mfccs[1].set_head_middle_tail(head_length, process_length, tail_length)
            self._step_end()

            # compute alignment at each level
            sync_root = Tree()
            sync_roots = [sync_root]
            text_files = [self.task.text_file]
            number_levels = len(level_rconfs)
            for i in range(1, number_levels):
                self._step_begin(u"compute alignment level %d" % i)
                self.rconf = level_rconfs[i]
                text_files, sync_roots = self._execute_level(
                    level=i,
                    audio_file_mfcc=level_mfccs[i],
                    text_files=text_files,
                    sync_roots=sync_roots,
                    force_aba_auto=force_aba_autos[i],
                )
                self._step_end()

            # restore original rconf, and create syncmap and add it to task
            self._step_begin(u"create sync map")
            self.rconf = orig_rconf
            self._create_sync_map(sync_root=sync_root)
            self._step_end()

            self._step_total()
            self.log(u"Executing multi level task... done")
        except Exception as exc:
            self._step_failure(exc)
491824
public synchronized void executeTask(long jobId, int taskId, JobConfig jobConfig,
      Serializable taskArgs, RunTaskContext context) {
    Future<?> future = mTaskExecutionService
        .submit(new TaskExecutor(jobId, taskId, jobConfig, taskArgs, context, this));
    Pair<Long, Integer> id = new Pair<>(jobId, taskId);
    mTaskFutures.put(id, future);
    TaskInfo.Builder taskInfo = TaskInfo.newBuilder();
    taskInfo.setJobId(jobId);
    taskInfo.setTaskId(taskId);
    taskInfo.setStatus(Status.RUNNING);
    mUnfinishedTasks.put(id, taskInfo);
    mTaskUpdates.put(id, taskInfo.build());
    LOG.info("Task {} for job {} started", taskId, jobId);
  }
608686
def task(ft):
	
	ft.pack(expand = True,  fill = BOTH,  side = TOP)
	pb_hD = ttk.Progressbar(ft, orient = 'horizontal', mode = 'indeterminate')
	pb_hD.pack(expand = True, fill = BOTH, side = TOP)
	pb_hD.start(50)
	ft.mainloop()
1053806
function Tasks(tasks, cwd){
  this.num = 0;
  this.finish = 0;
  var _this = this;
  this.setMaxListeners(50);
  
  forEach(tasks, function(task){
    var exec = require('./' + task.task);
    forEach(task.files, function(file){
      var cmd = new exec({'file': file, cwd: cwd});
      //console.log('[task ' + task.task + '] on file ' + file + ' begin');
      this.num = this.num + 1;
      cmd.on('finish', function(e){
        _this.emit('finish', {ret: e, file: file, task: task.task});
      });
    }, this);
  }, this);
  this._bind();
}
735032
public static void executeIn(ClassLoader loader, Runnable task) throws Exception
   {
      if (task == null)
         return;

      if (log.isLoggable(Level.FINE))
      {
         log.fine("ClassLoader [" + loader + "] task began.");
      }
      ClassLoader original = SecurityActions.getContextClassLoader();
      try
      {
         SecurityActions.setContextClassLoader(loader);
         task.run();
      }
      finally
      {
         SecurityActions.setContextClassLoader(original);
         if (log.isLoggable(Level.FINE))
         {
            log.fine("ClassLoader [" + loader + "] task ended.");
         }
      }
   }
843414
def execute_tasks(tasks,template_path)
      
      if File.exists?(File.expand_path(File.join(template_path,'tasks.rb')))
        load File.expand_path(File.join(template_path,'tasks.rb'))
      end
       
      tasks.each{
        |task|
        
        puts 'Running Task: ' + task
        
        task = replace_tags(task);
        
        options = task.split(', ')
        action = options.slice!(0)
        
        if(Tasks.respond_to?(action))
          Tasks.send action, options.join(', ')
        else
          send action, options.join(', ')
        end
        
      }
                  
    end
649620
def _execute(self, args, log=True):
        """"""
        if not self._ready:
            self.open_or_create()
        output = ''
        error = ''
        try:
            proc = subprocess.Popen(args, cwd=self.path, env=self.env, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
            output, error = proc.communicate()
            returncode = proc.returncode
            if returncode:
                raise subprocess.CalledProcessError(returncode, proc, (output, error))
            return to_text(output)
        except OSError as e:
            # raise a more meaningful error with the program name
            prog = args[0]
            if prog[0] != os.sep:
                prog = os.path.join(self.path, prog)
            raise OSError('%s: %s' % (prog, six.u(str(e))))
        except subprocess.CalledProcessError as e:
            output, error = e.output
            e.output = output
            raise e
        finally:
            if log:
                try:
                    self._write_to_log(to_text(output))
                    self._write_to_error(to_text(error))
                except NameError:
                    pass
1014348
def make_task(name='',
              run_name='',
              **kwargs) -> Task:
  """"""
  ncluster_globals.task_launched = True

  name = ncluster_globals.auto_assign_task_name_if_needed(name)

  # tmux can't use . for session names
  tmux_session = name.replace('.', '=')
  tmux_window_id = 0
  util.log(f'killing session {tmux_session}')

  if not util.is_set("NCLUSTER_NOKILL_TMUX"):
    os.system(f'tmux kill-session -t {tmux_session}')
  os.system(f'tmux new-session -s {tmux_session} -n {tmux_window_id} -d')

  task = Task(name,
              tmux_session=tmux_session,  # propagate optional args
              run_name=run_name,
              **kwargs)
  ncluster_globals.register_task(task, run_name)
  return task
57766
def execute(self):
        

        with self._lock_c:
            self.count = 0
            self.numtasks = 0
            self.taskset = []
            self.results = {}
            self.totaltime = time.time()
            # Start all tasks
            for task in self.taskseq:
                self.taskset.append(task)
                self.numtasks += 1
                task.init_and_start(self)

        num_tasks = self.getNumTasks()
        # Wait on each task to clean up results
        while num_tasks > 0:

            self.check_state()

            for i in range(num_tasks):
                try:
                    try:
                        task = self.getTask(i)
                    except IndexError:
                        # A task got deleted from the set.  Jump back out
                        # to outer loop and repoll the number of tasks
                        break

                    #self.logger.debug("waiting on %s" % task)
                    res = task.wait(timeout=self.idletime)

                    #self.logger.debug("finished: %s" % task)
                    self.child_done(res, task)

                except TaskTimeout:
                    continue

                except Exception as e:
                    #self.logger.warning("Subtask propagated exception: %s" % str(e))
                    self.child_done(e, task)
                    continue

            # wait a bit and try again
            #self.ev_quit.wait(self.idletime)

            # re-get number of tasks, in case some were added or deleted
            num_tasks = self.getNumTasks()

        # Scan results for errors (exceptions) and raise the first one we find
        for key in self.results.keys():
            value = self.results[key]
            if isinstance(value, Exception):
                (count, task) = key
                self.logger.error("Child task %s terminated with exception: %s" % (
                    task.tag, str(value)))
                raise value

        # Return value of last child to complete
        return value
682309
protected void performSubtasks(TaskRequest req, TaskResponse res, List<Task> tasks) {
        // Assertions...
        if (req == null) {
            String msg = "Argument 'req' cannot be null.";
            throw new IllegalArgumentException(msg);
        }
        if (res == null) {
            String msg = "Argument 'res' cannot be null.";
            throw new IllegalArgumentException(msg);
        }
        if (tasks == null) {
            String msg = "Child tasks have not been initialized.  Subclasses "
                            + "of AbstractContainerTask must call super.init() "
                            + "within their own init() method.";
            throw new IllegalStateException(msg);
        }
        
        // Invoke each of our children...
        for (Task k : tasks) {
            k.perform(req, res);
        }
	}
723195
function level (pipe, cachedLevelOf, taskKey) {
  var taskLevel = 0
  var parentsOf = parents.bind(null, pipe)

  if (typeof cachedLevelOf[taskKey] === 'number') {
    return cachedLevelOf[taskKey]
  }

  function computeLevel (parentTaskKey) {
    // ↓ Recursion here: the level of a task is the max level of its parents + 1.
    taskLevel = Math.max(taskLevel, level(pipe, cachedLevelOf, parentTaskKey) + 1)
  }

  parentsOf(taskKey).forEach(computeLevel)

  cachedLevelOf[taskKey] = taskLevel

  return taskLevel
}
577745
def handle_run_command(parser, args):
    """"""
    MAX_LEVELS = 15

    # --- Look for `pyftpsync.yaml` in current folder and parents ---

    cur_level = 0
    cur_folder = os.getcwd()
    config_path = None
    while cur_level < MAX_LEVELS:
        path = os.path.join(cur_folder, CONFIG_FILE_NAME)
        # print("Searching for {}...".format(path))
        if os.path.isfile(path):
            config_path = path
            break
        parent = os.path.dirname(cur_folder)
        if parent == cur_folder:
            break
        cur_folder = parent
        cur_level += 1

    if not config_path:
        parser.error(
            "Could not locate `.pyftpsync.yaml` in {} or {} parent folders.".format(
                os.getcwd(), cur_level
            )
        )

    # --- Parse `pyftpsync.yaml` and set `args` attributes ---

    try:
        with open(config_path, "rb") as f:
            config = yaml.safe_load(f)
    except Exception as e:
        parser.error("Error parsing {}: {}".format(config_path, e))
        # write_error("Error parsing {}: {}".format(config_path, e))
        # raise

    # print(config)
    if "tasks" not in config:
        parser.error("Missing option `tasks` in {}".format(config_path))

    common_config = config.get("common_config", {})

    default_task = config.get("default_task", "default")
    task_name = args.task or default_task
    if task_name not in config["tasks"]:
        parser.error("Missing option `tasks.{}` in {}".format(task_name, config_path))
    task = config["tasks"][task_name]

    write("Running task '{}' from {}".format(task_name, config_path))

    common_config.update(task)
    task = common_config
    # write("task", task)

    # --- Check task syntax ---

    task_args = set(task.keys())

    missing_args = MANDATORY_TASK_ARGS.difference(task_args)
    if missing_args:
        parser.error(
            "Missing mandatory options: tasks.{}.{}".format(
                task_name, ", ".join(missing_args)
            )
        )

    allowed_args = KNOWN_TASK_ARGS.union(MANDATORY_TASK_ARGS)
    invalid_args = task_args.difference(allowed_args)
    if invalid_args:
        parser.error(
            "Invalid options: tasks.{}.{}".format(task_name, ", ".join(invalid_args))
        )

    # write("args", args)

    for name in allowed_args:
        val = task.get(name, None)  # default)

        if val is None:
            continue  # option not specified in yaml

        # Override yaml entry by command line
        cmd_val = getattr(args, name, None)

        # write("check --{}: {} => {}".format(name, val, cmd_val))

        if cmd_val != val:
            override = False
            if name in OVERRIDABLE_BOOL_ARGS and cmd_val:
                override = True
            elif name in {"here", "root"} and (args.here or args.root):
                override = True
            elif name == "verbose" and cmd_val != 3:
                override = True

            if override:
                write(
                    "Yaml entry overriden by --{}: {} => {}".format(name, val, cmd_val)
                )
                continue

        setattr(args, name, val)

    # --- Figure out local target path ---

    cur_folder = os.getcwd()
    root_folder = os.path.dirname(config_path)
    path_ofs = os.path.relpath(os.getcwd(), root_folder)

    if cur_level == 0 or args.root:
        path_ofs = ""
        args.local = root_folder
    elif args.here:
        write("Using sub-branch {sub} of {root}".format(root=root_folder, sub=path_ofs))
        args.local = cur_folder
        args.remote = os.path.join(args.remote, path_ofs)
    else:
        parser.error(
            "`.pyftpsync.yaml` configuration was found in a parent directory. "
            "Please pass an additional argument to clarify:\n"
            "  --root: synchronize whole project ({root})\n"
            "  --here: synchronize sub branch ({root}/{sub})".format(
                root=root_folder, sub=path_ofs
            )
        )
118758
def run_job(key, node):
    """"""
    try:
        result = node.apply()
        return ResultMessage(key, 'done', result, None)

    except Exception as exc:
        return ResultMessage(key, 'error', None, exc)
1213275
protected void executeTaskIfMatchInternal(long millis) {
		for (int i = 0; i < size; i++) {
			if (patterns.get(i).match(timezone, millis, this.scheduler.matchSecond)) {
				this.scheduler.taskExecutorManager.spawnExecutor(tasks.get(i));
			}
		}
	}
280677
def task(self, body, priority=None, timeout=None, **kwargs):
        
        return self.nest(Task(body, priority=priority, timeout=timeout, **kwargs))
304858
def run_task(task_cls, task_data):
    
    task = instantiate(task_cls)
    task_callable = get_callable(task)
    return task_callable(TaskData(task_data))
1137514
public static void executeWithSystemPermissions(Runnable task) {
        ContextAwareRunnable contextAwaretask = new ContextAwareRunnable(task);
        Subject newsubject = new Subject.Builder().buildSubject();
        newsubject.login(new RootAuthenticationToken());
        try {
            newsubject.execute(contextAwaretask);
        } finally {
            newsubject.logout();
        }
    }