text:
package org.apache.spark.executor

import java.util.concurrent.ThreadPoolExecutor

import scala.collection.JavaConverters._

import com.codahale.metrics.{Gauge, MetricRegistry}
import org.apache.hadoop.fs.FileSystem

import org.apache.spark.metrics.source.Source

private[spark]
class ExecutorSource(threadPool: ThreadPoolExecutor, executorId: String) extends Source {

  private def fileStats(scheme: String) : Option[FileSystem.Statistics] =
    FileSystem.getAllStatistics.asScala.find(s => s.getScheme.equals(scheme))

  private def registerFileSystemStat[T](
        scheme: String, name: String, f: FileSystem.Statistics => T, defaultValue: T) = {
    metricRegistry.register(MetricRegistry.name("filesystem", scheme, name), new Gauge[T] {
      override def getValue: T = fileStats(scheme).map(f).getOrElse(defaultValue)
    })
  }

  override val metricRegistry = new MetricRegistry()

  override val sourceName = "executor"

  // Gauge for executor thread pool's actively executing task counts
  metricRegistry.register(MetricRegistry.name("threadpool", "activeTasks"), new Gauge[Int] {
    override def getValue: Int = threadPool.getActiveCount()
  })

  // Gauge for executor thread pool's approximate total number of tasks that have been completed
  metricRegistry.register(MetricRegistry.name("threadpool", "completeTasks"), new Gauge[Long] {
    override def getValue: Long = threadPool.getCompletedTaskCount()
  })

  // Gauge for executor thread pool's current number of threads
  metricRegistry.register(MetricRegistry.name("threadpool", "currentPool_size"), new Gauge[Int] {
    override def getValue: Int = threadPool.getPoolSize()
  })

  // Gauge got executor thread pool's largest number of threads that have ever simultaneously
  // been in th pool
  metricRegistry.register(MetricRegistry.name("threadpool", "maxPool_size"), new Gauge[Int] {
    override def getValue: Int = threadPool.getMaximumPoolSize()
  })

  // Gauge for file system stats of this executor
  for (scheme <- Array("hdfs", "file")) {
    registerFileSystemStat(scheme, "read_bytes", _.getBytesRead(), 0L)
    registerFileSystemStat(scheme, "write_bytes", _.getBytesWritten(), 0L)
    registerFileSystemStat(scheme, "read_ops", _.getReadOps(), 0)
    registerFileSystemStat(scheme, "largeRead_ops", _.getLargeReadOps(), 0)
    registerFileSystemStat(scheme, "write_ops", _.getWriteOps(), 0)
  }

  // Expose executor task metrics using the Dropwizard metrics system.
  // The list is taken from TaskMetrics.scala
  val METRIC_CPU_TIME = metricRegistry.counter(MetricRegistry.name("cpuTime"))
  val METRIC_RUN_TIME = metricRegistry.counter(MetricRegistry.name("runTime"))
  val METRIC_JVM_GC_TIME = metricRegistry.counter(MetricRegistry.name("jvmGCTime"))
  val METRIC_DESERIALIZE_TIME =
    metricRegistry.counter(MetricRegistry.name("deserializeTime"))
  val METRIC_DESERIALIZE_CPU_TIME =
    metricRegistry.counter(MetricRegistry.name("deserializeCpuTime"))
  val METRIC_RESULT_SERIALIZE_TIME =
    metricRegistry.counter(MetricRegistry.name("resultSerializationTime"))
  val METRIC_SHUFFLE_FETCH_WAIT_TIME =
    metricRegistry.counter(MetricRegistry.name("shuffleFetchWaitTime"))
  val METRIC_SHUFFLE_WRITE_TIME =
    metricRegistry.counter(MetricRegistry.name("shuffleWriteTime"))
  val METRIC_SHUFFLE_TOTAL_BYTES_READ =
    metricRegistry.counter(MetricRegistry.name("shuffleTotalBytesRead"))
  val METRIC_SHUFFLE_REMOTE_BYTES_READ =
    metricRegistry.counter(MetricRegistry.name("shuffleRemoteBytesRead"))
  val METRIC_SHUFFLE_REMOTE_BYTES_READ_TO_DISK =
    metricRegistry.counter(MetricRegistry.name("shuffleRemoteBytesReadToDisk"))
  val METRIC_SHUFFLE_LOCAL_BYTES_READ =
    metricRegistry.counter(MetricRegistry.name("shuffleLocalBytesRead"))
  val METRIC_SHUFFLE_RECORDS_READ =
    metricRegistry.counter(MetricRegistry.name("shuffleRecordsRead"))
  val METRIC_SHUFFLE_REMOTE_BLOCKS_FETCHED =
    metricRegistry.counter(MetricRegistry.name("shuffleRemoteBlocksFetched"))
  val METRIC_SHUFFLE_LOCAL_BLOCKS_FETCHED =
    metricRegistry.counter(MetricRegistry.name("shuffleLocalBlocksFetched"))
  val METRIC_SHUFFLE_BYTES_WRITTEN =
    metricRegistry.counter(MetricRegistry.name("shuffleBytesWritten"))
  val METRIC_SHUFFLE_RECORDS_WRITTEN =
    metricRegistry.counter(MetricRegistry.name("shuffleRecordsWritten"))
  val METRIC_INPUT_BYTES_READ =
    metricRegistry.counter(MetricRegistry.name("bytesRead"))
  val METRIC_INPUT_RECORDS_READ =
    metricRegistry.counter(MetricRegistry.name("recordsRead"))
  val METRIC_OUTPUT_BYTES_WRITTEN =
    metricRegistry.counter(MetricRegistry.name("bytesWritten"))
  val METRIC_OUTPUT_RECORDS_WRITTEN =
    metricRegistry.counter(MetricRegistry.name("recordsWritten"))
  val METRIC_RESULT_SIZE =
    metricRegistry.counter(MetricRegistry.name("resultSize"))
  val METRIC_DISK_BYTES_SPILLED =
    metricRegistry.counter(MetricRegistry.name("diskBytesSpilled"))
  val METRIC_MEMORY_BYTES_SPILLED =
    metricRegistry.counter(MetricRegistry.name("memoryBytesSpilled"))
}


text:
layout: tag_index
tag: monitoring
---

redpajama_set_name: RedPajamaGithub


text:
/**
 * This module defines a collection of static general animation functions.
 * @module animate
 */
(function () {
  // ------------------------------------------------------------------------------------------- //
  // Private static variables

  var DEFAULT_DURATION = 1000;

  var animate, params, util, log, currentlyLooping, currentAnimations, currentSynchronizations;

  currentAnimations = [];
  currentSynchronizations = [];

  // ------------------------------------------------------------------------------------------- //
  // Private static functions

  /**
   * Starts the animation loop, if it was not already running.
   * @function animate~startAnimationLoop
   */
  function startAnimationLoop() {
    if (!currentlyLooping) {
      requestAnimationFrame.call(window, animationLoop);
    }
  }

  /**
   * The animation loop. This continuously re-invokes itself while there are animations to animate.
   * @function animate~animationLoop
   */
  function animationLoop() {
    currentlyLooping = true;

    // Check whether there is anything to animate
    if (currentlyAnimating()) {
      updateAnimations(Date.now());
      refreshSynchronizations();

      requestAnimationFrame.call(window, animationLoop);
    } else {
      currentlyLooping = false;
    }
  }

  /**
   * Updates all of the current animations.
   * @function animate~updateAnimations
   * @param {Number} currentTime The current time.
   */
  function updateAnimations(currentTime) {
    var i, animationFinished, animation;

    for (i = 0; i < currentAnimations.length; i++) {
      animation = currentAnimations[i];

      animationFinished = updateAnimation(animation, currentTime);

      if (animationFinished) {
        // Remove the finished animation
        currentAnimations.splice(i, 1);
        i--;

        // Notify the client that the animation finished
        if (animation.onDoneCallback) {
          animation.onDoneCallback(animation, animation.identifier);
        }
      }
    }
  }

  /**
   * Updates the given animation.
   * @function animate~updateAnimation
   * @param {ObjectPropertyAnimation|NumericAttributeAnimation|ColorAttributeAnimation|NumericStyleAnimation|ColorStyleAnimation} animation
   * An object representing the animation.
   * @param {Number} currentTime The current time.
   * @returns {Boolean} True if the animation is finished at this time.
   */
  function updateAnimation(animation, currentTime) {
    var animationFinished, updateFunction;

    if (animation instanceof ObjectPropertyAnimation) {
      updateFunction = updateObjectPropertyAnimation;
    } else if (animation instanceof NumericAttributeAnimation) {
      updateFunction = updateNumericAttributeAnimation;
    } else if (animation instanceof NumericStyleAnimation) {
      updateFunction = updateNumericStyleAnimation;
    } else if (animation instanceof ColorAttributeAnimation) {
      if (animation.startColor instanceof HSLAColor) {
        updateFunction = updateHSLAAttributeAnimation;
      } else if (animation.endColor instanceof RGBAColor) {
        updateFunction = updateRGBAAttributeAnimation;
      }
    } else if (animation instanceof ColorStyleAnimation) {
      if (animation.startColor instanceof HSLAColor) {
        updateFunction = updateHSLAStyleAnimation;
      } else if (animation.endColor instanceof RGBAColor) {
        updateFunction = updateRGBAStyleAnimation;
      }
    }

    animationFinished = updateFunction(animation, currentTime);

    return animationFinished;
  }

  /**
   * Updates the given object property animation.
   * @function animate~updateObjectPropertyAnimation
   * @param {ObjectPropertyAnimation} animation An object representing the animation.
   * @param {Number} currentTime The current time.
   * @returns {Boolean} True if the animation is finished at this time.
   */
  function updateObjectPropertyAnimation(animation, currentTime) {
    var deltaTime, animationFinished, progress, remaining;

    deltaTime = currentTime - animation.startTime;

    if (deltaTime < animation.duration) {
      progress = util.getEasedProgress(deltaTime, animation.duration, animation.easingFunction);
      remaining = 1 - progress;
      animation.currentValue =
          util.interpolate(animation.startValue, animation.endValue, remaining, progress);
      animationFinished = false;
    } else {
      animation.currentValue = animation.endValue;
      animationFinished = true;
    }

    animation.object[animation.property] = animation.currentValue;

    return animationFinished;
  }

  /**
   * Updates the given numeric attribute animation.
   * @function animate~updateNumericAttributeAnimation
   * @param {NumericAttributeAnimation} animation An object representing the animation.
   * @param {Number} currentTime The current time.
   * @returns {Boolean} True if the animation is finished at this time.
   */
  function updateNumericAttributeAnimation(animation, currentTime) {
    var deltaTime, animationFinished, progress, remaining;

    deltaTime = currentTime - animation.startTime;

    if (deltaTime < animation.duration) {
      progress = util.getEasedProgress(deltaTime, animation.duration, animation.easingFunction);
      remaining = 1 - progress;
      animation.currentValue =
          util.interpolate(animation.startValue, animation.endValue, remaining, progress);
      animationFinished = false;
    } else {
      animation.currentValue = animation.endValue;
      animationFinished = true;
    }

    animation.element.setAttribute(animation.attribute,
        animation.prefix + animation.currentValue + animation.suffix);

    return animationFinished;
  }

  /**
   * Updates the given HSLA attribute animation.
   * @function animate~updateHSLAAttributeAnimation
   * @param {ColorAttributeAnimation} animation An object representing the animation.
   * @param {Number} currentTime The current time.
   * @returns {Boolean} True if the animation is finished at this time.
   */
  function updateHSLAAttributeAnimation(animation, currentTime) {
    var deltaTime, animationFinished, h, s, l, a, progress, remaining;

    deltaTime = currentTime - animation.startTime;

    if (deltaTime < animation.duration) {
      progress = util.getEasedProgress(deltaTime, animation.duration, animation.easingFunction);
      remaining = 1 - progress;
      h = util.interpolate(animation.startColor.h, animation.endColor.h, remaining, progress);
      s = util.interpolate(animation.startColor.s, animation.endColor.s, remaining, progress);
      l = util.interpolate(animation.startColor.l, animation.endColor.l, remaining, progress);
      a = util.interpolate(animation.startColor.a, animation.endColor.a, remaining, progress);
      animation.currentColor = new HSLAColor(h, s, l, a);
      animationFinished = false;
    } else {
      animation.currentColor = animation.endColor;
      animationFinished = true;
    }

    animation.element.setAttribute(animation.attribute, hslaColorToString(animation.currentColor));

    return animationFinished;
  }

  /**
   * Updates the given RGBA attribute animation.
   * @function animate~updateRGBAAttributeAnimation
   * @param {ColorAttributeAnimation} animation An object representing the animation.
   * @param {Number} currentTime The current time.
   * @returns {Boolean} True if the animation is finished at this time.
   */
  function updateRGBAAttributeAnimation(animation, currentTime) {
    var deltaTime, animationFinished, r, g, b, a, progress, remaining;

    deltaTime = currentTime - animation.startTime;

    if (deltaTime < animation.duration) {
      progress = util.getEasedProgress(deltaTime, animation.duration, animation.easingFunction);
      remaining = 1 - progress;
      r = util.interpolate(animation.startColor.r, animation.endColor.r, remaining, progress);
      g = util.interpolate(animation.startColor.g, animation.endColor.g, remaining, progress);
      b = util.interpolate(animation.startColor.b, animation.endColor.b, remaining, progress);
      a = util.interpolate(animation.startColor.a, animation.endColor.a, remaining, progress);
      animation.currentColor = new RGBAColor(r, g, b, a);
      animationFinished = false;
    } else {
      animation.currentColor = animation.endColor;
      animationFinished = true;
    }

    animation.element.setAttribute(animation.attribute, rgbaColorToString(animation.currentColor));

    return animationFinished;
  }

  /**
   * Updates the given numeric style property animation.
   * @function animate~updateNumericStyleAnimation
   * @param {NumericStyleAnimation} animation An object representing the animation.
   * @param {Number} currentTime The current time.
   * @returns {Boolean} True if the animation is finished at this time.
   */
  function updateNumericStyleAnimation(animation, currentTime) {
    var deltaTime, animationFinished, progress, remaining;

    deltaTime = currentTime - animation.startTime;

    if (deltaTime < animation.duration) {
      progress = util.getEasedProgress(deltaTime, animation.duration, animation.easingFunction);
      remaining = 1 - progress;
      animation.currentValue =
          util.interpolate(animation.startValue, animation.endValue, remaining, progress);
      animationFinished = false;
    } else {
      animation.currentValue = animation.endValue;
      animationFinished = true;
    }

    animation.element.style[animation.property] =
        animation.prefix + animation.currentValue + animation.suffix;

    return animationFinished;
  }

  /**
   * Updates the given HSLA style property animation.
   * @function animate~updateHSLAStyleAnimation
   * @param {ColorStyleAnimation} animation An object representing the animation.
   * @param {Number} currentTime The current time.
   * @returns {Boolean} True if the animation is finished at this time.
   */
  function updateHSLAStyleAnimation(animation, currentTime) {
    var deltaTime, animationFinished, h, s, l, a, progress, remaining;

    deltaTime = currentTime - animation.startTime;

    if (deltaTime < animation.duration) {
      progress = util.getEasedProgress(deltaTime, animation.duration, animation.easingFunction);
      remaining = 1 - progress;
      h = util.interpolate(animation.startColor.h, animation.endColor.h, remaining, progress);
      s = util.interpolate(animation.startColor.s, animation.endColor.s, remaining, progress);
      l = util.interpolate(animation.startColor.l, animation.endColor.l, remaining, progress);
      a = util.interpolate(animation.startColor.a, animation.endColor.a, remaining, progress);
      animation.currentColor = new HSLAColor(h, s, l, a);
      animationFinished = false;
    } else {
      animation.currentColor = animation.endColor;
      animationFinished = true;
    }

    animation.element.style[animation.property] = hslaColorToString(animation.currentColor);

    return animationFinished;
  }

  /**
   * Updates the given RGBA style property animation.
   * @function animate~updateRGBAStyleAnimation
   * @param {ColorStyleAnimation} animation An object representing the animation.
   * @param {Number} currentTime The current time.
   * @returns {Boolean} True if the animation is finished at this time.
   */
  function updateRGBAStyleAnimation(animation, currentTime) {
    var deltaTime, animationFinished, r, g, b, a, progress, remaining;

    deltaTime = currentTime - animation.startTime;

    if (deltaTime < animation.duration) {
      progress = util.getEasedProgress(deltaTime, animation.duration, animation.easingFunction);
      remaining = 1 - progress;
      r = util.interpolate(animation.startColor.r, animation.endColor.r, remaining, progress);
      g = util.interpolate(animation.startColor.g, animation.endColor.g, remaining, progress);
      b = util.interpolate(animation.startColor.b, animation.endColor.b, remaining, progress);
      a = util.interpolate(animation.startColor.a, animation.endColor.a, remaining, progress);
      animation.currentColor = new RGBAColor(r, g, b, a);
      animationFinished = false;
    } else {
      animation.currentColor = animation.endColor;
      animationFinished = true;
    }

    animation.element.style[animation.property] = rgbaColorToString(animation.currentColor);

    return animationFinished;
  }

  /**
   * Synchronizes all attributes/properties from the synchronization collection.
   * @function animate~refreshSynchronizations
   */
  function refreshSynchronizations() {
    currentSynchronizations.forEach(function (synchronization) {
      if (synchronization instanceof ObjectNumericPropertySync) {
        refreshNumericSynchronization(synchronization);
      } else if (synchronization instanceof ObjectHSLAColorPropertySync) {
        refreshHSLAColorSynchronization(synchronization);
      } else if (synchronization instanceof ObjectRGBAColorPropertySync) {
        refreshRGBAColorSynchronization(synchronization);
      }
    });
  }

  /**
   * Synchronizes the values represented by the given synchronization object.
   * @function animate~refreshNumericSynchronization
   * @param {ObjectNumericPropertySync} synchronization An object representing the synchronization.
   */
  function refreshNumericSynchronization(synchronization) {
    synchronization.element.setAttribute(synchronization.attribute,
        synchronization.prefix + synchronization.object[synchronization.property] +
            synchronization.suffix);
  }

  /**
   * Synchronizes the values represented by the given synchronization object.
   * @function animate~refreshHSLAColorSynchronization
   * @param {ObjectHSLAColorPropertySync} synchronization An object representing the
   * synchronization.
   */
  function refreshHSLAColorSynchronization(synchronization) {
    synchronization.element.setAttribute(synchronization.attribute,
        hslaColorToString(synchronization.object[synchronization.property]));
  }

  /**
   * Synchronizes the values represented by the given synchronization object.
   * @function animate~refreshRGBAColorSynchronization
   * @param {ObjectRGBAColorPropertySync} synchronization An object representing the
   * synchronization.
   */
  function refreshRGBAColorSynchronization(synchronization) {
    synchronization.element.setAttribute(synchronization.attribute,
        rgbaColorToString(synchronization.object[synchronization.property]));
  }

  // ------------------------------------------------------------------------------------------- //
  // Private classes

  /**
   * @constructor
   * @param {HTMLElement} element The element to animate.
   * @param {String} attribute The attribute to animate.
   * @param {Number} startValue The value of the attribute at the start of the animation.
   * @param {Number} endValue The value of the attribute at the end of the animation.
   * @param {Number} [startTime] The time at which the animation starts.
   * @param {Number} [duration] The duration of the animation.
   * @param {String} [prefix] A prefix to prepend to the numeric value.
   * @param {String} [suffix] A suffix to append to the numeric value.
   * @param {String} [easingFunction] The name of the easing function to use with this animation.
   * @param {Function} [onDoneCallback] A callback function to call when this animation has
   * finished. This callback will be given as arguments a reference to the animation object, and
   * whatever argument is passed to this constructor as the identifier parameter.
   * @param {*} [identifier] This will be passed as an argument to the onDoneCallback, and can
   * help the client to identify this particular animation.
   */
  function NumericAttributeAnimation(element, attribute, startValue, endValue, startTime, duration,
                                     prefix, suffix, easingFunction, onDoneCallback, identifier) {
    this.element = element;
    this.attribute = attribute;
    this.startValue = startValue;
    this.endValue = endValue;
    this.currentValue = startValue;
    this.startTime = startTime || Date.now();
    this.duration = duration || DEFAULT_DURATION;
    this.prefix = prefix || '';
    this.suffix = suffix || '';
    this.easingFunction =
        typeof easingFunction === 'function' ? easingFunction :
            util.getEasingFunction(easingFunction);
    this.onDoneCallback = onDoneCallback;
    this.identifier = identifier;
  }

  /**
   * @constructor
   * @param {HTMLElement} element The element to animate.
   * @param {String} attribute The attribute to animate.
   * @param {HSLAColor|RGBAColor} startColor The value of the attribute at the start of the
   * animation.
   * @param {HSLAColor|RGBAColor} endColor The value of the attribute at the end of the animation.
   * @param {Number} [startTime] The time at which the animation starts.
   * @param {Number} [duration] The duration of the animation.
   * @param {String} [easingFunction] The name of the easing function to use with this animation.
   * @param {Function} [onDoneCallback] A callback function to call when this animation has
   * finished. This callback will be given as arguments a reference to the animation object, and
   * whatever argument is passed to this constructor as the identifier parameter.
   * @param {*} [identifier] This will be passed as an argument to the onDoneCallback, and can
   * help the client to identify this particular animation.
   */
  function ColorAttributeAnimation(element, attribute, startColor, endColor, startTime, duration,
                                   easingFunction, onDoneCallback, identifier) {
    this.element = element;
    this.attribute = attribute;
    this.startColor = startColor;
    this.endColor = endColor;
    this.currentColor = startColor;
    this.startTime = startTime || Date.now();
    this.duration = duration || DEFAULT_DURATION;
    this.easingFunction =
        typeof easingFunction === 'function' ? easingFunction :
            util.getEasingFunction(easingFunction);
    this.onDoneCallback = onDoneCallback;
    this.identifier = identifier;
  }

  /**
   * @constructor
   * @param {HTMLElement} element The element to animate.
   * @param {String} property The style property to animate.
   * @param {Number} startValue The value of the property at the start of the animation.
   * @param {Number} endValue The value of the property at the end of the animation.
   * @param {Number} [startTime] The time at which the animation starts.
   * @param {Number} [duration] The duration of the animation.
   * @param {String} [prefix] A prefix to prepend to the numeric value.
   * @param {String} [suffix] A suffix to append to the numeric value.
   * @param {String} [easingFunction] The name of the easing function to use with this animation.
   * @param {Function} [onDoneCallback] A callback function to call when this animation has
   * finished. This callback will be given as arguments a reference to the animation object, and
   * whatever argument is passed to this constructor as the identifier parameter.
   * @param {*} [identifier] This will be passed as an argument to the onDoneCallback, and can
   * help the client to identify this particular animation.
   */
  function NumericStyleAnimation(element, property, startValue, endValue, startTime, duration,
                                 prefix, suffix, easingFunction, onDoneCallback, identifier) {
    this.element = element;
    this.property = property;
    this.startValue = startValue;
    this.endValue = endValue;
    this.currentValue = startValue;
    this.startTime = startTime || Date.now();
    this.duration = duration || DEFAULT_DURATION;
    this.prefix = prefix || '';
    this.suffix = suffix || '';
    this.easingFunction =
        typeof easingFunction === 'function' ? easingFunction :
            util.getEasingFunction(easingFunction);
    this.onDoneCallback = onDoneCallback;
    this.identifier = identifier;
  }

  /**
   * @constructor
   * @param {HTMLElement} element The element to animate.
   * @param {String} property The style property to animate.
   * @param {HSLAColor|RGBAColor} startColor The value of the property at the start of the
   * animation.
   * @param {HSLAColor|RGBAColor} endColor The value of the property at the end of the animation.
   * @param {Number} [startTime] The time at which the animation starts.
   * @param {Number} [duration] The duration of the animation.
   * @param {String} [easingFunction] The name of the easing function to use with this animation.
   * @param {Function} [onDoneCallback] A callback function to call when this animation has
   * finished. This callback will be given as arguments a reference to the animation object, and
   * whatever argument is passed to this constructor as the identifier parameter.
   * @param {*} [identifier] This will be passed as an argument to the onDoneCallback, and can
   * help the client to identify this particular animation.
   */
  function ColorStyleAnimation(element, property, startColor, endColor, startTime, duration,
                               easingFunction, onDoneCallback, identifier) {
    this.element = element;
    this.property = property;
    this.startColor = startColor;
    this.endColor = endColor;
    this.currentColor = startColor;
    this.startTime = startTime || Date.now();
    this.duration = duration || DEFAULT_DURATION;
    this.easingFunction =
        typeof easingFunction === 'function' ? easingFunction :
            util.getEasingFunction(easingFunction);
    this.onDoneCallback = onDoneCallback;
    this.identifier = identifier;
  }

  /**
   * @constructor
   * @param {object} object The object whose property this will animate.
   * @param {String} property The property to animate.
   * @param {Number} startValue The value of the property at the start of the animation.
   * @param {Number} endValue The value of the property at the end of the animation.
   * @param {Number} [startTime] The time at which the animation starts.
   * @param {Number} [duration] The duration of the animation.
   * @param {String} [easingFunction] The name of the easing function to use with this animation.
   * @param {Function} [onDoneCallback] A callback function to call when this animation has
   * finished. This callback will be given as arguments a reference to the animation object, and
   * whatever argument is passed to this constructor as the identifier parameter.
   * @param {*} [identifier] This will be passed as an argument to the onDoneCallback, and can
   * help the client to identify this particular animation.
   */
  function ObjectPropertyAnimation(object, property, startValue, endValue, startTime, duration,
                                   easingFunction, onDoneCallback, identifier) {
    this.object = object;
    this.property = property;
    this.startValue = startValue;
    this.endValue = endValue;
    this.currentValue = startValue;
    this.startTime = startTime || Date.now();
    this.duration = duration || DEFAULT_DURATION;
    this.easingFunction =
        typeof easingFunction === 'function' ? easingFunction :
            util.getEasingFunction(easingFunction);
    this.onDoneCallback = onDoneCallback;
    this.identifier = identifier;
  }

  /**
   * @constructor
   * @param {object} object The object whose property this will animate.
   * @param {String} property The property to animate.
   * @param {HTMLElement} element The element whose attribute will be kept in sync with the given
   * property.
   * @param {String} attribute The attribute to keep in sync with the given property.
   * @param {String} [prefix] A prefix to prepend to the attribute.
   * @param {String} [suffix] A suffix to append to the attribute.
   */
  function ObjectNumericPropertySync(object, property, element, attribute, prefix, suffix) {
    this.object = object;
    this.property = property;
    this.element = element;
    this.attribute = attribute;
    this.prefix = prefix || '';
    this.suffix = suffix || '';
  }

  /**
   * @constructor
   * @param {object} object The object whose property this will animate.
   * @param {String} property The property to animate.
   * @param {HTMLElement} element The element whose attribute will be kept in sync with the given
   * property.
   * @param {String} attribute The attribute to keep in sync with the given property.
   */
  function ObjectHSLAColorPropertySync(object, property, element, attribute) {
    this.object = object;
    this.property = property;
    this.element = element;
    this.attribute = attribute;
  }

  /**
   * @constructor
   * @param {object} object The object whose property this will animate.
   * @param {String} property The property to animate.
   * @param {HTMLElement} element The element whose attribute will be kept in sync with the given
   * property.
   * @param {String} attribute The attribute to keep in sync with the given property.
   */
  function ObjectRGBAColorPropertySync(object, property, element, attribute) {
    this.object = object;
    this.property = property;
    this.element = element;
    this.attribute = attribute;
  }

  // ------------------------------------------------------------------------------------------- //
  // Public static functions

  /**
   * Initializes some static state for this module.
   * @function animate.init
   */
  function init() {
    params = app.params;
    util = app.util;
    log = new app.Log('animate');
    log.d('init', 'Module initialized');
  }

  /**
   * Starts a new animation of the given numeric attribute for the given DOM element.
   * @function animate.startNumericAttributeAnimation
   * @param {HTMLElement} element The element to animate.
   * @param {String} attribute The attribute to animate.
   * @param {Number} startValue The value of the attribute at the start of the animation.
   * @param {Number} endValue The value of the attribute at the end of the animation.
   * @param {Number} [startTime] The time at which the animation starts.
   * @param {Number} [duration] The duration of the animation.
   * @param {String} [prefix] A prefix to prepend to the numeric value.
   * @param {String} [suffix] A suffix to append to the numeric value.
   * @param {String} [easingFunction] The name of the easing function to use with this animation.
   * @param {Function} [onDoneCallback] A callback function to call when this animation has
   * finished.
   * @param {*} [identifier] This will be passed as an argument to the onDoneCallback, and can
   * help the client to identify this particular animation.
   * @returns {NumericAttributeAnimation} The animation object created for this new animation.
   */
  function startNumericAttributeAnimation(element, attribute, startValue, endValue, startTime,
                                          duration, prefix, suffix, easingFunction, onDoneCallback,
                                          identifier) {
    var animation = new NumericAttributeAnimation(element, attribute, startValue, endValue,
        startTime, duration, prefix, suffix, easingFunction, onDoneCallback, identifier);
    currentAnimations.push(animation);
    startAnimationLoop();
    return animation;
  }

  /**
   * Starts a new animation of the given HSLA color attribute for the given DOM element.
   * @function animate.startHSLAColorAttributeAnimation
   * @param {HTMLElement} element The element to animate.
   * @param {String} attribute The attribute to animate.
   * @param {HSLAColor|RGBAColor} startColor The value of the attribute at the start of the
   * animation.
   * @param {HSLAColor|RGBAColor} endColor The value of the attribute at the end of the animation.
   * @param {Number} [startTime] The time at which the animation starts.
   * @param {Number} [duration] The duration of the animation.
   * @param {String} [easingFunction] The name of the easing function to use with this animation.
   * @param {Function} [onDoneCallback] A callback function to call when this animation has
   * finished.
   * @param {*} [identifier] This will be passed as an argument to the onDoneCallback, and can
   * help the client to identify this particular animation.
   * @returns {ColorAttributeAnimation} The animation object created for this new animation.
   */
  function startColorAttributeAnimation(element, attribute, startColor, endColor, startTime,
                                        duration, easingFunction, onDoneCallback, identifier) {
    var animation = new ColorAttributeAnimation(element, attribute, startColor, endColor, startTime,
        duration, easingFunction, onDoneCallback, identifier);
    currentAnimations.push(animation);
    startAnimationLoop();
    return animation;
  }

  /**
   * Starts a new animation of the given numeric style property for the given element.
   * @function animate.startNumericStyleAnimation
   * @param {HTMLElement} element The element to animate.
   * @param {String} property The style property to animate.
   * @param {Number} startValue The value of the property at the start of the animation.
   * @param {Number} endValue The value of the property at the end of the animation.
   * @param {Number} [startTime] The time at which the animation starts.
   * @param {Number} [duration] The duration of the animation.
   * @param {String} [prefix] A prefix to prepend to the numeric value.
   * @param {String} [suffix] A suffix to append to the numeric value.
   * @param {String} [easingFunction] The name of the easing function to use with this animation.
   * @param {Function} [onDoneCallback] A callback function to call when this animation has
   * finished.
   * @param {*} [identifier] This will be passed as an argument to the onDoneCallback, and can
   * help the client to identify this particular animation.
   * @returns {NumericStyleAnimation} The animation object created for this new animation.
   */
  function startNumericStyleAnimation(element, property, startValue, endValue, startTime, duration,
                                      prefix, suffix, easingFunction, onDoneCallback, identifier) {
    var animation = new NumericStyleAnimation(element, property, startValue, endValue, startTime,
        duration, prefix, suffix, easingFunction, onDoneCallback, identifier);
    currentAnimations.push(animation);
    startAnimationLoop();
    return animation;
  }

  /**
   * Starts a new animation of the given HSLA color style property for the given element.
   * @function animate.startColorStyleAnimation
   * @param {HTMLElement} element The element to animate.
   * @param {String} property The style property to animate.
   * @param {HSLAColor|RGBAColor} startColor The value of the property at the start of the
   * animation.
   * @param {HSLAColor|RGBAColor} endColor The value of the property at the end of the animation.
   * @param {Number} [startTime] The time at which the animation starts.
   * @param {Number} [duration] The duration of the animation.
   * @param {String} [easingFunction] The name of the easing function to use with this animation.
   * @param {Function} [onDoneCallback] A callback function to call when this animation has
   * finished.
   * @param {*} [identifier] This will be passed as an argument to the onDoneCallback, and can
   * help the client to identify this particular animation.
   * @returns {ColorStyleAnimation} The animation object created for this new animation.
   */
  function startColorStyleAnimation(element, property, startColor, endColor, startTime, duration,
                                    easingFunction, onDoneCallback, identifier) {
    var animation = new ColorStyleAnimation(element, property, startColor, endColor, startTime,
        duration, easingFunction, onDoneCallback, identifier);
    currentAnimations.push(animation);
    startAnimationLoop();
    return animation;
  }

  /**
   * Starts a new animation of the given numeric property for the given element.
   * @function animate.startNumericAttributeAnimation
   * @param {object} object The object whose property this will animate.
   * @param {String} property The property to animate.
   * @param {Number} startValue The value of the property at the start of the animation.
   * @param {Number} endValue The value of the property at the end of the animation.
   * @param {Number} [startTime] The time at which the animation starts.
   * @param {Number} [duration] The duration of the animation.
   * @param {String} [easingFunction] The name of the easing function to use with this animation.
   * @param {Function} [onDoneCallback] A callback function to call when this animation has
   * finished.
   * @param {*} [identifier] This will be passed as an argument to the onDoneCallback, and can
   * help the client to identify this particular animation.
   * @returns {ObjectPropertyAnimation} The animation object created for this new animation.
   */
  function startObjectPropertyAnimation(object, property, startValue, endValue, startTime, duration,
                                        easingFunction, onDoneCallback, identifier) {
    var animation = new ObjectPropertyAnimation(object, property, startValue, endValue, startTime,
        duration, easingFunction, onDoneCallback, identifier);
    currentAnimations.push(animation);
    startAnimationLoop();
    return animation;
  }

  /**
   * Stops the given animation. This will NOT result in the animation invoking its onDoneCallback.
   * @function animate.stopAnimation
   * @param {ObjectPropertyAnimation|NumericAttributeAnimation|ColorAttributeAnimation} animation
   * The object representing the animation to stop.
   * @returns {Boolean} True if the given animation was found and stopped.
   */
  function stopAnimation(animation) {
    var i, count;
    for (i = 0, count = currentAnimations.length; i < count; i++) {
      if (currentAnimations[i] === animation) {
        currentAnimations.splice(i, 1);
        return true;
      }
    }
    return false;
  }

  /**
   * Informs the animation module to start synchronizing the given attribute of the given element
   * with the property of the given object. This synchronizing is helpful when there is a single
   * attribute value that actually consists of multiple component values, which could all be
   * animating independently and simultaneously--e.g., the r, g, and b components of a color value.
   * @function animate.startSyncingObjectNumericProperty
   * @param {object} object The object whose property is, supposedly, changing.
   * @param {String} property The property that is, supposedly, changing.
   * @param {HTMLElement} element The element whose attribute needs to be kept synchronized with
   * the given property.
   * @param {String} attribute The attribute that needs to be kept synchronized with the given
   * property.
   * @param {String} [prefix] A prefix to prepend to the attribute.
   * @param {String} [suffix] A suffix to append to the attribute.
   * @returns {ObjectNumericPropertySync} An object representing the synchronization. This can
   * be passed to the stopSyncingObjectProperty function to stop the synchronization.
   */
  function startSyncingObjectNumericProperty(object, property, element, attribute, prefix, suffix) {
    var synchronization = new ObjectNumericPropertySync(object, property, element, attribute,
        prefix, suffix);
    currentSynchronizations.push(synchronization);
    return synchronization;
  }

  /**
   * Informs the animation module to start synchronizing the given attribute of the given element
   * with the property of the given object. This synchronizing is helpful when there is a single
   * attribute value that actually consists of multiple component values, which could all be
   * animating independently and simultaneously--e.g., the r, g, and b components of a color value.
   * @function animate.startSyncingObjectHSLAColorProperty
   * @param {object} object The object whose property is, supposedly, changing.
   * @param {String} property The property that is, supposedly, changing.
   * @param {HTMLElement} element The element whose attribute needs to be kept synchronized with
   * the given property.
   * @param {String} attribute The attribute that needs to be kept synchronized with the given
   * property.
   * @returns {ObjectHSLAColorPropertySync} An object representing the synchronization. This can
   * be passed to the stopSyncingObjectProperty function to stop the synchronization.
   */
  function startSyncingObjectHSLAColorProperty(object, property, element, attribute) {
    var synchronization = new ObjectHSLAColorPropertySync(object, property, element, attribute);
    currentSynchronizations.push(synchronization);
    return synchronization;
  }

  /**
   * Informs the animation module to start synchronizing the given attribute of the given element
   * with the property of the given object. This synchronizing is helpful when there is a single
   * attribute value that actually consists of multiple component values, which could all be
   * animating independently and simultaneously--e.g., the r, g, and b components of a color value.
   * @function animate.startSyncingObjectRGBAColorProperty
   * @param {object} object The object whose property is, supposedly, changing.
   * @param {String} property The property that is, supposedly, changing.
   * @param {HTMLElement} element The element whose attribute needs to be kept synchronized with
   * the given property.
   * @param {String} attribute The attribute that needs to be kept synchronized with the given
   * property.
   * @returns {ObjectRGBAColorPropertySync} An object representing the synchronization. This can
   * be passed to the stopSyncingObjectProperty function to stop the synchronization.
   */
  function startSyncingObjectRGBAColorProperty(object, property, element, attribute) {
    var synchronization = new ObjectRGBAColorPropertySync(object, property, element, attribute);
    currentSynchronizations.push(synchronization);
    return synchronization;
  }

  /**
   * Stops the given object property synchronization.
   * @function animate.stopSyncingObjectProperty
   * @param {ObjectNumericPropertySync|ObjectHSLAColorPropertySync|ObjectRGBAColorPropertySync} synchronization
   * The object representing the synchronization to stop.
   * @returns {Boolean} True if the given synchronization was found and stopped.
   */
  function stopSyncingObjectProperty(synchronization) {
    var i, count;
    for (i = 0, count = currentSynchronizations.length; i < count; i++) {
      if (currentSynchronizations[i] === synchronization) {
        currentSynchronizations.splice(i, 1);
        return true;
      }
    }
    return false;
  }

  /**
   * Gets whether there are any current animations in progress.
   * @function animate.currentlyAnimating
   * @returns {Boolean} True if there are current animations in progress.
   */
  function currentlyAnimating() {
    return currentAnimations.length > 0;
  }

  /**
   * A cross-browser compatible requestAnimationFrame.
   * @type {Function}
   */
  var requestAnimationFrame = window.requestAnimationFrame || // the standard
      window.webkitRequestAnimationFrame || // chrome/safari
      window.mozRequestAnimationFrame || // firefox
      window.oRequestAnimationFrame || // opera
      window.msRequestAnimationFrame || // ie
      function (callback) { // default
        window.setTimeout(callback, 16); // 60fps
      };

  /**
   * Creates a legal CSS string representation for the given HSLA color.
   * @function animate.hslaColorToString
   * @param {HSLAColor} color The HSLA color to get the string representation of.
   * @returns {String} The string representation of the given HSLA color.
   */
  function hslaColorToString(color) {
    return 'hsla(' + color.h + ',' + color.s + '%,' + color.l + '%,' + color.a + ')';
  }

  /**
   * Creates a legal CSS string representation for the given RGBA color.
   * @function animate.rgbaColorToString
   * @param {RGBAColor} color The RGBA color to get the string representation of.
   * @returns {String} The string representation of the given RGBA color.
   */
  function rgbaColorToString(color) {
    return 'rgba(' + color.r + ',' + color.g + ',' + color.b + ',' + color.a + ')';
  }

  // ------------------------------------------------------------------------------------------- //
  // Public classes

  /**
   * @constructor
   * @param {Number} h Hue value (from 0 to 360).
   * @param {Number} s Saturation value (from 0 to 100).
   * @param {Number} l Lightness value (from 0 to 100).
   * @param {Number} [a=1] Alpha (opacity) value (from 0 to 1).
   */
  function HSLAColor(h, s, l, a) {
    this.h = h;
    this.s = s;
    this.l = l;
    this.a = typeof a !== 'undefined' ? a : 1;
  }

  /**
   * @constructor
   * @param {Number} r Red color component (from 0 to 255).
   * @param {Number} g Green color component (from 0 to 255).
   * @param {Number} b Blue color component (from 0 to 255).
   * @param {Number} [a=1] Alpha (opacity) value (from 0 to 1).
   */
  function RGBAColor(r, g, b, a) {
    this.r = r;
    this.g = g;
    this.b = b;
    this.a = typeof a !== 'undefined' ? a : 1;
  }

  // ------------------------------------------------------------------------------------------- //
  // Expose this module

  /**
   * Exposes the static animate functions.
   * @global
   */
  animate = {
    init: init,
    startNumericAttributeAnimation: startNumericAttributeAnimation,
    startColorAttributeAnimation: startColorAttributeAnimation,
    startNumericStyleAnimation: startNumericStyleAnimation,
    startColorStyleAnimation: startColorStyleAnimation,
    startObjectPropertyAnimation: startObjectPropertyAnimation,
    stopAnimation: stopAnimation,
    startSyncingObjectNumericProperty: startSyncingObjectNumericProperty,
    startSyncingObjectHSLAColorProperty: startSyncingObjectHSLAColorProperty,
    startSyncingObjectRGBAColorProperty: startSyncingObjectRGBAColorProperty,
    stopSyncingObjectProperty: stopSyncingObjectProperty,
    currentlyAnimating: currentlyAnimating,
    hslaColorToString: hslaColorToString,
    rgbaColorToString: rgbaColorToString,
    HSLAColor: HSLAColor,
    RGBAColor: RGBAColor
  };

  // Expose this module
  if (!window.app) window.app = {};
  window.app.animate = animate;

  console.log('animate module loaded');
})();


text:
import functools
import hashlib
from flask import jsonify, request, url_for, current_app, make_response, g
from .rate_limit import RateLimit
from .errors import too_many_requests, precondition_failed, not_modified

def json(f):
    @functools.wraps(f)
    def wrapped(*args, **kwargs):
        rv = f(*args, **kwargs)
        status_or_headers = None
        headers = None
        if isinstance(rv, tuple):
            rv, status_or_headers, headers = rv + (None,) * (3 - len(rv))
        if isinstance(status_or_headers, (dict, list)):
            headers, status_or_headers = status_or_headers, None
        if not isinstance(rv, dict):
            rv = rv.to_json()
        rv = jsonify(rv)
        if status_or_headers is not None:
            rv.status_code = status_or_headers
        if headers is not None:
            rv.headers.extend(headers)
        return rv
    return wrapped

def rate_limit(limit, per, scope_func=lambda: request.remote_addr):
    def decorator(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            if current_app.config['USE_RATE_LIMITS']:
                key = 'rate-limit/%s/%s/' % (f.__name__, scope_func())
                limiter = RateLimit(key, limit, per)
                if not limiter.over_limit:
                    rv = f(*args, **kwargs)
                else:
                    rv = too_many_requests('You have exceeded your request rate')
                #rv = make_response(rv)
                g.headers = {
                    'X-RateLimit-Remaining': str(limiter.remaining),
                    'X-RateLimit-Limit': str(limiter.limit),
                    'X-RateLimit-Reset': str(limiter.reset)
                }
                return rv
            else:
                return f(*args, **kwargs)
        return wrapped
    return decorator

def paginate(max_per_page=10):
    def decorator(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            page = request.args.get('page', 1, type=int)
            per_page = min(request.args.get('per_page', max_per_page,
                                            type=int), max_per_page)
            query = f(*args, **kwargs)
            p = query.paginate(page, per_page)
            pages = {'page': page, 'per_page': per_page,
                     'total': p.total, 'pages': p.pages}
            if p.has_prev:
                pages['prev'] = url_for(request.endpoint, page=p.prev_num,
                                        per_page=per_page,
                                        _external=True, **kwargs)
            else:
                pages['prev'] = None
            if p.has_next:
                pages['next'] = url_for(request.endpoint, page=p.next_num,
                                        per_page=per_page,
                                        _external=True, **kwargs)
            else:
                pages['next'] = None
            pages['first'] = url_for(request.endpoint, page=1,
                                     per_page=per_page, _external=True,
                                     **kwargs)
            pages['last'] = url_for(request.endpoint, page=p.pages,
                                    per_page=per_page, _external=True,
                                    **kwargs)
            return jsonify({
                'urls': [item.get_url() for item in p.items],
                'meta': pages
            })
        return wrapped
    return decorator

def cache_control(*directives):
    def decorator(f):
        @functools.wraps(f)
        def wrapped(*args, **kwargs):
            rv = f(*args, **kwargs)
            rv = make_response(rv)
            rv.headers['Cache-Control'] =', '.join(directives)
            return rv
        return wrapped
    return decorator

def no_cache(f):
    return cache_control('no-cache', 'no-store', 'max-age=0')(f)

def etag(f):
    @functools.wraps(f)
    def wrapped(*args, **kwargs):
        # only for HEAD and GET requests
        assert request.method in ['HEAD', 'GET'],\
            '@etag is only supported for GET requests'
        rv = f(*args, **kwargs)
        rv = make_response(rv)
        etag = '"' + hashlib.md5(rv.get_data()).hexdigest() + '"'
        rv.headers['ETag'] = etag
        if_match = request.headers.get('If-Match')
        if_none_match = request.headers.get('If-None-Match')
        if if_match:
            etag_list = [tag.strip() for tag in if_match.split(',')]
            if etag not in etag_list and '*' not in etag_list:
                rv = precondition_failed()
        elif if_none_match:
            etag_list = [tag.strip() for tag in if_none_match.split(',')]
            if etag in etag_list or '*' in etag_list:
                rv = not_modified()
        return rv
    return wrapped


text:
from django.db import migrations

class Migration(migrations.Migration):

    dependencies = [
        ("foirequest", "0051_foimessage_email_headers"),
    ]

    operations = [
        migrations.AlterModelOptions(
            name="foirequest",
            options={
                "get_latest_by": "last_message",
                "ordering": ("-last_message",),
                "permissions": (
                    ("see_private", "Can see private requests"),
                    ("create_batch", "Create batch requests"),
                    ("mark_not_foi", "Can mark as not FOI"),
                    ("moderate", "Can moderate requests"),
                ),
                "verbose_name": "Freedom of Information Request",
                "verbose_name_plural": "Freedom of Information Requests",
            },
        ),
    ]


text:
"""

https://ctms.engin.umich.edu/CTMS/index.php?example=Introduction&section=ControlPID

"""

from sympy.abc import *
from sympy import *

"""

The standard equation for the PID controller transfer function is
G(s) = Kp + Ki/s + Kd*s

This stems from taking the laplace transform of the PID output equation
u(t) = Kp*e(t) + Ki * Integral(e(t)) dt  + Kd*de/dt
where we treat F(s) as 1 and F(0) as 0 to give the above equation

The standard feedback form for a transfer function H(s) with some controller G(s) is
G(s)*H(s)/(1 + G(s)*H(s))

So given a PID controller G(s) and a transfer function H(s)
We can use the above equation to analyze how the PID controller G(s) affect the transfer function H(s)

"""

Kp = Symbol('Kp')
Ki = Symbol('Ki')
Kd = Symbol('Kd')

def pidtf(G, H):
    return simplify(G*H/(1 + G*H))

# For a P controller
G = Kp
H = 1/(s*s + 10*s + 20)
print(pidtf(G, H))

# For a PD controller
G = Kp + Kd*s
print(pidtf(G, H))

# For a PI controller
G = Kp + Ki/s
print(pidtf(G, H))

# For a PID controller
G = Kp + Ki/s + Kd*s
print(pidtf(G, H))


text:
#include "util/test.h"
#include "util/init_module.h"
#include "util/sexpr/init_module.h"
#include "kernel/for_each_fn.h"
#include "kernel/abstract.h"
#include "kernel/init_module.h"
#include "library/init_module.h"
#include "library/deep_copy.h"
using namespace lean;

static void tst1() {
    expr f = Const("f");
    expr a = Const("a");
    expr x = Var(0);
    expr Type = mk_Type();
    expr t = Type;
    expr z = Const("z");
    expr m = mk_metavar("a", Type);
    expr F = mk_pi("y", t, mk_lambda("x", t, mk_app(f, mk_app(f, mk_app(f, x, a), Const("10")), mk_app(f, x, m))));
    expr G = deep_copy(F);
    lean_assert(F == G);
    lean_assert(!is_eqp(F, G));
}

int main() {
    save_stack_info();
    initialize_util_module();
    initialize_sexpr_module();
    initialize_kernel_module();
    initialize_library_core_module();
    initialize_library_module();
    tst1();
    finalize_library_module();
    finalize_library_core_module();
    finalize_kernel_module();
    finalize_sexpr_module();
    finalize_util_module();
    return has_violations() ? 1 : 0;
}


text:
var ospath = require('path');
var __update__ = require('../network/update.js');
var __run__ = require('./run.js');
var __logger__ = require('../../logger');

module.exports = function app(remote, path, command, config)
{
  'use strict';

  if(!(this instanceof app))
    throw {code: 1, description: 'Constructor must be called with new.', url: ''};

  if(!command)
    throw {code: 2, description: 'A command is required.', url: ''};

  var self = this;

  // Constructor

  var _remote = remote;
  var _path = path;

  var _command = typeof command === 'string' ? {command : command} : command;
  _command.args = _command.args || [];
  _command.env = _command.env || {};
  _command.cwd = _command.cwd || process.cwd();

  var _config = config;

  var _events = {error: [], shutdown: [], reboot: [], update: [], message: [], start: []};
  var _handles = {message: function(){}, bury: function(){}};

  // Getters

  self.version = function()
  {
    try
    {
      delete require.cache[require.resolve(ospath.resolve(_path.app(), 'package.json'))];
      var _version = require(ospath.resolve(_path.app(), 'package.json')).version;
      return _version;
    } catch(error)
    {
      return '';
    }
  };

  // Methods

  self.run = function(options)
  {
    __logger__.log('Running app.');
    __run__(self, _command, _config, options);
  };

  self.update = function(force)
  {
    __logger__.log('Updating app.');
    return __update__(self, _path, _config, _remote, force);
  };

  // Events and handles

  self.handle = {};

  self.handle.set = function(handle, callback)
  {
    if(!(handle in _handles))
      throw {code: 2, description: 'Handle not found.', url: ''};

    _handles[handle] = callback;
  };

  self.handle.call = function(handle, value)
  {
    if(!(handle in _handles))
      throw {code: 2, description: 'Handle not found.', url: ''};

    __logger__.log('App handle', handle, 'called with', value);
    _handles[handle](value);
  };

  self.on = function(event, callback)
  {
    if(!(event in _events))
      throw {code: 2, description: 'Event not found.', url: ''};

    _events[event].push(callback);
  };

  self.trigger = function(event, value)
  {
    if(!(event in _events))
      throw {code: 2, description: 'Event not found.', url: ''};

    __logger__.log('Event', event, 'triggered.');

    if(value)
      __logger__.log('Event value:', value);

    _events[event].forEach(function(callback)
    {
      callback(value);
    });
  };
};


text:
package jwk

import (
	"crypto/rsa"

	"github.com/pkg/errors"
	jose "gopkg.in/square/go-jose.v2"
)

func MustRSAPublic(key *jose.JSONWebKey) *rsa.PublicKey {
	res, err := ToRSAPublic(key)
	if err != nil {
		panic(err.Error())
	}

	return res
}

func ToRSAPublic(key *jose.JSONWebKey) (*rsa.PublicKey, error) {
	res, ok := key.Key.(*rsa.PublicKey)
	if !ok {
		return res, errors.New("Could not convert key to RSA Private Key.")
	}

	return res, nil
}

func MustRSAPrivate(key *jose.JSONWebKey) *rsa.PrivateKey {
	res, err := ToRSAPrivate(key)
	if err != nil {
		panic(err.Error())
	}

	return res
}

func ToRSAPrivate(key *jose.JSONWebKey) (*rsa.PrivateKey, error) {
	res, ok := key.Key.(*rsa.PrivateKey)
	if !ok {
		return res, errors.New("Could not convert key to RSA Private Key.")
	}

	return res, nil
}


text: I am the > relation.


text:
using Sharp9P.Exceptions;

namespace Sharp9P.Protocol.Messages
{
    public sealed class Ropen : Message
    {
        public uint Iounit;
        public Qid Qid;

        public Ropen(Qid qid, uint iounit)
        {
            Type = (byte) MessageType.Ropen;
            Qid = qid;
            Iounit = iounit;
            Length += Constants.Qidsz + Constants.Bit32Sz;
        }

        public Ropen(byte[] bytes) : base(bytes)
        {
            var offset = Constants.HeaderOffset;
            Qid = Protocol.ReadQid(bytes, offset);
            offset += Constants.Qidsz;
            Iounit = Protocol.ReadUInt(bytes, offset);
            offset += Constants.Bit32Sz;
            if (offset < Length)
            {
                throw new InsufficientDataException(Length, offset);
            }
        }

        public override byte[] ToBytes()
        {
            var bytes = new byte[Length];
            var offset = Protocol.WriteUint(bytes, Length, 0);
            bytes[offset] = Type;
            offset += Constants.Bit8Sz;
            offset += Protocol.WriteUshort(bytes, Tag, offset);

            offset += Protocol.WriteQid(bytes, Qid, offset);
            offset += Protocol.WriteUint(bytes, Iounit, offset);

            if (offset < Length)
            {
                throw new InsufficientDataException(Length, offset);
            }
            return bytes;
        }

        private bool Equals(Ropen other)
        {
            return base.Equals(other) && Equals(Qid, other.Qid) && Iounit == other.Iounit;
        }

        public override bool Equals(object obj)
        {
            if (ReferenceEquals(null, obj)) return false;
            if (ReferenceEquals(this, obj)) return true;
            return obj.GetType() == GetType() && Equals((Ropen) obj);
        }

        public override int GetHashCode()
        {
            unchecked
            {
                var hashCode = base.GetHashCode();
                hashCode = (hashCode*397) ^ (Qid?.GetHashCode() ?? 0);
                hashCode = (hashCode*397) ^ (int) Iounit;
                return hashCode;
            }
        }
    }
}


text:
//
// Unityちゃん用の三人称カメラ
//
// 2013/06/07 N.Kobyasahi
//
using UnityEngine;
using System.Collections;

public class ThirdPersonCamera : BaseScript
{
	public float smooth = 3f;		// カメラモーションのスムーズ化用変数
	Transform standardPos;			// the usual position for the camera, specified by a transform in the game
	Transform frontPos;			// Front Camera locater
	Transform jumpPos;			// Jump Camera locater

	// スムーズに繋がない時(クイック切り替え)用のブーリアンフラグ
	bool bQuickSwitch = false;	//Change Camera Position Quickly

	//
	void Start()
	{
		// 各参照の初期化
		standardPos = GameObject.Find ("CamPos").transform;
		Debug.Log("x = " + standardPos.position.x + ", y = "+ standardPos.position.y + ", z = " +standardPos.position.z);

		if(GameObject.Find ("FrontPos"))
			frontPos = GameObject.Find ("FrontPos").transform;

		if(GameObject.Find ("JumpPos"))
			jumpPos = GameObject.Find ("JumpPos").transform;

		//カメラをスタートする
		transform.position = standardPos.position;
		transform.forward = standardPos.forward;
	}

	void FixedUpdate ()	// このカメラ切り替えはFixedUpdate()内でないと正常に動かない
	{

//		if(Input.GetButton("Fire1"))	// left Ctlr
//		{
//			// Change Front Camera
//			setCameraPositionFrontView();
//		}
//
//		if(Input.GetButton("Fire2"))	//Alt
//		{
//			// Change Jump Camera
//			setCameraPositionJumpView();
//		}
//		else
//		{
			// return the camera to standard position and direction
			setCameraPositionNormalView();
//		}
	}

	void setCameraPositionNormalView()
	{
		if(bQuickSwitch == false){
		// the camera to standard position and direction
			transform.position = Vector3.Lerp(transform.position, standardPos.position, Time.fixedDeltaTime * smooth);
			transform.forward = Vector3.Lerp(transform.forward, standardPos.forward, Time.fixedDeltaTime * smooth);
		}
		else{
			// the camera to standard position and direction / Quick Change
			transform.position = standardPos.position;
			transform.forward = standardPos.forward;
			bQuickSwitch = false;
		}
	}

	void setCameraPositionFrontView()
	{
		// Change Front Camera
		bQuickSwitch = true;
		transform.position = frontPos.position;
		transform.forward = frontPos.forward;
	}

	void setCameraPositionJumpView()
	{
		// Change Jump Camera
		bQuickSwitch = false;
		transform.position = Vector3.Lerp(transform.position, jumpPos.position, Time.fixedDeltaTime * smooth);
		transform.forward = Vector3.Lerp(transform.forward, jumpPos.forward, Time.fixedDeltaTime * smooth);
	}
}


text:
#include <elf/elf.h>
#include <elf/net/message.h>
#include <map>
#include <string>

namespace elf {
struct message_handler_t {
    pb_new init;
    msg_proc proc;
};

typedef std::map<std::string, message_handler_t *> reg_map;

static reg_map s_regs;

void message_unregist_all(void)
{
    reg_map::iterator itr = s_regs.begin();

    for (; itr != s_regs.end(); ++itr) {
        E_DELETE itr->second;
    }
}

void message_regist(const std::string &name, pb_new init, msg_proc proc)
{
    message_handler_t *hdl = E_NEW message_handler_t;

    hdl->init = init;
    hdl->proc = proc;
    s_regs[name] = hdl;
}

void message_handle(recv_message_t *msg)
{
    assert(msg);

    reg_map::const_iterator itr = s_regs.find(msg->name);

    if (itr != s_regs.end()) {
        message_handler_t *hdl = itr->second;

        msg->pb = hdl->init();
        if (net_decode(msg)) {
            hdl->proc(*msg);
        }
    } else if (msg->ctx != NULL) {
        net_error(msg->ctx);
        net_close(msg->peer);
        LOG_WARN("net", "%lld INVALID message: %s.",
                msg->peer,
                msg->name.c_str());
    }
}
} // namespace elf


text:
package com.jetbrains.rest.run.docutils;

import com.intellij.execution.Location;
import com.intellij.execution.RunnerAndConfigurationSettings;
import com.intellij.execution.actions.ConfigurationContext;
import com.intellij.execution.junit.RuntimeConfigurationProducer;
import com.intellij.openapi.module.Module;
import com.intellij.openapi.module.ModuleUtil;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.util.io.FileUtil;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiFile;
import com.jetbrains.rest.RestFileType;
import com.jetbrains.rest.run.RestRunConfiguration;
import com.jetbrains.rest.run.RestRunConfigurationType;
import org.jetbrains.annotations.NotNull;
import org.jetbrains.annotations.Nullable;

import java.util.List;

/**
 * User : catherine
 */
public class DocutilsConfigurationProducer extends RuntimeConfigurationProducer implements Cloneable {
  private PsiFile mySourceFile = null;

  public DocutilsConfigurationProducer() {
    super(RestRunConfigurationType.getInstance().DOCUTILS_FACTORY);
  }

  public PsiElement getSourceElement() {
    return mySourceFile;
  }

  protected RunnerAndConfigurationSettings createConfigurationByElement(final Location location, final ConfigurationContext context) {
    PsiFile script = location.getPsiElement().getContainingFile();
    if (script == null || script.getFileType() != RestFileType.INSTANCE) {
      return null;
    }
    Module module = ModuleUtil.findModuleForPsiElement(script);
    mySourceFile = script;

    final Project project = mySourceFile.getProject();
    RunnerAndConfigurationSettings settings = cloneTemplateConfiguration(project, context);
    DocutilsRunConfiguration configuration = (DocutilsRunConfiguration) settings.getConfiguration();
    final VirtualFile vFile = mySourceFile.getVirtualFile();
    if (vFile == null) return null;
    configuration.setInputFile(vFile.getPath());
    configuration.setName(script.getName());

    String outputPath = vFile.getPath();
    int index = outputPath.lastIndexOf('.');
    if (index > 0) outputPath = outputPath.substring(0, index);
    outputPath += ".html";
    VirtualFile outputFile = LocalFileSystem.getInstance().findFileByPath(outputPath);
    if (outputFile == null) {
      configuration.setOutputFile(outputPath);
      configuration.setOpenInBrowser(true);
    }

    if (configuration.getTask().isEmpty())
      configuration.setTask("rst2html");
    final VirtualFile parent = vFile.getParent();
    if (parent != null) {
      configuration.setWorkingDirectory(parent.getPath());
    }
    configuration.setName(configuration.suggestedName());
    if (module != null) {
      configuration.setUseModuleSdk(true);
      configuration.setModule(module);
    }
    return settings;
  }

  @Nullable
  @Override
  protected RunnerAndConfigurationSettings findExistingByElement(Location location,
                                                                 @NotNull List<RunnerAndConfigurationSettings> existingConfigurations,
                                                                 ConfigurationContext context) {
    PsiFile script = location.getPsiElement().getContainingFile();
    if (script == null) {
      return null;
    }
    final VirtualFile vFile = script.getVirtualFile();
    if (vFile == null) {
      return null;
    }
    String path = vFile.getPath();
    for (RunnerAndConfigurationSettings configuration : existingConfigurations) {
      final String scriptName = ((RestRunConfiguration)configuration.getConfiguration()).getInputFile();
      if (FileUtil.toSystemIndependentName(scriptName).equals(FileUtil.toSystemIndependentName(path))) {
        return configuration;
      }
    }
    return null;
  }

  public int compareTo(final Object o) {
    return PREFERED;
  }
}


text:
def do_something(para1, para2, para3)
end


text:
; var root = root || {};

root.Analytics = root.Analytics || {};

// the semi-colon before function invocation is a safety net against concatenated
// scripts and/or other plugins which may not be closed properly.
(function ($, window, document, undefined, ko) {
    "use strict";

    // undefined is used here as the undefined global variable in ECMAScript 3 is
    // mutable (ie. it can be changed by someone else). undefined isn't really being
    // passed in so we can ensure the value of it is truly undefined. In ES5, undefined
    // can no longer be modified.

    // window and document are passed through as local variables rather than globals
    // as this (slightly) quickens the resolution process and can be more efficiently
    // minified (especially when both are regularly referenced in your plugin).

    //
    // MetricViewModel Model
    //
    var MetricViewModel = this.MetricViewModel = function (controller) {
        this._controller = controller;
        this.values = ko.observable();
    };

    MetricViewModel.prototype = {
        constructor: MetricViewModel,

        _init: function() {
        },

        _getMetricData: function() {
            var getStatsHandler = $.proxy(function (data) { this.values(data); }, this);
            this._controller.getMetricViewData(getStatsHandler);
        },

        show: function() {
            this._getMetricData();
        }

    };

    //
    // TimeLineViewModel
    //
    var TimeLineViewModel = this.TimeLineViewModel = function (controller, options) {
        this.scales = new root.Enum([
            { key: 0, value: "unspecified" },
            { key: 1, value: "Day" },
            { key: 2, value: "Week" },
            { key: 3, value: "Month" },
            { key: 4, value: "Year" }]);
        this.selectedScale = ko.observable(this.scales.Week);
        this.isDayScale = ko.computed(this._isDayScale, this);
        this.isWeekScale = ko.computed(this._isWeekScale, this);
        this.isMonthScale = ko.computed(this._isMonthScale, this);
        this.isYearScale = ko.computed(this._isYearScale, this);
        this.source = ko.observableArray();
        this.source.subscribe(this._onSourceChanged, this);

        this._controller = controller;
        this._options = options;

        this._init();
    };

    TimeLineViewModel.prototype = {
        constructor: TimeLineViewModel,

        _init: function() {
            var graphOptions = $.extend({}, {
                tooltipTextFunction: function (datum) { return datum.key.format("dd-MMM-yyyy") + " : " + datum.value + " Pageviews"; }
            }, this._options);
            this._graph = new root.TimeLineGraph($("#" + this._options.containerId)[0], graphOptions);
            this.source([]);

            this.selectedScale.subscribe(this._scaleChanged, this);

        },

        _scaleChanged: function (newValue) {
            this._getTimeLineViewData();
        },

        _getTimeLineViewData: function () {
            var callback = $.proxy(this._onGetTimeLineViewData, this);
            this._controller.getTimeLineViewData(this.selectedScale(), callback);
        },

        _onGetTimeLineViewData: function (data) {
            this.source(data);
        },

        _onSourceChanged: function (newValue) {
            this._show();
        },

        setScale: function (caller, evt) {
            var clickedOption = evt.currentTarget;
            var $clickedOption = $(clickedOption);
            this.selectedScale(parseInt($clickedOption.attr("data"), 10));
        },

        _isDayScale: function () {
            return this.selectedScale() === this.scales.Day;
        },

        _isWeekScale: function () {
            return this.selectedScale() === this.scales.Week;
        },

        _isMonthScale: function () {
            return this.selectedScale() === this.scales.Month;
        },

        _isYearScale: function () {
            return this.selectedScale() === this.scales.Year;
        },

        _show: function () {
            this._graph.draw(this.source(), this.scales.getEnumName(this.selectedScale()).toLowerCase());
        },

        show: function() {
            this._getTimeLineViewData();
        }

    };

    //
    // GeoMapViewModel
    //
    var GeoMapViewModel = this.GeoMapViewModel = function (controller, options) {
        this._controller = controller;
        this._options = options;
        this._init();
    };

    GeoMapViewModel.prototype = {
        constructor: GeoMapViewModel,

        _init: function() {
            var options = $.extend({}, {
                graphClass: "graph",
                size: { width: 960, height: 400 }
            }, this._options);
            this._map = new root.Analytics.ChoroplethMap($("#" + this._options.containerId)[0], options);
            var onSelectCountryHandler = $.proxy(this._onSelectCountry, this);
            $(this._map).on("onselectcountry", onSelectCountryHandler);

            var zoomOptions = {
                horizontal: false,
                vertical: true,
                yPrecision: 800,
                animationCallback: function(x, y) {
                    //alert(String(12 + x * 24) + 'px');
                }
            };
            //this._zoom = new Dragdealer(this._options.zoomId, zoomOptions);

            this.$this = $(this);
        },

        _onSelectCountry: function (eventObject, country) {
            var callback = $.proxy(this._onGetCountryMapViewData, this, country);
            this._controller.getCountryMapViewData(country, callback);
        },

        _onGetCountryMapViewData: function (country, data) {
            this.showCountry(data);
            this._getCountryChoroplethViewData(country);
        },

        _getCountryChoroplethViewData: function (country) {
            var callback = $.proxy(this._onGetCountryChoroplethViewData, this);
            this._controller.getCountryChoroplethViewData(country, callback);
        },

        _onGetCountryChoroplethViewData: function (data) {
            this.showCountryChoropleth(data);
        },

        _getMapViewData: function () {
            var callback = $.proxy(this._onGetMapViewData, this);
            this._controller.getMapViewData(callback);
        },

        _onGetMapViewData: function (data) {
            this.showWorld(data);
            this._getChoroplethViewData();
        },

        _getChoroplethViewData: function () {
            var callback = $.proxy(this._onGetChoroplethViewData, this);
            this._controller.getChoroplethViewData(callback);
        },

        _onGetChoroplethViewData: function (data) {
            this.showWorldChoropleth(data);
        },

        showCountry: function (data) {
            this._map.showCountry(data);
        },

        showWorld: function(data) {
            this._map.showWorld(data);
        },

        show: function () {
            this._getMapViewData();
        },

        showWorldChoropleth: function (data) {
            this._map.showWorldChoropleth(data);
        },

        showCountryChoropleth: function (data) {
            this._map.showCountryChoropleth(data);
        }

    };

    //
    // SourcesViewModel
    //
    var SourcesViewModel = this.SourcesViewModel = function (controller, options) {
        this._options = options;
        this._controller = controller;
        this.categories = ko.observableArray([]);
        this.metric = ko.observable();
        this.selectedCategory = ko.observable();
        this.selectedCategoryDescription = ko.computed(this._selectedCategoryDescription, this);
        this._init();
    };

    SourcesViewModel.prototype = {
        constructor: SourcesViewModel,

        _init: function () {
            var options = $.extend({}, {
                innerRadius: 60,
                outerRadius: 80,
                size: { width: 650, height: 400 },
                textOffset: 24,
                tweenDuration: 1050,
                tooltipTextFunction: $.proxy(this._getSliceTooltip, this)
            }, this._options);
            this._chart = new root.Analytics.PieChart($("#" + this._options.containerId)[0], options);
            var onSelectSliceHandler = $.proxy(this._onSelectSlice, this);
            $(this._chart).on("onselectslice", onSelectSliceHandler);

            this.$this = $(this);
        },

        _getSliceTooltip: function(d) {
            var slicePageViews = d.data.value.pageViews;
            var perecentage = (slicePageViews / this._getTotalViews()) * 100;
            return d.data.key + ": " + d.data.value.pageViews + " views | " + perecentage.toFixed(0) + "%";
        },

        _getSourcesViewData: function() {
            var callback = $.proxy(this._onGetSourcesViewData, this);
            this._controller.getSourcesViewData(callback);
        },

        _onGetSourcesViewData: function (data) {
            var sourceAccessor = {
                getName: function(d) { return d.key; },
                getValue: function(d) { return d.value.pageViews; },
                getSlices: function(data) { return data.categories; },
                getTotal: function(data) { return data.metric; },
                getTotalName: function(d) { return d.key; },
                getTotalValue: function(d) { return d.value.pageViews; }
            };

            this.categories(data.categories);
            this.metric(data.metric);
            this._chart.show(data, sourceAccessor);

            var categories = data.categories;
            var index = 0;
            var size = categories.length;
            if (size == 0) {
                return;
            }
            if (size > 1) {
                for (var i = 1; i < size; i++) {
                    if (categories[index].value.pageViews < categories[i].value.pageViews) {
                        index = i;
                    }
                }
                this._chart.selectSlice(index);
            }
            this.selectedCategory(data.categories[index]);
        },

        isSelected: function(category) {
            return category === this.selectedCategory();
        },

        selectCategory: function(category) {
            this.selectedCategory(category);
            this._chart.selectSlice(category);
        },

        _selectedCategoryDescription: function () {
            var selectedCategory = this.selectedCategory();
            if (!selectedCategory) {
                return "";
            }
            var total = this._getTotalViews();
            if (isNaN(total)) {
                return "";
            }
            var perecentage = (selectedCategory.value.pageViews / total) * 100;
            return perecentage.toFixed(0) + "%" + " (" + total + ")";
        },

        _getTotalViews: function() {
            var metric = this.metric();
            if (!metric) {
                return NaN;
            }
            return metric.value.pageViews;
        },

        _onSelectSlice: function (eventObject, slice) {
            this.selectedCategory(slice);
        },

        show: function () {
            this._getSourcesViewData();
        }

    };

    var ViewModel = this.ViewModel = function (options) {
        this._options = options;

        var endDateValue = new Date();
        var startDateValue = new Date(new Date().setDate(endDateValue.getDate() - 30));

        this.endDate = ko.observable(endDateValue);
        this.startDate = ko.observable(startDateValue);

        this.startDate.subscribe(this._startDateChanged, this);
        this.endDate.subscribe(this._endDateChanged, this);

        this.stats = ko.observable();

        this.metricTypes = ko.observableArray([]);
        this.selectedMetricType = ko.observable();

        this.init();
    };

    ViewModel.prototype = {
        constructor: ViewModel,

        init: function () {
            this._controller = new root.Analytics.Controller(this._options.services);

            this.metricTypes([
                { key: 0, value: "Pageviews" },
                { key: 1, value: "Unique Pageviews" },
                { key: 2, value: "Average Time" },
                { key: 3, value: "Entrances" },
                { key: 4, value: "Bounce Rate" },
                { key: 5, value: "Exit Rate" }
            ]);
            this.selectedMetricType(root.KeyValueConverter.getKeyValuePairByKey(this.metricTypes(), 0));

            this.metricView = new MetricViewModel(this._controller);
            this.timeLineView = new TimeLineViewModel(this._controller, this._options.timeLineView);
            this.geoMapView = new GeoMapViewModel(this._controller, this._options.geoMapView);
            //this.sourcesView = new SourcesViewModel(this._controller, this._options.sourcesView);

            this.show();
        },

        _startDateChanged: function (newValue) {
            this.show();
        },

        _endDateChanged: function (newValue) {
            this.show();
        },

        show: function () {
            this._controller.setDateRange(this.startDate(), this.endDate());
            this.metricView.show();
            this.timeLineView.show();
            this.geoMapView.show();
            //this.sourcesView.show();
        }

    };

    this.initialize = function (options) {
        $(document).ready(function () {
            var $element = $("#" + options.containerId);
            // in case when control is excluded from rendering by server tags logic,
            // a check on the html element existence is performed here:
            if ($element.length === 0) {
                return;
            }
            var element = $element[0];

            var model = new ViewModel(options);
            if (element.id) {
                root[element.id] = model;
            }
            ko.applyBindings(model, element);
            var datePickerOptions = {
                format: "dd-mm-yyyy",
                autoclose: true
            };
            $(".an-start-date").datepicker(datePickerOptions);
            $(".an-end-date").datepicker(datePickerOptions);
        });
    };

}).apply(root.Analytics, [jQuery, window, document, undefined, ko]);


text:
import DS from 'ember-data';

export default DS.Model.extend({
	name: DS.attr('string'),
    nodeClass : DS.attr('string'),
    sketch: DS.attr('string'),
    url: DS.attr('string'),
    description: DS.attr('string'),
    contentType: DS.attr('string'),
    headers: DS.attr(),
    statusCode: DS.attr('string'),
    reason: DS.attr('string'),
    body: DS.attr('string'),
    transitions: DS.attr(),
    method: DS.attr(),
    x: DS.attr(),
    y: DS.attr(),
    // Tags allow us to add descriptive labels to nodes (e.g.: CJ adds read, update, delete and create tags to nodes)
    tags: DS.attr(),
    // The published map attribute lets us know which parts of this node have been published and are therefore immutable
    // This is for future use
    // Example: published: { body, transitions: 1, }
    published: DS.attr()
});


text:
<?php

namespace Drupal\Console\Test;

use Symfony\Component\Console\Helper\FormatterHelper;
use Symfony\Component\Console\Helper\HelperSet;
use Drupal\Console\Helper\DialogHelper;
use Drupal\Console\Helper\TwigRendererHelper;
use Drupal\Console\Helper\HelperTrait;

abstract class BaseTestCase extends \PHPUnit_Framework_TestCase
{
    use HelperTrait;

    public $dir;

    /**
     * @var \Symfony\Component\Console\Helper\HelperSet
     */
    protected $helperSet;

    protected function setup()
    {
        $this->setUpTemporalDirectory();
    }

    public function setUpTemporalDirectory()
    {
        $this->dir = sys_get_temp_dir() . "/modules";
    }

    public function getHelperSet($input = null)
    {
        if (!$this->helperSet) {
            $dialog = new DialogHelper();
            $dialog->setInputStream($this->getInputStream($input));

            $stringHelper = $this->getMockBuilder('Drupal\Console\Helper\StringHelper')
                ->disableOriginalConstructor()
                ->setMethods(['createMachineName'])
                ->getMock();

            $stringHelper->expects($this->any())
                ->method('createMachineName')
                ->will($this->returnArgument(0));

            $validator = $this->getMockBuilder('Drupal\Console\Helper\ValidatorHelper')
                ->disableOriginalConstructor()
                ->setMethods(['validateModuleName'])
                ->getMock();

            $validator->expects($this->any())
                ->method('validateModuleName')
                ->will($this->returnArgument(0));

            $translator = $this->getTranslatorHelper();

            $message = $this
                ->getMockBuilder('Drupal\Console\Helper\MessageHelper')
                ->disableOriginalConstructor()
                ->setMethods(['showMessages', 'showMessage'])
                ->getMock();

            $chain = $this
                ->getMockBuilder('Drupal\Console\Helper\ChainCommandHelper')
                ->disableOriginalConstructor()
                ->setMethods(['addCommand', 'getCommands'])
                ->getMock();

            $drupal = $this
                ->getMockBuilder('Drupal\Console\Helper\DrupalHelper')
                ->setMethods(['isBootable', 'getDrupalRoot'])
                ->getMock();

            $siteHelper = $this
                ->getMockBuilder('Drupal\Console\Helper\SiteHelper')
                ->disableOriginalConstructor()
                ->setMethods(['setModulePath', 'getModulePath'])
                ->getMock();

            $siteHelper->expects($this->any())
                ->method('getModulePath')
                ->will($this->returnValue($this->dir));

            $this->helperSet = new HelperSet(
                [
                    'formatter' => new FormatterHelper(),
                    'renderer' => new TwigRendererHelper(),
                    'dialog' => $dialog,
                    'string' => $stringHelper,
                    'validator' => $validator,
                    'translator' => $translator,
                    'site' => $siteHelper,
                    'message' => $message,
                    'chain' => $chain,
                    'drupal' => $drupal,
                ]
            );
        }

        return $this->helperSet;
    }

    protected function getInputStream($input)
    {
        $stream = fopen('php://memory', 'r+', false);
        fputs($stream, $input . str_repeat("\n", 10));
        rewind($stream);

        return $stream;
    }

    public function getTranslatorHelper()
    {
        $translatorHelper = $this
            ->getMockBuilder('Drupal\Console\Helper\TranslatorHelper')
            ->disableOriginalConstructor()
            ->setMethods(['loadResource', 'trans', 'getMessagesByModule', 'writeTranslationsByModule'])
            ->getMock();

        $translatorHelper->expects($this->any())
            ->method('getMessagesByModule')
            ->will($this->returnValue([]));

        return $translatorHelper;
    }
}