text:
// Copyright 2014 The Bazel Authors. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//    http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package com.google.devtools.build.lib.analysis.configuredtargets;

import com.google.common.base.Joiner;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Interner;
import com.google.devtools.build.lib.actions.ActionAnalysisMetadata;
import com.google.devtools.build.lib.actions.Artifact;
import com.google.devtools.build.lib.analysis.FileProvider;
import com.google.devtools.build.lib.analysis.FilesToRunProvider;
import com.google.devtools.build.lib.analysis.RuleContext;
import com.google.devtools.build.lib.analysis.RunfilesProvider;
import com.google.devtools.build.lib.analysis.TransitiveInfoProvider;
import com.google.devtools.build.lib.analysis.TransitiveInfoProviderMap;
import com.google.devtools.build.lib.analysis.TransitiveInfoProviderMapBuilder;
import com.google.devtools.build.lib.analysis.Util;
import com.google.devtools.build.lib.analysis.config.ConfigMatchingProvider;
import com.google.devtools.build.lib.analysis.config.RunUnder;
import com.google.devtools.build.lib.analysis.starlark.StarlarkApiProvider;
import com.google.devtools.build.lib.cmdline.Label;
import com.google.devtools.build.lib.collect.nestedset.NestedSet;
import com.google.devtools.build.lib.concurrent.BlazeInterners;
import com.google.devtools.build.lib.concurrent.ThreadSafety.Immutable;
import com.google.devtools.build.lib.packages.Info;
import com.google.devtools.build.lib.packages.OutputFile;
import com.google.devtools.build.lib.packages.PackageSpecification.PackageGroupContents;
import com.google.devtools.build.lib.packages.Provider;
import com.google.devtools.build.lib.skyframe.BuildConfigurationValue;
import com.google.devtools.build.lib.skyframe.ConfiguredTargetKey;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec.Instantiator;
import com.google.devtools.build.lib.skyframe.serialization.autocodec.AutoCodec.VisibleForSerialization;
import com.google.devtools.build.lib.starlarkbuildapi.ActionApi;
import java.util.function.Consumer;
import javax.annotation.Nullable;
import net.starlark.java.eval.Printer;
import net.starlark.java.eval.Starlark;

/**
 * A {@link com.google.devtools.build.lib.analysis.ConfiguredTarget} that is produced by a rule.
 *
 * <p>Created by {@link com.google.devtools.build.lib.analysis.RuleConfiguredTargetBuilder}. There
 * is an instance of this class for every analyzed rule. For more information about how analysis
 * works, see {@link com.google.devtools.build.lib.analysis.RuleConfiguredTargetFactory}.
 */
@AutoCodec(checkClassExplicitlyAllowed = true)
@Immutable
public final class RuleConfiguredTarget extends AbstractConfiguredTarget {

  /** A set of this target's implicitDeps. */
  private final ImmutableSet<ConfiguredTargetKey> implicitDeps;

  /*
   * An interner for the implicitDeps set. {@link Util.findImplicitDeps} is called upon every
   * construction of a RuleConfiguredTarget and we expect many of these targets to contain the same
   * set of implicit deps so this reduces the memory load per build.
   */
  private static final Interner<ImmutableSet<ConfiguredTargetKey>> IMPLICIT_DEPS_INTERNER =
      BlazeInterners.newWeakInterner();

  private final TransitiveInfoProviderMap providers;
  private final ImmutableMap<Label, ConfigMatchingProvider> configConditions;
  private final String ruleClassString;
  private final ImmutableList<ActionAnalysisMetadata> actions;
  // TODO(b/133160730): can we only populate this map for outputs that have labels?
  private final ImmutableMap<Label, Artifact> artifactsByOutputLabel;

  @Instantiator
  @VisibleForSerialization
  RuleConfiguredTarget(
      Label label,
      BuildConfigurationValue.Key configurationKey,
      NestedSet<PackageGroupContents> visibility,
      TransitiveInfoProviderMap providers,
      ImmutableMap<Label, ConfigMatchingProvider> configConditions,
      ImmutableSet<ConfiguredTargetKey> implicitDeps,
      String ruleClassString,
      ImmutableList<ActionAnalysisMetadata> actions,
      ImmutableMap<Label, Artifact> artifactsByOutputLabel) {
    super(label, configurationKey, visibility);
    this.artifactsByOutputLabel = artifactsByOutputLabel;

    // We don't use ImmutableMap.Builder here to allow augmenting the initial list of 'default'
    // providers by passing them in.
    TransitiveInfoProviderMapBuilder providerBuilder =
        new TransitiveInfoProviderMapBuilder().addAll(providers);
    Preconditions.checkState(providerBuilder.contains(RunfilesProvider.class), label);
    Preconditions.checkState(providerBuilder.contains(FileProvider.class), label);
    Preconditions.checkState(providerBuilder.contains(FilesToRunProvider.class), label);

    // Initialize every StarlarkApiProvider
    for (int i = 0; i < providers.getProviderCount(); i++) {
      Object obj = providers.getProviderInstanceAt(i);
      if (obj instanceof StarlarkApiProvider) {
        ((StarlarkApiProvider) obj).init(this);
      }
    }

    this.providers = providerBuilder.build();
    this.configConditions = configConditions;
    this.implicitDeps = IMPLICIT_DEPS_INTERNER.intern(implicitDeps);
    this.ruleClassString = ruleClassString;
    this.actions = actions;
  }

  public RuleConfiguredTarget(
      RuleContext ruleContext,
      TransitiveInfoProviderMap providers,
      ImmutableList<ActionAnalysisMetadata> actions,
      ImmutableMap<Label, Artifact> artifactsByOutputLabel) {
    this(
        ruleContext.getLabel(),
        ruleContext.getConfigurationKey(),
        ruleContext.getVisibility(),
        providers,
        ruleContext.getConfigConditions(),
        Util.findImplicitDeps(ruleContext),
        ruleContext.getRule().getRuleClass(),
        actions,
        artifactsByOutputLabel);

    // If this rule is the run_under target, then check that we have an executable; note that
    // run_under is only set in the target configuration, and the target must also be analyzed for
    // the target configuration.
    RunUnder runUnder = ruleContext.getConfiguration().getRunUnder();
    if (runUnder != null && getLabel().equals(runUnder.getLabel())) {
      if (getProvider(FilesToRunProvider.class).getExecutable() == null) {
        ruleContext.ruleError("run_under target " + runUnder.getLabel() + " is not executable");
      }
    }

    // Make sure that all declared output files are also created as artifacts. The
    // CachingAnalysisEnvironment makes sure that they all have generating actions.
    if (!ruleContext.hasErrors()) {
      for (OutputFile out : ruleContext.getRule().getOutputFiles()) {
        ruleContext.createOutputArtifact(out);
      }
    }
  }

  /**
   * The configuration conditions that trigger this rule's configurable attributes.
   */
  public ImmutableMap<Label, ConfigMatchingProvider> getConfigConditions() {
    return configConditions;
  }

  public ImmutableSet<ConfiguredTargetKey> getImplicitDeps() {
    return implicitDeps;
  }

  @Override
  public String getRuleClassString() {
    return ruleClassString;
  }

  @Nullable
  @Override
  public <P extends TransitiveInfoProvider> P getProvider(Class<P> providerClass) {
    // TODO(bazel-team): Should aspects be allowed to override providers on the configured target
    // class?
    return providers.getProvider(providerClass);
  }

  @Override
  public String getErrorMessageForUnknownField(String name) {
    return Starlark.format(
        "%r (rule '%s') doesn't have provider '%s'", this, getRuleClassString(), name);
  }

  @Override
  protected void addExtraStarlarkKeys(Consumer<String> result) {
    for (int i = 0; i < providers.getProviderCount(); i++) {
      Object classAt = providers.getProviderKeyAt(i);
      if (classAt instanceof String) {
        result.accept((String) classAt);
      }
    }
    result.accept(ACTIONS_FIELD_NAME);
  }

  @Override
  protected Info rawGetStarlarkProvider(Provider.Key providerKey) {
    return providers.get(providerKey);
  }

  @Override
  protected Object rawGetStarlarkProvider(String providerKey) {
    if (providerKey.equals(ACTIONS_FIELD_NAME)) {
      // Only expose actions which are legitimate Starlark values, otherwise they will later
      // cause a Bazel crash.
      // TODO(cparsons): Expose all actions to Starlark.
      return actions.stream()
          .filter(action -> action instanceof ActionApi)
          .collect(ImmutableList.toImmutableList());
    }
    return providers.get(providerKey);
  }

  @Override
  public void repr(Printer printer) {
    printer.append("<target " + getLabel() + ">");
  }

  @Override
  public void debugPrint(Printer printer) {
    // Show the names of the provider keys that this target propagates.
    // Provider key names might potentially be *private* information, and thus a comprehensive
    // list of provider keys should not be exposed in any way other than for debug information.
    printer.append("<target " + getLabel() + ", keys:[");
    ImmutableList.Builder<String> starlarkProviderKeyStrings = ImmutableList.builder();
    for (int providerIndex = 0; providerIndex < providers.getProviderCount(); providerIndex++) {
      Object providerKey = providers.getProviderKeyAt(providerIndex);
      if (providerKey instanceof Provider.Key) {
        starlarkProviderKeyStrings.add(providerKey.toString());
      }
    }
    printer.append(Joiner.on(", ").join(starlarkProviderKeyStrings.build()));
    printer.append("]>");
  }

  /** Returns a list of actions that this configured target generated. */
  public ImmutableList<ActionAnalysisMetadata> getActions() {
    return actions;
  }

  /**
   * Provide an artifact by its corresponding output label, for use by output file configured
   * targets.
   */
  public Artifact getArtifactByOutputLabel(Label outputLabel) {
    return Preconditions.checkNotNull(
        artifactsByOutputLabel.get(outputLabel),
        "%s %s %s",
        outputLabel,
        this,
        this.artifactsByOutputLabel);
  }
}


text:
using CRTG.Common.Attributes;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using CRTG.Common.Data;
using CRTG.Common;

namespace CRTG.Actions.ConditionLibrary
{
    public class ThresholdCondition : BaseCondition
    {
        [AutoUI(Group ="Error Threshold")]
        public decimal? HighError { get; set; }
        [AutoUI(Group = "Error Threshold")]
        public string ErrorMessage { get; set; }
        [AutoUI(Group = "Error Threshold")]
        public decimal? LowError { get; set; }

        [AutoUI(Group = "Warning Threshold")]
        public decimal? HighWarning { get; set; }
        [AutoUI(Group = "Warning Threshold")]
        public string WarningMessage { get; set; }
        [AutoUI(Group = "Warning Threshold")]
        public decimal? LowWarning { get; set; }

        private ErrorState CurrentState { get; set; }

        public override void TestCondition(SensorCollectEventArgs args)
        {
            // Determine the state we are in
            ErrorState newState = ErrorState.Normal;
            if (args.Data == null) {
                newState = ErrorState.Exception;
            } else {
                if (args.Data.Value < LowError) {
                    newState = ErrorState.ErrorLow;
                } else if (args.Data.Value > HighError) {
                    newState = ErrorState.ErrorHigh;
                } else if (args.Data.Value < LowWarning) {
                    newState = ErrorState.WarningLow;
                } else if (args.Data.Value > HighWarning) {
                    newState = ErrorState.WarningHigh;
                } else {
                    newState = ErrorState.Normal;
                }
            }

            // If the state has changed, notify
            if (newState != CurrentState) {
                args.ConditionMessage = String.Format("{0}: {1} is now {2}", newState, Sensor.Name, args.Data.Value);
                TriggerActions(args);
            }
            CurrentState = newState;
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
"""
WSGI middleware for OpenStack Volume API.
"""

import nova.api.openstack
from nova.api.openstack.volume import extensions
from nova.api.openstack.volume import snapshots
from nova.api.openstack.volume import types
from nova.api.openstack.volume import volumes
from nova.api.openstack.volume import versions
from nova import log as logging

LOG = logging.getLogger(__name__)

class APIRouter(nova.api.openstack.APIRouter):
    """
    Routes requests on the OpenStack API to the appropriate controller
    and method.
    """
    ExtensionManager = extensions.ExtensionManager

    def _setup_routes(self, mapper):
        self.resources['versions'] = versions.create_resource()
        mapper.connect("versions", "/",
                    controller=self.resources['versions'],
                    action='show')

        mapper.redirect("", "/")

        self.resources['volumes'] = volumes.create_resource()
        mapper.resource("volume", "volumes",
                        controller=self.resources['volumes'],
                        collection={'detail': 'GET'})

        self.resources['types'] = types.create_resource()
        mapper.resource("type", "types",
                        controller=self.resources['types'])

        self.resources['snapshots'] = snapshots.create_resource()
        mapper.resource("snapshot", "snapshots",
                        controller=self.resources['snapshots'])


text:
package com.google.code.guice.repository.spi;

import com.google.inject.MembersInjector;

import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceUnit;
import java.lang.reflect.Field;

/**
 * EntityManagerFactory injector for fields, annotated with {@link PersistenceUnit} with {@link
 * PersistenceUnit#unitName()}:
 * <pre>
 *    {@literal @}PersistenceUnit(unitName="persistence-unit1")
 *     private EntityManagerFactory entityManagerFactory;
 * </pre>
 *
 * @author Alexey Krylov
 * @since 08.12.12
 */
public class EntityManagerFactoryMembersInjector<T> implements MembersInjector<T> {

	/*===========================================[ INSTANCE VARIABLES ]===========*/

    private Field field;
    private EntityManagerFactory entityManagerFactory;

	/*===========================================[ CONSTRUCTORS ]=================*/

    protected EntityManagerFactoryMembersInjector(Field field, EntityManagerFactory entityManagerFactory) {
        this.field = field;
        this.entityManagerFactory = entityManagerFactory;
        field.setAccessible(true);
    }

	/*===========================================[ INTERFACE METHODS ]============*/

    @Override
    public void injectMembers(T instance) {
        try {
            field.set(instance, entityManagerFactory);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}


text:
package org.scijava.module;

/**
 * An exception thrown when something goes wrong with a module.
 *
 * @author Curtis Rueden
 */
public class ModuleException extends Exception {

	public ModuleException() {
		super();
	}

	public ModuleException(final String s) {
		super(s);
	}

	public ModuleException(final String s, final Throwable cause) {
		super(s, cause);
	}

	public ModuleException(final Throwable cause) {
		super(cause);
	}

}


text:
package workbench.sql.wbcommands;

import java.util.regex.PatternSyntaxException;
import workbench.db.exporter.RegexReplacingModifier;
import workbench.log.LogMgr;
import workbench.util.ArgumentParser;
import workbench.util.StringUtil;

/**
 *
 * @author Thomas Kellerer
 */
public class RegexModifierParameter
{

	public static final String ARG_REPLACE_REGEX = "replaceExpression";
	public static final String ARG_REPLACE_WITH = "replaceWith";

	public static void addArguments(ArgumentParser cmdLine)
	{
		cmdLine.addArgument(ARG_REPLACE_WITH);
		cmdLine.addArgument(ARG_REPLACE_REGEX);
	}

	public static RegexReplacingModifier buildFromCommandline(ArgumentParser cmdLine)
	{
		String regex = cmdLine.getValue(ARG_REPLACE_REGEX);
		String replacement = cmdLine.getValue(ARG_REPLACE_WITH);

		if (StringUtil.isNonBlank(regex) && replacement != null)
		{
			try
			{
				RegexReplacingModifier modifier = new RegexReplacingModifier(regex, replacement);
				return modifier;
			}
			catch (PatternSyntaxException ex)
			{
				LogMgr.logError("RegexModifierParameter.parseParameterValue()", "Could not create modifier", ex);
			}
		}
		return null;
	}

}


text:
class MonoRuntime {
public:
    static bool IsLoaded() {
        return isLoaded_;
    }
    static void Load(std::string assemblyDir, std::string configDir,
        std::string traceLevel, std::string file);
    static void Unload();
private:
    static bool isLoaded_;
};


text:
Images in this folder will not be added to source control.

Unit Tests can write images to this folder for quick viewing.

If you want to permanently add images for Kumo to showcase, add them to `kumo-core/output/`.

The point of this directory is to encourage more unit tests without resulting in all new images to be checked into source control, but we want the images to be easy to view within IntelliJ.


text:
package com.cinchapi.concourse.server.plugin.data;

import java.nio.ByteBuffer;

import io.atomix.catalyst.buffer.Buffer;

import com.cinchapi.concourse.thrift.TObject;
import com.cinchapi.concourse.thrift.Type;

/**
 * A {@link ResultDataset} that uses {@link TObject TObjects} for values.
 *
 * @author Jeff Nelson
 */
public class TObjectResultDataset extends ResultDataset<TObject> {

    /**
     * Return a {@link TObjectResultDataset} that wraps the original
     * {@code dataset}
     *
     * @param dataset the {@link ObjectResultDataset} to wrap
     * @return the wrapped dataset
     */
    public static TObjectResultDataset wrap(ObjectResultDataset dataset) {
        return (TObjectResultDataset) dataset.thrift;
    }

    @Override
    protected TObject deserializeValue(Buffer buffer) {
        Type type = Type.values()[buffer.readByte()];
        int length = buffer.readInt();
        byte[] data = new byte[length];
        buffer.read(data);
        return new TObject(ByteBuffer.wrap(data), type);
    }

    @Override
    protected void serializeValue(TObject value, Buffer buffer) {
        buffer.writeByte(value.getType().ordinal());
        byte[] data = value.getData();
        buffer.writeInt(data.length);
        buffer.write(data);
    }

}


text:
/*
* Author   Jonathan Lurie - http://me.jonathanlurie.fr
* License  MIT
* Link      https://github.com/Pixpipe/pixpipejs
* Lab       MCIN - Montreal Neurological Institute
*/

import { PixpipeObject } from '../core/PixpipeObject.js';
import { Image2D } from '../core/Image2D.js';
import { ColorScales } from './ColorScales.js';

/**
* A Colormap instance is a range of color and can be used in two ways. The first,
* is by getting a single color using `.getValueAt(p)` where `p` is a position in [0, 1] and, second,
* by building en entire LUT with a given granularity and then getting back these values.
* In case of intensive use (ie. applying fake colors), building a LUT is a faster option.
* Once a LUT is built,  an image of this LUT can be created (horizontal or vertical, flipped or not).
* The image will be flipped is the `flip` matadata is set to `true`;
* This image, which is an Image2D is not supposed to be used as a LUT but just as a visual reference.
*
* **Usage**
* - [examples/colormap.html](../examples/colormap.html)
*
*/
class Colormap extends PixpipeObject {

  /**
  * Build a colormap with some options.
  * @param {Object} options - here is the list of options:
  *     style {String} - one of the available styles (see property names in ColorScales.js)
  *     description {Object} - colormap description like in ColorScales.js. Can also be the equivalent JSON string.
  *     lutSize {Number} - Number of samples to pregenerate a LUT
  *     Note: "style" and "description" are mutually exclusive and "style" has the priority in case both are set.
  */
  constructor( options = {} ) {
    super();
    this._type = Colormap.TYPE();
    this._colormapDescription = null;
    this._LUT = [];
    this.setMetadata("flip", false);

    var style = this._getOption(options, "style", null);

    if( style ){
      this.setStyle( style );
    }else {
      var description = this._getOption(options, "description", null);
      this.setDescription( description );
    }

    if( this._colormapDescription ){
      var lutSize = this._getOption(options, "lutSize", null);
      if( lutSize ){
        this.buildLut( lutSize );
      }
    }

  }

  /**
  * Hardcode the datatype
  */
  static TYPE(){
    return "COLORMAP";
  }

  /**
  * [STATIC]
  * Get all the style id available
  * @return {Array} all the styles
  */
  static getAvailableStyles(){
    return Object.keys(ColorScales)
  }

  /**
  * Define the style of the colormap
  * @param {String} style - the colormap style. They are all listed with `Colormap.getAvailableStyles()`
  */
  setStyle( style ){
    if(style in ColorScales){
      if( this._validateDescription( ColorScales[ style ] ) ){
        this._colormapDescription = JSON.parse(JSON.stringify( ColorScales[ style ] ));
      }
    }else {
      console.warn("The given colormap style des not exist.");
    }
  }

  /**
  * Set the description of the colormap. See ColorScales.js for the format
  * @param {Object} d - description, can be the equivalent JSON string
  */
  setDescription( d ){
    // the description in argument can be a json string
    var description = typeof d === "string" ? JSON.parse( d ) : d;

    if(description && this._validateDescription(description) ){
      this._colormapDescription = description;
    }
  }

  /**
  * @private
  * Validates a colormap description integrity.
  * @return {Boolean} true is the description is valid, false if not
  */
  _validateDescription( d ){
    if( ! Array.isArray(d) ){
      console.warn("The colormap description has to be an Array");
      return false;
    }

    for(var i=0; i<d.length; i++){
      // each color segment is an object containing a position as 'index'
      // and an array of number as "rgb"

      // each is a non-null object
      if( d[i] !== null && typeof d[i] === 'object' ){
        if( "index" in d[i] && "rgb" in d[i]){
          if(typeof d[i].index === 'number'){
            if( d[i].index < 0 || d[i].index >1 ){
              console.warn("Each colormap segment 'index' property should be in [0, 1]");
              return false;
            }
          }else{
            console.warn("Each colormap segment 'index' property should be a number.");
            return false;
          }

          // the rgb property has to be an array
          if( Array.isArray( d[i].rgb ) ){
            if(d[i].rgb.length == 3){
              for(var j=0; j<d[i].rgb.length; j++){
                if( d[i].rgb[j] < 0 || d[i].rgb[j] > 255 ){
                  console.warn("The colormap must have only values in [0, 255]");
                  return false;
                }
              }
            }else{
              console.warn("Each colormap segment 'rgb' should contain 3 values");
              return false;
            }
          }
        }else{
          console.warn("Each colormap segment must have a 'index' property and a 'rgb' property.");
          return false;
        }
      }else{
        console.warn("Each colormap segment must be a non-null object");
        return false;
      }
    }
    return true;
  }

  /**
  * Get the color at the colormap position
  * @param {Number} position - position within the colormap in [0, 1]
  * @return {Array} color array as [r, g, b] , values being in [0, 255]
  */
  getValueAt( position ){
    if( !this._colormapDescription ){
      console.warn("The colormap description is not defined.");
      return null;
    }

    if( this._metadata.flip )
      position = 1 - position;

    // case 1: before the first "index" position
    if(position <= this._colormapDescription[0].index){
      return this._colormapDescription[0].rgb.slice()
    }

    // case 2: after the last "index" position
    if(position >= this._colormapDescription[this._colormapDescription.length - 1].index){
      return this._colormapDescription[this._colormapDescription.length - 1].rgb.slice()
    }

    // case 3: between 2 values of the descrition (most likely to happen)
    for(var i=0; i<this._colormapDescription.length-1; i++){
      if( position >= this._colormapDescription[i].index && position < this._colormapDescription[i+1].index ){

        var unitDistanceToFirst = (position - this._colormapDescription[i].index) / (this._colormapDescription[i+1].index -  this._colormapDescription[i].index);
        var unitDistanceToSecond = 1 - unitDistanceToFirst;

        var color = [
          Math.round(this._colormapDescription[i].rgb[0] * unitDistanceToSecond + this._colormapDescription[i+1].rgb[0] * unitDistanceToFirst), // R
          Math.round(this._colormapDescription[i].rgb[1] * unitDistanceToSecond + this._colormapDescription[i+1].rgb[1] * unitDistanceToFirst), // G
          Math.round(this._colormapDescription[i].rgb[2] * unitDistanceToSecond + this._colormapDescription[i+1].rgb[2] * unitDistanceToFirst), // B
        ]

        return color;
      }
    }
  }

  /**
   * Get an interpolated value of a colormap but using a certain amount of color clustering
   * @param  {Number} position - normalized position on the color spectrum, from 0 to 1
   * @param  {Number} clusters - Number of clusters
   * @return {Array} A color [r, g, b]
   */
  getValueAtWithClusters( position, clusters ){
    var custeredPosition = ( (Math.floor(position * clusters) + 0.5) / clusters );
    return this.getValueAt( custeredPosition );
  }

  /**
  * Build a LUT from the colormap description
  * @param {Number} size - number of samples in the LUT
  */
  buildLut( size=Math.pow(2, 16) ){
    if( !this._colormapDescription ){
      console.warn("The colormap description is not defined, the LUT cannot be created");
      return null;
    }

    if( size < 0 ){
      console.warn("Size of the colormap can not be negative.");
      return;
    }

    this._LUT = new Array( size );

    for(var i=0; i<size; i++){
      this._LUT[i] = this.getValueAt( i/size  + 0.5/size );
    }
  }

  /**
  * Get the color within the internal LUT
  * @param {Number} index - the index in the LUT
  * @return {Array} color array as [r, g, b] , values being in [0, 255]
  */
  getLutAt( index ){
    if( index <0 || index > this._LUT.length )
      return null;

    return this._LUT[ index ];
  }

  getLutAtNormalized( position ){
    var index = -1;

    if( position < 0 ){
      index = 0
    }else if( position < this._LUT.length  ){
      index = Math.floor( position * (this._LUT.length - 1) )
    }else{
      index = this._LUT.length - 1
    }

    return this._LUT[ index ];
  }

  /**
  * Creates a horizontal RGB Image2D of the colormap. The height is 1px and
  * the width is the size of the LUT currently in use.
  * A RGBA image can be created when passing the argument `forceRGBA` to `true`.
  * In this case, the alpha channel is `255`.
  * The image can be horizontally flipped when the "flip" metadata is true
  * @param {Boolean} forceRGBA - forces the creation of a RGBA image instead of a RGB image
  * @return {Image2D} the result image
  */
  createHorizontalLutImage( forceRGBA=false ){
    if(! this._LUT ){
      console.warn("The LUT must be built before creating a LUT image.");
      return;
    }

    var initColor = forceRGBA ? [0, 0, 0, 255] : [0, 0, 0];
    var LutSize = this._LUT.length;
    var colorStrip = new Image2D({width: LutSize, height: 1 , color: initColor});

    for(var i=0; i<LutSize; i++){
      colorStrip.setPixel( {x: i, y: 0},  this._LUT[ i ] );
    }

    return colorStrip;
  }

  /**
  * Creates a vertical RGB Image2D of the colormap. The height is 1px and
  * the width is the size of the LUT currently in use.
  * The image can be vertically flipped when the "flip" metadata is true
  * @param {Boolean} forceRGBA - forces the creation of a RGBA image instead of a RGB image
  * @return {Image2D} the result image
  */
  createVerticalLutImage( forceRGBA=false ){
    if(! this._LUT ){
      console.warn("The LUT must be built before creating a LUT image.");
      return;
    }

    var initColor = forceRGBA ? [0, 0, 0, 255] : [0, 0, 0];
    var LutSize = this._LUT.length;
    var colorStrip = new Image2D({width: 1, height: LutSize, color: initColor});

    for(var i=0; i<LutSize; i++){
      colorStrip.setPixel( {x: 0, y: i},  this._LUT[ i ] );
    }

    return colorStrip;
  }

  /**
  * Add a color to the color description. This color must be at a non-taken index
  * @param {Number} index - index to place the color, must be in [0, 1]
  * @param {Array} rgb - rgb array of the form [r, g, b], each value being in [0, 255]
  * @return {Boolean} true if the color was succesfully added, false if not
  */
  addColor( index, rgb ){
    // the colormap is possibly empty
    if( !this._colormapDescription ){
      this._colormapDescription = [];
    }

    if(index<0 || index>1){
      console.warn("The color cannot be added because its index is out of range [0, 1]");
      return false;
    }

    // checking if a color is already present at the given index
    var indexAlreadyPresent = this._colormapDescription.find(function(indexAndColor){
      return indexAndColor.index == index;
    })

    if( indexAlreadyPresent ){
      console.warn("A color is already present at index " + index);
      return false;
    }

    if( rgb && Array.isArray(rgb) && rgb.length == 3){
      for(var i=0; i<rgb.length; i++){
        if(typeof rgb[i] !== 'number' || rgb[i] < 0  || rgb[i] > 255){
          console.warn("The rgb colors must be in [0, 255]");
          return false;
        }
      }
    }else{
      console.warn("The color cannot be added because its rgb array is the wrong size.");
      return false;
    }

    // data integrity is ok
    this._colormapDescription.push({"index":index,"rgb":rgb.slice()})
    this._colormapDescription.sort(function(a, b) {
      return a.index - b.index;
    });

    return true;
  }

  /**
  * Remove the color at the given index
  * @param {Number} index - the [0, 1] index of the color to remove
  * @return {Boolean} true if successfully remove, false if not
  */
  removeColor( index ){
    if( !this._colormapDescription ){
      console.warn("The colormap description is empty.");
      return false;
    }

    var indexAlreadyIn = this._colormapDescription.findIndex(function(element){
      return (element.index == index);
    })

    if( indexAlreadyIn == -1 ){
      console.warn("Such index does not exist.");
      return false;
    }

    this._colormapDescription.splice(indexAlreadyIn, 1);
    return true;
  }

  /**
  * Get a json version of the colormap description
  * @return {String} the json string
  */
  toJson(){
    return JSON.stringify(this._colormapDescription);
  }

} /* END of class Colormap */

export { Colormap }


text:
require 'fileutils'

module XcodeTrashRemover
  module SizeHelper
    module_function

    def dir_size(dir_path)
      dir_path << '/' unless dir_path.end_with?('/')
      total_size = 0
      if File.directory?(dir_path)
        Dir["#{dir_path}**/*"].each do |f|
          total_size += File.size(f) if File.file?(f) && File.size?(f)
        end
      end
      total_size
    end
  end
end


text:
export const swal = require('../dist/sweetalert.min');

export const $ = require('jquery');

export const removeSwal = () => $('.swal-overlay').remove();

export const $$ = (className) => $(`.${className}`);

export { CLASS_NAMES } from '../src/modules/class-list';

export const delay = (ms) => {
  return new Promise(resolve => setTimeout(resolve, ms));
}


text:
.profile-picture{
    width: 200px;
    height: 200px;
    padding: 0;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
    -webkit-animation: pulse 2s linear;
    -webkit-animation-iteration-count: infinite;
}

.wide {
    width: 100%;
    max-height: 100%;
}
.tall {
    max-width: 100%;
    height: 100%;
}

@-webkit-keyframes pulse {
    0% {-webkit-box-shadow: 0px 0px 20px blue;}
    50% {-webkit-box-shadow: 0px 0px 50px blue;}
    100% {-webkit-box-shadow: 0px 0px 20px blue;}
}

.form-group{
    padding: 15px;
}

.post-prof-img{
    width: 100px;
    height: 100px;
    -webkit-border-radius: 100%;
    -moz-border-radius: 100%;
    border-radius: 100%;
    padding: 0;
}

.post-cont{
    height: 70%;
    padding: 2%;
    margin-left: 1%;
    overflow: hidden;
    text-align: justify;
    text-overflow: ellipsis;
    background-color: white;
    border: 1px groove blue;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
}

.blog-post{
    height: 200px;
}

.title-par{
    color: blue;
    border-bottom: 1px solid grey;
}

.hoverin-cont{
    cursor: pointer;
    background: skyblue;
    border: none;
}

.span-class {
    font-size: 220%;
}

.post-cont p{
    visibility: hidden;
    position: absolute;
    padding-left: 25%;
    padding-top: 10%;
    font-size: 220%;
    -webkit-animation: pulsating 2s linear;
    -webkit-animation-iteration-count: infinite;
    z-index: 1;
}

@-webkit-keyframes pulsating {
    0% {-webkit-transform: scale(0.8, 0.8);}
    50% {-webkit-transform: scale(1, 1);}
    100% {-webkit-transform: scale(0.8, 0.8);}
}

.resize-btn{
    width: 120px;
}

.resize-label-input{
    margin-top: 0.7%;
}

.resize-label-input div{
    padding: 0.5%;
}

.table-data-style{
    padding: 20px;
}

.admin-menu{
    position: relative;
}

.admin-menu ul{
    list-style: none;
}

.menu-head{
    background: darkgrey; /* For browsers that do not support gradients */
    background: -webkit-linear-gradient(90deg, white, orange); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(90deg, white, orange); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(90deg, white, orange); /* For Firefox 3.6 to 15 */
    background: linear-gradient(90deg, white, orange); /* Standard syntax */
    background-color: grey;
    width: 60%;
    -webkit-border-radius: 20px;
    -moz-border-radius: 20px;
    border-radius: 20px;
    margin: auto;
    margin-bottom: -5%;
}

.menu-head{
    cursor: pointer;
    font-family: Vijaya;
}

.menu-options{
    display: none;
    margin-left: 20%;
    /*display: none;*/
    font-family: Vijaya;
    width: 60%;
    padding: 1%;
}

.menu-options li{
    background: darkgrey; /* For browsers that do not support gradients */
    background: -webkit-linear-gradient(90deg, white, orange); /* For Safari 5.1 to 6.0 */
    background: -o-linear-gradient(90deg, white, orange); /* For Opera 11.1 to 12.0 */
    background: -moz-linear-gradient(90deg, white, orange); /* For Firefox 3.6 to 15 */
    background: linear-gradient(90deg, white, orange); /* Standard syntax */
    color: black;
    cursor: pointer;
    -webkit-border-radius: 20px;
    -moz-border-radius: 20px;
    border-radius: 20px;
    background-color: yellow;
    font-size: 140%;
    margin-top: 2%;
    padding-top: 5%;
}

#userMessages{
    background-color: lightcyan;
    max-height: 100%;
    overflow: auto;
}

#userMessages table thead td{
    font-weight: bold;
}

#userMessages table tr td{
    width: 33.3%;
}

.users-table{
    font-size: 130%;
    font-family: Verdana, sans-serif;
    font-weight: bold;
    line-height: 160%;
}

.users-table tr{
    border: 8px groove lightblue;
}

.users-table tr.data-row td{
    padding: 10px;
}

.users-table tr td{
    width: 25%;
    background: #cccccc;
}

.users-table tr td.view-profile-datacell{
    text-align: center;
}

.posts-info{
    padding: 0;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
    height: 150px;
}

.panel-body-class{
    height: 100px;
    overflow: auto;
}

.posts-info div{
    background: lightgrey;
    margin: 0;
    padding:0;
}

.table-posts{
    text-align: center;
    font-size: 120%;
    font-family: Verdana, sans-serif;
}

.table-posts tr td{
    padding: 2% 0 2% 0;
    border-bottom: 1px solid grey;
    width: 18%;
}

.post-author-info{
    margin-left: 15%;
    margin-top: 5%;
    font-size: 140%;
    font-weight: bold;
    color: white;
    background-color: lightseagreen;
    -webkit-border-radius: 10px;
    -moz-border-radius: 10px;
    border-radius: 10px;
    border: 1px solid lightskyblue;
}


text:
namespace VersionAttribute
{
    using System;

    [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface |
                    AttributeTargets.Enum | AttributeTargets.Method)]
    class VersionAttribute : Attribute
    {
        private string version;

        public VersionAttribute(string version)
        {
            this.Version = version;
        }

        public string Version
        {
            get
            {
                return this.version;
            }

            private set
            {
                this.version = value;
            }
        }

        public override string ToString()
        {
            return string.Format("Version: {0}", this.Version);
        }
    }
}


text:
These tests are for browsers, but the data for
`a-element.html`, `url-constructor.html`, `a-element-xhtml.xhtml`, and `failure.html`
is in `resources/urltestdata.json` and can be re-used by non-browser implementations.
This file contains a JSON array of comments as strings and test cases as objects.
The keys for each test case are:

* `base`: an absolute URL as a string whose [parsing] without a base of its own must succeed.
  This key is always present,
  and may have a value like `"about:blank"` when `input` is an absolute URL.
* `input`: an URL as a string to be [parsed][parsing] with `base` as its base URL.
* Either:
  * `failure` with the value `true`, indicating that parsing `input` should return failure,
  * or `href`, `origin`, `protocol`, `username`, `password`, `host`, `hostname`, `port`,
    `pathname`, `search`, and `hash` with string values;
    indicating that parsing `input` should return an URL record
    and that the getters of each corresponding attribute in that URL's [API]
    should return the corresponding value.

    The `origin` key may be missing.
    In that case, the API's `origin` attribute is not tested.

In addition to testing that parsing `input` against `base` gives the result, a test harness for the
`URL` constructor (or similar APIs) should additionally test the following pattern: if `failure` is
true, parsing `about:blank` against `input` must give failure. This tests that the logic for
converting base URLs into strings properly fails the whole parsing algorithm if the base URL cannot
be parsed.

## setters_tests.json

`resources/setters_tests.json` is self-documented.

## toascii.json

`resources/toascii.json` is a JSON resource containing an array where each item is an object
consisting of an optional `comment` field and mandatory `input` and `output` fields. `input` is the
domain to be parsed according to the rules of UTS #46 (as stipulated by the URL Standard). `output`
gives the expected output of the parser after serialization. An `output` of `null` means parsing is
expected to fail.

## URL parser's encoding argument

Tests in `/encoding` and `/html/infrastructure/urls/resolving-urls/query-encoding/` cover the
encoding argument to the URL parser.

## Specification

The tests in this directory assert conformance with [the URL Standard][URL].

[parsing]: https://url.spec.whatwg.org/#concept-basic-url-parser
[API]: https://url.spec.whatwg.org/#api
[URL]: https://url.spec.whatwg.org/


text:
//
//  RXJLRouterViewController.m
//  RXVerifyExample
//
//  Created by Rush.D.Xzj on 2019/2/13.
//  Copyright © 2019 Rush.D.Xzj. All rights reserved.
//

#import "RXJLRouterViewController.h"
#import "JLRoutes.h"
#import "RXLayoutViewController.h"
@interface RXJLRouterViewController ()

@end

@implementation RXJLRouterViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.

//    [self _test_global_scheme];

//    [self _test2];

    [self _test4];
}

- (void)_test4 {
    [[JLRoutes globalRoutes] addRoute:@"/ksad/log/:moudle/:level/:message" handler:^BOOL(NSDictionary *parameters) {
        NSString *object = parameters[@"object"];
        NSString *action = parameters[@"action"];
        NSString *primaryKey = parameters[@"primaryKey"];
        void(^block)(void) = parameters[@"block"];
        if (block != nil) {
            block();
        }
        // stuff
        return YES;
    }];
    __weak typeof(self) weakSelf = self;
    NSURL *editPost = [NSURL URLWithString:@"myapp://ksad/log/ui/debug/abc"];
    void(^customBlock)(void) = ^{
        NSLog(@"1111111111111:%@", weakSelf.view);
    };
    NSDictionary *dic = @{@"abc": @"bcd",
                          @"block": customBlock
    };
    [JLRoutes routeURL:editPost withParameters:dic];
}

- (void)_test3 {
    JLRoutes.globalRoutes[@"/user/view/:userID"] = ^BOOL(NSDictionary *parameters) {
      // ...
        NSLog(@"%@", parameters);
        return YES;
    };

    NSURL *viewUserURL = [NSURL URLWithString:@"myapp://user/view/joeldev"];
    [JLRoutes routeURL:viewUserURL];

}

- (void)_test2 {
    [[JLRoutes globalRoutes] addRoute:@"/:object/:action/:primaryKey" handler:^BOOL(NSDictionary *parameters) {
      NSString *object = parameters[@"object"];
      NSString *action = parameters[@"action"];
      NSString *primaryKey = parameters[@"primaryKey"];
      // stuff
      return YES;
    }];

    NSURL *editPost = [NSURL URLWithString:@"myapp://post/edit/123?debug=true&foo=bar"];
    [JLRoutes routeURL:editPost];
}

- (void)_test_global_scheme
{
    [[JLRoutes globalRoutes] addRoute:@"/:object/:action" handler:^BOOL(NSDictionary *parameters) {
        NSString *object = parameters[@"object"];
        NSString *action = parameters[@"action"];
        NSLog(@"object:%@ action:%@", object, action);
        // stuff
        return YES;
    }];

    NSURL *editPost = [NSURL URLWithString:@"xes://post/halfrost?debug=true&foo=bar"];
    [JLRoutes routeURL:editPost];

}
- (void)_test_custom_scheme
{
    [[JLRoutes routesForScheme:@"xes"] addRoute:@"/:object/:action" handler:^BOOL(NSDictionary *parameters) {
        NSString *object = parameters[@"object"];
        NSString *action = parameters[@"action"];

        NSLog(@"object:%@ action:%@", object, action);
        [self.navigationController pushViewController:[[RXLayoutViewController alloc] init] animated:YES];
        // stuff
        return YES;
    }];
    NSURL *editPost = [NSURL URLWithString:@"xes://post/halfrost?debug=true&foo=bar"];
    BOOL ok = [JLRoutes routeURL:editPost];

    NSLog(@"ok:%zd", (long)ok);
}
- (void)_test_async
{
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[JLRoutes routesForScheme:@"xes"] addRoute:@"/:object/:action" handler:^BOOL(NSDictionary *parameters) {
            NSString *object = parameters[@"object"];
            NSString *action = parameters[@"action"];

            NSLog(@"object:%@ action:%@", object, action);

            [weakSelf.navigationController pushViewController:[[RXLayoutViewController alloc] init] animated:YES];
            // stuff
            return YES;
        }];
    });

    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
        NSURL *editPost = [NSURL URLWithString:@"xes://post/halfrost?debug=true&foo=bar"];
        //    [[UIApplication sharedApplication] openURL:editPost];
        [JLRoutes routeURL:editPost];
    });
}
- (void)_test_async_2
{
    __weak typeof(self) weakSelf = self;
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        [[JLRoutes routesForScheme:@"xes"] addRoute:@"/:object/:action" handler:^BOOL(NSDictionary *parameters) {
            NSString *object = parameters[@"object"];
            NSString *action = parameters[@"action"];

            NSLog(@"object:%@ action:%@", object, action);
            [weakSelf.navigationController pushViewController:[[RXLayoutViewController alloc] init] animated:YES];
            // stuff
            return YES;
        }];
    });

    NSURL *editPost = [NSURL URLWithString:@"xes://post/halfrost?debug=true&foo=bar"];
    BOOL ok = [JLRoutes routeURL:editPost];
    if (!ok) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 3 * NSEC_PER_SEC), dispatch_get_main_queue(), ^{
            [JLRoutes routeURL:editPost];
        });
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end


text:
<?xml version="1.0" encoding="UTF-8"?>
<section version="5.0" xml:id="drools.WorkbenchRemoteAPI"
         xsi:schemaLocation="http://docbook.org/ns/docbook http://www.docbook.org/xml/5.0/xsd/docbook.xsd http://www.w3.org/1999/xlink http://www.docbook.org/xml/5.0/xsd/xlink.xsd"
         xml:base="../" xmlns="http://docbook.org/ns/docbook" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xlink="http://www.w3.org/1999/xlink"
         xmlns:xi="http://www.w3.org/2001/XInclude" xmlns:ns="http://docbook.org/ns/docbook">
  <title>REST</title>

     <para>REST API calls to Knowledge Store allow you to manage the Knowledge Store content and manipulate the static data in the repositories of
          the Knowledge Store. The calls are asynchronous, that is, they continue their execution after the call was performed as a job. The job ID
          is returned by every calls to allow after the REST API call was performed to request the job status and verify whether the job finished
          successfully. Parameters of these calls are provided in the form of JSON entities. </para>
     <para>When using Java code to interface with the REST API, the classes used in POST operations
          or otherwise returned by various operations can be found in the (org.kie.workbench.services:)kie-wb-common-services JAR. All
          of the classes mentioned below can be found in the org.kie.workbench.common.services.shared.rest package in that JAR.</para>

          <title>Job calls</title>
          <para>Every Knowledge Store REST call returns its job ID after it was sent. This is necessary as the calls are asynchronous and you need
               to be able to reference the job to check its status as it goes through its lifecycle. During its lifecycle, a job can have the
               following statuses:
          </para>
          <itemizedlist>
               <listitem>
                    <para>ACCEPTED: the job was accepted and is being processed</para>
               </listitem>
               <listitem>
                    <para>BAD_REQUEST: the request was not accepted as it contained incorrect content</para>
               </listitem>
               <listitem>
                    <para>RESOURCE_NOT_EXIST: the requested resource (path) does not exist</para>
               </listitem>
               <listitem>
                    <para>DUPLICATE_RESOURCE: the resource already exists</para>
               </listitem>
               <listitem>
                    <para>SERVER_ERROR: an error on the server occurred</para>
               </listitem>
               <listitem>
                    <para>SUCCESS: the job finished successfully</para>
               </listitem>
               <listitem>
                    <para>FAIL: the job failed</para>
               </listitem>
               <listitem>
                    <para>DENIED: the job was denied</para>
               </listitem>
               <listitem>
                    <para>GONE: the job ID could not be found</para>
                    <para>A job can be GONE in the following cases:</para>
                    <itemizedlist>
                         <listitem>
                              <para>The job was explicitly removed</para>
                         </listitem>
                         <listitem>
                              <para>The job finished and has been deleted from the status cache (the job is removed from status cache after the cache
                              has reached its maximum capacity)</para>
                         </listitem>
                         <listitem>
                              <para>The job never existed</para>
                         </listitem>
                    </itemizedlist>
               </listitem>
          </itemizedlist>
          <para>The following job calls are provided:</para>
          <variablelist>
               <varlistentry xml:id="url-get-job">
                    <term>[GET] <command>/jobs/<emphasis>{jobID}</emphasis></command></term>
                    <listitem>
                         <para>Returns the job status</para>
                         <para>Returns a JobResult instance</para>
                         <example>
                              <title>An example (formatted) response body to the get job call on a
                                   repository clone request</title>
                              <programlisting>"{
  "status":"SUCCESS",
  "jodId":"1377770574783-27",
  "result":"Alias: testInstallAndDeployProject, Scheme: git, Uri: git://testInstallAndDeployProject",
  "lastModified":1377770578194,"detailedResult":null
}"</programlisting>
                         </example>
                    </listitem>
               </varlistentry>
               <varlistentry xml:id="url-delete-job">
                    <term>[DELETE] <command>/jobs/<emphasis>{jobID}</emphasis></command></term>
                    <listitem>
                         <para>Removes the job: If the job is not yet being processed, this will
                              remove the job from the job queue. However, this will not cancel or
                              stop an ongoing job</para>
                         <para>Returns a JobResult instance</para>
                    </listitem>
               </varlistentry>
          </variablelist>

          <title>Repository calls</title>
          <para>Repository calls are calls to the Knowledge Store that allow you to manage its Git repositories and their projects.</para>
          <para>The following repositories calls are provided:</para>
          <variablelist>
               <varlistentry xml:id="url-get-repositories">
                    <term>[GET] <command>/repositories</command></term>
                    <listitem>
                         <para>Gets information about the repositories in the Knowledge Store</para>
                         <para>Returns a Collection<Map<String, String>> or Collection<RepositoryRequest> instance,
                               depending on the JSON serialization library being used. The keys used in the Map<String, String> instance match
                               the fields in the RepositoryRequest class</para>
                         <example>
                              <title>An example (formatted) response body to the get repositories
                                   call</title>
                              <programlisting>[
  {
    "name":"wb-assets",
    "description":"generic assets",
    "userName":null,
    "password":null,
    "requestType":null,
    "gitURL":"git://bpms-assets"
 },
 {
   "name":"loanProject",
   "description":"Loan processes and rules",
   "userName":null,
   "password":null,
   "requestType":null,
   "gitURL":"git://loansProject"
 }
]</programlisting>
                         </example>
                    </listitem>
               </varlistentry>
               <varlistentry xml:id="url-get-repository">
                    <term>[GET] <command>/repositories/{repositoryName}</command></term>
                    <listitem>
                         <para>Gets information about a repository</para>
                         <para>Returns a Map<String, String> or RepositoryRequest instance, depending on the JSON serialization library being used. The keys used in the Map<String, String> instance match the fields in the RepositoryRequest class</para>
                         <example>
                              <title>An example (formatted) response body to the get repository call</title>
                              <programlisting>{
  "name":"wb-assets",
  "description":"generic assets",
  "userName":null,
  "password":null,
  "requestType":null,
  "gitURL":"git://bpms-assets"
}</programlisting>
                         </example>
                    </listitem>
               </varlistentry>
               <varlistentry xml:id="url-create-repository">
                    <term>[POST] <command>/repositories</command></term>
                    <listitem>
                         <para>Creates a new empty repository or a new repository cloned from an existing (git) repository</para>
                         <para>Consumes a RepositoryRequest instance</para>
                         <para>Returns a CreateOrCloneRepositoryRequest instance</para>
                         <example>
                              <title>An example (formatted) response body to the create repositories
                                   call</title>
                              <programlisting>{
  "name":"new-project-repo",
  "description":"repo for my new project",
  "userName":null,"password":null,
  "requestType":"new",
  "gitURL":null
}</programlisting>
                         </example>
                    </listitem>
               </varlistentry>
               <varlistentry xml:id="url-delete-repository">
                    <term>[DELETE] <command>/repositories/<emphasis>{repositoryName}</emphasis></command></term>
                    <listitem>
                         <para>Removes the repository from the Knowledge Store</para>
                         <para>Returns a RemoveRepositoryRequest instance</para>
                    </listitem>
               </varlistentry>
               <varlistentry xml:id="url-create-project">
                    <term>[POST] <command>/repositories/<emphasis>{repositoryName}</emphasis>/projects/</command></term>
                    <listitem>
                         <para>Creates a project in the repository</para>
                         <para>Consumes an Entity instance</para>
                         <para>Returns a CreateProjectRequest instance</para>
                         <example>
                              <title>An example (formatted) request body that defines the project to be created</title>
                              <programlisting>{
  "name":"myProject",
  "description": "my project"
}</programlisting>
                         </example>
                    </listitem>
               </varlistentry>
               <varlistentry xml:id="url-delete-project">
                    <term>[DELETE] <command>/repositories/<emphasis>{repositoryName}</emphasis>/projects/</command></term>
                    <listitem>
                         <para>Deletes the project in the repository</para>
                         <para>Returns a DeleteProjectRequest instance</para>
                    </listitem>
               </varlistentry>
              <varlistentry xml:id="url-get-projects">
                <term>[GET] <command>/repositories/<emphasis>{repositoryName}</emphasis>/projects/</command></term>
                <listitem>
                  <para>Gets information about the projects</para>
                  <para>Returns a Collection<Map<String, String>> or Collection<ProjectResponse> instance, depending on the JSON serialization library being used. The keys used in the Map<String, String> instance match the fields in the ProjectResponse class</para>
                  <example>
                    <title>An example (formatted) response body to the get projects call</title>
                    <programlisting>[
  {
    "name":"wb-assets",
    "description":"generic assets",
    "groupId":"org.test",
    "version":"1.0"
 },
 {
   "name":"loanProject",
   "description":"Loan processes and rules",
    "groupId":"com.bank",
    "version":"3.7"
 }
]</programlisting>
                  </example>
                </listitem>
              </varlistentry>
          </variablelist>

          <title>Organizational unit calls</title>
          <para>Organizational unit calls are calls to the Knowledge Store that allow you to manage its organizational units, so as to organize the
                connected Git repositories.
          </para>
          <para>The following organizationalUnits calls are provided:</para>
          <variablelist>
             <varlistentry xml:id="url-create-org-unit">
                    <term>[POST] <command>/organizationalunits</command></term>
                    <listitem>
                         <para>Creates an organizational unit in the Knowledge Store</para>
                         <para>Consumes an OrganizationalUnit instance</para>
                         <para>Returns a CreateOrganizationalUnitRequest instance</para>
                         <example>
                              <title>An example (formatted) request body defining a new organizational unit to be created</title>
                              <programlisting>{
  "name":"testgroup",
  "description":"",
  "owner":"tester",
  "repositories":["testGroupRepository"]
}</programlisting>
                         </example>
                    </listitem>
               </varlistentry>
            <varlistentry xml:id="url-get-org-unit">
              <term>[GET] <command>/organizationalunits/{orgUnitName}</command></term>
              <listitem>
                <para>Creates an organizational unit</para>
                <para>Consumes an OrganizationalUnit instance</para>
                <para>Returns a CreateOrganizationalUnitRequest instance</para>
                <example>
                  <title>An example (formatted) request body defining a new organizational unit to be created</title>
                  <programlisting>{
  "name":"testgroup",
  "description":"",
  "owner":"tester",
  "repositories":["testGroupRepository"]
}</programlisting>
                </example>
              </listitem>
            </varlistentry>
            <varlistentry xml:id="url-update-org-unit">
              <term>[POST] <command>/organizationalunits/{orgUnitName}</command></term>
              <listitem>
                <para>Creates an organizational unit in the Knowledge Store</para>
                <para>Consumes an UpdateOrganizationalUnit instance</para>
                <para>Returns a UpdateOrganizationalUnitRequest instance</para>
                <example>
                  <title>An example (formatted) request body defining a new organizational unit to be created</title>
                  <programlisting>{
  "name":"testgroup",
  "description":"",
  "owner":"tester",
  "repositories":["testGroupRepository"]
}</programlisting>
                </example>
              </listitem>
            </varlistentry>
            <varlistentry xml:id="url-remove-org-unit">
              <term>[DELETE] <command>/organizationalunits/<emphasis>{organizationalUnitName}</emphasis></command></term>
              <listitem>
                <para>Deletes a organizational unit</para>
                <para>Returns a RemoveOrganizationalUnitRequest instance</para>
              </listitem>
            </varlistentry>
            <varlistentry xml:id="url-add-repo-to-org-unit">
                    <term>[POST] <command>/organizationalunits/<emphasis>{organizationalUnitName}</emphasis>/repositories/<emphasis>{repositoryName}</emphasis></command></term>
                    <listitem>
                         <para>Adds the repository to the organizational unit</para>
                         <para>Returns a AddRepositoryToOrganizationalUnitRequest instance</para>
                    </listitem>
               </varlistentry>
               <varlistentry xml:id="url-remove-repo-to-org-unit">
                    <term>[DELETE] <command>/organizationalunits/<emphasis>{organizationalUnitName}</emphasis>/repositories/<emphasis>{repositoryName}</emphasis></command></term>
                    <listitem>
                         <para>Removes the repository from the organizational unit</para>
                         <para>Returns a RemoveRepositoryFromOrganizationalUnitRequest instance</para>
                    </listitem>
               </varlistentry>

          </variablelist>

          <title>Maven calls</title>
          <para>Maven calls are calls to a Project in the Knowledge Store that allow you compile and deploy the Project resources.</para>
          <para>The following maven calls are provided:</para>
          <variablelist>
               <varlistentry xml:id="url-compile-project">
                    <term> [POST] <command>/repositories/<emphasis>{repositoryName}</emphasis>/projects/<emphasis>{projectName}</emphasis>/maven/compile</command></term>
                    <listitem>
                         <para>Compiles the project (equivalent to mvn compile)</para>
                         <para>Consumes a BuildConfig instance. While this must be supplied, it's not needed for the operation and may be left blank.</para>
                         <para>Returns a CompileProjectRequest instance</para>
                    </listitem>
               </varlistentry>
               <varlistentry xml:id="url-install-project">
                    <term>[POST] <command>/repositories/<emphasis>{repositoryName}</emphasis>/projects/<emphasis>{projectName}</emphasis>/maven/install</command></term>
                    <listitem>
                         <para>Installs the project (equivalent to mvn install)</para>
                         <para>Consumes a BuildConfig instance. While this must be supplied, it's not needed for the operation and may be left blank.</para>
                         <para>Returns a InstallProjectRequest instance</para>
                    </listitem>
               </varlistentry>
               <varlistentry xml:id="url-test-project">
                    <term>[POST] <command>/repositories/<emphasis>{repositoryName}</emphasis>/projects/<emphasis>{projectName}</emphasis>/maven/test</command></term>
                    <listitem>
                         <para>Compiles the project runs a test as part of compilation</para>
                         <para>Consumes a BuildConfig instance</para>
                         <para>Returns a TestProjectRequest instance</para>
                    </listitem>
               </varlistentry>
               <varlistentry xml:id="url-deploy-project">
                    <term>[POST] <command>/repositories/<emphasis>{repositoryName}</emphasis>/projects/<emphasis>{projectName}</emphasis>/maven/deploy</command></term>
                    <listitem>
                         <para>Deploys the project (equivalent to  mvn deploy)</para>
                         <para>Consumes a BuildConfig instance. While this must be supplied, it's not needed for the operation and may be left blank.</para>
                         <para>Returns a DeployProjectRequest instance</para>
                    </listitem>
               </varlistentry>
          </variablelist>

      <title>REST summary</title>

      <para>
        The URL templates in the table below are relative the following URL:
        <itemizedlist>
          <listitem>
            <para>
              http://server:port/business-central/rest
            </para>
          </listitem>
        </itemizedlist>
      </para>

      <title>Knowledge Store REST calls</title>
      <tgroup align="left" cols="3">
        <colspec colname="c1" colwidth="62*"/>
        <colspec colname="c2" colwidth="8*"/>
        <colspec colname="c3" colwidth="30*"/>

          <row>
            <entry>URL Template</entry>
            <entry>Type</entry>
            <entry>Description</entry>
          </row>

          <row valign="top">
            <entry>/jobs/{jobID}</entry>
            <entry>GET</entry>
            <entry>return the job status</entry>
          </row>
          <row valign="top">
            <entry>/jobs/{jobID}</entry>
            <entry>DELETE</entry>
            <entry>remove the job</entry>
          </row>
          <row valign="top">
            <entry>/organizationalunits</entry>
            <entry>GET</entry>
            <entry>return a list of organizational units</entry>
          </row>
          <row valign="top">
            <entry>/organizationalunits</entry>
            <entry>POST</entry>
            <entry>
              <para>create an organizational unit in the Knowledge Store described by the JSON OrganizationalUnit entity</para>
            </entry>
          </row>
          <row valign="top">
            <entry>/organizationalunits/{organizationalUnitName}/repositories/{repositoryName}</entry>
            <entry>POST</entry>
            <entry>add a repository to an organizational unit</entry>
          </row>
          <row valign="top">
            <entry>/organizationalunits/{organizationalUnitName}/repositories/{repositoryName}</entry>
            <entry>DELETE</entry>
            <entry>remove a repository from an organizational unit</entry>
          </row>

          <row valign="top">
            <entry>/repositories/</entry>
            <entry>POST</entry>
            <entry>
              <para>add the repository to the organizational unit described by the JSON RepositoryReqest entity</para>
            </entry>
          </row>
          <row valign="top">
            <entry>/repositories</entry>
            <entry>GET</entry>
            <entry>return the repositories in the Knowledge Store</entry>
          </row>
          <row valign="top">
            <entry>/repositories/{repositoryName}</entry>
            <entry>DELETE</entry>
            <entry>remove the repository from the Knowledge Store</entry>
          </row>
          <row valign="top">
            <entry>/repositories/</entry>
            <entry>POST</entry>
            <entry>create or clone the repository defined by the JSON RepositoryRequest entity</entry>
          </row>
          <row valign="top">
            <entry>/repositories/{repositoryName}/projects/</entry>
            <entry>POST</entry>
            <entry>create the project defined by the JSON entity in the repository</entry>
          </row>

          <row valign="top">
            <entry>/repositories/{repositoryName}/projects/{projectName}/maven/compile/</entry>
            <entry>POST</entry>
            <entry>compile the project</entry>
          </row>
          <row valign="top">
            <entry>/repositories/{repositoryName}/projects/{projectName}/maven/install</entry>
            <entry>POST</entry>
            <entry>install the project</entry>
          </row>
          <row valign="top">
            <entry>/repositories/{repositoryName}/projects/{projectName}/maven/test/</entry>
            <entry>POST</entry>
            <entry>
              <para>compile the project and run tests as part of compilation</para>
            </entry>
          </row>
          <row valign="top">
            <entry>/repositories/{repositoryName}/projects/{projectName}/maven/deploy/</entry>
            <entry>POST</entry>
            <entry>deploy the project</entry>
          </row>

      </tgroup>


text:
require 'spec_helper'

describe Neo4j::ActiveRel::Callbacks do
  let(:session) { double('Session') }
  let(:node1) { double('Node1') }
  let(:node2) { double('Node2') }

  before do
    @session = double('Mock Session')
    Neo4j::Session.stub(:current).and_return(@session)
    clazz.stub(:neo4j_session).and_return(session)
  end

  class Foo
    def save(*)
      true
    end
  end

  let(:clazz) do
    class MyBar < Foo
      include Neo4j::ActiveRel::Callbacks
    end
  end

  describe 'save' do
    let(:rel) { clazz.new }

    before do
      clazz.any_instance.stub(:_persisted_obj).and_return(nil)
      clazz.any_instance.stub_chain('errors.full_messages').and_return([])
    end

    it 'raises an error if unpersisted and outbound is not valid' do
      clazz.any_instance.stub_chain('to_node.neo_id')
      clazz.any_instance.stub_chain('from_node').and_return(nil)
      expect { rel.save }.to raise_error(Neo4j::ActiveRel::Persistence::RelInvalidError)
    end

    it 'raises an error if unpersisted and inbound is not valid' do
      clazz.any_instance.stub_chain('from_node.neo_id')
      clazz.any_instance.stub_chain('to_node').and_return(nil)
      expect { rel.save }.to raise_error(Neo4j::ActiveRel::Persistence::RelInvalidError)
    end

    it 'does not raise an error if inbound and outbound are valid' do
      clazz.any_instance.stub_chain('from_node.neo_id')
      clazz.any_instance.stub_chain('to_node.neo_id')
      expect { rel.save }.not_to raise_error
    end
  end
end


text:
@interface ViewController : BaseController <UITableViewDelegate, UITableViewDataSource>

@property(nonatomic,retain) IBOutlet UITableView* productsTable;

@end


text:
package org.wso2.carbon.transport.jms.internal;

import org.osgi.framework.BundleActivator;
import org.osgi.framework.BundleContext;

/**
 * OSGi BundleActivator of the JMS Server Connector Bundle.
 */
public class JMSConnectorBundleActivator implements BundleActivator {
    @Override
    public void start(BundleContext bundleContext) throws Exception {
//      bundleContext.registerService(ServerConnectorProvider.class.toString(), new JMSServerConnectorProvider(), null);
    }

    @Override
    public void stop(BundleContext bundleContext) throws Exception {

    }
}


text:
package com.ghstudios.android.loader;

import android.content.Context;
import android.database.Cursor;

import com.ghstudios.android.data.DataManager;
import com.ghstudios.android.data.cursors.PalicoWeaponCursor;

/**
 * Created by Joseph on 7/10/2016.
 */
public class PalicoWeaponListCursorLoader extends SQLiteCursorLoader {

    public PalicoWeaponListCursorLoader(Context context) {
        super(context);
    }

    @Override
    protected Cursor loadCursor() {
        PalicoWeaponCursor cursor = DataManager.get().queryPalicoWeapons();
        return cursor;
    }

}


text:
struct QVideoFrameScopeMap
{
    QVideoFrameScopeMap(QVideoFrame *frame, QAbstractVideoBuffer::MapMode mode) : frame(frame)
    {
        if(frame)
        {
            status = frame->map(mode);
            if (!status)
            {
                qWarning("Can't map!");
            }
        }
    }
    ~QVideoFrameScopeMap()
    {
        if(frame)
        {
            frame->unmap();
        }
    }
    operator bool() const { return status; }
    QVideoFrame *frame = nullptr;
    bool status = false;
};

#endif // Q_VIDEO_FRAME_SCOPE_MAP


text:
<?php

namespace Umurkaragoz\StdAdmin;

use Illuminate\Database\Eloquent\Builder;

/**
 * Trait ManagesDeletables
 * Manages deletable operations of the module.
 *
 * @package Umurkaragoz\StdAdmin
 */
trait GeneratesIndexes
{
    /* ---------------------------------------------------------------------------------------------------------------------------------- index -+- */
    /**
     * @return mixed
     */
    public function defaultIndex()
    {
        $columns = module('functions.index.columns');

        $headers = $this->generateHeaders(array_keys($columns));

        return app('view')->make('std-admin::index')
            ->with('columns', $columns)
            ->with('headers', $headers)
            ->with('rows', $this->indexRows());
    }

    /* ----------------------------------------------------------------------------------------------------------------------------- index Rows -+- */
    /**
     * Queries and returns $rows for the index view. This can be called from custom controllers to be used in custom views.
     *
     * @return array
     */
    protected function indexRows(Builder $query = null)
    {
        $query = $query ?: module('class')::query();

        if (method_exists(module('class'), 'scopeOrder')) {
            $query = $query->order();
        }

        $rows = $query->filter(app('request')->input('filters'))->get();

        return $rows;
    }
}


text:
package org.avantssar.aslanpp.flow;

import java.io.PrintStream;
import java.util.Set;
import org.avantssar.aslan.IASLanSpec;
import org.avantssar.aslan.RewriteRule;
import org.avantssar.aslanpp.model.SymbolsState;

public interface IVisitable {

	Counters assignIndexes(Counters counters);

	void renderGraphviz(PrintStream out);

	int gatherTransitions(IASLanSpec spec, int nextTransitionIndex);

	int gatherTransitionsLumped(IASLanSpec spec, RewriteRule soFar, SymbolsState symState, Set<Integer> visitedStates, int nextTransitionIndex, int sourceNodeIndex, TransitionsRecorder rec);

	void clearVisited();

}


text:
//===- Job.cpp - Command to Execute ---------------------------------------===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//

#include "clang/Driver/Job.h"
#include "InputInfo.h"
#include "clang/Basic/LLVM.h"
#include "clang/Driver/Driver.h"
#include "clang/Driver/DriverDiagnostic.h"
#include "clang/Driver/Tool.h"
#include "clang/Driver/ToolChain.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/SmallString.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/StringRef.h"
#include "llvm/ADT/StringSet.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/CrashRecoveryContext.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/Path.h"
#include "llvm/Support/PrettyStackTrace.h"
#include "llvm/Support/Program.h"
#include "llvm/Support/raw_ostream.h"
#include <algorithm>
#include <cassert>
#include <cstddef>
#include <string>
#include <system_error>
#include <utility>

using namespace clang;
using namespace driver;

Command::Command(const Action &Source, const Tool &Creator,
                 const char *Executable,
                 const llvm::opt::ArgStringList &Arguments,
                 ArrayRef<InputInfo> Inputs)
    : Source(Source), Creator(Creator), Executable(Executable),
      Arguments(Arguments) {
  for (const auto &II : Inputs)
    if (II.isFilename())
      InputFilenames.push_back(II.getFilename());
}

/// Check if the compiler flag in question should be skipped when
/// emitting a reproducer. Also track how many arguments it has and if the
/// option is some kind of include path.
static bool skipArgs(const char *Flag, bool HaveCrashVFS, int &SkipNum,
                     bool &IsInclude) {
  SkipNum = 2;
  // These flags are all of the form -Flag <Arg> and are treated as two
  // arguments.  Therefore, we need to skip the flag and the next argument.
  bool ShouldSkip = llvm::StringSwitch<bool>(Flag)
    .Cases("-MF", "-MT", "-MQ", "-serialize-diagnostic-file", true)
    .Cases("-o", "-dependency-file", true)
    .Cases("-fdebug-compilation-dir", "-diagnostic-log-file", true)
    .Cases("-dwarf-debug-flags", "-ivfsoverlay", true)
    .Default(false);
  if (ShouldSkip)
    return true;

  // Some include flags shouldn't be skipped if we have a crash VFS
  IsInclude = llvm::StringSwitch<bool>(Flag)
    .Cases("-include", "-header-include-file", true)
    .Cases("-idirafter", "-internal-isystem", "-iwithprefix", true)
    .Cases("-internal-externc-isystem", "-iprefix", true)
    .Cases("-iwithprefixbefore", "-isystem", "-iquote", true)
    .Cases("-isysroot", "-I", "-F", "-resource-dir", true)
    .Cases("-iframework", "-include-pch", true)
    .Default(false);
  if (IsInclude)
    return !HaveCrashVFS;

  // The remaining flags are treated as a single argument.

  // These flags are all of the form -Flag and have no second argument.
  ShouldSkip = llvm::StringSwitch<bool>(Flag)
    .Cases("-M", "-MM", "-MG", "-MP", "-MD", true)
    .Case("-MMD", true)
    .Default(false);

  // Match found.
  SkipNum = 1;
  if (ShouldSkip)
    return true;

  // These flags are treated as a single argument (e.g., -F<Dir>).
  StringRef FlagRef(Flag);
  IsInclude = FlagRef.startswith("-F") || FlagRef.startswith("-I");
  if (IsInclude)
    return !HaveCrashVFS;
  if (FlagRef.startswith("-fmodules-cache-path="))
    return true;

  SkipNum = 0;
  return false;
}

void Command::printArg(raw_ostream &OS, StringRef Arg, bool Quote) {
  const bool Escape = Arg.find_first_of(" \"\\$") != StringRef::npos;

  if (!Quote && !Escape) {
    OS << Arg;
    return;
  }

  // Quote and escape. This isn't really complete, but good enough.
  OS << '"';
  for (const auto c : Arg) {
    if (c == '"' || c == '\\' || c == '$')
      OS << '\\';
    OS << c;
  }
  OS << '"';
}

void Command::writeResponseFile(raw_ostream &OS) const {
  // In a file list, we only write the set of inputs to the response file
  if (Creator.getResponseFilesSupport() == Tool::RF_FileList) {
    for (const auto *Arg : InputFileList) {
      OS << Arg << '\n';
    }
    return;
  }

  // In regular response files, we send all arguments to the response file.
  // Wrapping all arguments in double quotes ensures that both Unix tools and
  // Windows tools understand the response file.
  for (const auto *Arg : Arguments) {
    OS << '"';

    for (; *Arg != '\0'; Arg++) {
      if (*Arg == '\"' || *Arg == '\\') {
        OS << '\\';
      }
      OS << *Arg;
    }

    OS << "\" ";
  }
}

void Command::buildArgvForResponseFile(
    llvm::SmallVectorImpl<const char *> &Out) const {
  // When not a file list, all arguments are sent to the response file.
  // This leaves us to set the argv to a single parameter, requesting the tool
  // to read the response file.
  if (Creator.getResponseFilesSupport() != Tool::RF_FileList) {
    Out.push_back(Executable);
    Out.push_back(ResponseFileFlag.c_str());
    return;
  }

  llvm::StringSet<> Inputs;
  for (const auto *InputName : InputFileList)
    Inputs.insert(InputName);
  Out.push_back(Executable);
  // In a file list, build args vector ignoring parameters that will go in the
  // response file (elements of the InputFileList vector)
  bool FirstInput = true;
  for (const auto *Arg : Arguments) {
    if (Inputs.count(Arg) == 0) {
      Out.push_back(Arg);
    } else if (FirstInput) {
      FirstInput = false;
      Out.push_back(Creator.getResponseFileFlag());
      Out.push_back(ResponseFile);
    }
  }
}

/// Rewrite relative include-like flag paths to absolute ones.
static void
rewriteIncludes(const llvm::ArrayRef<const char *> &Args, size_t Idx,
                size_t NumArgs,
                llvm::SmallVectorImpl<llvm::SmallString<128>> &IncFlags) {
  using namespace llvm;
  using namespace sys;

  auto getAbsPath = [](StringRef InInc, SmallVectorImpl<char> &OutInc) -> bool {
    if (path::is_absolute(InInc)) // Nothing to do here...
      return false;
    std::error_code EC = fs::current_path(OutInc);
    if (EC)
      return false;
    path::append(OutInc, InInc);
    return true;
  };

  SmallString<128> NewInc;
  if (NumArgs == 1) {
    StringRef FlagRef(Args[Idx + NumArgs - 1]);
    assert((FlagRef.startswith("-F") || FlagRef.startswith("-I")) &&
            "Expecting -I or -F");
    StringRef Inc = FlagRef.slice(2, StringRef::npos);
    if (getAbsPath(Inc, NewInc)) {
      SmallString<128> NewArg(FlagRef.slice(0, 2));
      NewArg += NewInc;
      IncFlags.push_back(std::move(NewArg));
    }
    return;
  }

  assert(NumArgs == 2 && "Not expecting more than two arguments");
  StringRef Inc(Args[Idx + NumArgs - 1]);
  if (!getAbsPath(Inc, NewInc))
    return;
  IncFlags.push_back(SmallString<128>(Args[Idx]));
  IncFlags.push_back(std::move(NewInc));
}

void Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
                    CrashReportInfo *CrashInfo) const {
  // Always quote the exe.
  OS << ' ';
  printArg(OS, Executable, /*Quote=*/true);

  ArrayRef<const char *> Args = Arguments;
  SmallVector<const char *, 128> ArgsRespFile;
  if (ResponseFile != nullptr) {
    buildArgvForResponseFile(ArgsRespFile);
    Args = ArrayRef<const char *>(ArgsRespFile).slice(1); // no executable name
  }

  bool HaveCrashVFS = CrashInfo && !CrashInfo->VFSPath.empty();
  for (size_t i = 0, e = Args.size(); i < e; ++i) {
    const char *const Arg = Args[i];

    if (CrashInfo) {
      int NumArgs = 0;
      bool IsInclude = false;
      if (skipArgs(Arg, HaveCrashVFS, NumArgs, IsInclude)) {
        i += NumArgs - 1;
        continue;
      }

      // Relative includes need to be expanded to absolute paths.
      if (HaveCrashVFS && IsInclude) {
        SmallVector<SmallString<128>, 2> NewIncFlags;
        rewriteIncludes(Args, i, NumArgs, NewIncFlags);
        if (!NewIncFlags.empty()) {
          for (auto &F : NewIncFlags) {
            OS << ' ';
            printArg(OS, F.c_str(), Quote);
          }
          i += NumArgs - 1;
          continue;
        }
      }

      auto Found = llvm::find_if(InputFilenames,
                                 [&Arg](StringRef IF) { return IF == Arg; });
      if (Found != InputFilenames.end() &&
          (i == 0 || StringRef(Args[i - 1]) != "-main-file-name")) {
        // Replace the input file name with the crashinfo's file name.
        OS << ' ';
        StringRef ShortName = llvm::sys::path::filename(CrashInfo->Filename);
        printArg(OS, ShortName.str(), Quote);
        continue;
      }
    }

    OS << ' ';
    printArg(OS, Arg, Quote);
  }

  if (CrashInfo && HaveCrashVFS) {
    OS << ' ';
    printArg(OS, "-ivfsoverlay", Quote);
    OS << ' ';
    printArg(OS, CrashInfo->VFSPath.str(), Quote);

    // The leftover modules from the crash are stored in
    //  <name>.cache/vfs/modules
    // Leave it untouched for pcm inspection and provide a clean/empty dir
    // path to contain the future generated module cache:
    //  <name>.cache/vfs/repro-modules
    SmallString<128> RelModCacheDir = llvm::sys::path::parent_path(
        llvm::sys::path::parent_path(CrashInfo->VFSPath));
    llvm::sys::path::append(RelModCacheDir, "repro-modules");

    std::string ModCachePath = "-fmodules-cache-path=";
    ModCachePath.append(RelModCacheDir.c_str());

    OS << ' ';
    printArg(OS, ModCachePath, Quote);
  }

  if (ResponseFile != nullptr) {
    OS << "\n Arguments passed via response file:\n";
    writeResponseFile(OS);
    // Avoiding duplicated newline terminator, since FileLists are
    // newline-separated.
    if (Creator.getResponseFilesSupport() != Tool::RF_FileList)
      OS << "\n";
    OS << " (end of response file)";
  }

  OS << Terminator;
}

void Command::setResponseFile(const char *FileName) {
  ResponseFile = FileName;
  ResponseFileFlag = Creator.getResponseFileFlag();
  ResponseFileFlag += FileName;
}

void Command::setEnvironment(llvm::ArrayRef<const char *> NewEnvironment) {
  Environment.reserve(NewEnvironment.size() + 1);
  Environment.assign(NewEnvironment.begin(), NewEnvironment.end());
  Environment.push_back(nullptr);
}

void Command::PrintFileNames() const {
  if (PrintInputFilenames) {
    for (const char *Arg : InputFilenames)
      llvm::outs() << llvm::sys::path::filename(Arg) << "\n";
    llvm::outs().flush();
  }
}

int Command::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
                     std::string *ErrMsg, bool *ExecutionFailed) const {
  PrintFileNames();

  SmallVector<const char *, 128> Argv;
  if (ResponseFile == nullptr) {
    Argv.push_back(Executable);
    Argv.append(Arguments.begin(), Arguments.end());
    Argv.push_back(nullptr);
  } else {
    // If the command is too large, we need to put arguments in a response file.
    std::string RespContents;
    llvm::raw_string_ostream SS(RespContents);

    // Write file contents and build the Argv vector
    writeResponseFile(SS);
    buildArgvForResponseFile(Argv);
    Argv.push_back(nullptr);
    SS.flush();

    // Save the response file in the appropriate encoding
    if (std::error_code EC = writeFileWithEncoding(
            ResponseFile, RespContents, Creator.getResponseFileEncoding())) {
      if (ErrMsg)
        *ErrMsg = EC.message();
      if (ExecutionFailed)
        *ExecutionFailed = true;
      // Return -1 by convention (see llvm/include/llvm/Support/Program.h) to
      // indicate the requested executable cannot be started.
      return -1;
    }
  }

  Optional<ArrayRef<StringRef>> Env;
  std::vector<StringRef> ArgvVectorStorage;
  if (!Environment.empty()) {
    assert(Environment.back() == nullptr &&
           "Environment vector should be null-terminated by now");
    ArgvVectorStorage = llvm::toStringRefArray(Environment.data());
    Env = makeArrayRef(ArgvVectorStorage);
  }

  auto Args = llvm::toStringRefArray(Argv.data());
  return llvm::sys::ExecuteAndWait(Executable, Args, Env, Redirects,
                                   /*secondsToWait*/ 0,
                                   /*memoryLimit*/ 0, ErrMsg, ExecutionFailed);
}

CC1Command::CC1Command(const Action &Source, const Tool &Creator,
                       const char *Executable,
                       const llvm::opt::ArgStringList &Arguments,
                       ArrayRef<InputInfo> Inputs)
    : Command(Source, Creator, Executable, Arguments, Inputs) {
  InProcess = true;
}

void CC1Command::Print(raw_ostream &OS, const char *Terminator, bool Quote,
                       CrashReportInfo *CrashInfo) const {
  if (InProcess)
    OS << " (in-process)\n";
  Command::Print(OS, Terminator, Quote, CrashInfo);
}

int CC1Command::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
                        std::string *ErrMsg, bool *ExecutionFailed) const {
  // FIXME: Currently, if there're more than one job, we disable
  // -fintegrate-cc1. If we're no longer a integrated-cc1 job, fallback to
  // out-of-process execution. See discussion in https://reviews.llvm.org/D74447
  if (!InProcess)
    return Command::Execute(Redirects, ErrMsg, ExecutionFailed);

  PrintFileNames();

  SmallVector<const char *, 128> Argv;
  Argv.push_back(getExecutable());
  Argv.append(getArguments().begin(), getArguments().end());
  Argv.push_back(nullptr);

  // This flag simply indicates that the program couldn't start, which isn't
  // applicable here.
  if (ExecutionFailed)
    *ExecutionFailed = false;

  llvm::CrashRecoveryContext CRC;
  CRC.DumpStackAndCleanupOnFailure = true;

  const void *PrettyState = llvm::SavePrettyStackState();
  const Driver &D = getCreator().getToolChain().getDriver();

  int R = 0;
  // Enter ExecuteCC1Tool() instead of starting up a new process
  if (!CRC.RunSafely([&]() { R = D.CC1Main(Argv); })) {
    llvm::RestorePrettyStackState(PrettyState);
    return CRC.RetCode;
  }
  return R;
}

void CC1Command::setEnvironment(llvm::ArrayRef<const char *> NewEnvironment) {
  // We don't support set a new environment when calling into ExecuteCC1Tool()
  llvm_unreachable(
      "The CC1Command doesn't support changing the environment vars!");
}

FallbackCommand::FallbackCommand(const Action &Source_, const Tool &Creator_,
                                 const char *Executable_,
                                 const llvm::opt::ArgStringList &Arguments_,
                                 ArrayRef<InputInfo> Inputs,
                                 std::unique_ptr<Command> Fallback_)
    : Command(Source_, Creator_, Executable_, Arguments_, Inputs),
      Fallback(std::move(Fallback_)) {}

void FallbackCommand::Print(raw_ostream &OS, const char *Terminator,
                            bool Quote, CrashReportInfo *CrashInfo) const {
  Command::Print(OS, "", Quote, CrashInfo);
  OS << " ||";
  Fallback->Print(OS, Terminator, Quote, CrashInfo);
}

static bool ShouldFallback(int ExitCode) {
  // FIXME: We really just want to fall back for internal errors, such
  // as when some symbol cannot be mangled, when we should be able to
  // parse something but can't, etc.
  return ExitCode != 0;
}

int FallbackCommand::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
                             std::string *ErrMsg, bool *ExecutionFailed) const {
  int PrimaryStatus = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
  if (!ShouldFallback(PrimaryStatus))
    return PrimaryStatus;

  // Clear ExecutionFailed and ErrMsg before falling back.
  if (ErrMsg)
    ErrMsg->clear();
  if (ExecutionFailed)
    *ExecutionFailed = false;

  const Driver &D = getCreator().getToolChain().getDriver();
  D.Diag(diag::warn_drv_invoking_fallback) << Fallback->getExecutable();

  int SecondaryStatus = Fallback->Execute(Redirects, ErrMsg, ExecutionFailed);
  return SecondaryStatus;
}

ForceSuccessCommand::ForceSuccessCommand(
    const Action &Source_, const Tool &Creator_, const char *Executable_,
    const llvm::opt::ArgStringList &Arguments_, ArrayRef<InputInfo> Inputs)
    : Command(Source_, Creator_, Executable_, Arguments_, Inputs) {}

void ForceSuccessCommand::Print(raw_ostream &OS, const char *Terminator,
                            bool Quote, CrashReportInfo *CrashInfo) const {
  Command::Print(OS, "", Quote, CrashInfo);
  OS << " || (exit 0)" << Terminator;
}

int ForceSuccessCommand::Execute(ArrayRef<llvm::Optional<StringRef>> Redirects,
                                 std::string *ErrMsg,
                                 bool *ExecutionFailed) const {
  int Status = Command::Execute(Redirects, ErrMsg, ExecutionFailed);
  (void)Status;
  if (ExecutionFailed)
    *ExecutionFailed = false;
  return 0;
}

void JobList::Print(raw_ostream &OS, const char *Terminator, bool Quote,
                    CrashReportInfo *CrashInfo) const {
  for (const auto &Job : *this)
    Job.Print(OS, Terminator, Quote, CrashInfo);
}

void JobList::clear() { Jobs.clear(); }


text:
"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
var game_info_1 = require('./game-info');
var core_1 = require('@angular/core');
var GameController = (function () {
    function GameController() {
        this.game = new game_info_1.GameInfo();
    }
    GameController.prototype.ngOnInit = function () {
        var _this = this;
        setInterval(function () { return _this.nextTick(); }, 50);
    };
    GameController.prototype.nextTick = function () {
        this.game.miniTicks--;
        if (this.game.miniTicks == 0) {
            this.game.miniTicks = this.game.miniTicksToTick;
            var speedSortedHeroes = this.game.getHeroesByGreatestSpeed();
            var speedSortedEnemies = this.game.getEnemiesByGreatestSpeed();
            var currentHero = void 0;
            var currentEnemy = void 0;
            currentHero = speedSortedHeroes.shift();
            currentEnemy = speedSortedEnemies.shift();
            while (currentHero || currentEnemy) {
                if (!currentEnemy || (currentHero && currentHero.hero.speedPriority >= currentEnemy.enemy.speedPriority)) {
                    currentHero.nextTick(this.game);
                    currentHero = speedSortedHeroes.shift();
                }
                else if (!currentHero || (currentEnemy && currentEnemy.enemy.speedPriority > currentHero.hero.speedPriority)) {
                    currentEnemy.nextTick(this.game);
                    currentEnemy = speedSortedEnemies.shift();
                }
            }
            for (var _i = 0, _a = this.game.heroes; _i < _a.length; _i++) {
                var x = _a[_i];
                x.checkIfDead(this.game);
            }
            for (var _b = 0, _c = this.game.enemies; _b < _c.length; _b++) {
                var x = _c[_b];
                x.checkIfDead(this.game);
            }
        }
    };
    GameController = __decorate([
        core_1.Component({
            moduleId: module.id,
            selector: 'game',
            template: "\n\t\t<game-info [game]=\"game\"></game-info>\n\t",
            styles: ["\n\t\t:host {\n\t\t\tdisplay: block;\n\t\t\theight: 100%;\n\t\t}\n\t"]
        }),
        __metadata('design:paramtypes', [])
    ], GameController);
    return GameController;
}());
exports.GameController = GameController;
var game = new GameController();
//# sourceMappingURL=game-controller.js.map


text:
import BABYLON from 'babylonjs/babylon.max'

class Object3d {
  constructor (scene, position, rotation) {
    this.scene = scene
    this._position = position
    this._rotation = rotation
  }

  init () {
  }

  removeFromScene () {
    this._removeFromScene(this.mesh)
  }

  _removeFromScene (mesh) {
    this.scene.removeMesh(mesh)
    this.scene.removeFromShadows(mesh)
    let meshes = mesh.getChildMeshes()
    for (let i = 0; i < meshes.length; i++) {
      this._removeFromScene(meshes[i])
    }
  }

  set castShadows (value) {
    if (value) {
      this.scene.addToShadows(this.mesh)
    } else {
      this.scene.removeFromShadows(this.mesh)
    }
  }

  get castShadows () {
    return this.scene.castShadows(this.mesh)
  }

  set receiveShadows (value) {
    this.mesh.receiveShadows = value
  }

  get metadata () {
    return this.mesh.metadata
  }

  set metadata (value) {
    this.mesh.metadata = value
  }

  get receiveShadows () {
    return this.mesh.receiveShadows
  }

  set position (val) {
    this.mesh.position = val
  }
  get position () {
    return this.mesh.position
  }
  set rotation (val) {
    this.mesh.rotation = val
  }
  get rotation () {
    return this.mesh.rotation
  }
  set scaling (val) {
    this.mesh.scaling = val
  }
  get scaling () {
    return this.mesh.scaling
  }
  hide () {
    this.mesh.setEnabled(0)
  }
  show () {
    this.mesh.setEnabled(1)
  }
  set name (val) {
    this.mesh.name = val
  }
  get name () {
    return this.mesh.name
  }
}

class ObjectHolder extends Object3d {
  constructor (scene, mesh) {
    super(scene, mesh.position, mesh.rotation)
    this.mesh = mesh
  }
}

class MeshGroup extends Object3d {
  constructor (scene, position, rotation) {
    super(scene, position, rotation)
    this.objects = []
  }

  init () {
    this.mesh = new BABYLON.Mesh('', this.scene)
    this.mesh.position = this._position
    this.mesh.rotation = this._rotation
  }

  addMeshes (objs) {
    for (let i = 0; i < objs.length; i++) {
      this.addMesh(objs[i])
    }
  }

  addMesh (obj) {
    this.objects.push(obj)
    obj.parent = this.mesh
  }
}

class ObjectsGroup extends Object3d {
  constructor (scene, position, rotation) {
    super(scene, position, rotation)
    this.objects = []
  }

  init () {
    this.mesh = new BABYLON.Mesh('', this.scene)
    this.mesh.position = this._position
    this.mesh.rotation = this._rotation
  }

  addObjects (objs) {
    for (let i = 0; i < objs.length; i++) {
      this.addObject(objs[i])
    }
  }

  addObject (obj) {
    this.objects.push(obj)
    obj.mesh.parent = this.mesh
  }
}

class Points2d extends Object3d {
  constructor (scene, position, rotation, points) {
    super(scene, position, rotation)
        // points Vector2d
    this._points = points
  }

  init () {
    this.mesh = new BABYLON.Mesh.CreateLines(null, this.getPoints(), this.scene)
    this.mesh.position = this._position
    this.mesh.rotation = this._rotation
  }

  getPoints () {
    return this._points.map(function (point) {
      return new BABYLON.Vector3(point.x, point.y, 0)
    })
  }

  set color (value) {
    this.mesh.color = value
  }

  get color () {
    return this.mesh.color
  }
}

export { Object3d, Points2d, ObjectsGroup, ObjectHolder, MeshGroup }