Build config for behat.yml.

@param int $parallelruns how many parallel runs feature needs to be divided.
@param int $currentrun current run for which features should be returned.
@return array
508282
protected function build_config($parallelruns = 0, $currentrun = 0) {
        global $CFG;

        if (!empty($parallelruns) && !empty($currentrun)) {
            $this->set_parallel_run($parallelruns, $currentrun);
        } else {
            $currentrun = $this->get_current_run();
            $parallelruns = $this->get_number_of_parallel_run();
        }

        $selenium2wdhost = array('wd_host' => 'http://localhost:4444/wd/hub');
        // If parallel run, then set wd_host if specified.
        if (!empty($currentrun) && !empty($parallelruns)) {
            // Set proper selenium2 wd_host if defined.
            if (!empty($CFG->behat_parallel_run[$currentrun - 1]['wd_host'])) {
                $selenium2wdhost = array('wd_host' => $CFG->behat_parallel_run[$currentrun - 1]['wd_host']);
            }
        }

        // It is possible that it has no value as we don't require a full behat setup to list the step definitions.
        if (empty($CFG->behat_wwwroot)) {
            $CFG->behat_wwwroot = 'http://itwillnotbeused.com';
        }

        $suites = $this->get_behat_suites($parallelruns, $currentrun);

        $selectortypes = ['named_partial', 'named_exact'];
        $allpaths = [];
        foreach (array_keys($suites) as $theme) {
            // Remove selectors from step definitions.
            foreach ($selectortypes as $selectortype) {
                // Don't include selector classes.
                $selectorclass = self::get_behat_theme_selector_override_classname($theme, $selectortype);
                if (isset($suites[$theme]['contexts'][$selectorclass])) {
                    unset($suites[$theme]['contexts'][$selectorclass]);
                }
            }

            // Get a list of all step definition paths.
            $allpaths = array_merge($allpaths, $suites[$theme]['contexts']);

            // Convert the contexts array to a list of names only.
            $suites[$theme]['contexts'] = array_keys($suites[$theme]['contexts']);
        }

        // Comments use black color, so failure path is not visible. Using color other then black/white is safer.
        // https://github.com/Behat/Behat/pull/628.
        $config = array(
            'default' => array(
                'formatters' => array(
                    'moodle_progress' => array(
                        'output_styles' => array(
                            'comment' => array('magenta'))
                    )
                ),
                'suites' => $suites,
                'extensions' => array(
                    'Behat\MinkExtension' => array(
                        'base_url' => $CFG->behat_wwwroot,
                        'goutte' => null,
                        'selenium2' => $selenium2wdhost
                    ),
                    'Moodle\BehatExtension' => array(
                        'moodledirroot' => $CFG->dirroot,
                        'steps_definitions' => $allpaths,
                    )
                )
            )
        );

        return $config;
    }
366270
public function runInBackground(DateTime $now = null) : array
    {
        $jobs = $this->getDueJobs($now);

        foreach ($jobs as $job) {
            $this->processes[] = $job->runInBackground();
        }

        return $this->processes;
    }
1266094
protected function configure()
    {
        $this->addArgument(
            'stage',
            InputArgument::OPTIONAL,
            'Stage or hostname'
        );
        $this->addOption(
            'parallel',
            'p',
            Option::VALUE_NONE,
            'Run tasks in parallel'
        );
        $this->addOption(
            'limit',
            'l',
            Option::VALUE_REQUIRED,
            'How many host to run in parallel?'
        );
        $this->addOption(
            'no-hooks',
            null,
            Option::VALUE_NONE,
            'Run task without after/before hooks'
        );
        $this->addOption(
            'log',
            null,
            Option::VALUE_REQUIRED,
            'Log to file'
        );
        $this->addOption(
            'roles',
            null,
            Option::VALUE_REQUIRED,
            'Roles to deploy'
        );
        $this->addOption(
            'hosts',
            null,
            Option::VALUE_REQUIRED,
            'Host to deploy, comma separated, supports ranges [:]'
        );
        $this->addOption(
            'option',
            'o',
            Option::VALUE_REQUIRED | Option::VALUE_IS_ARRAY,
            'Sets configuration option'
        );
    }
1367791
public function getConfig()
    {
        if ($this->config === null) {
            $path = $this->getInputDirectory() . '/makedocs.json';
            if (!is_file($path)) {
                throw new \RuntimeException('The input directory does not contain a makedocs.json file.');
            }

            $data = json_decode(file_get_contents($path));
            if (!$data) {
                throw new \RuntimeException('The JSON could not be loaded.');
            }

            $this->config = new Config((array)$data);
        }
        return $this->config;
    }
503242
def runner(queue, parallel):
    
    def run(fn_name, items):
        logger.info("clusterk: %s" % fn_name)
        assert "wrapper" in parallel, "Clusterk requires bcbio-nextgen-vm wrapper"
        fn = getattr(__import__("{base}.clusterktasks".format(base=parallel["module"]),
                                fromlist=["clusterktasks"]),
                     parallel["wrapper"])
        wrap_parallel = {k: v for k, v in parallel.items() if k in set(["fresources", "pack"])}
        out = []
        for data in [fn(fn_name, queue, parallel.get("wrapper_args"), wrap_parallel, x) for x in items]:
            if data:
                out.extend(data)
        return out
    return run
1130030
public static function recursiveConfigurableTree(array &$tree, array $available_config, array $current_config = []) {
    $subtree = ['#available_config' => $available_config];

    foreach ($available_config as $id => $config) {
      $subtree_available_config = $available_config;
      unset($subtree_available_config[$id]);

      foreach ($config['values'] as $option) {
        $value = $option['value_id'];
        $subtree_current_config = array_merge($current_config, [$id => $value]);

        if (count($subtree_available_config) > 0) {
          $subtree["$id:$value"] = Configurable::recursiveConfigurableTree(
            $tree,
            $subtree_available_config,
            $subtree_current_config
          );
        }
        else {
          $subtree["$id:$value"] = Configurable::findProductInTreeWithConfig(
            $tree,
            $subtree_current_config
          );
        }
      }
    }

    return $subtree;
  }
185940
@Override
  protected List<Runner> getChildren() {
    // one runner for each parameter
    List<Runner> runners = super.getChildren();
    List<Runner> proxyRunners = new ArrayList<>(runners.size());
    for (Runner runner : runners) {
      // if the next line fails then the internal of Parameterized.class has been updated since this works with JUnit 4.11
      BlockJUnit4ClassRunner blockJUnit4ClassRunner = (BlockJUnit4ClassRunner) runner;
      Description description = blockJUnit4ClassRunner.getDescription();
      String name = description.getDisplayName();
      try {
        proxyRunners
            .add(new ProxyTestClassRunnerForParameters(mTestClass, mContainerUrl, name));
      } catch (InitializationError e) {
        throw new RuntimeException("Could not create runner for paramamter " + name, e);
      }
    }
    return proxyRunners;
  }
654059
protected function matchCurrentPathPart($pathPart, $previousConfiguration, &$currentPrototypeDefinitions)
    {
        if (preg_match('#^([^<]*)(<(.*?)>)?$#', $pathPart, $matches) !== 1) {
            throw new Exception('Path Part ' . $pathPart . ' not well-formed', 1332494645);
        }

        $currentPathSegment = $matches[1];
        $configuration = [];

        if (isset($previousConfiguration[$currentPathSegment])) {
            $configuration = is_array($previousConfiguration[$currentPathSegment]) ? $previousConfiguration[$currentPathSegment] : $this->simpleTypeToArrayClosure->__invoke($previousConfiguration[$currentPathSegment]);
        }

        if (isset($configuration['__prototypes'])) {
            $currentPrototypeDefinitions = Arrays::arrayMergeRecursiveOverruleWithCallback($currentPrototypeDefinitions, $configuration['__prototypes'], $this->simpleTypeToArrayClosure);
        }

        $currentPathSegmentType = null;
        if (isset($configuration['__objectType'])) {
            $currentPathSegmentType = $configuration['__objectType'];
        }
        if (isset($matches[3])) {
            $currentPathSegmentType = $matches[3];
        }

        if ($currentPathSegmentType !== null) {
            $configuration['__objectType'] = $currentPathSegmentType;
            $configuration = $this->mergePrototypesWithConfigurationForPathSegment($configuration, $currentPrototypeDefinitions);
        }

        if (is_array($configuration) && !isset($configuration['__value']) && !isset($configuration['__eelExpression']) && !isset($configuration['__meta']['class']) && !isset($configuration['__objectType']) && isset($configuration['__meta']['process'])) {
            $configuration['__value'] = '';
        }

        return $configuration;
    }
851027
public static <T> T forkJoinExecution(Callable<T> callable, ConcurrencyConfiguration concurrencyConfiguration, boolean parallelStream) {
        if(parallelStream && concurrencyConfiguration.isParallelized()) {
            try {
                ForkJoinPool pool = new ForkJoinPool(concurrencyConfiguration.getMaxNumberOfThreadsPerTask());
                
                T results = pool.submit(callable).get();
                pool.shutdown();
                return results;
            } 
            catch (InterruptedException | ExecutionException ex) {
                throw new RuntimeException(ex);
            }
        }
        else {
            try {
                return callable.call();
            } 
            catch (Exception ex) {
                throw new RuntimeException(ex);
            }
        }
    }
44677
private function readBundleConfiguration(): array
    {
        $configurationFilePath = $this->getApplicationDir() . '/config/bundles.yml';
        if (!is_readable($configurationFilePath)) {
            throw new \RuntimeException('The file "' . $configurationFilePath . '" could not be read.', 1504272377);
        }

        return Yaml::parse(file_get_contents($configurationFilePath));
    }
89782
public function run($connections, $autorun = true)
    {
        if (!is_array($connections)) {
            $connections = array($connections);
        }

        $this->on('connect.error', function($message, $connection, $logger) {
            $logger->error($message);
        });

        $this->emit('connect.before.all', array($connections));

        foreach ($connections as $connection) {
            $this->addConnection($connection);
        }

        $writes = array_map(
            function($connection) {
                return $connection->getData('write');
            },
            $connections
        );
        $this->emit('connect.after.all', array($connections, $writes));

        if ($autorun) {
            $this->getLoop()->run();
        }
    }
666585
public function getLocalBehatConfig() {
    $behat_local_config_file = $this->getConfigValue('repo.root') . '/tests/behat/local.yml';

    $behat_local_config = new BltConfig();
    $loader = new YamlConfigLoader();
    $processor = new YamlConfigProcessor();
    $processor->extend($loader->load($behat_local_config_file));
    $processor->extend($loader->load($this->getConfigValue('repo.root') . '/tests/behat/behat.yml'));
    $behat_local_config->import($processor->export());

    return $behat_local_config;
  }
285342
public function build(array $items, $currentUri)
    {
        foreach ($items as $item) {
            if ($item->isDivider()) {
                continue;
            }

            $this->buildItem($item, $currentUri);
        }

        return $items;
    }
1057931
def set_parallelism(self, num_instances):
        
        assert (num_instances > 0)
        self.env._set_parallelism(self.src_operator_id, num_instances)
        return self
598418
def add_cores_to_config(args, cores_per_job, parallel=None):
    
    def _update_cores(config):
        config["algorithm"]["num_cores"] = int(cores_per_job)
        if parallel:
            parallel.pop("view", None)
            config["parallel"] = parallel
        return config
    return _update_config(args, _update_cores)
324811
private function runStep(
        string $name,
        array $step,
        array $conditions,
        array $metDependencies,
        array $stepArguments
    ): array {

        // If array, run commands in parallel
        if (!empty($step['steps'])) {
            $providedDependencies = [];
            foreach ($step['steps'] as $parallelName => $parallelStep) {
                Loop::delay(
                    0,
                    // Since these are run in parallel, they cannot provide dependencies for each other
                    function () use (
                        $parallelName,
                        $parallelStep,
                        $conditions,
                        $metDependencies,
                        $stepArguments,
                        &
                        $providedDependencies
                    ) {
                        $stepProvidedDependencies = $this->runStep(
                            $parallelName,
                            $parallelStep,
                            $conditions,
                            $metDependencies,
                            $stepArguments
                        );
                        $providedDependencies = array_unique(
                            array_merge($providedDependencies, $stepProvidedDependencies)
                        );
                    }
                );
            }

            Loop::run();
            return $providedDependencies;
        }

        if (!empty($step['conditions'])) {
            if (!array_intersect($conditions, $step['conditions'])) {
                $this->logger->debug(
                    sprintf(
                        'Step: %s - skipped because run %s [%s] not met.',
                        $name,
                        (1 == count($step['conditions'])) ? 'condition' : 'conditions',
                        implode(', ', $step['conditions'])
                    )
                );
                return [];
            }
        }

        if (!empty($step['depends'])) {
            $allDependenciesMet = count(array_intersect($metDependencies, $step['depends'])) == count($step['depends']);
            if (!$allDependenciesMet) {
                $this->logger->debug(
                    sprintf(
                        'Step: %s - skipped because %s [%s] not deployed.',
                        $name,
                        (1 == count($step['depends'])) ? 'dependency' : 'dependencies',
                        implode(', ', $step['depends'])
                    )
                );
                return [];
            }
        }

        $this->logger->info("Step: $name");
        if (!empty($step['comment'])) {
            $this->logger->debug($step['comment']);
        }
        # @todo Add logic that logs a notice if run_in_code_root is specified for a given step, but class is given instead of command
        $commandWorkingDirectory = !empty($step['run_in_code_root'])
            ? $stepArguments['codePath']
            : $this->planPath;

        if (!empty($step['command'])) {
            $environmentVariables = array_replace(
                getenv(),
                $stepArguments,
                $step['environment_variables'] ?? []
            );

            $stringEnvironmentVariables = [];
            foreach ($environmentVariables as $key => $value) {
                if (is_string($value)) {
                    $stringEnvironmentVariables[$key] = $value;
                }
            }

            $output = $this->shellAdapter->runShellCommand(
                $step['command'],
                $commandWorkingDirectory,
                $stringEnvironmentVariables,
                $step['run_priority'] ?? ShellAdapterInterface::PRIORITY_NORMAL,
                $step['options'] ?? null
            );

            // @todo Allow callable? Not sure where this could be more useful than creating a class that implements the
            //       correct interface and this could cause confusion
//        } elseif (!empty($step['callable'])) {
//            chdir($commandWorkingDirectory);
//            $output = call_user_func_array($step['callable'], $step['arguments'] ?? []);
        } else {
            chdir($commandWorkingDirectory);
            $stepObject = new $step['class']();
            if ($stepObject instanceof LoggerAwareInterface) {
                $stepObject->setLogger($this->logger);
            }

            if ($stepObject instanceof ApplicationConfigAwareInterface) {
                $stepObject->setApplicationConfig($this->applicationConfig);
            }

            if ($stepObject instanceof RepositoryAdapterAwareInterface) {
                $stepObject->setRepositoryAdapter($this->repositoryAdapter);
            }

            if ($stepObject instanceof ShellAdapterAwareInterface) {
                $stepObject->setShellAdapter($this->shellAdapter);
            }

            if ($stepObject instanceof MountManagerAwareInterface) {
                $stepObject->setMountManager($this->mountManager);
            }

            if ($stepObject instanceof MaintenanceStrategyAwareInterface) {
                $stepObject->setMaintenanceStrategy($this->maintenanceStrategy);
            }

            if ($stepObject instanceof DatabaseAdapterManagerAwareInterface) {
                $stepObject->setDatabaseAdapterManager($this->databaseAdapterManager);
            }

            if ($stepObject instanceof DatabaseImportExportAdapterManagerAwareInterface) {
                $stepObject->setDatabaseImportExportAdapterManager($this->databaseImportExportAdapterManager);
            }

            if ($stepObject instanceof ApplicationSkeletonDeployerAwareInterface) {
                $stepObject->setApplicationSkeletonDeployer($this->applicationSkeletonDeployer);
            }

            if ($stepObject instanceof ApplicationCodeDeployerAwareInterface) {
                $stepObject->setApplicationCodeDeployer($this->applicationCodeDeployer);
            }

            if ($stepObject instanceof ApplicationAssetDeployerAwareInterface) {
                $stepObject->setApplicationAssetDeployer($this->applicationAssetDeployer);
            }

            if ($stepObject instanceof ApplicationDatabaseDeployerAwareInterface) {
                $stepObject->setApplicationDatabaseDeployer($this->applicationDatabaseDeployer);
            }

            $output = call_user_func_array(
                [$stepObject, 'run'],
                array_merge($stepArguments, ['options' => $step['options'] ?? []])
            );
        }

        if (!empty($output)) {
            $output = trim($output);
            // If output is multi-line, start the output on a new line
            if (false !== strpos($output, "\n")) {
                $output = "\n$output";
            }
            $this->logger->debug('Step "' . $name . '" output: ' . $output);
        }

        return $step['provides'] ?? [];
    }
417068
public static function CurrentConfig() {
        if(empty(self::$_currentConfig)) {
            self::$_currentConfig=CodeBankConfig::get()->first();
        }
        
        return self::$_currentConfig;
    }